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
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
//! The main context structure which drives the drawing process.

use float_cmp::approx_eq;
use gio::prelude::*;
use glib::translate::*;
use pango::ffi::PangoMatrix;
use pango::prelude::FontMapExt;
use regex::{Captures, Regex};
use std::cell::RefCell;
use std::convert::TryFrom;
use std::f64::consts::*;
use std::rc::Rc;
use std::{borrow::Cow, sync::OnceLock};

use crate::accept_language::UserLanguage;
use crate::bbox::BoundingBox;
use crate::color::color_to_rgba;
use crate::coord_units::CoordUnits;
use crate::document::{AcquiredNodes, NodeId, RenderingOptions};
use crate::dpi::Dpi;
use crate::element::{Element, ElementData};
use crate::error::{AcquireError, ImplementationLimit, InternalRenderingError};
use crate::filters::{self, FilterSpec};
use crate::float_eq_cairo::ApproxEqCairo;
use crate::gradient::{GradientVariant, SpreadMethod, UserSpaceGradient};
use crate::layout::{
    Filter, Group, Image, Layer, LayerKind, LayoutViewport, Shape, StackingContext, Stroke, Text,
    TextSpan,
};
use crate::length::*;
use crate::marker;
use crate::node::{CascadedValues, Node, NodeBorrow, NodeDraw};
use crate::paint_server::{PaintSource, UserSpacePaintSource};
use crate::path_builder::*;
use crate::pattern::UserSpacePattern;
use crate::properties::{
    ClipRule, ComputedValues, FillRule, ImageRendering, MaskType, MixBlendMode, Opacity,
    PaintTarget, ShapeRendering, StrokeLinecap, StrokeLinejoin, TextRendering,
};
use crate::rect::{rect_to_transform, IRect, Rect};
use crate::rsvg_log;
use crate::session::Session;
use crate::surface_utils::shared_surface::{
    ExclusiveImageSurface, Interpolation, SharedImageSurface, SurfaceType,
};
use crate::transform::{Transform, ValidTransform};
use crate::unit_interval::UnitInterval;
use crate::viewbox::ViewBox;
use crate::{borrow_element_as, is_element_of_type};

/// Opaque font options for a DrawingCtx.
///
/// This is used for DrawingCtx::create_pango_context.
pub struct FontOptions {
    options: cairo::FontOptions,
}

/// Set path on the cairo context, or clear it.
/// This helper object keeps track whether the path has been set already,
/// so that it isn't recalculated every so often.
struct PathHelper<'a> {
    cr: &'a cairo::Context,
    transform: ValidTransform,
    path: &'a Path,
    is_square_linecap: bool,
    has_path: Option<bool>,
}

impl<'a> PathHelper<'a> {
    pub fn new(
        cr: &'a cairo::Context,
        transform: ValidTransform,
        path: &'a Path,
        linecap: StrokeLinecap,
    ) -> Self {
        PathHelper {
            cr,
            transform,
            path,
            is_square_linecap: linecap == StrokeLinecap::Square,
            has_path: None,
        }
    }

    pub fn set(&mut self) -> Result<(), InternalRenderingError> {
        match self.has_path {
            Some(false) | None => {
                self.has_path = Some(true);
                self.cr.set_matrix(self.transform.into());
                self.path.to_cairo(self.cr, self.is_square_linecap)
            }
            Some(true) => Ok(()),
        }
    }

    pub fn unset(&mut self) {
        match self.has_path {
            Some(true) | None => {
                self.has_path = Some(false);
                self.cr.new_path();
            }
            Some(false) => {}
        }
    }
}

/// Holds the size of the current viewport in the user's coordinate system.
#[derive(Clone)]
pub struct Viewport {
    pub dpi: Dpi,

    /// Corners of the current coordinate space.
    pub vbox: ViewBox,

    /// The viewport's coordinate system, or "user coordinate system" in SVG terms.
    transform: Transform,
}

impl Viewport {
    /// FIXME: this is just used in Handle::with_height_to_user(), and in length.rs's test suite.
    /// Find a way to do this without involving a default identity transform.
    pub fn new(dpi: Dpi, view_box_width: f64, view_box_height: f64) -> Viewport {
        Viewport {
            dpi,
            vbox: ViewBox::from(Rect::from_size(view_box_width, view_box_height)),
            transform: Default::default(),
        }
    }

    /// Creates a new viewport suitable for a certain kind of units.
    ///
    /// For `objectBoundingBox`, CSS lengths which are in percentages
    /// refer to the size of the current viewport.  Librsvg implements
    /// that by keeping the same current transformation matrix, and
    /// setting a viewport size of (1.0, 1.0).
    ///
    /// For `userSpaceOnUse`, we just duplicate the current viewport,
    /// since that kind of units means to use the current coordinate
    /// system unchanged.
    pub fn with_units(&self, units: CoordUnits) -> Viewport {
        match units {
            CoordUnits::ObjectBoundingBox => Viewport {
                dpi: self.dpi,
                vbox: ViewBox::from(Rect::from_size(1.0, 1.0)),
                transform: self.transform,
            },

            CoordUnits::UserSpaceOnUse => Viewport {
                dpi: self.dpi,
                vbox: self.vbox,
                transform: self.transform,
            },
        }
    }

    /// Returns a viewport with a new size for normalizing `Length` values.
    pub fn with_view_box(&self, width: f64, height: f64) -> Viewport {
        Viewport {
            dpi: self.dpi,
            vbox: ViewBox::from(Rect::from_size(width, height)),
            transform: self.transform,
        }
    }
}

/// Values that stay constant during rendering with a DrawingCtx.
#[derive(Clone)]
pub struct RenderingConfiguration {
    pub dpi: Dpi,
    pub cancellable: Option<gio::Cancellable>,
    pub user_language: UserLanguage,
    pub svg_nesting: SvgNesting,
    pub measuring: bool,
    pub testing: bool,
}

pub struct DrawingCtx {
    session: Session,

    initial_viewport: Viewport,

    cr_stack: Rc<RefCell<Vec<cairo::Context>>>,
    cr: cairo::Context,

    drawsub_stack: Vec<Node>,

    config: RenderingConfiguration,
}

pub enum DrawingMode {
    LimitToStack { node: Node, root: Node },

    OnlyNode(Node),
}

/// Whether an SVG document is being rendered standalone or referenced from an `<image>` element.
///
/// Normally, the coordinate system used when rendering a toplevel SVG is determined from the
/// initial viewport and the `<svg>` element's `viewBox` and `preserveAspectRatio` attributes.
/// However, when an SVG document is referenced from an `<image>` element, as in `<image href="foo.svg"/>`,
/// its `preserveAspectRatio` needs to be ignored so that the one from the `<image>` element can
/// be used instead.  This lets the parent document (the one with the `<image>` element) specify
/// how it wants the child SVG to be scaled into the viewport.
#[derive(Copy, Clone)]
pub enum SvgNesting {
    Standalone,
    ReferencedFromImageElement,
}

/// The toplevel drawing routine.
///
/// This creates a DrawingCtx internally and starts drawing at the specified `node`.
pub fn draw_tree(
    session: Session,
    mode: DrawingMode,
    cr: &cairo::Context,
    viewport_rect: Rect,
    config: RenderingConfiguration,
    acquired_nodes: &mut AcquiredNodes<'_>,
) -> Result<BoundingBox, InternalRenderingError> {
    let (drawsub_stack, node) = match mode {
        DrawingMode::LimitToStack { node, root } => (node.ancestors().collect(), root),

        DrawingMode::OnlyNode(node) => (Vec::new(), node),
    };

    let cascaded = CascadedValues::new_from_node(&node);

    // Preserve the user's transform and use it for the outermost bounding box.  All bounds/extents
    // will be converted to this transform in the end.
    let user_transform = Transform::from(cr.matrix());
    let mut user_bbox = BoundingBox::new().with_transform(user_transform);

    // https://www.w3.org/TR/SVG2/coords.html#InitialCoordinateSystem
    //
    // "For the outermost svg element, the SVG user agent must
    // determine an initial viewport coordinate system and an
    // initial user coordinate system such that the two
    // coordinates systems are identical. The origin of both
    // coordinate systems must be at the origin of the SVG
    // viewport."
    //
    // "... the initial viewport coordinate system (and therefore
    // the initial user coordinate system) must have its origin at
    // the top/left of the viewport"

    // Translate so (0, 0) is at the viewport's upper-left corner.
    let transform = user_transform.pre_translate(viewport_rect.x0, viewport_rect.y0);

    // Here we exit immediately if the transform is not valid, since we are in the
    // toplevel drawing function.  Downstream cases would simply not render the current
    // element and ignore the error.
    let valid_transform = ValidTransform::try_from(transform)?;
    cr.set_matrix(valid_transform.into());

    // Per the spec, so the viewport has (0, 0) as upper-left.
    let viewport_rect = viewport_rect.translate((-viewport_rect.x0, -viewport_rect.y0));
    let initial_viewport = Viewport {
        dpi: config.dpi,
        vbox: ViewBox::from(viewport_rect),
        transform,
    };

    let mut draw_ctx = DrawingCtx::new(session, cr, &initial_viewport, config, drawsub_stack);

    let content_bbox = draw_ctx.draw_node_from_stack(
        &node,
        acquired_nodes,
        &cascaded,
        &initial_viewport,
        false,
    )?;

    user_bbox.insert(&content_bbox);

    if draw_ctx.is_rendering_cancelled() {
        Err(InternalRenderingError::Cancelled)
    } else {
        Ok(user_bbox)
    }
}

pub fn with_saved_cr<O, F>(cr: &cairo::Context, f: F) -> Result<O, InternalRenderingError>
where
    F: FnOnce() -> Result<O, InternalRenderingError>,
{
    cr.save()?;
    match f() {
        Ok(o) => {
            cr.restore()?;
            Ok(o)
        }

        Err(e) => Err(e),
    }
}

impl Drop for DrawingCtx {
    fn drop(&mut self) {
        self.cr_stack.borrow_mut().pop();
    }
}

const CAIRO_TAG_LINK: &str = "Link";

impl DrawingCtx {
    fn new(
        session: Session,
        cr: &cairo::Context,
        initial_viewport: &Viewport,
        config: RenderingConfiguration,
        drawsub_stack: Vec<Node>,
    ) -> DrawingCtx {
        DrawingCtx {
            session,
            initial_viewport: initial_viewport.clone(),
            cr_stack: Rc::new(RefCell::new(Vec::new())),
            cr: cr.clone(),
            drawsub_stack,
            config,
        }
    }

    /// Copies a `DrawingCtx` for temporary use on a Cairo surface.
    ///
    /// `DrawingCtx` maintains state using during the drawing process, and sometimes we
    /// would like to use that same state but on a different Cairo surface and context
    /// than the ones being used on `self`.  This function copies the `self` state into a
    /// new `DrawingCtx`, and ties the copied one to the supplied `cr`.
    fn nested(&self, cr: cairo::Context) -> DrawingCtx {
        let cr_stack = self.cr_stack.clone();

        cr_stack.borrow_mut().push(self.cr.clone());

        DrawingCtx {
            session: self.session.clone(),
            initial_viewport: self.initial_viewport.clone(),
            cr_stack,
            cr,
            drawsub_stack: self.drawsub_stack.clone(),
            config: self.config.clone(),
        }
    }

    pub fn session(&self) -> &Session {
        &self.session
    }

    /// Returns the `RenderingOptions` being used for rendering.
    pub fn rendering_options(&self, svg_nesting: SvgNesting) -> RenderingOptions {
        RenderingOptions {
            dpi: self.config.dpi,
            cancellable: self.config.cancellable.clone(),
            user_language: self.config.user_language.clone(),
            svg_nesting,
            testing: self.config.testing,
        }
    }

    pub fn user_language(&self) -> &UserLanguage {
        &self.config.user_language
    }

    pub fn toplevel_viewport(&self) -> Rect {
        *self.initial_viewport.vbox
    }

    /// Gets the transform that will be used on the target surface,
    /// whether using an isolated stacking context or not.
    ///
    /// This is only used in the text code, and we should probably try
    /// to remove it.
    pub fn get_transform_for_stacking_ctx(
        &self,
        stacking_ctx: &StackingContext,
        clipping: bool,
    ) -> Result<ValidTransform, InternalRenderingError> {
        if stacking_ctx.should_isolate() && !clipping {
            let affines = CompositingAffines::new(
                *self.get_transform(),
                self.initial_viewport.transform,
                self.cr_stack.borrow().len(),
            );

            Ok(ValidTransform::try_from(affines.for_temporary_surface)?)
        } else {
            Ok(self.get_transform())
        }
    }

    pub fn svg_nesting(&self) -> SvgNesting {
        self.config.svg_nesting
    }

    pub fn is_measuring(&self) -> bool {
        self.config.measuring
    }

    pub fn is_testing(&self) -> bool {
        self.config.testing
    }

    pub fn get_transform(&self) -> ValidTransform {
        let t = Transform::from(self.cr.matrix());
        ValidTransform::try_from(t)
            .expect("Cairo should already have checked that its current transform is valid")
    }

    pub fn empty_bbox(&self) -> BoundingBox {
        BoundingBox::new().with_transform(*self.get_transform())
    }

    fn size_for_temporary_surface(&self) -> (i32, i32) {
        let rect = self.toplevel_viewport();

        let (viewport_width, viewport_height) = (rect.width(), rect.height());

        let (width, height) = self
            .initial_viewport
            .transform
            .transform_distance(viewport_width, viewport_height);

        // We need a size in whole pixels, so use ceil() to ensure the whole viewport fits
        // into the temporary surface.
        (width.ceil().abs() as i32, height.ceil().abs() as i32)
    }

    pub fn create_surface_for_toplevel_viewport(
        &self,
    ) -> Result<cairo::ImageSurface, InternalRenderingError> {
        let (w, h) = self.size_for_temporary_surface();

        Ok(cairo::ImageSurface::create(cairo::Format::ARgb32, w, h)?)
    }

    fn create_similar_surface_for_toplevel_viewport(
        &self,
        surface: &cairo::Surface,
    ) -> Result<cairo::Surface, InternalRenderingError> {
        let (w, h) = self.size_for_temporary_surface();

        Ok(cairo::Surface::create_similar(
            surface,
            cairo::Content::ColorAlpha,
            w,
            h,
        )?)
    }

    /// Creates a new coordinate space inside a viewport and sets a clipping rectangle.
    ///
    /// Note that this actually changes the `draw_ctx.cr`'s transformation to match
    /// the new coordinate space, but the old one is not restored after the
    /// result's `Viewport` is dropped.  Thus, this function must be called
    /// inside `with_saved_cr` or `draw_ctx.with_discrete_layer`.
    pub fn push_new_viewport(
        &self,
        current_viewport: &Viewport,
        layout_viewport: &LayoutViewport,
    ) -> Option<Viewport> {
        let LayoutViewport {
            geometry,
            vbox,
            preserve_aspect_ratio,
            overflow,
        } = *layout_viewport;

        if !overflow.overflow_allowed() || (vbox.is_some() && preserve_aspect_ratio.is_slice()) {
            clip_to_rectangle(&self.cr, &geometry);
        }

        preserve_aspect_ratio
            .viewport_to_viewbox_transform(vbox, &geometry)
            .unwrap_or_else(|_e| {
                match vbox {
                    None => unreachable!(
                        "viewport_to_viewbox_transform only returns errors when vbox != None"
                    ),
                    Some(v) => {
                        rsvg_log!(
                            self.session,
                            "ignoring viewBox ({}, {}, {}, {}) since it is not usable",
                            v.x0,
                            v.y0,
                            v.width(),
                            v.height()
                        );
                    }
                }
                None
            })
            .map(|t| {
                self.cr.transform(t.into());

                Viewport {
                    dpi: self.config.dpi,
                    vbox: vbox.unwrap_or(current_viewport.vbox),
                    transform: current_viewport.transform.post_transform(&t),
                }
            })
    }

    fn clip_to_node(
        &mut self,
        clip_node: &Option<Node>,
        acquired_nodes: &mut AcquiredNodes<'_>,
        viewport: &Viewport,
        bbox: &BoundingBox,
    ) -> Result<(), InternalRenderingError> {
        if clip_node.is_none() {
            return Ok(());
        }

        let node = clip_node.as_ref().unwrap();
        let units = borrow_element_as!(node, ClipPath).get_units();

        if let Ok(transform) = rect_to_transform(&bbox.rect, units) {
            let cascaded = CascadedValues::new_from_node(node);
            let values = cascaded.get();

            let node_transform = values.transform().post_transform(&transform);
            let transform_for_clip = ValidTransform::try_from(node_transform)?;

            let orig_transform = self.get_transform();
            self.cr.transform(transform_for_clip.into());

            for child in node.children().filter(|c| {
                c.is_element() && element_can_be_used_inside_clip_path(&c.borrow_element())
            }) {
                child.draw(
                    acquired_nodes,
                    &CascadedValues::clone_with_node(&cascaded, &child),
                    viewport,
                    self,
                    true,
                )?;
            }

            self.cr.clip();

            self.cr.set_matrix(orig_transform.into());
        }

        Ok(())
    }

    fn generate_cairo_mask(
        &mut self,
        mask_node: &Node,
        viewport: &Viewport,
        transform: Transform,
        bbox: &BoundingBox,
        acquired_nodes: &mut AcquiredNodes<'_>,
    ) -> Result<Option<cairo::ImageSurface>, InternalRenderingError> {
        if bbox.rect.is_none() {
            // The node being masked is empty / doesn't have a
            // bounding box, so there's nothing to mask!
            return Ok(None);
        }

        let _mask_acquired = match acquired_nodes.acquire_ref(mask_node) {
            Ok(n) => n,

            Err(AcquireError::CircularReference(_)) => {
                rsvg_log!(self.session, "circular reference in element {}", mask_node);
                return Ok(None);
            }

            _ => unreachable!(),
        };

        let mask_element = mask_node.borrow_element();
        let mask = borrow_element_as!(mask_node, Mask);

        let bbox_rect = bbox.rect.as_ref().unwrap();

        let cascaded = CascadedValues::new_from_node(mask_node);
        let values = cascaded.get();

        let mask_units = mask.get_units();

        let mask_rect = {
            let params = NormalizeParams::new(values, &viewport.with_units(mask_units));
            mask.get_rect(&params)
        };

        let mask_transform = values.transform().post_transform(&transform);
        let transform_for_mask = ValidTransform::try_from(mask_transform)?;

        let mask_content_surface = self.create_surface_for_toplevel_viewport()?;

        // Use a scope because mask_cr needs to release the
        // reference to the surface before we access the pixels
        {
            let mask_cr = cairo::Context::new(&mask_content_surface)?;
            mask_cr.set_matrix(transform_for_mask.into());

            let bbtransform = Transform::new_unchecked(
                bbox_rect.width(),
                0.0,
                0.0,
                bbox_rect.height(),
                bbox_rect.x0,
                bbox_rect.y0,
            );

            let clip_rect = if mask_units == CoordUnits::ObjectBoundingBox {
                bbtransform.transform_rect(&mask_rect)
            } else {
                mask_rect
            };

            clip_to_rectangle(&mask_cr, &clip_rect);

            if mask.get_content_units() == CoordUnits::ObjectBoundingBox {
                if bbox_rect.is_empty() {
                    return Ok(None);
                }
                mask_cr.transform(ValidTransform::try_from(bbtransform)?.into());
            }

            let mask_viewport = viewport.with_units(mask.get_content_units());

            let mut mask_draw_ctx = self.nested(mask_cr);

            let stacking_ctx = StackingContext::new(
                self.session(),
                acquired_nodes,
                &mask_element,
                Transform::identity(),
                None,
                values,
            );

            rsvg_log!(self.session, "(mask {}", mask_element);

            let res = mask_draw_ctx.with_discrete_layer(
                &stacking_ctx,
                acquired_nodes,
                &mask_viewport,
                None,
                false,
                &mut |an, dc, new_viewport| {
                    mask_node.draw_children(an, &cascaded, new_viewport, dc, false)
                },
            );

            rsvg_log!(self.session, ")");

            res?;
        }

        let tmp = SharedImageSurface::wrap(mask_content_surface, SurfaceType::SRgb)?;

        let mask_result = match values.mask_type() {
            MaskType::Luminance => tmp.to_luminance_mask()?,
            MaskType::Alpha => tmp.extract_alpha(IRect::from_size(tmp.width(), tmp.height()))?,
        };

        let mask = mask_result.into_image_surface()?;

        Ok(Some(mask))
    }

    fn is_rendering_cancelled(&self) -> bool {
        match &self.config.cancellable {
            None => false,
            Some(cancellable) => cancellable.is_cancelled(),
        }
    }

    pub fn with_discrete_layer(
        &mut self,
        stacking_ctx: &StackingContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        viewport: &Viewport,
        layout_viewport: Option<LayoutViewport>,
        clipping: bool,
        draw_fn: &mut dyn FnMut(
            &mut AcquiredNodes<'_>,
            &mut DrawingCtx,
            &Viewport,
        ) -> Result<BoundingBox, InternalRenderingError>,
    ) -> Result<BoundingBox, InternalRenderingError> {
        if self.is_rendering_cancelled() {
            return Err(InternalRenderingError::Cancelled);
        }

        let stacking_ctx_transform = ValidTransform::try_from(stacking_ctx.transform)?;

        let orig_transform = self.get_transform();
        self.cr.transform(stacking_ctx_transform.into());

        let res = if clipping {
            if let Some(layout_viewport) = layout_viewport.as_ref() {
                // FIXME: here we ignore the Some() result of push_new_viewport().  We do that because
                // the returned one is just a copy of the one that got passeed in, but with a changed
                // transform.  However, we are in fact not using that transform anywhere!
                //
                // In case push_new_viewport() returns None, we just don't draw anything.
                //
                // Note that push_new_viewport() changes the cr's transform.  However it will be restored
                // at the end of this function with set_matrix.
                if let Some(new_viewport) = self.push_new_viewport(viewport, layout_viewport) {
                    draw_fn(acquired_nodes, self, &new_viewport)
                } else {
                    Ok(self.empty_bbox())
                }
            } else {
                draw_fn(acquired_nodes, self, viewport)
            }
        } else {
            with_saved_cr(&self.cr.clone(), || {
                if let Some(ref link_target) = stacking_ctx.link_target {
                    self.link_tag_begin(link_target);
                }

                let Opacity(UnitInterval(opacity)) = stacking_ctx.opacity;

                let affine_at_start = self.get_transform();

                if let Some(rect) = stacking_ctx.clip_rect.as_ref() {
                    clip_to_rectangle(&self.cr, rect);
                }

                // Here we are clipping in user space, so the bbox doesn't matter
                self.clip_to_node(
                    &stacking_ctx.clip_in_user_space,
                    acquired_nodes,
                    viewport,
                    &self.empty_bbox(),
                )?;

                let should_isolate = stacking_ctx.should_isolate();

                let res = if should_isolate {
                    // Compute our assortment of affines

                    let affines = CompositingAffines::new(
                        *affine_at_start,
                        self.initial_viewport.transform,
                        self.cr_stack.borrow().len(),
                    );

                    // Create temporary surface and its cr

                    let cr = match stacking_ctx.filter {
                        None => cairo::Context::new(
                            &self
                                .create_similar_surface_for_toplevel_viewport(&self.cr.target())?,
                        )?,
                        Some(_) => {
                            cairo::Context::new(self.create_surface_for_toplevel_viewport()?)?
                        }
                    };

                    cr.set_matrix(ValidTransform::try_from(affines.for_temporary_surface)?.into());

                    let (source_surface, mut res, bbox) = {
                        let mut temporary_draw_ctx = self.nested(cr.clone());

                        // Draw!

                        let res = with_saved_cr(&cr, || {
                            if let Some(layout_viewport) = layout_viewport.as_ref() {
                                // FIXME: here we ignore the Some() result of push_new_viewport().  We do that because
                                // the returned one is just a copy of the one that got passeed in, but with a changed
                                // transform.  However, we are in fact not using that transform anywhere!
                                //
                                // In case push_new_viewport() returns None, we just don't draw anything.
                                if let Some(new_viewport) =
                                    temporary_draw_ctx.push_new_viewport(viewport, layout_viewport)
                                {
                                    draw_fn(acquired_nodes, &mut temporary_draw_ctx, &new_viewport)
                                } else {
                                    Ok(self.empty_bbox())
                                }
                            } else {
                                draw_fn(acquired_nodes, &mut temporary_draw_ctx, viewport)
                            }
                        });

                        let bbox = if let Ok(ref bbox) = res {
                            *bbox
                        } else {
                            BoundingBox::new().with_transform(affines.for_temporary_surface)
                        };

                        if let Some(ref filter) = stacking_ctx.filter {
                            let surface_to_filter = SharedImageSurface::copy_from_surface(
                                &cairo::ImageSurface::try_from(temporary_draw_ctx.cr.target())
                                    .unwrap(),
                            )?;

                            let stroke_paint_source =
                                Rc::new(filter.stroke_paint_source.to_user_space(
                                    &bbox.rect,
                                    viewport,
                                    &filter.normalize_values,
                                ));
                            let fill_paint_source =
                                Rc::new(filter.fill_paint_source.to_user_space(
                                    &bbox.rect,
                                    viewport,
                                    &filter.normalize_values,
                                ));

                            // Filter functions (like "blend()", not the <filter> element) require
                            // being resolved in userSpaceonUse units, since that is the default
                            // for primitive_units.  So, get the corresponding NormalizeParams
                            // here and pass them down.
                            let user_space_params = NormalizeParams::from_values(
                                &filter.normalize_values,
                                &viewport.with_units(CoordUnits::UserSpaceOnUse),
                            );

                            let filtered_surface = temporary_draw_ctx
                                .run_filters(
                                    viewport,
                                    surface_to_filter,
                                    filter,
                                    acquired_nodes,
                                    &stacking_ctx.element_name,
                                    &user_space_params,
                                    stroke_paint_source,
                                    fill_paint_source,
                                    bbox,
                                )?
                                .into_image_surface()?;

                            let generic_surface: &cairo::Surface = &filtered_surface; // deref to Surface

                            (generic_surface.clone(), res, bbox)
                        } else {
                            (temporary_draw_ctx.cr.target(), res, bbox)
                        }
                    };

                    // Set temporary surface as source

                    self.cr
                        .set_matrix(ValidTransform::try_from(affines.compositing)?.into());
                    self.cr.set_source_surface(&source_surface, 0.0, 0.0)?;

                    // Clip

                    self.cr.set_matrix(
                        ValidTransform::try_from(affines.outside_temporary_surface)?.into(),
                    );
                    self.clip_to_node(
                        &stacking_ctx.clip_in_object_space,
                        acquired_nodes,
                        viewport,
                        &bbox,
                    )?;

                    // Mask

                    if let Some(ref mask_node) = stacking_ctx.mask {
                        res = res.and_then(|bbox| {
                            self.generate_cairo_mask(
                                mask_node,
                                viewport,
                                affines.for_temporary_surface,
                                &bbox,
                                acquired_nodes,
                            )
                            .and_then(|mask_surf| {
                                if let Some(surf) = mask_surf {
                                    self.cr.push_group();

                                    self.cr.set_matrix(
                                        ValidTransform::try_from(affines.compositing)?.into(),
                                    );
                                    self.cr.mask_surface(&surf, 0.0, 0.0)?;

                                    Ok(self.cr.pop_group_to_source()?)
                                } else {
                                    Ok(())
                                }
                            })
                            .map(|_: ()| bbox)
                        });
                    }

                    {
                        // Composite the temporary surface

                        self.cr
                            .set_matrix(ValidTransform::try_from(affines.compositing)?.into());
                        self.cr.set_operator(stacking_ctx.mix_blend_mode.into());

                        if opacity < 1.0 {
                            self.cr.paint_with_alpha(opacity)?;
                        } else {
                            self.cr.paint()?;
                        }
                    }

                    self.cr.set_matrix(affine_at_start.into());
                    res
                } else if let Some(layout_viewport) = layout_viewport.as_ref() {
                    // FIXME: here we ignore the Some() result of push_new_viewport().  We do that because
                    // the returned one is just a copy of the one that got passeed in, but with a changed
                    // transform.  However, we are in fact not using that transform anywhere!
                    //
                    // In case push_new_viewport() returns None, we just don't draw anything.
                    //
                    // Note that push_new_viewport() changes the cr's transform.  However it will be restored
                    // at the end of this function with set_matrix.
                    if let Some(new_viewport) = self.push_new_viewport(viewport, layout_viewport) {
                        draw_fn(acquired_nodes, self, &new_viewport)
                    } else {
                        self.cr.set_matrix(orig_transform.into());
                        Ok(self.empty_bbox())
                    }
                } else {
                    draw_fn(acquired_nodes, self, viewport)
                };

                if stacking_ctx.link_target.is_some() {
                    self.link_tag_end();
                }

                res
            })
        };

        self.cr.set_matrix(orig_transform.into());
        res
    }

    /// Run the drawing function with the specified opacity
    fn with_alpha(
        &mut self,
        opacity: UnitInterval,
        draw_fn: &mut dyn FnMut(&mut DrawingCtx) -> Result<BoundingBox, InternalRenderingError>,
    ) -> Result<BoundingBox, InternalRenderingError> {
        let res;
        let UnitInterval(o) = opacity;
        if o < 1.0 {
            self.cr.push_group();
            res = draw_fn(self);
            self.cr.pop_group_to_source()?;
            self.cr.paint_with_alpha(o)?;
        } else {
            res = draw_fn(self);
        }

        res
    }

    /// Start a Cairo tag for PDF links
    fn link_tag_begin(&mut self, link_target: &str) {
        let attributes = format!("uri='{}'", escape_link_target(link_target));

        let cr = self.cr.clone();
        cr.tag_begin(CAIRO_TAG_LINK, &attributes);
    }

    /// End a Cairo tag for PDF links
    fn link_tag_end(&mut self) {
        self.cr.tag_end(CAIRO_TAG_LINK);
    }

    fn run_filters(
        &mut self,
        viewport: &Viewport,
        surface_to_filter: SharedImageSurface,
        filter: &Filter,
        acquired_nodes: &mut AcquiredNodes<'_>,
        node_name: &str,
        user_space_params: &NormalizeParams,
        stroke_paint_source: Rc<UserSpacePaintSource>,
        fill_paint_source: Rc<UserSpacePaintSource>,
        node_bbox: BoundingBox,
    ) -> Result<SharedImageSurface, InternalRenderingError> {
        let session = self.session();

        // We try to convert each item in the filter_list to a FilterSpec.
        //
        // However, the spec mentions, "If the filter references a non-existent object or
        // the referenced object is not a filter element, then the whole filter chain is
        // ignored." - https://www.w3.org/TR/filter-effects/#FilterProperty
        //
        // So, run through the filter_list and collect into a Result<Vec<FilterSpec>>.
        // This will return an Err if any of the conversions failed.
        let filter_specs = filter
            .filter_list
            .iter()
            .map(|filter_value| {
                filter_value.to_filter_spec(
                    acquired_nodes,
                    user_space_params,
                    filter.current_color,
                    viewport,
                    session,
                    node_name,
                )
            })
            .collect::<Result<Vec<FilterSpec>, _>>();

        match filter_specs {
            Ok(specs) => {
                // Start with the surface_to_filter, and apply each filter spec in turn;
                // the final result is our return value.
                specs.iter().try_fold(surface_to_filter, |surface, spec| {
                    filters::render(
                        spec,
                        stroke_paint_source.clone(),
                        fill_paint_source.clone(),
                        surface,
                        acquired_nodes,
                        self,
                        *self.get_transform(),
                        node_bbox,
                    )
                })
            }

            Err(e) => {
                rsvg_log!(
                    self.session,
                    "not rendering filter list on node {} because it was in error: {}",
                    node_name,
                    e
                );
                // just return the original surface without filtering it
                Ok(surface_to_filter)
            }
        }
    }

    fn set_gradient(&mut self, gradient: &UserSpaceGradient) -> Result<(), InternalRenderingError> {
        let g = match gradient.variant {
            GradientVariant::Linear { x1, y1, x2, y2 } => {
                cairo::Gradient::clone(&cairo::LinearGradient::new(x1, y1, x2, y2))
            }

            GradientVariant::Radial {
                cx,
                cy,
                r,
                fx,
                fy,
                fr,
            } => cairo::Gradient::clone(&cairo::RadialGradient::new(fx, fy, fr, cx, cy, r)),
        };

        g.set_matrix(ValidTransform::try_from(gradient.transform)?.into());
        g.set_extend(cairo::Extend::from(gradient.spread));

        for stop in &gradient.stops {
            let UnitInterval(stop_offset) = stop.offset;

            let rgba = color_to_rgba(&stop.color);

            g.add_color_stop_rgba(
                stop_offset,
                f64::from(rgba.red.unwrap_or(0)) / 255.0,
                f64::from(rgba.green.unwrap_or(0)) / 255.0,
                f64::from(rgba.blue.unwrap_or(0)) / 255.0,
                f64::from(rgba.alpha.unwrap_or(0.0)),
            );
        }

        Ok(self.cr.set_source(&g)?)
    }

    fn set_pattern(
        &mut self,
        pattern: &UserSpacePattern,
        acquired_nodes: &mut AcquiredNodes<'_>,
    ) -> Result<bool, InternalRenderingError> {
        // Bail out early if the pattern has zero size, per the spec
        if approx_eq!(f64, pattern.width, 0.0) || approx_eq!(f64, pattern.height, 0.0) {
            return Ok(false);
        }

        // Bail out early if this pattern has a circular reference
        let pattern_node_acquired = match pattern.acquire_pattern_node(acquired_nodes) {
            Ok(n) => n,

            Err(AcquireError::CircularReference(ref node)) => {
                rsvg_log!(self.session, "circular reference in element {}", node);
                return Ok(false);
            }

            _ => unreachable!(),
        };

        let pattern_node = pattern_node_acquired.get();

        let taffine = self.get_transform().pre_transform(&pattern.transform);

        let mut scwscale = (taffine.xx.powi(2) + taffine.xy.powi(2)).sqrt();
        let mut schscale = (taffine.yx.powi(2) + taffine.yy.powi(2)).sqrt();

        let pw: i32 = (pattern.width * scwscale) as i32;
        let ph: i32 = (pattern.height * schscale) as i32;

        if pw < 1 || ph < 1 {
            return Ok(false);
        }

        scwscale = f64::from(pw) / pattern.width;
        schscale = f64::from(ph) / pattern.height;

        // Apply the pattern transform
        let (affine, caffine) = if scwscale.approx_eq_cairo(1.0) && schscale.approx_eq_cairo(1.0) {
            (pattern.coord_transform, pattern.content_transform)
        } else {
            (
                pattern
                    .coord_transform
                    .pre_scale(1.0 / scwscale, 1.0 / schscale),
                pattern.content_transform.post_scale(scwscale, schscale),
            )
        };

        // Draw to another surface
        let surface = self
            .cr
            .target()
            .create_similar(cairo::Content::ColorAlpha, pw, ph)?;

        let cr_pattern = cairo::Context::new(&surface)?;

        // Set up transformations to be determined by the contents units

        let transform = ValidTransform::try_from(caffine)?;
        cr_pattern.set_matrix(transform.into());

        // Draw everything

        {
            let mut pattern_draw_ctx = self.nested(cr_pattern);

            let pattern_viewport = Viewport {
                dpi: self.config.dpi,
                vbox: ViewBox::from(Rect::from_size(pattern.width, pattern.height)),
                transform: *transform,
            };

            pattern_draw_ctx
                .with_alpha(pattern.opacity, &mut |dc| {
                    let pattern_cascaded = CascadedValues::new_from_node(pattern_node);
                    let pattern_values = pattern_cascaded.get();

                    let elt = pattern_node.borrow_element();

                    let stacking_ctx = StackingContext::new(
                        self.session(),
                        acquired_nodes,
                        &elt,
                        Transform::identity(),
                        None,
                        pattern_values,
                    );

                    dc.with_discrete_layer(
                        &stacking_ctx,
                        acquired_nodes,
                        &pattern_viewport,
                        None,
                        false,
                        &mut |an, dc, new_viewport| {
                            pattern_node.draw_children(
                                an,
                                &pattern_cascaded,
                                new_viewport,
                                dc,
                                false,
                            )
                        },
                    )
                })
                .map(|_| ())?;
        }

        // Set the final surface as a Cairo pattern into the Cairo context
        let pattern = cairo::SurfacePattern::create(&surface);

        if let Some(m) = affine.invert() {
            pattern.set_matrix(ValidTransform::try_from(m)?.into());
            pattern.set_extend(cairo::Extend::Repeat);
            pattern.set_filter(cairo::Filter::Best);
            self.cr.set_source(&pattern)?;
        }

        Ok(true)
    }

    fn set_paint_source(
        &mut self,
        paint_source: &UserSpacePaintSource,
        acquired_nodes: &mut AcquiredNodes<'_>,
    ) -> Result<bool, InternalRenderingError> {
        match *paint_source {
            UserSpacePaintSource::Gradient(ref gradient, _c) => {
                self.set_gradient(gradient)?;
                Ok(true)
            }
            UserSpacePaintSource::Pattern(ref pattern, ref c) => {
                if self.set_pattern(pattern, acquired_nodes)? {
                    Ok(true)
                } else if let Some(c) = c {
                    set_source_color_on_cairo(&self.cr, c);
                    Ok(true)
                } else {
                    Ok(false)
                }
            }
            UserSpacePaintSource::SolidColor(ref c) => {
                set_source_color_on_cairo(&self.cr, c);
                Ok(true)
            }
            UserSpacePaintSource::None => Ok(false),
        }
    }

    /// Computes and returns a surface corresponding to the given paint server.
    pub fn get_paint_source_surface(
        &mut self,
        width: i32,
        height: i32,
        acquired_nodes: &mut AcquiredNodes<'_>,
        paint_source: &UserSpacePaintSource,
    ) -> Result<SharedImageSurface, InternalRenderingError> {
        let mut surface = ExclusiveImageSurface::new(width, height, SurfaceType::SRgb)?;

        surface.draw(&mut |cr| {
            let mut temporary_draw_ctx = self.nested(cr);

            // FIXME: we are ignoring any error

            let had_paint_server =
                temporary_draw_ctx.set_paint_source(paint_source, acquired_nodes)?;
            if had_paint_server {
                temporary_draw_ctx.cr.paint()?;
            }

            Ok(())
        })?;

        Ok(surface.share()?)
    }

    fn stroke(
        &mut self,
        cr: &cairo::Context,
        acquired_nodes: &mut AcquiredNodes<'_>,
        paint_source: &UserSpacePaintSource,
    ) -> Result<(), InternalRenderingError> {
        let had_paint_server = self.set_paint_source(paint_source, acquired_nodes)?;
        if had_paint_server {
            cr.stroke_preserve()?;
        }

        Ok(())
    }

    fn fill(
        &mut self,
        cr: &cairo::Context,
        acquired_nodes: &mut AcquiredNodes<'_>,
        paint_source: &UserSpacePaintSource,
    ) -> Result<(), InternalRenderingError> {
        let had_paint_server = self.set_paint_source(paint_source, acquired_nodes)?;
        if had_paint_server {
            cr.fill_preserve()?;
        }

        Ok(())
    }

    pub fn draw_layer(
        &mut self,
        layer: &Layer,
        acquired_nodes: &mut AcquiredNodes<'_>,
        clipping: bool,
        viewport: &Viewport,
    ) -> Result<BoundingBox, InternalRenderingError> {
        match &layer.kind {
            LayerKind::Shape(shape) => self.draw_shape(
                shape,
                &layer.stacking_ctx,
                acquired_nodes,
                clipping,
                viewport,
            ),
            LayerKind::Text(text) => self.draw_text(
                text,
                &layer.stacking_ctx,
                acquired_nodes,
                clipping,
                viewport,
            ),
            LayerKind::Image(image) => self.draw_image(
                image,
                &layer.stacking_ctx,
                acquired_nodes,
                clipping,
                viewport,
            ),
            LayerKind::Group(group) => self.draw_group(
                group,
                &layer.stacking_ctx,
                acquired_nodes,
                clipping,
                viewport,
            ),
        }
    }

    fn draw_shape(
        &mut self,
        shape: &Shape,
        stacking_ctx: &StackingContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        clipping: bool,
        viewport: &Viewport,
    ) -> Result<BoundingBox, InternalRenderingError> {
        if shape.extents.is_none() {
            return Ok(self.empty_bbox());
        }

        self.with_discrete_layer(
            stacking_ctx,
            acquired_nodes,
            viewport,
            None,
            clipping,
            &mut |an, dc, new_viewport| {
                let cr = dc.cr.clone();

                let transform = dc.get_transform_for_stacking_ctx(stacking_ctx, clipping)?;
                let mut path_helper =
                    PathHelper::new(&cr, transform, &shape.path, shape.stroke.line_cap);

                if clipping {
                    if shape.is_visible {
                        cr.set_fill_rule(cairo::FillRule::from(shape.clip_rule));
                        path_helper.set()?;
                    }
                    return Ok(dc.empty_bbox());
                }

                cr.set_antialias(cairo::Antialias::from(shape.shape_rendering));

                setup_cr_for_stroke(&cr, &shape.stroke);

                cr.set_fill_rule(cairo::FillRule::from(shape.fill_rule));

                path_helper.set()?;
                let bbox = compute_stroke_and_fill_box(
                    &cr,
                    &shape.stroke,
                    &shape.stroke_paint,
                    &dc.initial_viewport,
                )?;

                if shape.is_visible {
                    for &target in &shape.paint_order.targets {
                        // fill and stroke operations will preserve the path.
                        // markers operation will clear the path.
                        match target {
                            PaintTarget::Fill => {
                                path_helper.set()?;
                                dc.fill(&cr, an, &shape.fill_paint)?;
                            }

                            PaintTarget::Stroke => {
                                path_helper.set()?;
                                let backup_matrix = if shape.stroke.non_scaling {
                                    let matrix = cr.matrix();
                                    cr.set_matrix(
                                        ValidTransform::try_from(dc.initial_viewport.transform)?
                                            .into(),
                                    );
                                    Some(matrix)
                                } else {
                                    None
                                };
                                dc.stroke(&cr, an, &shape.stroke_paint)?;
                                if let Some(matrix) = backup_matrix {
                                    cr.set_matrix(matrix);
                                }
                            }

                            PaintTarget::Markers => {
                                path_helper.unset();
                                marker::render_markers_for_shape(
                                    shape,
                                    new_viewport,
                                    dc,
                                    an,
                                    clipping,
                                )?;
                            }
                        }
                    }
                }

                path_helper.unset();
                Ok(bbox)
            },
        )
    }

    fn paint_surface(
        &mut self,
        surface: &SharedImageSurface,
        width: f64,
        height: f64,
        image_rendering: ImageRendering,
    ) -> Result<(), cairo::Error> {
        let cr = self.cr.clone();

        // We need to set extend appropriately, so can't use cr.set_source_surface().
        //
        // If extend is left at its default value (None), then bilinear scaling uses
        // transparency outside of the image producing incorrect results.
        // For example, in svg1.1/filters-blend-01-b.svgthere's a completely
        // opaque 100×1 image of a gradient scaled to 100×98 which ends up
        // transparent almost everywhere without this fix (which it shouldn't).
        let ptn = surface.to_cairo_pattern();
        ptn.set_extend(cairo::Extend::Pad);

        let interpolation = Interpolation::from(image_rendering);

        ptn.set_filter(cairo::Filter::from(interpolation));
        cr.set_source(&ptn)?;

        // Clip is needed due to extend being set to pad.
        clip_to_rectangle(&cr, &Rect::from_size(width, height));

        cr.paint()
    }

    fn draw_image(
        &mut self,
        image: &Image,
        stacking_ctx: &StackingContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        clipping: bool,
        viewport: &Viewport,
    ) -> Result<BoundingBox, InternalRenderingError> {
        let image_width = image.surface.width();
        let image_height = image.surface.height();
        if clipping || image.rect.is_empty() || image_width == 0 || image_height == 0 {
            return Ok(self.empty_bbox());
        }

        let image_width = f64::from(image_width);
        let image_height = f64::from(image_height);
        let vbox = ViewBox::from(Rect::from_size(image_width, image_height));

        // The bounding box for <image> is decided by the values of the image's x, y, w, h
        // and not by the final computed image bounds.
        let bounds = self.empty_bbox().with_rect(image.rect);

        let layout_viewport = LayoutViewport {
            vbox: Some(vbox),
            geometry: image.rect,
            preserve_aspect_ratio: image.aspect,
            overflow: image.overflow,
        };

        if image.is_visible {
            self.with_discrete_layer(
                stacking_ctx,
                acquired_nodes,
                viewport,
                Some(layout_viewport),
                clipping,
                &mut |_an, dc, _new_viewport| {
                    dc.paint_surface(
                        &image.surface,
                        image_width,
                        image_height,
                        image.image_rendering,
                    )?;

                    Ok(bounds)
                },
            )
        } else {
            Ok(bounds)
        }
    }

    fn draw_group(
        &mut self,
        _group: &Group,
        _stacking_ctx: &StackingContext,
        _acquired_nodes: &mut AcquiredNodes<'_>,
        _clipping: bool,
        _viewport: &Viewport,
    ) -> Result<BoundingBox, InternalRenderingError> {
        unimplemented!()
    }

    fn draw_text_span(
        &mut self,
        span: &TextSpan,
        acquired_nodes: &mut AcquiredNodes<'_>,
        clipping: bool,
    ) -> Result<BoundingBox, InternalRenderingError> {
        let path = pango_layout_to_path(span.x, span.y, &span.layout, span.gravity)?;
        if path.is_empty() {
            // Empty strings, or only-whitespace text, get turned into empty paths.
            // In that case, we really want to return "no bounds" rather than an
            // empty rectangle.
            return Ok(self.empty_bbox());
        }

        // #851 - We can't just render all text as paths for PDF; it
        // needs the actual text content so text is selectable by PDF
        // viewers.
        let can_use_text_as_path = self.cr.target().type_() != cairo::SurfaceType::Pdf;

        with_saved_cr(&self.cr.clone(), || {
            self.cr
                .set_antialias(cairo::Antialias::from(span.text_rendering));

            setup_cr_for_stroke(&self.cr, &span.stroke);

            if clipping {
                path.to_cairo(&self.cr, false)?;
                return Ok(self.empty_bbox());
            }

            path.to_cairo(&self.cr, false)?;
            let bbox = compute_stroke_and_fill_box(
                &self.cr,
                &span.stroke,
                &span.stroke_paint,
                &self.initial_viewport,
            )?;
            self.cr.new_path();

            if span.is_visible {
                if let Some(ref link_target) = span.link_target {
                    self.link_tag_begin(link_target);
                }

                for &target in &span.paint_order.targets {
                    match target {
                        PaintTarget::Fill => {
                            let had_paint_server =
                                self.set_paint_source(&span.fill_paint, acquired_nodes)?;

                            if had_paint_server {
                                if can_use_text_as_path {
                                    path.to_cairo(&self.cr, false)?;
                                    self.cr.fill()?;
                                    self.cr.new_path();
                                } else {
                                    self.cr.move_to(span.x, span.y);

                                    let matrix = self.cr.matrix();

                                    let rotation_from_gravity = span.gravity.to_rotation();
                                    if !rotation_from_gravity.approx_eq_cairo(0.0) {
                                        self.cr.rotate(-rotation_from_gravity);
                                    }

                                    pangocairo::functions::update_layout(&self.cr, &span.layout);
                                    pangocairo::functions::show_layout(&self.cr, &span.layout);

                                    self.cr.set_matrix(matrix);
                                }
                            }
                        }

                        PaintTarget::Stroke => {
                            let had_paint_server =
                                self.set_paint_source(&span.stroke_paint, acquired_nodes)?;

                            if had_paint_server {
                                path.to_cairo(&self.cr, false)?;
                                self.cr.stroke()?;
                                self.cr.new_path();
                            }
                        }

                        PaintTarget::Markers => {}
                    }
                }

                if span.link_target.is_some() {
                    self.link_tag_end();
                }
            }

            Ok(bbox)
        })
    }

    fn draw_text(
        &mut self,
        text: &Text,
        stacking_ctx: &StackingContext,
        acquired_nodes: &mut AcquiredNodes<'_>,
        clipping: bool,
        viewport: &Viewport,
    ) -> Result<BoundingBox, InternalRenderingError> {
        self.with_discrete_layer(
            stacking_ctx,
            acquired_nodes,
            viewport,
            None,
            clipping,
            &mut |an, dc, _new_viewport| {
                let mut bbox = dc.empty_bbox();

                for span in &text.spans {
                    let span_bbox = dc.draw_text_span(span, an, clipping)?;
                    bbox.insert(&span_bbox);
                }

                Ok(bbox)
            },
        )
    }

    pub fn get_snapshot(
        &self,
        width: i32,
        height: i32,
    ) -> Result<SharedImageSurface, InternalRenderingError> {
        // TODO: as far as I can tell this should not render elements past the last (topmost) one
        // with enable-background: new (because technically we shouldn't have been caching them).
        // Right now there are no enable-background checks whatsoever.
        //
        // Addendum: SVG 2 has deprecated the enable-background property, and replaced it with an
        // "isolation" property from the CSS Compositing and Blending spec.
        //
        // Deprecation:
        //   https://www.w3.org/TR/filter-effects-1/#AccessBackgroundImage
        //
        // BackgroundImage, BackgroundAlpha in the "in" attribute of filter primitives:
        //   https://www.w3.org/TR/filter-effects-1/#attr-valuedef-in-backgroundimage
        //
        // CSS Compositing and Blending, "isolation" property:
        //   https://www.w3.org/TR/compositing-1/#isolation
        let mut surface = ExclusiveImageSurface::new(width, height, SurfaceType::SRgb)?;

        surface.draw(&mut |cr| {
            // TODO: apparently DrawingCtx.cr_stack is just a way to store pairs of
            // (surface, transform).  Can we turn it into a DrawingCtx.surface_stack
            // instead?  See what CSS isolation would like to call that; are the pairs just
            // stacking contexts instead, or the result of rendering stacking contexts?
            for (depth, draw) in self.cr_stack.borrow().iter().enumerate() {
                let affines = CompositingAffines::new(
                    Transform::from(draw.matrix()),
                    self.initial_viewport.transform,
                    depth,
                );

                cr.set_matrix(ValidTransform::try_from(affines.for_snapshot)?.into());
                cr.set_source_surface(&draw.target(), 0.0, 0.0)?;
                cr.paint()?;
            }

            Ok(())
        })?;

        Ok(surface.share()?)
    }

    pub fn draw_node_to_surface(
        &mut self,
        node: &Node,
        acquired_nodes: &mut AcquiredNodes<'_>,
        cascaded: &CascadedValues<'_>,
        affine: Transform,
        width: i32,
        height: i32,
    ) -> Result<SharedImageSurface, InternalRenderingError> {
        let surface = cairo::ImageSurface::create(cairo::Format::ARgb32, width, height)?;

        let save_cr = self.cr.clone();

        {
            let cr = cairo::Context::new(&surface)?;
            cr.set_matrix(ValidTransform::try_from(affine)?.into());

            self.cr = cr;
            let viewport = Viewport {
                dpi: self.config.dpi,
                transform: affine,
                vbox: ViewBox::from(Rect::from_size(f64::from(width), f64::from(height))),
            };

            let _ = self.draw_node_from_stack(node, acquired_nodes, cascaded, &viewport, false)?;
        }

        self.cr = save_cr;

        Ok(SharedImageSurface::wrap(surface, SurfaceType::SRgb)?)
    }

    pub fn draw_node_from_stack(
        &mut self,
        node: &Node,
        acquired_nodes: &mut AcquiredNodes<'_>,
        cascaded: &CascadedValues<'_>,
        viewport: &Viewport,
        clipping: bool,
    ) -> Result<BoundingBox, InternalRenderingError> {
        let stack_top = self.drawsub_stack.pop();

        let draw = if let Some(ref top) = stack_top {
            top == node
        } else {
            true
        };

        let res = if draw {
            node.draw(acquired_nodes, cascaded, viewport, self, clipping)
        } else {
            Ok(self.empty_bbox())
        };

        if let Some(top) = stack_top {
            self.drawsub_stack.push(top);
        }

        res
    }

    pub fn draw_from_use_node(
        &mut self,
        node: &Node,
        acquired_nodes: &mut AcquiredNodes<'_>,
        values: &ComputedValues,
        use_rect: Rect,
        link: &NodeId,
        clipping: bool,
        viewport: &Viewport,
        fill_paint: Rc<PaintSource>,
        stroke_paint: Rc<PaintSource>,
    ) -> Result<BoundingBox, InternalRenderingError> {
        // <use> is an element that is used directly, unlike
        // <pattern>, which is used through a fill="url(#...)"
        // reference.  However, <use> will always reference another
        // element, potentially itself or an ancestor of itself (or
        // another <use> which references the first one, etc.).  So,
        // we acquire the <use> element itself so that circular
        // references can be caught.
        let _self_acquired = match acquired_nodes.acquire_ref(node) {
            Ok(n) => n,

            Err(AcquireError::CircularReference(_)) => {
                rsvg_log!(self.session, "circular reference in element {}", node);
                return Ok(self.empty_bbox());
            }

            _ => unreachable!(),
        };

        let acquired = match acquired_nodes.acquire(link) {
            Ok(acquired) => acquired,

            Err(AcquireError::CircularReference(node)) => {
                rsvg_log!(self.session, "circular reference in element {}", node);
                return Ok(self.empty_bbox());
            }

            Err(AcquireError::MaxReferencesExceeded) => {
                return Err(InternalRenderingError::LimitExceeded(
                    ImplementationLimit::TooManyReferencedElements,
                ));
            }

            Err(AcquireError::InvalidLinkType(_)) => unreachable!(),

            Err(AcquireError::LinkNotFound(node_id)) => {
                rsvg_log!(
                    self.session,
                    "element {} references nonexistent \"{}\"",
                    node,
                    node_id
                );
                return Ok(self.empty_bbox());
            }
        };

        // width or height set to 0 disables rendering of the element
        // https://www.w3.org/TR/SVG/struct.html#UseElementWidthAttribute
        if use_rect.is_empty() {
            return Ok(self.empty_bbox());
        }

        let child = acquired.get();

        if clipping && !element_can_be_used_inside_use_inside_clip_path(&child.borrow_element()) {
            return Ok(self.empty_bbox());
        }

        let orig_transform = self.get_transform();

        self.cr
            .transform(ValidTransform::try_from(values.transform())?.into());

        let use_element = node.borrow_element();

        let defines_a_viewport = if is_element_of_type!(child, Symbol) {
            let symbol = borrow_element_as!(child, Symbol);
            Some((symbol.get_viewbox(), symbol.get_preserve_aspect_ratio()))
        } else if is_element_of_type!(child, Svg) {
            let svg = borrow_element_as!(child, Svg);
            Some((svg.get_viewbox(), svg.get_preserve_aspect_ratio()))
        } else {
            None
        };

        let res = if let Some((vbox, preserve_aspect_ratio)) = defines_a_viewport {
            // <symbol> and <svg> define a viewport, as described in the specification:
            // https://www.w3.org/TR/SVG2/struct.html#UseElement
            // https://gitlab.gnome.org/GNOME/librsvg/-/issues/875#note_1482705

            let elt = child.borrow_element();

            let child_values = elt.get_computed_values();

            let stacking_ctx = StackingContext::new(
                self.session(),
                acquired_nodes,
                &use_element,
                Transform::identity(),
                None,
                values,
            );

            let layout_viewport = LayoutViewport {
                vbox,
                geometry: use_rect,
                preserve_aspect_ratio,
                overflow: child_values.overflow(),
            };

            self.with_discrete_layer(
                &stacking_ctx,
                acquired_nodes,
                viewport,
                Some(layout_viewport),
                clipping,
                &mut |an, dc, new_viewport| {
                    child.draw_children(
                        an,
                        &CascadedValues::new_from_values(
                            child,
                            values,
                            Some(fill_paint.clone()),
                            Some(stroke_paint.clone()),
                        ),
                        new_viewport,
                        dc,
                        clipping,
                    )
                },
            )
        } else {
            // otherwise the referenced node is not a <symbol>; process it generically

            let stacking_ctx = StackingContext::new(
                self.session(),
                acquired_nodes,
                &use_element,
                Transform::new_translate(use_rect.x0, use_rect.y0),
                None,
                values,
            );

            self.with_discrete_layer(
                &stacking_ctx,
                acquired_nodes,
                viewport,
                None,
                clipping,
                &mut |an, dc, new_viewport| {
                    child.draw(
                        an,
                        &CascadedValues::new_from_values(
                            child,
                            values,
                            Some(fill_paint.clone()),
                            Some(stroke_paint.clone()),
                        ),
                        new_viewport,
                        dc,
                        clipping,
                    )
                },
            )
        };

        self.cr.set_matrix(orig_transform.into());

        if let Ok(bbox) = res {
            let mut res_bbox = BoundingBox::new().with_transform(*orig_transform);
            res_bbox.insert(&bbox);
            Ok(res_bbox)
        } else {
            res
        }
    }

    /// Extracts the font options for the current state of the DrawingCtx.
    ///
    /// You can use the font options later with create_pango_context().
    pub fn get_font_options(&self) -> FontOptions {
        let mut options = cairo::FontOptions::new().unwrap();
        if self.config.testing {
            options.set_antialias(cairo::Antialias::Gray);
        }

        options.set_hint_style(cairo::HintStyle::None);
        options.set_hint_metrics(cairo::HintMetrics::Off);

        FontOptions { options }
    }
}

impl From<ImageRendering> for Interpolation {
    fn from(r: ImageRendering) -> Interpolation {
        match r {
            ImageRendering::Pixelated
            | ImageRendering::CrispEdges
            | ImageRendering::OptimizeSpeed => Interpolation::Nearest,

            ImageRendering::Smooth
            | ImageRendering::OptimizeQuality
            | ImageRendering::HighQuality
            | ImageRendering::Auto => Interpolation::Smooth,
        }
    }
}

pub fn compute_path_extents(path: &Path) -> Result<Option<Rect>, InternalRenderingError> {
    if path.is_empty() {
        return Ok(None);
    }

    let surface = cairo::RecordingSurface::create(cairo::Content::ColorAlpha, None)?;
    let cr = cairo::Context::new(&surface)?;

    path.to_cairo(&cr, false)?;
    let (x0, y0, x1, y1) = cr.path_extents()?;

    Ok(Some(Rect::new(x0, y0, x1, y1)))
}

/// Create a Pango context with a particular configuration.
pub fn create_pango_context(font_options: &FontOptions, transform: &Transform) -> pango::Context {
    let font_map = pangocairo::FontMap::default();
    let context = font_map.create_context();

    context.set_round_glyph_positions(false);

    let pango_matrix = PangoMatrix {
        xx: transform.xx,
        xy: transform.xy,
        yx: transform.yx,
        yy: transform.yy,
        x0: transform.x0,
        y0: transform.y0,
    };

    let pango_matrix_ptr: *const PangoMatrix = &pango_matrix;

    let matrix = unsafe { pango::Matrix::from_glib_none(pango_matrix_ptr) };
    context.set_matrix(Some(&matrix));

    pangocairo::functions::context_set_font_options(&context, Some(&font_options.options));

    // Pango says this about pango_cairo_context_set_resolution():
    //
    //     Sets the resolution for the context. This is a scale factor between
    //     points specified in a #PangoFontDescription and Cairo units. The
    //     default value is 96, meaning that a 10 point font will be 13
    //     units high. (10 * 96. / 72. = 13.3).
    //
    // I.e. Pango font sizes in a PangoFontDescription are in *points*, not pixels.
    // However, we are normalizing everything to userspace units, which amount to
    // pixels.  So, we will use 72.0 here to make Pango not apply any further scaling
    // to the size values we give it.
    //
    // An alternative would be to divide our font sizes by (dpi_y / 72) to effectively
    // cancel out Pango's scaling, but it's probably better to deal with Pango-isms
    // right here, instead of spreading them out through our Length normalization
    // code.
    pangocairo::functions::context_set_resolution(&context, 72.0);

    context
}

pub fn set_source_color_on_cairo(cr: &cairo::Context, color: &cssparser::Color) {
    let rgba = color_to_rgba(color);

    cr.set_source_rgba(
        f64::from(rgba.red.unwrap_or(0)) / 255.0,
        f64::from(rgba.green.unwrap_or(0)) / 255.0,
        f64::from(rgba.blue.unwrap_or(0)) / 255.0,
        f64::from(rgba.alpha.unwrap_or(0.0)),
    );
}

/// Converts a Pango layout to a Cairo path on the specified cr starting at (x, y).
/// Does not clear the current path first.
fn pango_layout_to_cairo(
    x: f64,
    y: f64,
    layout: &pango::Layout,
    gravity: pango::Gravity,
    cr: &cairo::Context,
) {
    let rotation_from_gravity = gravity.to_rotation();
    let rotation = if !rotation_from_gravity.approx_eq_cairo(0.0) {
        Some(-rotation_from_gravity)
    } else {
        None
    };

    cr.move_to(x, y);

    let matrix = cr.matrix();
    if let Some(rot) = rotation {
        cr.rotate(rot);
    }

    pangocairo::functions::update_layout(cr, layout);
    pangocairo::functions::layout_path(cr, layout);
    cr.set_matrix(matrix);
}

/// Converts a Pango layout to a Path starting at (x, y).
pub fn pango_layout_to_path(
    x: f64,
    y: f64,
    layout: &pango::Layout,
    gravity: pango::Gravity,
) -> Result<Path, InternalRenderingError> {
    let surface = cairo::RecordingSurface::create(cairo::Content::ColorAlpha, None)?;
    let cr = cairo::Context::new(&surface)?;

    pango_layout_to_cairo(x, y, layout, gravity, &cr);

    let cairo_path = cr.copy_path()?;
    Ok(Path::from_cairo(cairo_path))
}

// https://www.w3.org/TR/css-masking-1/#ClipPathElement
fn element_can_be_used_inside_clip_path(element: &Element) -> bool {
    use ElementData::*;

    matches!(
        element.element_data,
        Circle(_)
            | Ellipse(_)
            | Line(_)
            | Path(_)
            | Polygon(_)
            | Polyline(_)
            | Rect(_)
            | Text(_)
            | Use(_)
    )
}

// https://www.w3.org/TR/css-masking-1/#ClipPathElement
fn element_can_be_used_inside_use_inside_clip_path(element: &Element) -> bool {
    use ElementData::*;

    matches!(
        element.element_data,
        Circle(_) | Ellipse(_) | Line(_) | Path(_) | Polygon(_) | Polyline(_) | Rect(_) | Text(_)
    )
}

#[derive(Debug)]
struct CompositingAffines {
    pub outside_temporary_surface: Transform,
    #[allow(unused)]
    pub initial: Transform,
    pub for_temporary_surface: Transform,
    pub compositing: Transform,
    pub for_snapshot: Transform,
}

impl CompositingAffines {
    fn new(current: Transform, initial: Transform, cr_stack_depth: usize) -> CompositingAffines {
        let is_topmost_temporary_surface = cr_stack_depth == 0;

        let initial_inverse = initial.invert().unwrap();

        let outside_temporary_surface = if is_topmost_temporary_surface {
            current
        } else {
            current.post_transform(&initial_inverse)
        };

        let (scale_x, scale_y) = initial.transform_distance(1.0, 1.0);

        let for_temporary_surface = if is_topmost_temporary_surface {
            current
                .post_transform(&initial_inverse)
                .post_scale(scale_x, scale_y)
        } else {
            current
        };

        let compositing = if is_topmost_temporary_surface {
            initial.pre_scale(1.0 / scale_x, 1.0 / scale_y)
        } else {
            Transform::identity()
        };

        let for_snapshot = compositing.invert().unwrap();

        CompositingAffines {
            outside_temporary_surface,
            initial,
            for_temporary_surface,
            compositing,
            for_snapshot,
        }
    }
}

fn compute_stroke_and_fill_extents(
    cr: &cairo::Context,
    stroke: &Stroke,
    stroke_paint_source: &UserSpacePaintSource,
    initial_viewport: &Viewport,
) -> Result<PathExtents, InternalRenderingError> {
    // Dropping the precision of cairo's bezier subdivision, yielding 2x
    // _rendering_ time speedups, are these rather expensive operations
    // really needed here? */
    let backup_tolerance = cr.tolerance();
    cr.set_tolerance(1.0);

    // Bounding box for fill
    //
    // Unlike the case for stroke, for fills we always compute the bounding box.
    // In GNOME we have SVGs for symbolic icons where each icon has a bounding
    // rectangle with no fill and no stroke, and inside it there are the actual
    // paths for the icon's shape.  We need to be able to compute the bounding
    // rectangle's extents, even when it has no fill nor stroke.

    let (x0, y0, x1, y1) = cr.fill_extents()?;
    let fill_extents = if x0 != 0.0 || y0 != 0.0 || x1 != 0.0 || y1 != 0.0 {
        Some(Rect::new(x0, y0, x1, y1))
    } else {
        None
    };

    // Bounding box for stroke
    //
    // When presented with a line width of 0, Cairo returns a
    // stroke_extents rectangle of (0, 0, 0, 0).  This would cause the
    // bbox to include a lone point at the origin, which is wrong, as a
    // stroke of zero width should not be painted, per
    // https://www.w3.org/TR/SVG2/painting.html#StrokeWidth
    //
    // So, see if the stroke width is 0 and just not include the stroke in the
    // bounding box if so.

    let stroke_extents = if !stroke.width.approx_eq_cairo(0.0)
        && !matches!(stroke_paint_source, UserSpacePaintSource::None)
    {
        let backup_matrix = if stroke.non_scaling {
            let matrix = cr.matrix();
            cr.set_matrix(ValidTransform::try_from(initial_viewport.transform)?.into());
            Some(matrix)
        } else {
            None
        };
        let (x0, y0, x1, y1) = cr.stroke_extents()?;
        if let Some(matrix) = backup_matrix {
            cr.set_matrix(matrix);
        }
        Some(Rect::new(x0, y0, x1, y1))
    } else {
        None
    };

    // objectBoundingBox

    let (x0, y0, x1, y1) = cr.path_extents()?;
    let path_extents = Some(Rect::new(x0, y0, x1, y1));

    // restore tolerance

    cr.set_tolerance(backup_tolerance);

    Ok(PathExtents {
        path_only: path_extents,
        fill: fill_extents,
        stroke: stroke_extents,
    })
}

fn compute_stroke_and_fill_box(
    cr: &cairo::Context,
    stroke: &Stroke,
    stroke_paint_source: &UserSpacePaintSource,
    initial_viewport: &Viewport,
) -> Result<BoundingBox, InternalRenderingError> {
    let extents =
        compute_stroke_and_fill_extents(cr, stroke, stroke_paint_source, initial_viewport)?;

    let ink_rect = match (extents.fill, extents.stroke) {
        (None, None) => None,
        (Some(f), None) => Some(f),
        (None, Some(s)) => Some(s),
        (Some(f), Some(s)) => Some(f.union(&s)),
    };

    let mut bbox = BoundingBox::new().with_transform(Transform::from(cr.matrix()));

    if let Some(rect) = extents.path_only {
        bbox = bbox.with_rect(rect);
    }

    if let Some(ink_rect) = ink_rect {
        bbox = bbox.with_ink_rect(ink_rect);
    }

    Ok(bbox)
}

fn setup_cr_for_stroke(cr: &cairo::Context, stroke: &Stroke) {
    cr.set_line_width(stroke.width);
    cr.set_miter_limit(stroke.miter_limit.0);
    cr.set_line_cap(cairo::LineCap::from(stroke.line_cap));
    cr.set_line_join(cairo::LineJoin::from(stroke.line_join));

    let total_length: f64 = stroke.dashes.iter().sum();

    if total_length > 0.0 {
        cr.set_dash(&stroke.dashes, stroke.dash_offset);
    } else {
        cr.set_dash(&[], 0.0);
    }
}

/// escape quotes and backslashes with backslash
fn escape_link_target(value: &str) -> Cow<'_, str> {
    let regex = {
        static REGEX: OnceLock<Regex> = OnceLock::new();
        REGEX.get_or_init(|| Regex::new(r"['\\]").unwrap())
    };

    regex.replace_all(value, |caps: &Captures<'_>| {
        match caps.get(0).unwrap().as_str() {
            "'" => "\\'".to_owned(),
            "\\" => "\\\\".to_owned(),
            _ => unreachable!(),
        }
    })
}

fn clip_to_rectangle(cr: &cairo::Context, r: &Rect) {
    cr.rectangle(r.x0, r.y0, r.width(), r.height());
    cr.clip();
}

impl From<SpreadMethod> for cairo::Extend {
    fn from(s: SpreadMethod) -> cairo::Extend {
        match s {
            SpreadMethod::Pad => cairo::Extend::Pad,
            SpreadMethod::Reflect => cairo::Extend::Reflect,
            SpreadMethod::Repeat => cairo::Extend::Repeat,
        }
    }
}

impl From<StrokeLinejoin> for cairo::LineJoin {
    fn from(j: StrokeLinejoin) -> cairo::LineJoin {
        match j {
            StrokeLinejoin::Miter => cairo::LineJoin::Miter,
            StrokeLinejoin::Round => cairo::LineJoin::Round,
            StrokeLinejoin::Bevel => cairo::LineJoin::Bevel,
        }
    }
}

impl From<StrokeLinecap> for cairo::LineCap {
    fn from(j: StrokeLinecap) -> cairo::LineCap {
        match j {
            StrokeLinecap::Butt => cairo::LineCap::Butt,
            StrokeLinecap::Round => cairo::LineCap::Round,
            StrokeLinecap::Square => cairo::LineCap::Square,
        }
    }
}

impl From<MixBlendMode> for cairo::Operator {
    fn from(m: MixBlendMode) -> cairo::Operator {
        use cairo::Operator;

        match m {
            MixBlendMode::Normal => Operator::Over,
            MixBlendMode::Multiply => Operator::Multiply,
            MixBlendMode::Screen => Operator::Screen,
            MixBlendMode::Overlay => Operator::Overlay,
            MixBlendMode::Darken => Operator::Darken,
            MixBlendMode::Lighten => Operator::Lighten,
            MixBlendMode::ColorDodge => Operator::ColorDodge,
            MixBlendMode::ColorBurn => Operator::ColorBurn,
            MixBlendMode::HardLight => Operator::HardLight,
            MixBlendMode::SoftLight => Operator::SoftLight,
            MixBlendMode::Difference => Operator::Difference,
            MixBlendMode::Exclusion => Operator::Exclusion,
            MixBlendMode::Hue => Operator::HslHue,
            MixBlendMode::Saturation => Operator::HslSaturation,
            MixBlendMode::Color => Operator::HslColor,
            MixBlendMode::Luminosity => Operator::HslLuminosity,
        }
    }
}

impl From<ClipRule> for cairo::FillRule {
    fn from(c: ClipRule) -> cairo::FillRule {
        match c {
            ClipRule::NonZero => cairo::FillRule::Winding,
            ClipRule::EvenOdd => cairo::FillRule::EvenOdd,
        }
    }
}

impl From<FillRule> for cairo::FillRule {
    fn from(f: FillRule) -> cairo::FillRule {
        match f {
            FillRule::NonZero => cairo::FillRule::Winding,
            FillRule::EvenOdd => cairo::FillRule::EvenOdd,
        }
    }
}

impl From<ShapeRendering> for cairo::Antialias {
    fn from(sr: ShapeRendering) -> cairo::Antialias {
        match sr {
            ShapeRendering::Auto | ShapeRendering::GeometricPrecision => cairo::Antialias::Default,
            ShapeRendering::OptimizeSpeed | ShapeRendering::CrispEdges => cairo::Antialias::None,
        }
    }
}

impl From<TextRendering> for cairo::Antialias {
    fn from(tr: TextRendering) -> cairo::Antialias {
        match tr {
            TextRendering::Auto
            | TextRendering::OptimizeLegibility
            | TextRendering::GeometricPrecision => cairo::Antialias::Default,
            TextRendering::OptimizeSpeed => cairo::Antialias::None,
        }
    }
}

impl From<cairo::Matrix> for Transform {
    #[inline]
    fn from(m: cairo::Matrix) -> Self {
        Self::new_unchecked(m.xx(), m.yx(), m.xy(), m.yy(), m.x0(), m.y0())
    }
}

impl From<ValidTransform> for cairo::Matrix {
    #[inline]
    fn from(t: ValidTransform) -> cairo::Matrix {
        cairo::Matrix::new(t.xx, t.yx, t.xy, t.yy, t.x0, t.y0)
    }
}

/// Extents for a path in its current coordinate system.
///
/// Normally you'll want to convert this to a BoundingBox, which has knowledge about just
/// what that coordinate system is.
pub struct PathExtents {
    /// Extents of the "plain", unstroked path, or `None` if the path is empty.
    pub path_only: Option<Rect>,

    /// Extents of just the fill, or `None` if the path is empty.
    pub fill: Option<Rect>,

    /// Extents for the stroked path, or `None` if the path is empty or zero-width.
    pub stroke: Option<Rect>,
}

impl Path {
    pub fn to_cairo(
        &self,
        cr: &cairo::Context,
        is_square_linecap: bool,
    ) -> Result<(), InternalRenderingError> {
        assert!(!self.is_empty());

        for subpath in self.iter_subpath() {
            // If a subpath is empty and the linecap is a square, then draw a square centered on
            // the origin of the subpath. See #165.
            if is_square_linecap {
                let (x, y) = subpath.origin();
                if subpath.is_zero_length() {
                    let stroke_size = 0.002;

                    cr.move_to(x - stroke_size / 2., y);
                    cr.line_to(x + stroke_size / 2., y);
                }
            }

            for cmd in subpath.iter_commands() {
                cmd.to_cairo(cr);
            }
        }

        // We check the cr's status right after feeding it a new path for a few reasons:
        //
        // * Any of the individual path commands may cause the cr to enter an error state, for
        //   example, if they come with coordinates outside of Cairo's supported range.
        //
        // * The *next* call to the cr will probably be something that actually checks the status
        //   (i.e. in cairo-rs), and we don't want to panic there.

        cr.status().map_err(|e| e.into())
    }

    /// Converts a `cairo::Path` to a librsvg `Path`.
    fn from_cairo(cairo_path: cairo::Path) -> Path {
        let mut builder = PathBuilder::default();

        // Cairo has the habit of appending a MoveTo to some paths, but we don't want a
        // path for empty text to generate that lone point.  So, strip out paths composed
        // only of MoveTo.

        if !cairo_path_is_only_move_tos(&cairo_path) {
            for segment in cairo_path.iter() {
                match segment {
                    cairo::PathSegment::MoveTo((x, y)) => builder.move_to(x, y),
                    cairo::PathSegment::LineTo((x, y)) => builder.line_to(x, y),
                    cairo::PathSegment::CurveTo((x2, y2), (x3, y3), (x4, y4)) => {
                        builder.curve_to(x2, y2, x3, y3, x4, y4)
                    }
                    cairo::PathSegment::ClosePath => builder.close_path(),
                }
            }
        }

        builder.into_path()
    }
}

fn cairo_path_is_only_move_tos(path: &cairo::Path) -> bool {
    path.iter()
        .all(|seg| matches!(seg, cairo::PathSegment::MoveTo((_, _))))
}

impl PathCommand {
    fn to_cairo(&self, cr: &cairo::Context) {
        match *self {
            PathCommand::MoveTo(x, y) => cr.move_to(x, y),
            PathCommand::LineTo(x, y) => cr.line_to(x, y),
            PathCommand::CurveTo(ref curve) => curve.to_cairo(cr),
            PathCommand::Arc(ref arc) => arc.to_cairo(cr),
            PathCommand::ClosePath => cr.close_path(),
        }
    }
}

impl EllipticalArc {
    fn to_cairo(&self, cr: &cairo::Context) {
        match self.center_parameterization() {
            ArcParameterization::CenterParameters {
                center,
                radii,
                theta1,
                delta_theta,
            } => {
                let n_segs = (delta_theta / (PI * 0.5 + 0.001)).abs().ceil() as u32;
                let d_theta = delta_theta / f64::from(n_segs);

                let mut theta = theta1;
                for _ in 0..n_segs {
                    arc_segment(center, radii, self.x_axis_rotation, theta, theta + d_theta)
                        .to_cairo(cr);
                    theta += d_theta;
                }
            }
            ArcParameterization::LineTo => {
                let (x2, y2) = self.to;
                cr.line_to(x2, y2);
            }
            ArcParameterization::Omit => {}
        }
    }
}

impl CubicBezierCurve {
    fn to_cairo(&self, cr: &cairo::Context) {
        let Self { pt1, pt2, to } = *self;
        cr.curve_to(pt1.0, pt1.1, pt2.0, pt2.1, to.0, to.1);
    }
}

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

    #[test]
    fn rsvg_path_from_cairo_path() {
        let surface = cairo::ImageSurface::create(cairo::Format::ARgb32, 10, 10).unwrap();
        let cr = cairo::Context::new(&surface).unwrap();

        cr.move_to(1.0, 2.0);
        cr.line_to(3.0, 4.0);
        cr.curve_to(5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
        cr.close_path();

        let cairo_path = cr.copy_path().unwrap();
        let path = Path::from_cairo(cairo_path);

        assert_eq!(
            path.iter().collect::<Vec<PathCommand>>(),
            vec![
                PathCommand::MoveTo(1.0, 2.0),
                PathCommand::LineTo(3.0, 4.0),
                PathCommand::CurveTo(CubicBezierCurve {
                    pt1: (5.0, 6.0),
                    pt2: (7.0, 8.0),
                    to: (9.0, 10.0),
                }),
                PathCommand::ClosePath,
                PathCommand::MoveTo(1.0, 2.0), // cairo inserts a MoveTo after ClosePath
            ],
        );
    }
}