impellers 0.4.2

Bindings to Flutter's 2D vector graphics renderer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
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
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
#![doc = include_str!("../README.md")]
//! ## API
//!
//! In a normal application, you usually have the phases of initialization, event loop and cleanup.
//!
//! ### Initialization
//! The initialization phase is usually the one where you create singletons. For example:
//!
//! 1. Create a [Context] (opengl/vk/metal) with the respective `new` functions. This is used to:
//!     1. create [Surface]/[VkSwapChain] (usually wrapping the default framebuffer).
//!     2. create a [Texture] from raw pixel data
//! 2. Create a [TypographyContext] (and register any custom fonts you may want to use).
//!
//!
//! ### Event Loop
//!
//! Impeller has two core objects: [Paint] and [DisplayListBuilder]. You need to understand both of them, to use this library.
//!
//! [DisplayListBuilder] acts like a canvas on to which we "draw" using methods like [DisplayListBuilder::draw_rect].
//! Internally, it builds up a list of draw commands, so that we can execute those commands later.
//!
//! The draw command is modified by three things before being added to the list:
//! 1. **Transformation**: decides the final position/size/shape of the draw command.
//! 2. **clipping**: how much of the draw command is effectively visible.
//! 3. **[Paint]**: further details of the draw command like color to use or other effects like blur.
//!
//! #### Transformation and Clip
//! The builder maintains an internal "stack" of transformation matrices and clip rects, manipulated by [DisplayListBuilder::save] and [DisplayListBuilder::restore].
//!
//! You can modify the current transformation with [DisplayListBuilder::scale], [DisplayListBuilder::translate] and
//! [DisplayListBuilder::rotate]. You can directly set a transformation matrix with
//! [DisplayListBuilder::set_transform] too or append additional matrix with [DisplayListBuilder::transform].
//! These will be applied to the draw commands that follow, until you use [DisplayListBuilder::restore] (to pop off the stack)
//! or [DisplayListBuilder::reset_transform] to just set the current matrix to identity.
//!
//! You can modify the current clip with [clip](DisplayListBuilder::clip_rect) and [DisplayListBuilder::clip_path].
//! The clip_op argument [ClipOperation] controls whether you want the draw commands to only
//! be visible *inside* or *outside* the clip shape.
//!
//! #### Paint
//! The [Paint] is used to configure the details of draw commands like:
//!
//! * Color, Transparency, Blend mode
//! * Draw style (filled rect or a stroked rect), width of the stroke
//! * Filters for blurs, color tinting a texture draw etc..
//!
//! Finally, once you have added all the draw commands, you build a [DisplayList] with
//! [DisplayListBuilder::build].
//!
//! [DisplayList] is an immutable, self-contained and reusable copy of draw commands that you can
//! execute/replay on to a surface (or add it to another [DisplayListBuilder]).
//!
//! You can use it as a reusable piece of drawing logic. And as you can append
//! it to [DisplayListBuilder], it will be affected by the transformation/clip
//! of the builder.
//!
//! For example, you can buid a [DisplayList] for a button background, and all button
//! widgets can reuse that for drawing different sized/rotated/positioned buttons.
//!
//! After building up this mega displaylist that contains your entire render tree,
//! you draw it to a [Surface]/[VkSwapChain] with [Surface::draw_display_list]
//! and preset it using [Surface::present].
//!
//! ### Cleanup
//! During the cleanup phase, you drop the all the objects including singletons.
//! And then,you destroy the window.
//!
//! ## Shapes
//!
//! Drawing most shapes like rect/circle is pretty simple, but there's a few
//! that are a bit more complex.
//!
//! ### Paths
//! You use [PathBuilder] to build a
//! list of path commands (start here, move to A, move to B etc..) and
//! eventually call [PathBuilder::copy_path_new] or [PathBuilder::take_path_new] to create a [Path].
//!
//! A [Path] is an immutable and reusable list of lines, curves and other path commands.
//! Each path contains zero or more sub-paths. So, a path can contain two independent circles or lines.
//! You draw it using [DisplayListBuilder::draw_path].
//!
//! ### Paragraphs
//!
//! A [ParagraphBuilder] is used to record a bunch of text sections with
//! different styles and then, build an immutable and reusable [Paragraph].
//!
//! 1. [TypographyContext] holds your fonts and provides them to [ParagraphBuilder].
//! 2. [ParagraphBuilder] to record text (with different pieces of text using different styles like colors/fonts/sizes etc..)
//! 3. You layout text with [ParagraphBuilder::build] using some max width and build a [Paragraph]
//! 4. You draw [Paragraph] with [DisplayListBuilder::draw_paragraph].
//!
//! [ParagraphBuilder] also maintains an internal stack of text styles.
//! So, you can push a style, add some text which will be rendered using that style and then,
//! pop the style to go back to previous style.
//!
//! ### Textures
//! You can create a [Texture] from raw pixel data or adopt an opengl texture using a [Context].
//!
//! While you can just draw a texture (image) directly using [DisplayListBuilder::draw_texture],
//! you can also use [ImageFilter] or [ColorFilter] of the [Paint] object to apply fancy effects
//! when sampling a texture.
//!
//! ### Filters/Sources etc..
//! The other objects are there mostly to add fancy effects like blur, color tint, color gradients etc..
//! Read the respective docs for more details.
//!
//! NOTE: The crate currently has *very* little API for some structs like matrices or rects. Contributions welcome :)
#![warn(missing_docs)]
#![warn(clippy::missing_safety_doc)]

mod color;
#[cfg(feature = "sys")]
pub mod sys;
#[cfg(not(feature = "sys"))]
mod sys;

use std::borrow::Cow;

use bytemuck::cast;
use bytemuck::cast_ref;

/// The commit hash of the prebuilt library artefacts used by this crate.
pub const FLUTTER_ARTEFACT_COMMIT: &str = include_str!("../ENGINE_SHA");

// enums
/// <https://api.flutter.dev/flutter/dart-ui/BlendMode.html>
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/blend-modes/>
pub use sys::BlendMode;
/// <https://api.flutter.dev/flutter/dart-ui/BlurStyle.html>
///
/// <https://shopify.github.io/react-native-skia/docs/mask-filters#example>
pub use sys::BlurStyle;
/// Layout of color components of the pixels
pub use sys::PixelFormat;

/// <https://api.flutter.dev/flutter/dart-ui/ClipOp.html>
pub use sys::ClipOperation;

/// <https://api.flutter.dev/flutter/dart-ui/ColorSpace.html>
pub use sys::ColorSpace;

/// <https://api.flutter.dev/flutter/dart-ui/PaintingStyle.html>
pub use sys::DrawStyle;

/// <https://api.flutter.dev/flutter/dart-ui/PathFillType.html>
///
/// <https://shopify.github.io/react-native-skia/docs/shapes/path#fill-type>
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/fill-types>
pub use sys::FillType;

/// <https://api.flutter.dev/flutter/dart-ui/FontStyle.html>
pub use sys::FontStyle;

/// <https://api.flutter.dev/flutter/dart-ui/FontWeight-class.html>
pub use sys::FontWeight;

/// <https://api.flutter.dev/flutter/dart-ui/StrokeCap.html>
pub use sys::StrokeCap;

/// <https://api.flutter.dev/flutter/dart-ui/StrokeJoin.html>
pub use sys::StrokeJoin;

/// <https://api.flutter.dev/flutter/dart-ui/TextAlign.html>
pub use sys::TextAlignment;

/// <https://api.flutter.dev/flutter/dart-ui/TextDirection.html>
pub use sys::TextDirection;

/// <https://api.flutter.dev/flutter/dart-ui/TextDecorationStyle.html>
pub use sys::TextDecorationStyle;

/// The sampling mode to use when drawing a texture.
pub use sys::TextureSampling;

/// <https://api.flutter.dev/flutter/dart-ui/TileMode.html>
pub use sys::TileMode;

pub use sys::{
    ImpellerColor as Color, ImpellerColorMatrix as ColorMatrix,
    ImpellerContextVulkanInfo as VulkanInfo, ImpellerRange as Range,
};
#[allow(missing_docs)]
pub type Rect = euclid::Rect<f32, euclid::UnknownUnit>;
#[allow(missing_docs)]
pub type Point = euclid::Point2D<f32, euclid::UnknownUnit>;
#[allow(missing_docs)]
pub type ISize = euclid::Size2D<i64, euclid::UnknownUnit>;
#[allow(missing_docs)]
pub type Size = euclid::Size2D<f32, euclid::UnknownUnit>;
#[allow(missing_docs)]
pub type Matrix = euclid::Transform3D<f32, euclid::UnknownUnit, euclid::UnknownUnit>;
//------------------------------------------------------------------------------
/// The current Impeller API version.
///
/// Rust bindings will automatically pass the version behind the scenes, so this is mostly useless for users.
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ImpellerVersion(u32);

impl ImpellerVersion {
    /// The header version from which we parsed the bindings
    pub fn get_header_version() -> Self {
        Self(
            (sys::IMPELLER_VERSION_VARIANT << 29)
                | (sys::IMPELLER_VERSION_MAJOR << 22)
                | (sys::IMPELLER_VERSION_MINOR << 12)
                | sys::IMPELLER_VERSION_PATCH,
        )
    }
    /// Extracts the version variant
    pub fn get_variant(self) -> u32 {
        self.0 >> 29
    }
    /// Extracts the major version
    pub fn get_major(self) -> u32 {
        // zero the first 3 bits (variant) and then shift by 22
        (self.0 & (!0 >> 3)) >> 22
    }
    /// Extracts the minor version
    pub fn get_minor(self) -> u32 {
        (self.0 & (!0 >> 12)) >> 12
    }
    /// Extracts the patch version
    pub fn get_patch(self) -> u32 {
        self.0 & (!0 >> 20)
    }
    /// Extracts major, minor, patch and variant components as one tuple.
    /// Just a convenience function.w
    pub fn get_tuple(self) -> (u32, u32, u32, u32) {
        (
            self.get_major(),
            self.get_minor(),
            self.get_patch(),
            self.get_variant(),
        )
    }
    /// Get the version of *linked* Impeller library. This is the API that
    /// will be accepted for validity checks when provided to the
    /// context creation methods.
    ///
    /// NOTE: Rust bindings do the version validity checks behind the scenes, so the following doesn't really apply to users.
    ///
    /// The current version of the API generated from `impeller.h` is denoted by the
    /// given by [Self::get_header_version]. This version must be passed to APIs
    /// that create top-level objects like graphics contexts.
    /// Construction of the context may fail if the API version expected
    /// by the caller is not supported by the library.
    ///
    /// Since there are no API stability guarantees today, passing a
    /// version that is different to the one returned by
    /// [Self::get_linked_version] will always fail.
    ///
    /// see [Context::new_opengl_es]
    ///
    ///
    /// @return     The version of the standalone API. None if the version of the bindings is not compatible with the version of the Impeller library that was linked into the application.
    #[doc(alias = "ImpellerGetVersion")]
    pub fn get_linked_version() -> Self {
        Self(unsafe { sys::ImpellerGetVersion() })
    }
    /// Checks that the [Self::get_header_version] is the same as the [Self::get_linked_version].
    /// ```
    /// impellers::ImpellerVersion::sanity_check();
    /// ```
    pub fn sanity_check() -> bool {
        Self::get_header_version() == Self::get_linked_version()
    }
}
/// The primary form of WSI when using a Vulkan context, these swapchains use
/// the `VK_KHR_surface` Vulkan extension.
///
/// Creating a swapchain is extremely expensive. One must be created at
/// application startup and re-used throughout the application lifecycle.
///
/// Swapchains are resilient to the underlying surfaces being resized. The
/// swapchain images will be re-created as necessary on-demand.
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerVulkanSwapchain")]
pub struct VkSwapChain(sys::ImpellerVulkanSwapchain);

impl Drop for VkSwapChain {
    #[doc(alias = "ImpellerVulkanSwapchainRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerVulkanSwapchainRelease(self.0);
        }
    }
}
impl VkSwapChain {
    //------------------------------------------------------------------------------
    /// A potentially blocking operation, acquires the next surface to
    /// render to. Since this may block, surface acquisition must be
    /// delayed for as long as possible to avoid an idle wait on the
    /// CPU.
    ///
    ///
    /// @return     The surface if one could be obtained, NULL otherwise.
    #[doc(alias = "ImpellerVulkanSwapchainAcquireNextSurfaceNew")]
    pub fn acquire_next_surface_new(&mut self) -> Option<Surface> {
        let surface = unsafe { sys::ImpellerVulkanSwapchainAcquireNextSurfaceNew(self.0) };
        if surface.is_null() {
            None
        } else {
            Some(Surface(surface))
        }
    }
}
/// An Impeller graphics context. Contexts are platform and client-rendering-API
/// specific.
///
/// Contexts are thread-safe objects (not thread-safe with openGL) that are expensive to create. Most
/// applications will only ever create a single context during their lifetimes.
/// Once setup, Impeller is ready to render frames as performantly as possible.
///
/// During setup, context create the underlying graphics pipelines, allocators,
/// worker threads, etc...
///
/// The general guidance is to create as few contexts as possible (typically
/// just one) and share them as much as possible.
///
#[derive(Debug)]
#[doc(alias = "ImpellerContext")]
pub struct Context(sys::ImpellerContext, ContextType);

#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum ContextType {
    Gl,
    Vk,
    Mtl,
}

impl Drop for Context {
    #[doc(alias = "ImpellerContextRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerContextRelease(self.0);
        }
    }
}
unsafe extern "C" fn wrap_gl_proc_address<F: FnMut(&str) -> *mut std::os::raw::c_void>(
    name: *const std::os::raw::c_char,
    user_data: *mut std::os::raw::c_void,
) -> *mut std::os::raw::c_void {
    let name = if name.is_null() {
        c""
    } else {
        unsafe { std::ffi::CStr::from_ptr(name) }
    };
    let Ok(name) = name.to_str() else {
        panic!("Invalid GL function name: {}", name.to_string_lossy());
    };
    (*(user_data as *mut F))(name)
}
unsafe extern "C" fn wrap_vk_proc_address<
    F: FnMut(*mut std::os::raw::c_void, *const std::os::raw::c_char) -> *mut std::os::raw::c_void,
>(
    vulkan_instance: *mut std::os::raw::c_void,
    vulkan_proc_name: *const std::os::raw::c_char,
    user_data: *mut std::os::raw::c_void,
) -> *mut std::os::raw::c_void {
    (*(user_data as *mut F))(vulkan_instance, vulkan_proc_name)
}

impl Context {
    /// Create an OpenGL(ES) Impeller context.
    ///
    /// @param
    /// - gl_proc_address: A closure that returns the address of GL fn pointers
    ///
    /// @return The context or error if the context could not be created.
    ///
    /// ```
    /// fn create_impeller_ctx(window: &mut glfw::PWindow) {
    ///     // as easy as it gets
    ///     let impeller_ctx = unsafe {
    ///         // safety:  drop all objects created from this context
    ///         //          before `window` is dropped
    ///         impellers::Context::new_opengl_es( |name| {
    ///             window.get_proc_address(name) as _
    ///         })
    ///     };
    ///
    /// }
    /// ```
    ///
    /// # Safety
    /// * The context must be dropped before the underlying window is dropped.
    /// * The context may only be used while the underlying context is current on the thread.
    /// * Any object (like texture or surface) that you create using this context
    ///   must be dropped before the context is dropped.
    /// * Unlike other context types, the OpenGL ES context can only be
    ///   created, used, and collected on the calling thread. This
    ///   restriction may be lifted in the future once reactor workers are
    ///   exposed in the API. No other context types have threading
    ///   restrictions. Till reactor workers can be used, using the
    ///   context on a background thread will cause a stall of OpenGL
    ///   operations.
    #[must_use = "opengl context has scary lifetime requirements. So, prefer dropping it explicitly with `std::mem:drop`"]
    #[doc(alias = "ImpellerContextCreateOpenGLESNew")]
    pub unsafe fn new_opengl_es<F: FnMut(&str) -> *mut std::os::raw::c_void>(
        mut gl_proc_address: F,
    ) -> Result<Context, &'static str> {
        if !ImpellerVersion::sanity_check() {
            return Err("Impeller version mismatch when creating opengl context");
        }
        let ctx = unsafe {
            sys::ImpellerContextCreateOpenGLESNew(
                ImpellerVersion::get_linked_version().0,
                Some(wrap_gl_proc_address::<F>),
                &raw mut gl_proc_address as *mut _,
            )
        };
        if ctx.is_null() {
            Err("ImpellerContextCreateOpenGLESNew returned null :(")
        } else {
            Ok(Self(ctx, ContextType::Gl))
        }
    }
    /// Create a new surface by wrapping an existing framebuffer object.
    /// The surface is just a cheap use-and-throw object.
    /// Create it, draw to it (once) and drop it .
    ///
    ///
    /// - fbo      The framebuffer object handle.
    /// - format   The format of the framebuffer.
    /// - size     The size of the framebuffer is texels.
    ///
    /// @return    The surface if once can be created, NULL otherwise.
    ///
    /// # Safety
    /// * The surface must be properly configured (eg: no pending resizes)
    /// * must be drawn to only once and then dropped (presented if vulkan).
    /// * must be dropped before the context is dropped
    /// * The framebuffer must be complete as determined by
    ///   `glCheckFramebufferStatus`. The framebuffer is still owned by
    ///   the caller and it must be collected once the surface is
    ///   collected.
    pub unsafe fn wrap_fbo(
        &mut self,
        fbo: u64,
        format: PixelFormat,
        size: ISize,
    ) -> Option<Surface> {
        assert_eq!(self.1, ContextType::Gl);
        let surface = unsafe {
            sys::ImpellerSurfaceCreateWrappedFBONew(self.0, fbo, format, cast_ref(&size))
        };
        if surface.is_null() {
            None
        } else {
            Some(Surface(surface))
        }
    }

    /// Create a texture with decompressed bytes.
    ///
    /// @warning    Do **not** supply compressed image data directly (PNG, JPEG,
    ///             etc...). This function only works with tightly packed
    ///             decompressed data.
    /// @param
    /// - contents  texture bytes. contiguously laid out as RGBA8888
    /// - width     width of texture
    /// - height    height of texture
    ///
    /// @return     The texture if one can be created using the provided data, NULL
    ///             otherwise.
    ///
    /// # Safety
    ///
    /// * The texture must be dropped before the context is dropped
    ///
    #[doc(alias = "ImpellerTextureCreateWithContentsNew")]
    pub unsafe fn create_texture_with_rgba8(
        &self,
        contents: Cow<'static, [u8]>,
        width: u32,
        height: u32,
    ) -> Result<Texture, &'static str> {
        if width == 0 || height == 0 {
            return Err("width and height must be greater than zero");
        }

        // we know this is 4 byte per pixel
        let total_bytes = width as usize * height as usize * 4;
        if contents.len() != total_bytes {
            return Err("provided buffer size does not match expected size");
        }
        let mip_count = flutter_mip_count(width as f32, height as f32);

        let t = unsafe {
            // SAFETY: pass the mapping with the right user_data returned from the function.
            let (mapping, user_data) = sys::ImpellerMapping::from_cow(contents);
            sys::ImpellerTextureCreateWithContentsNew(
                self.0,
                &sys::ImpellerTextureDescriptor {
                    size: cast(ISize::new(width.into(), height.into())),
                    pixel_format: PixelFormat::RGBA8888,
                    mip_count,
                },
                &mapping,
                user_data,
            )
        };
        if t.is_null() {
            Err("ImpellerTextureCreateWithContentsNew returned null")
        } else {
            Ok(Texture(t))
        }
    }

    /// Create a texture with an externally created OpenGL texture handle.
    ///
    /// - width     width of texture
    /// - height    height of texture
    /// - mip_count mipcount of texture
    /// - handle      The handle
    ///
    /// @return     The texture if one could be created by adopting the supplied
    ///             texture handle, NULL otherwise.
    /// # Safety
    ///
    /// * The texture must be dropped before the context is dropped
    /// * Ownership of the handle is transferred over to Impeller after a
    ///   successful call to this method. Impeller is responsible for
    ///   calling glDeleteTextures on this handle. Do **not** collect this
    ///   handle yourself as this will lead to a double-free.
    ///
    /// * The handle must be created in the same context as the one used
    ///   by Impeller. If a different context is used, that context must
    ///   be in the same sharegroup as Impellers OpenGL context and all
    ///   synchronization of texture contents must already be complete.
    ///
    /// If the context is not an OpenGL context, this call will always fail.
    ///
    #[doc(alias = "ImpellerTextureCreateWithOpenGLTextureHandleNew")]
    pub unsafe fn adopt_opengl_texture(
        &self,
        width: u32,
        height: u32,
        mip_count: u32,
        handle: u64,
    ) -> Option<Texture> {
        assert_eq!(self.1, ContextType::Gl);
        let size = sys::ImpellerISize {
            width: width.into(),
            height: height.into(),
        };
        let t = sys::ImpellerTextureCreateWithOpenGLTextureHandleNew(
            self.0,
            &sys::ImpellerTextureDescriptor {
                pixel_format: PixelFormat::RGBA8888,
                size,
                mip_count,
            },
            handle,
        );
        if t.is_null() {
            None
        } else {
            Some(Texture(t))
        }
    }
    //------------------------------------------------------------------------------
    /// Create a Metal context using the system default Metal device.
    ///
    /// # Safety
    /// I don't know much about Metal, so I will
    /// leave the work of figuring out the safety to users. good luck :)
    ///
    /// @return     The Metal context or NULL if one cannot be created.
    #[doc(alias = "ImpellerContextCreateMetalNew")]
    #[must_use = "don't just drop a context like that. They usually have scary lifetimes, so prefer dropping them with an explicit `std::mem::drop`"]
    pub unsafe fn new_metal() -> Result<Context, &'static str> {
        if !ImpellerVersion::sanity_check() {
            return Err("ImpellerVersion::sanity_check failed");
        }
        let ctx = sys::ImpellerContextCreateMetalNew(ImpellerVersion::get_linked_version().0);
        if ctx.is_null() {
            Err("ImpellerContextCreateMetalNew returned null")
        } else {
            Ok(Self(ctx, ContextType::Mtl))
        }
    }
    /// Create a Vulkan context using the provided Vulkan Settings.
    ///
    /// - enable_validation  Enable Vulkan validation layers
    /// - proc_address_callback  A callback to query the address of Vulkan function pointers. The first argument is a pointer to vulkan instance. The second argument is a pointer to the function name.
    ///
    /// @return     The Vulkan context or NULL if one cannot be created.
    ///
    /// # Safety
    ///
    /// Don't know much vulkan either, so users will have to figure out the safety invariants.
    ///
    /// Just look at vulkan docs for how your proc_address_callback should work.
    /// Don't hold on to any pointers given to your closure (instance pointer or char pointer).
    #[must_use = "don't just drop vulkan context like that :( It's lifetimes are scary, so prefer dropping it explicitly using `std::mem::drop`"]
    #[doc(alias = "ImpellerContextCreateVulkanNew")]
    pub unsafe fn new_vulkan<
        F: FnMut(*mut std::os::raw::c_void, *const std::os::raw::c_char) -> *mut std::os::raw::c_void,
    >(
        enable_validation: bool,
        mut proc_address_callback: F,
    ) -> Result<Context, &'static str> {
        if !ImpellerVersion::sanity_check() {
            return Err("ImpellerVersion::sanity_check failed");
        }
        let settings = sys::ImpellerContextVulkanSettings {
            user_data: &raw mut proc_address_callback as *mut _,
            proc_address_callback: Some(wrap_vk_proc_address::<F>),
            enable_vulkan_validation: enable_validation,
        };
        let ctx =
            sys::ImpellerContextCreateVulkanNew(ImpellerVersion::get_linked_version().0, &settings);
        if ctx.is_null() {
            Err("ImpellerContextCreateVulkanNew returned null")
        } else {
            Ok(Self(ctx, ContextType::Vk))
        }
    }
    /// Get internal Vulkan handles managed by the given Vulkan context.
    /// Ownership of the handles is still maintained by Impeller. This
    /// accessor is just available so embedders can create resources
    /// using the same device and instance as Impeller for interop.
    ///
    /// @warning    If the context is not a Vulkan context, this will return Err.
    ///
    #[doc(alias = "ImpellerContextGetVulkanInfo")]
    pub fn get_vulkan_info(&self) -> Result<VulkanInfo, &'static str> {
        assert_eq!(self.1, ContextType::Vk);
        let mut vulkan_info = VulkanInfo::default();
        if unsafe { sys::ImpellerContextGetVulkanInfo(self.0, &mut vulkan_info) } {
            Ok(vulkan_info)
        } else {
            Err("ImpellerContextGetVulkanInfo returned false. Is the context a Vulkan context?")
        }
    }

    //------------------------------------------------------------------------------
    /// Create a new Vulkan swapchain using a VkSurfaceKHR instance.
    /// Ownership of the surface is transferred over to Impeller.
    ///
    /// - vulkan_surface_khr  The vulkan surface.
    ///
    /// @return     The vulkan swapchain.
    ///
    /// # Safety
    ///
    /// The Vulkan instance the surface is created from must the same as the
    /// context provided.
    ///
    /// The context must be a Vulkan context whose
    ///          instance is the same used to create the
    ///          surface passed into the next argument.
    ///
    /// The surface pointer must be valid (and kept alive until this swapchain is dropped).
    #[doc(alias = "ImpellerVulkanSwapchainCreateNew")]
    pub unsafe fn create_new_vulkan_swapchain(
        &self,
        vulkan_surface_khr: *mut std::os::raw::c_void,
    ) -> Option<VkSwapChain> {
        assert_eq!(self.1, ContextType::Vk);
        let swapchain = sys::ImpellerVulkanSwapchainCreateNew(self.0, vulkan_surface_khr);
        if swapchain.is_null() {
            None
        } else {
            Some(VkSwapChain(swapchain))
        }
    }
    //------------------------------------------------------------------------------
    /// Create a surface by wrapping a Metal drawable. This is useful
    /// during WSI when the drawable is the backing store of the Metal
    /// layer being drawn to.
    ///
    /// # Safety
    ///
    /// The Metal layer must be using the same device managed by the
    /// underlying context.
    ///
    /// The Metal device managed by this
    /// context must be the same used to create the
    /// drawable that is being wrapped.
    ///
    /// - metal_drawable  The drawable to wrap as a surface.
    ///
    /// @return     The surface if one could be wrapped, NULL otherwise.
    pub unsafe fn wrap_metal_drawable(
        &self,
        metal_drawable: *mut std::os::raw::c_void,
    ) -> Option<Surface> {
        assert_eq!(self.1, ContextType::Mtl);
        let surface = sys::ImpellerSurfaceCreateWrappedMetalDrawableNew(self.0, metal_drawable);
        if surface.is_null() {
            None
        } else {
            Some(Surface(surface))
        }
    }
    /// Create a color source whose pixels are shaded by a fragment program.
    ///
    /// <https://docs.flutter.dev/ui/design/graphics/fragment-shaders>
    ///
    ///
    /// # Safety
    /// Make sure the uniform data is laid out according to the fragment program's requirements
    ///
    /// TODO: add an example and better docs
    pub unsafe fn new_color_source_from_fragment_program(
        &self,
        frag_program: &FragmentProgram,
        samplers: &[Texture],
        uniform_data: &[u8],
    ) -> ColorSource {
        let samplers_len = samplers.len();
        let mut samplers: Vec<sys::ImpellerTexture> = samplers.iter().map(|t| t.0).collect();
        let cs = unsafe {
            sys::ImpellerColorSourceCreateFragmentProgramNew(
                self.0,
                frag_program.0,
                if samplers_len == 0 {
                    std::ptr::null_mut()
                } else {
                    samplers.as_mut_ptr()
                },
                samplers_len,
                uniform_data.as_ptr(),
                uniform_data.len(),
            )
        };
        assert!(!cs.is_null());
        ColorSource(cs)
    }
    /// Create an image filter where each pixel is shaded by a fragment program.
    ///
    /// <https://docs.flutter.dev/ui/design/graphics/fragment-shaders>
    ///
    /// # Safety
    /// Make sure the uniform data is laid out according to the fragment program's requirements
    ///
    /// TODO: add an example and better docs
    pub unsafe fn new_image_filter_from_fragment_program(
        &self,
        frag_program: &FragmentProgram,
        samplers: &[Texture],
        uniform_data: &[u8],
    ) -> ImageFilter {
        let samplers_len = samplers.len();
        let mut samplers: Vec<sys::ImpellerTexture> = samplers.iter().map(|t| t.0).collect();
        let cs = unsafe {
            sys::ImpellerImageFilterCreateFragmentProgramNew(
                self.0,
                frag_program.0,
                if samplers_len == 0 {
                    std::ptr::null_mut()
                } else {
                    samplers.as_mut_ptr()
                },
                samplers_len,
                uniform_data.as_ptr(),
                uniform_data.len(),
            )
        };
        assert!(!cs.is_null());
        ImageFilter(cs)
    }
}

/// Display lists represent encoded rendering intent (draw commands). These objects are
/// immutable, reusable, thread-safe, and context-agnostic.
///
/// While it is perfectly fine to create new display lists per frame, there may
/// be opportunities for optimization when display lists are reused multiple
/// times.
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerDisplayList")]
pub struct DisplayList(sys::ImpellerDisplayList);
unsafe impl Send for DisplayList {}
unsafe impl Sync for DisplayList {}
impl Clone for DisplayList {
    #[doc(alias = "ImpellerDisplayListRetain")]
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerDisplayListRetain(self.0);
        }
        Self(self.0)
    }
}

impl Drop for DisplayList {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerDisplayListRelease(self.0);
        }
    }
}
/// Display list builders allow for the incremental creation of display lists.
///
/// Display list builders are context-agnostic.
///
/// ### Recorder Semantics
///
/// This is a mix of skia's Canvas and PictureRecorder. You call functions
/// to draw things, but technically, you are just queuing draw commands.
///
/// And when you are done recording, you use [Self::build] to create a
/// [DisplayList].
///
/// Finally, you "execute" all the queued draw commands
/// on an actual [Surface] with [Surface::draw_display_list].
///
/// [Self::draw_display_list] can be used to push a copy of draw commands from
/// a [DisplayList] into a [DisplayListBuilder].
///
/// <https://api.flutter.dev/flutter/dart-ui/Canvas-class.html>
///
/// <https://learn.microsoft.com/en-us/dotnet/api/skiasharp.skcanvas?view=skiasharp-2.88>
///
/// ### Transformation And Clip Stack
///
/// Internally, this maintains a stack of (transformation matrices + clip rects).
///
/// You push a new transformation or clip on to the stack using [Self::save]
/// and pop them off [Self::restore].
///
/// You can check the current size of the stack with [Self::get_save_count].
/// You can use this to pop off all elements above that that point using [Self::restore_to_count].
///
/// <https://learn.microsoft.com/en-us/dotnet/api/skiasharp.skcanvas?view=skiasharp-2.88#clipping-and-state>
///
/// ### Save Layer
///
/// [Self::save_layer] creates an offscreen layer and redirects
/// all the subsequent draw commands to this layer. This offscreen
/// layer is blended back onto the parent layer using [Self::restore].
///
/// This is expensive, but is useful to apply fancy effects for a whole
/// "group" of draw commands (a whole layer).
///
/// ### Transforms
///
/// You can apply transforms to the canvas using [Self::translate], [Self::scale], [Self::rotate] and [Self::transform].
/// This allows you to affect the size/positions of the subsequent draw commands (until you pop off the transform from stack).
///
/// On hidpi screens, you might want to scale your canvas by scale factor of the screen.
/// This will ensure that the rest of the application can just draw normally and still be the right size.
///
/// Remember that the transforms compose. So, if you scale by 2.0, save stack, scale by 2.0, you
/// are now scaling by 4.0 (2.0 from first transform and 2.0 from current transform).
///
/// <https://learn.microsoft.com/en-us/dotnet/api/skiasharp.skcanvas?view=skiasharp-2.88#transformations>
///
/// ### Clipping
///
/// Clipping simply ignores all the draws outside of its shape. While [Self::clip_rect]
/// is used often, you can use [Self::clip_path] to do arbitrary shaped clipping.
///
/// ### Paint
///
/// [Paint] is the most commonly used object and stores the configuration
/// for draw commands.
///
/// For example, [Self::draw_rect] draws a rectangle. But whether it is a filled rect or just
/// a stroked (bordered) rect is decided by the paint's [Paint::set_draw_style].
///
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerDisplayListBuilder")]
pub struct DisplayListBuilder(sys::ImpellerDisplayListBuilder);

unsafe impl Send for DisplayListBuilder {}
unsafe impl Sync for DisplayListBuilder {}
impl Drop for DisplayListBuilder {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerDisplayListBuilderRelease(self.0);
        }
    }
}
impl DisplayListBuilder {
    /// Create a new display list builder.
    ///
    /// An optional cull rectangle may be specified. Impeller is allowed
    /// to treat the contents outside this rectangle as being undefined.
    /// This may aid performance optimizations.
    ///
    /// @param
    /// - cull_rect:    The cull rectangle or NULL.
    ///
    /// @return         The display list builder.
    #[doc(alias = "ImpellerDisplayListBuilderNew")]
    pub fn new(cull_rect: Option<&Rect>) -> Self {
        let result = unsafe {
            sys::ImpellerDisplayListBuilderNew(cull_rect.map_or(std::ptr::null(), |r| cast_ref(r)))
        };
        assert!(!result.is_null(), "Failed to create display list builder");
        Self(result)
    }
    //------------------------------------------------------------------------------
    /// Create a new display list using the rendering intent already
    /// encoded in the builder. The builder is reset after this call.
    ///
    /// @return     The display list.
    #[must_use]
    #[doc(alias = "ImpellerDisplayListBuilderCreateDisplayListNew")]
    pub fn build(&mut self) -> Option<DisplayList> {
        let d = unsafe { sys::ImpellerDisplayListBuilderCreateDisplayListNew(self.0) };
        if d.is_null() {
            None
        } else {
            Some(DisplayList(d))
        }
    }
    //------------------------------------------------------------------------------
    // Display List Builder: Managing the transformation stack.
    //------------------------------------------------------------------------------

    //------------------------------------------------------------------------------
    /// Stashes the current transformation and clip state onto a save
    /// stack.
    #[doc(alias = "ImpellerDisplayListBuilderSave")]
    pub fn save(&mut self) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderSave(self.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Stashes the current transformation and clip state onto a save
    /// stack and creates and creates an offscreen layer onto which
    /// subsequent rendering intent will be directed to.
    ///
    /// On the balancing call to restore, the supplied paints filters
    /// and blend modes will be used to composite the offscreen contents
    /// back onto the display display list.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/saveLayer.html>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/group#layer-effects>
    ///
    /// - bounds    The bounds.
    /// - paint     The paint.
    /// - backdrop  The backdrop.
    ///
    #[doc(alias = "ImpellerDisplayListBuilderSaveLayer")]
    pub fn save_layer(
        &mut self,
        bounds: &Rect,
        paint: Option<&Paint>,
        backdrop: Option<&ImageFilter>,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderSaveLayer(
                self.0,
                cast_ref(bounds),
                paint.map_or(std::ptr::null_mut(), |p| p.0),
                backdrop.map_or(std::ptr::null_mut(), |b| b.0),
            );
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Pops the last entry pushed onto the save stack using a call to
    /// [Self::save] or [Self::save_layer].
    #[doc(alias = "ImpellerDisplayListBuilderRestore")]
    pub fn restore(&mut self) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderRestore(self.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Apply a scale to the transformation matrix currently on top of
    /// the save stack.
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/scale>
    ///
    /// - x_scale  The x scale.
    /// - y_scale  The y scale.
    #[doc(alias = "ImpellerDisplayListBuilderScale")]
    pub fn scale(&mut self, x_scale: f32, y_scale: f32) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderScale(self.0, x_scale, y_scale);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Apply a clockwise rotation to the transformation matrix
    /// currently on top of the save stack.
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/rotate>
    ///
    /// - angle_degrees  The angle in degrees.
    #[doc(alias = "ImpellerDisplayListBuilderRotate")]
    pub fn rotate(&mut self, angle_degrees: f32) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderRotate(self.0, angle_degrees);
        }
        self
    }
    /// Apply a translation to the transformation matrix currently on
    /// top of the save stack.
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/translate>
    ///
    /// - x_translation  The x translation.
    /// - y_translation  The y translation.
    #[doc(alias = "ImpellerDisplayListBuilderTranslate")]
    pub fn translate(&mut self, x_translation: f32, y_translation: f32) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderTranslate(self.0, x_translation, y_translation);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Appends the the provided transformation to the transformation
    /// already on the save stack.
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/matrix>
    ///
    /// - transform  The transform to append.
    #[doc(alias = "ImpellerDisplayListBuilderTransform")]
    pub fn transform(&mut self, transform: &Matrix) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderTransform(self.0, cast_ref(transform));
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Clear the transformation on top of the save stack and replace it
    /// with a new value.
    ///
    /// <https://shopify.github.io/react-native-skia/docs/group/#transformations>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/transforms/matrix>
    ///
    /// - transform  The new transform.
    #[doc(alias = "ImpellerDisplayListBuilderSetTransform")]
    pub fn set_transform(&mut self, transform: &Matrix) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderSetTransform(self.0, cast_ref(transform));
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Get the transformation currently built up on the top of the
    /// transformation stack.
    ///
    /// @see [Self::set_transform] and [Self::transform]
    ///
    /// @return The transform.
    #[doc(alias = "ImpellerDisplayListBuilderGetTransform")]
    pub fn get_transform(&self) -> Matrix {
        let mut out_transform = Matrix::default();
        unsafe {
            sys::ImpellerDisplayListBuilderGetTransform(
                self.0,
                // TODO: is converting mut ref to mut pointer UB?
                bytemuck::cast_mut(&mut out_transform),
            );
        }
        out_transform
    }

    //------------------------------------------------------------------------------
    /// Reset the transformation on top of the transformation stack to
    /// identity.
    ///
    /// @see [Self::set_transform], [Self::transform] and [Self::get_transform]
    #[doc(alias = "ImpellerDisplayListBuilderResetTransform")]
    pub fn reset_transform(&mut self) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderResetTransform(self.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Get the current size of the save stack.
    ///
    /// @see [Self::save], [Self::save_layer], [Self::restore] and [Self::restore_to_count]
    ///
    /// @return     The save stack size.
    #[doc(alias = "ImpellerDisplayListBuilderGetSaveCount")]
    pub fn get_save_count(&mut self) -> u32 {
        unsafe { sys::ImpellerDisplayListBuilderGetSaveCount(self.0) }
    }
    //------------------------------------------------------------------------------
    /// Effectively calls ImpellerDisplayListBuilderRestore till the
    /// size of the save stack becomes a specified count.
    ///
    /// @see [Self::save], [Self::save_layer], [Self::restore] and [Self::get_save_count]
    ///
    /// - count    The count.
    #[doc(alias = "ImpellerDisplayListBuilderRestoreToCount")]
    pub fn restore_to_count(&mut self, count: u32) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderRestoreToCount(self.0, count);
        }
        self
    }
    //------------------------------------------------------------------------------
    // Display List Builder: Clipping
    //------------------------------------------------------------------------------

    //------------------------------------------------------------------------------
    /// Reduces the clip region to the intersection of the current clip
    /// and the given rectangle taking into account the clip operation.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/clipRect.html>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/group/#clip-rectangle>
    ///
    /// - rect     The rectangle.
    /// - op       The operation.
    #[doc(alias = "ImpellerDisplayListBuilderClipRect")]
    pub fn clip_rect(&mut self, rect: &Rect, op: ClipOperation) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderClipRect(self.0, cast_ref(rect), op);
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Reduces the clip region to the intersection of the current clip
    /// and the given oval taking into account the clip operation.
    ///
    /// - oval_bounds  The oval bounds.
    /// - op           The operation.
    #[doc(alias = "ImpellerDisplayListBuilderClipOval")]
    pub fn clip_oval(&mut self, oval_bounds: &Rect, op: ClipOperation) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderClipOval(self.0, cast_ref(oval_bounds), op);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Reduces the clip region to the intersection of the current clip
    /// and the given rounded rectangle taking into account the clip
    /// operation.
    ///
    /// <https://shopify.github.io/react-native-skia/docs/group/#clip-rounded-rectangle>
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/clipRRect.html>
    ///
    /// - rect     The rectangle.
    /// - radii    The radii.
    /// - op       The operation.
    #[doc(alias = "ImpellerDisplayListBuilderClipRoundedRect")]
    pub fn clip_rounded_rect(
        &mut self,
        rect: &Rect,
        radii: &RoundingRadii,
        op: ClipOperation,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderClipRoundedRect(
                self.0,
                cast_ref(rect),
                &radii.into(),
                op,
            );
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Reduces the clip region to the intersection of the current clip
    /// and the given path taking into account the clip operation.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/clipPath.html>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/curves/clipping>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/group#clip-path>
    ///
    /// - path     The path.
    /// - op       The operation.
    #[doc(alias = "ImpellerDisplayListBuilderClipPath")]
    pub fn clip_path(&mut self, path: &Path, op: ClipOperation) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderClipPath(self.0, path.0, op);
        }
        self
    }
    //------------------------------------------------------------------------------
    // Display List Builder: Drawing Shapes
    //------------------------------------------------------------------------------

    //------------------------------------------------------------------------------
    /// Fills the current clip with the specified paint.
    ///
    /// - paint    The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawPaint")]
    pub fn draw_paint(&mut self, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawPaint(self.0, paint.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draws a line segment.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/drawLine.html>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/lines>
    ///
    /// - from     The starting point of the line.
    /// - to       The end point of the line.
    /// - paint    The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawLine")]
    pub fn draw_line(&mut self, from: Point, to: Point, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawLine(
                self.0,
                cast_ref(&from),
                cast_ref(&to),
                paint.0,
            );
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Draws a dash line segment.
    ///
    /// - from        The starting point of the line.
    /// - to          The end point of the line.
    /// - on_length   On length.
    /// - off_length  Off length.
    /// - paint       The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawDashedLine")]
    pub fn draw_dashed_line(
        &mut self,
        from: Point,
        to: Point,
        on_length: f32,
        off_length: f32,
        paint: &Paint,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawDashedLine(
                self.0,
                cast_ref(&from),
                cast_ref(&to),
                on_length,
                off_length,
                paint.0,
            );
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Draws a rectangle.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/drawRect.html>
    ///
    /// - rect     The rectangle.
    /// - paint    The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawRect")]
    pub fn draw_rect(&mut self, rect: &Rect, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawRect(self.0, cast_ref(rect), paint.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draws an oval.
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shapes/ellipses#oval>
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/drawOval.html>
    ///
    /// - oval_bounds  The oval bounds.
    /// - paint        The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawOval")]
    pub fn draw_oval(&mut self, oval_bounds: &Rect, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawOval(self.0, cast_ref(oval_bounds), paint.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draws a rounded rect.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/drawRRect.html>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shapes/polygons#using-custom-radii>
    ///
    /// - rect     The rectangle.
    /// - radii    The radii.
    /// - paint    The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawRoundedRect")]
    pub fn draw_rounded_rect(
        &mut self,
        rect: &Rect,
        radii: &RoundingRadii,
        paint: &Paint,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawRoundedRect(
                self.0,
                cast_ref(rect),
                &radii.into(),
                paint.0,
            );
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draws a shape that is the different between the specified
    /// rectangles (each with configurable corner radii).
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shapes/polygons#diffrect>
    ///
    /// - outer_rect   The outer rectangle.
    /// - outer_radii  The outer radii.
    /// - inner_rect   The inner rectangle.
    /// - inner_radii  The inner radii.
    /// - paint        The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawRoundedRectDifference")]
    pub fn draw_rounded_rect_difference(
        &mut self,
        outer_rect: &Rect,
        outer_radii: &RoundingRadii,
        inner_rect: &Rect,
        inner_radii: &RoundingRadii,
        paint: &Paint,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawRoundedRectDifference(
                self.0,
                cast_ref(outer_rect),
                &outer_radii.into(),
                cast_ref(inner_rect),
                &inner_radii.into(),
                paint.0,
            );
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draws the specified path shape.
    ///
    /// @see [Path] and [PathBuilder]
    ///
    /// - path     The path.
    /// - paint    The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawPath")]
    pub fn draw_path(&mut self, path: &Path, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawPath(self.0, path.0, paint.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Flattens the contents of another display list into the one
    /// currently being built.
    ///
    /// In skia, display lists are often called `Pictures`.
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shapes/pictures>
    ///
    /// - display_list  The display list.
    /// - opacity       The opacity.
    #[doc(alias = "ImpellerDisplayListBuilderDrawDisplayList")]
    pub fn draw_display_list(&mut self, display_list: &DisplayList, opacity: f32) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawDisplayList(self.0, display_list.0, opacity);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draw a paragraph at the specified point.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Canvas/drawParagraph.html>
    ///
    /// @see [Paragraph], [ParagraphBuilder] and [ParagraphStyle]
    ///
    /// - paragraph  The paragraph.
    /// - point      The point where to draw the paragraph. (offset)
    #[doc(alias = "ImpellerDisplayListBuilderDrawParagraph")]
    pub fn draw_paragraph(&mut self, paragraph: &Paragraph, point: Point) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawParagraph(self.0, paragraph.0, cast_ref(&point));
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Draw a shadow for a Path given a material elevation. If the
    /// occluding object is not opaque, additional hints (via the
    /// `occluder_is_transparent` argument) must be provided to render
    /// the shadow correctly.
    ///
    /// * path       The shadow path.
    /// * color      The shadow color.
    /// * elevation  The material elevation.
    /// * occluder_is_transparent If the object casting the shadow is transparent.
    /// *  device_pixel_ratio The device pixel ratio.
    #[doc(alias = "ImpellerDisplayListBuilderDrawShadow")]
    pub fn draw_shadow(
        &mut self,
        path: &Path,
        color: &Color,
        elevation: f32,
        occluder_is_transparent: bool,
        device_pixel_ratio: f32,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawShadow(
                self.0,
                path.0,
                cast_ref(color),
                elevation,
                occluder_is_transparent,
                device_pixel_ratio,
            );
        }
        self
    }
    //------------------------------------------------------------------------------
    // Display List Builder: Drawing Textures
    //------------------------------------------------------------------------------

    //------------------------------------------------------------------------------
    /// Draw a texture at the specified point.
    ///
    /// When you draw a texture, you draw it in its full size.
    /// To adjust the size, you can use [DisplayListBuilder::scale].
    /// eg: if you wanted to draw a 500x500 texture as 250x250, just scale by 0.5
    ///     Make sure to use the same scale for both x and y, or you will stretch/compress the image.
    ///
    /// Another way to draw a texture is to use [DisplayListBuilder::draw_texture_rect],
    /// which allows you to choose a source rect (part of image) and draw it to any rect on canvas.
    ///
    /// - texture   The texture.
    /// - point     The point.
    /// - sampling  The sampling.
    /// - paint     The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawTexture")]
    pub fn draw_texture(
        &mut self,
        texture: &Texture,
        point: Point,
        sampling: TextureSampling,
        paint: &Paint,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawTexture(
                self.0,
                texture.0,
                cast_ref(&point),
                sampling,
                paint.0,
            );
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Draw a portion of texture at the specified location.
    ///
    /// This function takes a portion (src_rect) of the texture
    /// and draws it at dst_rect on canvas. It will do the necessary
    /// scaling to make sure that the src_rect will fit onto dst_rect exactly.
    ///
    /// Look at [Paint] struct for how you can customize the drawing.
    /// eg: blurring the image or adding a color tint.
    ///
    /// - texture   The texture.
    /// - src_rect  The source rectangle.
    /// - dst_rect  The destination rectangle.
    /// - sampling  The sampling.
    /// - paint     The paint.
    #[doc(alias = "ImpellerDisplayListBuilderDrawTextureRect")]
    pub fn draw_texture_rect(
        &mut self,
        texture: &Texture,
        src_rect: &Rect,
        dst_rect: &Rect,
        sampling: TextureSampling,
        paint: Option<&Paint>,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerDisplayListBuilderDrawTextureRect(
                self.0,
                texture.0,
                cast_ref(src_rect),
                cast_ref(dst_rect),
                sampling,
                paint.map_or(std::ptr::null_mut(), |p| p.0),
            );
        }
        self
    }
}
/// Paints control the behavior of draw calls encoded in a display list.
///
/// Like display lists, paints are context-agnostic.
///
/// NOTE: If you understand this struct, then you understand Impeller.
///
/// <https://api.flutter.dev/flutter/dart-ui/Paint-class.html>
///
/// <https://shopify.github.io/react-native-skia/docs/paint/overview>
///
/// <https://shopify.github.io/react-native-skia/docs/paint/properties>
///
/// <https://learn.microsoft.com/en-us/dotnet/api/skiasharp.skpaint?view=skiasharp-2.88>
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerPaint")]
pub struct Paint(sys::ImpellerPaint);

unsafe impl Send for Paint {}
unsafe impl Sync for Paint {}

impl Drop for Paint {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerPaintRelease(self.0);
        }
    }
}
impl Default for Paint {
    fn default() -> Self {
        let p = unsafe { sys::ImpellerPaintNew() };
        assert!(!p.is_null());
        Self(p)
    }
}
impl Paint {
    /// Set the paint color for stroking or filling.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Paint/color.html>
    ///
    /// - color     The color.
    #[doc(alias = "ImpellerPaintSetColor")]
    pub fn set_color(&mut self, color: Color) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetColor(self.0, &color);
        }
        self
    }

    /// Set the paint blend mode. The blend mode controls how the new
    /// paints contents are mixed with the values already drawn using
    /// previous draw calls.
    ///
    /// - mode      The mode.
    #[doc(alias = "ImpellerPaintSetBlendMode")]
    pub fn set_blend_mode(&mut self, mode: BlendMode) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetBlendMode(self.0, mode);
        }
        self
    }

    /// Set the paint draw style. The style controls if the closed
    /// shapes are filled and/or stroked.
    ///
    /// - style     The style.
    #[doc(alias = "ImpellerPaintSetDrawStyle")]
    pub fn set_draw_style(&mut self, style: DrawStyle) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetDrawStyle(self.0, style);
        }
        self
    }

    /// Sets how strokes rendered using this paint are capped.
    ///
    /// - cap       The stroke cap style.
    #[doc(alias = "ImpellerPaintSetStrokeCap")]
    pub fn set_stroke_cap(&mut self, cap: StrokeCap) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetStrokeCap(self.0, cap);
        }
        self
    }

    /// Sets how strokes rendered using this paint are joined.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Paint/strokeJoin.html>
    ///
    /// - join      The join.
    #[doc(alias = "ImpellerPaintSetStrokeJoin")]
    pub fn set_stroke_join(&mut self, join: StrokeJoin) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetStrokeJoin(self.0, join);
        }
        self
    }

    /// Set the width of the strokes rendered using this paint.
    ///
    /// - width     The width.
    #[doc(alias = "ImpellerPaintSetStrokeWidth")]
    pub fn set_stroke_width(&mut self, width: f32) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetStrokeWidth(self.0, width);
        }
        self
    }

    /// Set the miter limit of the strokes rendered using this paint.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Paint/strokeMiterLimit.html>
    ///
    /// - miter     The miter limit.
    #[doc(alias = "ImpellerPaintSetStrokeMiter")]
    pub fn set_stroke_miter(&mut self, miter: f32) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetStrokeMiter(self.0, miter);
        }
        self
    }

    /// Set the color filter of the paint.
    ///
    /// Color filters are functions that take two colors and mix them to
    /// produce a single color. This color is then usually merged with
    /// the destination during blending.
    ///
    /// - color_filter  The color filter.
    #[doc(alias = "ImpellerPaintSetColorFilter")]
    pub fn set_color_filter(&mut self, color_filter: &ColorFilter) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetColorFilter(self.0, color_filter.0);
        }
        self
    }

    /// Set the image filter of a paint.
    ///
    /// Image filters are functions that are applied to regions of a
    /// texture to produce a single color.
    ///
    /// - image_filter  The image filter.
    #[doc(alias = "ImpellerPaintSetImageFilter")]
    pub fn set_image_filter(&mut self, image_filter: &ImageFilter) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetImageFilter(self.0, image_filter.0);
        }
        self
    }
    /// Set the color source of the paint.
    ///
    /// Color sources are functions that generate colors for each
    /// texture element covered by a draw call.
    ///
    /// - color_source  The color source.
    #[doc(alias = "ImpellerPaintSetColorSource")]
    pub fn set_color_source(&mut self, color_source: &ColorSource) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetColorSource(self.0, color_source.0);
        }
        self
    }
    /// Set the mask filter of a paint.
    ///
    /// Mask filters are functions that are applied over a shape after it
    /// has been drawn but before it has been blended into the final
    /// image.
    ///
    /// - mask_filter  The mask filter.
    #[doc(alias = "ImpellerPaintSetMaskFilter")]
    pub fn set_mask_filter(&mut self, mask_filter: &MaskFilter) -> &mut Self {
        unsafe {
            sys::ImpellerPaintSetMaskFilter(self.0, mask_filter.0);
        }
        self
    }
}
/// Color filters are functions that take two colors and mix them to produce a
/// single color. This color is then merged with the destination during
/// blending.
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/color-filters>
///
/// <https://api.flutter.dev/flutter/dart-ui/ColorFilter-class.html>
///
/// <https://shopify.github.io/react-native-skia/docs/color-filters>
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerColorFilter")]
pub struct ColorFilter(sys::ImpellerColorFilter);
unsafe impl Send for ColorFilter {}
unsafe impl Sync for ColorFilter {}
impl Clone for ColorFilter {
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerColorFilterRetain(self.0);
        }
        Self(self.0)
    }
}

impl Drop for ColorFilter {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerColorFilterRelease(self.0);
        }
    }
}
impl ColorFilter {
    /// Create a color filter that performs blending of pixel values
    /// independently.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/ColorFilter/ColorFilter.mode.html>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/color-filters#blendcolor>
    ///
    ///
    /// - color       The color.
    /// - blend_mode  The blend mode.
    ///
    /// @return     The color filter.
    #[doc(alias = "ImpellerColorFilterCreateBlendNew")]
    pub fn new_blend(color: Color, blend_mode: BlendMode) -> Self {
        unsafe { Self(sys::ImpellerColorFilterCreateBlendNew(&color, blend_mode)) }
    }

    /// Create a color filter that transforms pixel color values
    /// independently.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/ColorFilter/ColorFilter.matrix.html>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/color-filters#color-matrix>
    ///
    /// playground to play with matrices: <https://fecolormatrix.com/>
    ///
    /// read more in struct docs [ColorFilter]
    #[doc(alias = "ImpellerColorFilterCreateColorMatrixNew")]
    pub fn new_matrix(color_matrix: ColorMatrix) -> Self {
        unsafe { Self(sys::ImpellerColorFilterCreateColorMatrixNew(&color_matrix)) }
    }
}
/// Color sources are functions that generate colors for each texture element
/// covered by a draw call. The colors for each element can be generated using a
/// mathematical function (to produce gradients for example) or sampled from a
/// texture.
///
/// <https://api.flutter.dev/flutter/dart-ui/Gradient-class.html>
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/shaders/>
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerColorSource")]
pub struct ColorSource(sys::ImpellerColorSource);
unsafe impl Send for ColorSource {}
unsafe impl Sync for ColorSource {}
impl Clone for ColorSource {
    #[doc(alias = "ImpellerColorSourceRetain")]
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerColorSourceRetain(self.0);
        }
        Self(self.0)
    }
}

impl Drop for ColorSource {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerColorSourceRelease(self.0);
        }
    }
}
impl ColorSource {
    //------------------------------------------------------------------------------
    /// Create a color source that forms a linear gradient.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Gradient/Gradient.linear.html>
    ///
    /// <https://api.flutter.dev/flutter/painting/LinearGradient-class.html>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shaders/gradients#linear-gradient>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/shaders/linear-gradient>
    ///
    /// - start_point     The start point.
    /// - end_point       The end point.
    /// - colors          The colors.
    /// - stops           The stops.
    /// - tile_mode       The tile mode.
    /// - transformation  The transformation.
    ///
    /// @return     The color source.
    #[doc(alias = "ImpellerColorSourceCreateLinearGradientNew")]
    pub fn new_linear_gradient(
        start: Point,
        end: Point,
        colors: &[Color],
        stops: &[f32],
        tile_mode: TileMode,
        transformation: Option<&Matrix>,
    ) -> Self {
        assert_eq!(colors.len(), stops.len());
        assert!(!colors.is_empty());
        let result = unsafe {
            sys::ImpellerColorSourceCreateLinearGradientNew(
                cast_ref(&start),
                cast_ref(&end),
                stops.len() as _,
                colors.as_ptr(),
                stops.as_ptr(),
                tile_mode,
                transformation.map_or(std::ptr::null(), |m| cast_ref(m)),
            )
        };
        assert!(!result.is_null());
        Self(result)
    }

    //------------------------------------------------------------------------------
    /// Create a color source that forms a radial gradient.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Gradient/Gradient.radial.html>
    ///
    /// <https://api.flutter.dev/flutter/painting/RadialGradient-class.html>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/shaders/circular-gradients#the-radial-gradient>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shaders/gradients#radial-gradient>
    ///
    /// - center          The center.
    /// - radius          The radius.
    /// - stop_count      The stop count.
    /// - colors          The colors.
    /// - stops           The stops.
    /// - tile_mode       The tile mode.
    /// - transformation  The transformation.
    ///
    /// @return     The color source.
    #[doc(alias = "ImpellerColorSourceCreateRadialGradientNew")]
    pub fn new_radial_gradient(
        center: Point,
        radius: f32,
        colors: &[Color],
        stops: &[f32],
        tile_mode: TileMode,
        transformation: Option<&Matrix>,
    ) -> Self {
        assert_eq!(colors.len(), stops.len());
        assert!(!colors.is_empty());
        let result = unsafe {
            sys::ImpellerColorSourceCreateRadialGradientNew(
                cast_ref(&center),
                radius,
                stops.len() as _,
                colors.as_ptr(),
                stops.as_ptr(),
                tile_mode,
                transformation.map_or(std::ptr::null(), |m| cast_ref(m)),
            )
        };
        assert!(!result.is_null());
        Self(result)
    }

    //------------------------------------------------------------------------------
    /// Create a color source that forms a conical gradient.
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/shaders/circular-gradients#the-two-point-conical-gradient>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shaders/gradients#two-point-conical-gradient>
    ///
    /// - start_center    The start center.
    /// - start_radius    The start radius.
    /// - end_center      The end center.
    /// - end_radius      The end radius.
    /// - stop_count      The stop count.
    /// - colors          The colors.
    /// - stops           The stops.
    /// - tile_mode       The tile mode.
    /// - transformation  The transformation.
    ///
    /// @return     The color source.
    #[allow(clippy::too_many_arguments)]
    #[doc(alias = "ImpellerColorSourceCreateConicalGradientNew")]
    pub fn new_conical_gradient(
        start_center: Point,
        start_radius: f32,
        end_center: Point,
        end_radius: f32,
        colors: &[Color],
        stops: &[f32],
        tile_mode: TileMode,
        transformation: Option<&Matrix>,
    ) -> Self {
        assert_eq!(colors.len(), stops.len());
        assert!(!colors.is_empty());
        let result = unsafe {
            sys::ImpellerColorSourceCreateConicalGradientNew(
                cast_ref(&start_center),
                start_radius,
                cast_ref(&end_center),
                end_radius,
                stops.len() as _,
                colors.as_ptr(),
                stops.as_ptr(),
                tile_mode,
                transformation.map_or(std::ptr::null(), |m| cast_ref(m)),
            )
        };
        assert!(!result.is_null());
        Self(result)
    }

    //------------------------------------------------------------------------------
    /// Create a color source that forms a sweep gradient.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/Gradient/Gradient.sweep.html>
    ///
    /// <https://api.flutter.dev/flutter/painting/SweepGradient-class.html>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/shaders/circular-gradients#the-sweep-gradient>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shaders/gradients#sweep-gradient>
    ///
    /// - center          The center.
    /// - start           The start.
    /// - end             The end.
    /// - stop_count      The stop count.
    /// - colors          The colors.
    /// - stops           The stops.
    /// - tile_mode       The tile mode.
    /// - transformation  The transformation.
    ///
    /// @return     The color source.car
    #[doc(alias = "ImpellerColorSourceCreateSweepGradientNew")]
    pub fn new_sweep_gradient(
        center: Point,
        start: f32,
        end: f32,
        colors: &[Color],
        stops: &[f32],
        tile_mode: TileMode,
        transformation: Option<&Matrix>,
    ) -> Self {
        assert_eq!(colors.len(), stops.len());
        assert!(!colors.is_empty());
        let result = unsafe {
            sys::ImpellerColorSourceCreateSweepGradientNew(
                cast_ref(&center),
                start,
                end,
                stops.len() as _,
                colors.as_ptr(),
                stops.as_ptr(),
                tile_mode,
                transformation.map_or(std::ptr::null(), |m| cast_ref(m)),
            )
        };
        assert!(!result.is_null());
        Self(result)
    }
    /// Create a color source that samples from an image.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/ImageShader/ImageShader.html>
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/shaders/bitmap-tiling>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/shaders/images>
    ///
    /// - image                 The image.
    /// - horizontal_tile_mode  The horizontal tile mode.
    /// - vertical_tile_mode    The vertical tile mode.
    /// - sampling              The sampling.
    /// - transformation        The transformation.
    ///
    /// @return     The color source.
    #[doc(alias = "ImpellerColorSourceCreateImageNew")]
    pub fn new_image(
        image: &Texture,
        horizontal_tile_mode: TileMode,
        vertical_tile_mode: TileMode,
        sampling: TextureSampling,
        transformation: Option<&Matrix>,
    ) -> Self {
        let result = unsafe {
            sys::ImpellerColorSourceCreateImageNew(
                image.0,
                horizontal_tile_mode,
                vertical_tile_mode,
                sampling,
                transformation.map_or(std::ptr::null(), |m| cast_ref(m)),
            )
        };
        assert!(!result.is_null());
        Self(result)
    }
}
/// Image filters are functions that are applied regions of a texture to produce
/// a single color. Contrast this with color filters that operate independently
/// on a per-pixel basis. The generated color is then merged with the
/// destination during blending.
///
/// <https://api.flutter.dev/flutter/dart-ui/ImageFilter-class.html>
///
/// <https://shopify.github.io/react-native-skia/docs/image-filters/overview>
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/image-filters>
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerImageFilter")]
pub struct ImageFilter(sys::ImpellerImageFilter);
unsafe impl Send for ImageFilter {}
unsafe impl Sync for ImageFilter {}
impl Clone for ImageFilter {
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerImageFilterRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for ImageFilter {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerImageFilterRelease(self.0);
        }
    }
}
impl ImageFilter {
    /// Creates an image filter that applies a Gaussian blur.
    ///
    /// The Gaussian blur applied may be an approximation for
    /// performance.
    ///
    /// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/image-filters#blurring-vector-graphics-and-bitmaps>
    ///
    /// <https://shopify.github.io/react-native-skia/docs/image-filters/blur>
    ///
    /// - x_sigma    The x sigma.
    /// - y_sigma    The y sigma.
    /// - tile_mode  The tile mode.
    ///
    /// @return     The image filter.
    #[doc(alias = "ImpellerImageFilterCreateBlurNew")]
    pub fn new_blur(x_sigma: f32, y_sigma: f32, tile_mode: TileMode) -> Self {
        let result = unsafe { sys::ImpellerImageFilterCreateBlurNew(x_sigma, y_sigma, tile_mode) };
        assert!(!result.is_null());
        Self(result)
    }
    /// Creates an image filter that enhances the per-channel pixel
    /// values to the maximum value in a circle around the pixel.
    ///
    /// <https://shopify.github.io/react-native-skia/docs/image-filters/morphology>
    ///
    /// - x_radius  The x radius.
    /// - y_radius  The y radius.
    ///
    /// @return     The image filter.
    #[doc(alias = "ImpellerImageFilterCreateDilateNew")]
    pub fn new_dilate(x_radius: f32, y_radius: f32) -> Self {
        let result = unsafe { sys::ImpellerImageFilterCreateDilateNew(x_radius, y_radius) };
        assert!(!result.is_null());
        Self(result)
    }
    /// Creates an image filter that dampens the per-channel pixel
    /// values to the minimum value in a circle around the pixel.
    ///
    /// <https://shopify.github.io/react-native-skia/docs/image-filters/morphology>
    ///
    /// - x_radius  The x radius.
    /// - y_radius  The y radius.
    ///
    /// @return     The image filter.
    #[doc(alias = "ImpellerImageFilterCreateErodeNew")]
    pub fn new_erode(x_radius: f32, y_radius: f32) -> Self {
        let result = unsafe { sys::ImpellerImageFilterCreateErodeNew(x_radius, y_radius) };
        assert!(!result.is_null());
        Self(result)
    }
    /// Creates an image filter that applies a transformation matrix to
    /// the underlying image.
    ///
    /// - matrix    The transformation matrix.
    /// - sampling  The image sampling mode.
    ///
    /// @return     The image filter.
    #[doc(alias = "ImpellerImageFilterCreateMatrixNew")]
    pub fn new_matrix(matrix: &Matrix, sampling: TextureSampling) -> Self {
        let result = unsafe { sys::ImpellerImageFilterCreateMatrixNew(cast_ref(matrix), sampling) };
        assert!(!result.is_null());
        Self(result)
    }

    //------------------------------------------------------------------------------
    /// Creates a composed filter that when applied is identical to
    /// subsequently applying the inner and then the outer filters.
    ///
    /// ```cpp
    /// destination = outer_filter(inner_filter(source))
    /// ```
    ///
    /// <https://shopify.github.io/react-native-skia/docs/image-filters/overview#composing-filters>
    ///
    /// - outer  The outer image filter.
    /// - inner  The inner image filter.
    ///
    /// @return     The combined image filter.
    #[doc(alias = "ImpellerImageFilterCreateComposeNew")]
    pub fn new_compose(outer: &Self, inner: &Self) -> Self {
        let result = unsafe { sys::ImpellerImageFilterCreateComposeNew(outer.0, inner.0) };
        assert!(!result.is_null());
        Self(result)
    }
}
/// Mask filters are functions that are applied over a shape after it has been
/// drawn but before it has been blended into the final image.
///
/// <https://api.flutter.dev/flutter/dart-ui/MaskFilter-class.html>
///
/// <https://shopify.github.io/react-native-skia/docs/mask-filters>
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/effects/mask-filters>
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerMaskFilter")]
pub struct MaskFilter(sys::ImpellerMaskFilter);
unsafe impl Send for MaskFilter {}
unsafe impl Sync for MaskFilter {}
impl Clone for MaskFilter {
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerMaskFilterRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for MaskFilter {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerMaskFilterRelease(self.0);
        }
    }
}
impl MaskFilter {
    //------------------------------------------------------------------------------
    /// Create a mask filter that blurs contents in the masked shape.
    ///
    /// <https://api.flutter.dev/flutter/dart-ui/MaskFilter/MaskFilter.blur.html>
    ///
    /// @see doc of struct [MaskFilter]
    ///
    /// - style  The style.
    /// - sigma  The sigma.
    ///
    /// @return     The mask filter.
    #[doc(alias = "ImpellerMaskFilterCreateBlurNew")]
    pub fn new_blur(style: BlurStyle, sigma: f32) -> Self {
        let result = unsafe { sys::ImpellerMaskFilterCreateBlurNew(style, sigma) };
        assert!(!result.is_null());
        Self(result)
    }
}
/// A fragment shader is a small program that is authored in GLSL and compiled using impellerc that runs on each pixel covered by a polygon and allows the user to configure how it is shaded.
///
/// @see <https://docs.flutter.dev/ui/design/graphics/fragment-shaders>
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerFragmentProgram")]
pub struct FragmentProgram(sys::ImpellerFragmentProgram);

unsafe impl Sync for FragmentProgram {}
unsafe impl Send for FragmentProgram {}
impl Clone for FragmentProgram {
    #[doc(alias = "ImpellerFragmentProgramRetain")]
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerFragmentProgramRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for FragmentProgram {
    #[doc(alias = "ImpellerFragmentProgramRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerFragmentProgramRelease(self.0);
        }
    }
}
impl FragmentProgram {
    /// Create a new fragment program using data obtained by compiling a GLSL shader with impellerc.
    /// # Safety
    /// The data provided MUST be compiled by impellerc.
    /// Providing raw GLSL strings is not supported.
    /// Impeller does not compile shaders at runtime.
    #[doc(alias = "ImpellerFragmentProgramNew")]
    pub unsafe fn new(glsl_shader_compiled_by_impellerc: Cow<'static, [u8]>) -> Option<Self> {
        let f = unsafe {
            let (mapping, userdata) =
                sys::ImpellerMapping::from_cow(glsl_shader_compiled_by_impellerc);
            sys::ImpellerFragmentProgramNew(&mapping, userdata)
        };
        if f.is_null() {
            None
        } else {
            Some(Self(f))
        }
    }
}
/// Typography contexts allow for the layout and rendering of text.
///
/// These are typically expensive to create and applications will only ever need
/// to create a single one of these during their lifetimes.
///
/// These hold the "font data" for building paragraphs.
/// You can optionally register custom fonts or just use the fonts
/// available on user's system.
///
/// Unlike graphics context, typograhy contexts are not thread-safe. These must
/// be created, used, and collected on a single thread.
///
/// @see [ParagraphStyle]
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerTypographyContext")]
pub struct TypographyContext(sys::ImpellerTypographyContext);
impl Drop for TypographyContext {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerTypographyContextRelease(self.0);
        }
    }
}
impl Default for TypographyContext {
    fn default() -> Self {
        let result = unsafe { sys::ImpellerTypographyContextNew() };
        assert!(!result.is_null());
        Self(result)
    }
}
impl TypographyContext {
    /// Register a custom font.
    ///
    /// The following font formats are supported:
    /// * OpenType font collections (.ttc extension)
    /// * TrueType fonts: (.ttf extension)
    /// * OpenType fonts: (.otf extension)
    ///
    /// @warning: Web Open Font Formats (.woff and .woff2 extensions) are **not**
    /// supported.
    ///
    /// The family alias name can be NULL. In such cases, the font
    /// family specified in paragraph styles must match the family that
    /// is specified in the font data.
    ///
    /// If the family name alias is not NULL, that family name must be
    /// used in the paragraph style to reference glyphs from this font
    /// instead of the one encoded in the font itself.
    ///
    /// Multiple fonts (with glyphs for different styles) can be
    /// specified with the same family.
    ///
    /// @see        [ParagraphStyle::set_font_family]
    ///
    /// - font_data: The contents.
    /// - family_name_alias: The family name alias or NULL if the one specified in the font data is to be used.
    ///
    /// @return     If the font could be successfully registered.
    #[doc(alias = "ImpellerTypographyContextRegisterFont")]
    pub fn register_font(
        &mut self,
        font_data: Cow<'static, [u8]>,
        family_name_alias: Option<&str>,
    ) -> Result<(), &'static str> {
        let family_name_alias = if let Some(s) = family_name_alias {
            Some(std::ffi::CString::new(s).map_err(|_| "the family name alias has a null byte")?)
        } else {
            None
        };

        let result = unsafe {
            // SAFETY: pass the correct userdata with the correct mapping. Here, we only have one pair, so, we are good.
            let (mapping, userdata) = sys::ImpellerMapping::from_cow(font_data);
            sys::ImpellerTypographyContextRegisterFont(
                self.0,
                &mapping,
                userdata,
                family_name_alias
                    .as_ref()
                    .map_or(std::ptr::null(), |s| s.as_ptr()),
            )
        };
        // explicit drop to ensure that it's not dropped before this point.
        // When I first wrote this function, I used family_name_alias.map(|s|s.as_ptr()) in the previous line, which would have been UB :/
        std::mem::drop(family_name_alias);
        result.then_some(()).ok_or("Failed to register font")
    }
}

/// An immutable, fully laid out paragraph.
///
///
/// <https://shopify.github.io/react-native-skia/docs/text/paragraph>
///
/// @see [ParagraphStyle] and [ParagraphBuilder]
///
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerParagraph")]
pub struct Paragraph(sys::ImpellerParagraph);
unsafe impl Send for Paragraph {}
unsafe impl Sync for Paragraph {}
impl Clone for Paragraph {
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerParagraphRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for Paragraph {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerParagraphRelease(self.0);
        }
    }
}
impl Paragraph {
    //------------------------------------------------------------------------------
    /// @see        [Self::get_min_intrinsic_width]
    ///
    /// The width provided to the paragraph builder during the call to
    /// layout. This is the maximum width any line in the laid out
    /// paragraph can occupy. But, it is not necessarily the actual
    ///             width of the paragraph after layout.
    #[doc(alias = "ImpellerParagraphGetMaxWidth")]
    pub fn get_max_width(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetMaxWidth(self.0) }
    }
    //------------------------------------------------------------------------------
    /// The height of the laid out paragraph. This is **not** a tight
    /// bounding box and some glyphs may not reach the minimum location
    /// they are allowed to reach.
    #[doc(alias = "ImpellerParagraphGetHeight")]
    pub fn get_height(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetHeight(self.0) }
    }
    //------------------------------------------------------------------------------
    /// The length of the longest line in the paragraph. This is the
    /// horizontal distance between the left edge of the leftmost glyph
    /// and the right edge of the rightmost glyph, in the longest line
    /// in the paragraph.
    #[doc(alias = "ImpellerParagraphGetLongestLineWidth")]
    pub fn get_longest_line_width(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetLongestLineWidth(self.0) }
    }
    //------------------------------------------------------------------------------
    /// @see        [Self::get_max_width]
    ///
    /// The actual width of the longest line in the paragraph after
    /// layout. This is expected to be less than or equal to
    /// [Self::get_max_width].
    #[doc(alias = "ImpellerParagraphGetMinIntrinsicWidth")]
    pub fn get_min_intrinsic_width(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetMinIntrinsicWidth(self.0) }
    }
    //------------------------------------------------------------------------------
    /// The width of the paragraph without line breaking.
    #[doc(alias = "ImpellerParagraphGetMaxIntrinsicWidth")]
    pub fn get_max_intrinsic_width(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetMaxIntrinsicWidth(self.0) }
    }
    //------------------------------------------------------------------------------
    /// The distance from the top of the paragraph to the ideographic
    /// baseline of the first line when using ideographic fonts
    /// (Japanese, Korean, etc...).
    #[doc(alias = "ImpellerParagraphGetIdeographicBaseline")]
    pub fn get_ideographic_baseline(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetIdeographicBaseline(self.0) }
    }
    //------------------------------------------------------------------------------
    /// The distance from the top of the paragraph to the alphabetic
    /// baseline of the first line when using alphabetic fonts (A-Z,
    /// a-z, Greek, etc...).
    #[doc(alias = "ImpellerParagraphGetAlphabeticBaseline")]
    pub fn get_alphabetic_baseline(&self) -> f32 {
        unsafe { sys::ImpellerParagraphGetAlphabeticBaseline(self.0) }
    }
    //------------------------------------------------------------------------------
    /// The number of lines visible in the paragraph after line
    /// breaking.
    #[doc(alias = "ImpellerParagraphGetLineCount")]
    pub fn get_line_count(&self) -> u32 {
        unsafe { sys::ImpellerParagraphGetLineCount(self.0) }
    }
    /// Get the range into the UTF-16 code unit buffer that represents
    /// the word at the specified caret location in the same buffer.
    ///
    /// Word boundaries are defined more precisely in [Unicode Standard
    /// Annex #29](http://www.unicode.org/reports/tr29/#Word_Boundaries)
    ///
    /// * code_unit_index The code unit index
    ///
    /// * return The impeller range.
    #[doc(alias = "ImpellerParagraphGetWordBoundary")]
    pub fn get_word_boundary_utf16(&self, code_unit_index: usize) -> Range {
        let mut range = Range::default();
        unsafe { sys::ImpellerParagraphGetWordBoundary(self.0, code_unit_index, &raw mut range) };
        range
    }

    //------------------------------------------------------------------------------
    /// Get the line metrics of this laid out paragraph. Calculating the
    /// line metrics is expensive. The first time line metrics are
    /// requested, they will be cached along with the paragraph (which
    /// is immutable).
    ///
    /// * return The line metrics.
    #[doc(alias = "ImpellerParagraphGetLineMetrics")]
    pub fn get_line_metrics(&self) -> Option<LineMetrics> {
        let ptr = unsafe { sys::ImpellerParagraphGetLineMetrics(self.0) };
        if ptr.is_null() {
            None
        } else {
            // safety: https://github.com/flutter/flutter/tree/master/engine/src/flutter/impeller/toolkit/interop#reference-management
            // only functions that end with `new` return an object with reference count 1
            // All other functions return "borrowed" objects, so,
            // we increment ref count to get an "owned" version
            unsafe { sys::ImpellerLineMetricsRetain(ptr) };
            Some(LineMetrics(ptr))
        }
    }
    //------------------------------------------------------------------------------
    /// Create a new instance of glyph info that can be queried for
    /// information about the glyph at the given UTF-16 code unit index.
    /// The instance must be freed using `ImpellerGlyphInfoRelease`.
    ///
    /// * code_unit_index  The UTF-16 code unit index.
    ///
    /// * return     The glyph information.
    #[doc(alias = "ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew")]
    pub fn create_glyph_info_at_code_unit_index_utf16(
        &self,
        code_unit_index: usize,
    ) -> Option<GlyphInfo> {
        let ptr = unsafe {
            sys::ImpellerParagraphCreateGlyphInfoAtCodeUnitIndexNew(self.0, code_unit_index)
        };
        if ptr.is_null() {
            None
        } else {
            Some(GlyphInfo(ptr))
        }
    }

    //------------------------------------------------------------------------------
    /// Create a new instance of glyph info that can be queried for
    /// information about the glyph closest to the specified coordinates
    /// relative to the origin of the paragraph. The instance must be
    /// freed using `ImpellerGlyphInfoRelease`.
    ///
    /// * x          The x coordinate relative to paragraph origin.
    /// * y          The x coordinate relative to paragraph origin.
    ///
    /// * return     The glyph information.
    #[doc(alias = "ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew")]
    pub fn create_glyph_info_at_paragraph_coordinates(&self, x: f64, y: f64) -> Option<GlyphInfo> {
        let ptr =
            unsafe { sys::ImpellerParagraphCreateGlyphInfoAtParagraphCoordinatesNew(self.0, x, y) };
        if ptr.is_null() {
            None
        } else {
            Some(GlyphInfo(ptr))
        }
    }
}

/// Describes the metrics of lines in a fully laid out paragraph.
///
/// Regardless of how the string of text is specified to the paragraph builder,
/// offsets into buffers that are returned by line metrics are always assumed to be
/// into buffers of UTF-16 code units.
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerLineMetrics")]
pub struct LineMetrics(sys::ImpellerLineMetrics);
unsafe impl Send for LineMetrics {}
unsafe impl Sync for LineMetrics {}
impl Clone for LineMetrics {
    #[doc(alias = "ImpellerLineMetricsRetain")]
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerLineMetricsRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for LineMetrics {
    #[doc(alias = "ImpellerLineMetricsRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerLineMetricsRelease(self.0);
        }
    }
}
impl LineMetrics {
    //------------------------------------------------------------------------------
    /// The rise from the baseline as calculated from the font and style
    /// for this line ignoring the height from the text style.
    ///
    /// * line     The line index (zero based).
    ///
    /// @return     The unscaled ascent.
    #[doc(alias = "ImpellerLineMetricsGetUnscaledAscent")]
    pub fn get_unscaled_ascent(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetUnscaledAscent(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// The rise from the baseline as calculated from the font and style
    /// for this line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The ascent.
    ///
    #[doc(alias = "ImpellerLineMetricsGetAscent")]
    pub fn get_ascent(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetAscent(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// The drop from the baseline as calculated from the font and style
    /// for this line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The descent.
    #[doc(alias = "ImpellerLineMetricsGetDescent")]
    pub fn get_descent(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetDescent(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// The y coordinate of the baseline for this line from the top of
    /// the paragraph.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The baseline.
    ///
    #[doc(alias = "ImpellerLineMetricsGetBaseline")]
    pub fn get_baseline(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetBaseline(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// Used to determine if this line ends with an explicit line break
    /// (e.g. '\n') or is the end of the paragraph.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     True if the line is a hard break.
    #[doc(alias = "ImpellerLineMetricsIsHardbreak")]
    pub fn is_hardbreak(&self, line: usize) -> bool {
        unsafe { sys::ImpellerLineMetricsIsHardbreak(self.0, line) }
    }

    //------------------------------------------------------------------------------
    /// Width of the line from the left edge of the leftmost glyph to
    /// the right edge of the rightmost glyph.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The width.
    #[doc(alias = "ImpellerLineMetricsGetWidth")]
    pub fn get_width(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetWidth(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// Total height of the line from the top edge to the bottom edge.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The height.
    #[doc(alias = "ImpellerLineMetricsGetHeight")]
    pub fn get_height(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetHeight(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// @brief      The x coordinate of left edge of the line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The left edge coordinate.
    #[doc(alias = "ImpellerLineMetricsGetLeft")]
    pub fn get_left(&self, line: usize) -> f64 {
        unsafe { sys::ImpellerLineMetricsGetLeft(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// Fetch the start index in the buffer of UTF-16 code units used to
    /// represent the paragraph line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The UTF-16 code units start index.
    #[doc(alias = "ImpellerLineMetricsGetCodeUnitStartIndex")]
    pub fn get_code_unit_start_index_utf16(&self, line: usize) -> usize {
        unsafe { sys::ImpellerLineMetricsGetCodeUnitStartIndex(self.0, line) }
    }

    //------------------------------------------------------------------------------
    /// Fetch the end index in the buffer of UTF-16 code units used to
    /// represent the paragraph line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The UTF-16 code units end index.
    #[doc(alias = "ImpellerLineMetricsGetCodeUnitEndIndex")]
    pub fn get_code_unit_end_index_utf16(&self, line: usize) -> usize {
        unsafe { sys::ImpellerLineMetricsGetCodeUnitEndIndex(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// Fetch the end index (excluding whitespace) in the buffer of
    /// UTF-16 code units used to represent the paragraph line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The UTF-16 code units end index excluding whitespace.
    #[doc(alias = "ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace")]
    pub fn get_code_unit_end_index_excluding_whitespace_utf16(&self, line: usize) -> usize {
        unsafe { sys::ImpellerLineMetricsGetCodeUnitEndIndexExcludingWhitespace(self.0, line) }
    }
    //------------------------------------------------------------------------------
    /// Fetch the end index (including newlines) in the buffer of
    /// UTF-16 code units used to represent the paragraph line.
    ///
    /// * line     The line index (zero based).
    ///
    /// * return     The UTF-16 code units end index including newlines.
    #[doc(alias = "ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline")]
    pub fn get_code_unit_end_index_including_newline_utf16(&self, line: usize) -> usize {
        unsafe { sys::ImpellerLineMetricsGetCodeUnitEndIndexIncludingNewline(self.0, line) }
    }
}
/// Describes the metrics of glyphs in a paragraph line.
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerGlyphInfo")]
pub struct GlyphInfo(sys::ImpellerGlyphInfo);
impl Clone for GlyphInfo {
    #[doc(alias = "ImpellerGlyphInfoRetain")]
    fn clone(&self) -> Self {
        unsafe { sys::ImpellerGlyphInfoRetain(self.0) };
        GlyphInfo(self.0)
    }
}
unsafe impl Send for GlyphInfo {}
unsafe impl Sync for GlyphInfo {}
impl Drop for GlyphInfo {
    #[doc(alias = "ImpellerGlyphInfoRelease")]
    fn drop(&mut self) {
        unsafe { sys::ImpellerGlyphInfoRelease(self.0) };
    }
}
impl GlyphInfo {
    /// Fetch the start index in the buffer of UTF-16 code units used to
    /// represent the grapheme cluster for a glyph.
    ///
    /// * return     The UTF-16 code units start index.
    #[doc(alias = "ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin")]
    pub fn get_grapheme_cluster_code_unit_range_begin_utf16(&self) -> usize {
        unsafe { sys::ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeBegin(self.0) }
    }
    /// Fetch the end index in the buffer of UTF-16 code units used to
    /// represent the grapheme cluster for a glyph.
    ///
    /// * return     The UTF-16 code units end index.
    #[doc(alias = "ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd")]
    pub fn get_grapheme_cluster_code_unit_range_end_utf16(&self) -> usize {
        unsafe { sys::ImpellerGlyphInfoGetGraphemeClusterCodeUnitRangeEnd(self.0) }
    }
    /// Fetch the bounds of the grapheme cluster for the glyph in the
    /// coordinate space of the paragraph.
    ///
    /// * return     The grapheme cluster bounds.
    #[doc(alias = "ImpellerGlyphInfoGetGraphemeClusterBounds")]
    pub fn get_grapheme_cluster_bounds(&self) -> Rect {
        let mut rect = crate::sys::ImpellerRect::default();
        unsafe { sys::ImpellerGlyphInfoGetGraphemeClusterBounds(self.0, &raw mut rect) };
        cast(rect)
    }
    /// * return True if the glyph represents an ellipsis. False otherwise.
    #[doc(alias = "ImpellerGlyphInfoIsEllipsis")]
    pub fn is_ellipsis(&self) -> bool {
        unsafe { sys::ImpellerGlyphInfoIsEllipsis(self.0) }
    }
    /// * return The direction of the run that contains the glyph.
    #[doc(alias = "ImpellerGlyphInfoGetTextDirection")]
    pub fn get_text_direction(&self) -> TextDirection {
        unsafe { sys::ImpellerGlyphInfoGetTextDirection(self.0) }
    }
}
/// Paragraph builders allow for the creation of fully laid out paragraphs
/// (which themselves are immutable).
///
/// This is not thread-safe, as TypoGraphy context is not thread-safe. But
/// [Paragraph] is thread-safe.
///
/// <https://api.flutter.dev/flutter/dart-ui/ParagraphBuilder-class.html>
///
/// To build a paragraph, users push/pop paragraph styles onto a stack then add
/// UTF-8 encoded text. The properties on the top of paragraph style stack when
/// the text is added are used to layout and shape that subset of the paragraph.
///
/// @see      [ParagraphStyle]
///
/// ```
/// # use impellers::{TypographyContext, ParagraphStyle, ParagraphBuilder};
/// // this contains the fonts from user's system (or you can add custom fonts)
/// let fonts = TypographyContext::default();
/// // style decides the appearance of the text
/// let mut style = ParagraphStyle::default();
/// style.set_font_family("Arial");
/// style.set_font_size(12.0);
/// let mut builder = ParagraphBuilder::new(&fonts).expect("failed to create para builder");
/// builder.push_style(&style); // DON'T forget to set the style before adding text
/// builder.add_text("Hello, world!\n");
/// style.set_font_size(24.0);
/// builder.push_style(&style);
/// builder.add_text("Big World!\n"); // 24.0 font size
/// builder.pop_style(); // the 24.0 style is popped off. the previous 12.0 style is used
/// builder.add_text("Small World!\n"); // 12.0 font size
/// let paragraph = builder.build(100.0).expect("building paragraph failed");
/// ```
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerParagraphBuilder")]
pub struct ParagraphBuilder(sys::ImpellerParagraphBuilder);
impl Drop for ParagraphBuilder {
    #[doc(alias = "ImpellerParagraphBuilderRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerParagraphBuilderRelease(self.0);
        }
    }
}

impl ParagraphBuilder {
    //------------------------------------------------------------------------------
    /// Create a new paragraph builder.
    ///
    /// @return     The paragraph builder.
    #[doc(alias = "ImpellerParagraphBuilderNew")]
    pub fn new(context: &TypographyContext) -> Option<ParagraphBuilder> {
        let result = unsafe { sys::ImpellerParagraphBuilderNew(context.0) };
        (!result.is_null()).then_some(ParagraphBuilder(result))
    }
    //------------------------------------------------------------------------------
    /// Push a new paragraph style onto the paragraph style stack
    /// managed by the paragraph builder.
    ///
    /// Not all paragraph styles can be combined. For instance, it does
    /// not make sense to mix text alignment for different text runs
    /// within a paragraph. In such cases, the preference of the the
    /// first paragraph style on the style stack will take hold.
    ///
    /// If text is pushed onto the paragraph builder without a style
    /// previously pushed onto the stack, a default paragraph text style
    /// will be used. This may not always be desirable because some
    /// style element cannot be overridden. It is recommended that a
    /// default paragraph style always be pushed onto the stack before
    /// the addition of any text.
    ///
    /// - style              The style.
    #[doc(alias = "ImpellerParagraphBuilderPushStyle")]
    pub fn push_style(&mut self, style: &ParagraphStyle) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphBuilderPushStyle(self.0, style.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Pop a previously pushed paragraph style from the paragraph style
    /// stack.
    ///
    #[doc(alias = "ImpellerParagraphBuilderPopStyle")]
    pub fn pop_style(&mut self) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphBuilderPopStyle(self.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Add UTF-8 encoded text to the paragraph. The text will be styled
    /// according to the paragraph style already on top of the paragraph
    /// style stack.
    #[doc(alias = "ImpellerParagraphBuilderAddText")]
    pub fn add_text(&mut self, text: &str) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphBuilderAddText(
                self.0,
                text.as_ptr(),
                text.len().try_into().unwrap(),
            );
        }
        self
    }

    //------------------------------------------------------------------------------
    /// Layout and build a new paragraph using the specified width. The
    /// resulting paragraph is immutable. The paragraph builder must be
    /// discarded and a new one created to build more paragraphs.
    ///
    /// - width              The paragraph width.
    ///
    /// @return     The paragraph if one can be created, NULL otherwise.
    #[must_use]
    #[doc(alias = "ImpellerParagraphBuilderBuildParagraphNew")]
    pub fn build(self, width: f32) -> Option<Paragraph> {
        let result = unsafe { sys::ImpellerParagraphBuilderBuildParagraphNew(self.0, width) };
        (!result.is_null()).then_some(Paragraph(result))
    }
}

/// Specified when building a paragraph, paragraph styles are managed in a stack
/// with specify text properties to apply to text that is added to the paragraph
/// builder.
///
/// The below link should be considered a full reference of what's possible with text.
///
/// <https://api.flutter.dev/flutter/painting/TextStyle-class.html>
///
/// @see [Paragraph] and [ParagraphBuilder]
///
#[derive(Debug)]
#[repr(transparent)]
#[doc = "ImpellerParagraphStyle"]
pub struct ParagraphStyle(sys::ImpellerParagraphStyle);
unsafe impl Send for ParagraphStyle {}
unsafe impl Sync for ParagraphStyle {}
impl Drop for ParagraphStyle {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerParagraphStyleRelease(self.0);
        }
    }
}
impl Default for ParagraphStyle {
    fn default() -> Self {
        let result = unsafe { sys::ImpellerParagraphStyleNew() };
        assert!(!result.is_null());
        Self(result)
    }
}
impl ParagraphStyle {
    /// Set the paint used to render the text glyph contents.
    ///
    /// - paint            The paint.
    #[doc(alias = "ImpellerParagraphStyleSetForeground")]
    pub fn set_foreground(&mut self, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetForeground(self.0, paint.0);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Set the paint used to render the background of the text glyphs.
    ///
    /// - paint            The paint.
    #[doc(alias = "ImpellerParagraphStyleSetBackground")]
    pub fn set_background(&mut self, paint: &Paint) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetBackground(self.0, paint.0);
        }
        self
    }
    /// Set the weight of the font to select when rendering glyphs.
    ///
    /// - weight           The weight.
    #[doc(alias = "ImpellerParagraphStyleSetFontWeight")]
    pub fn set_font_weight(&mut self, weight: FontWeight) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetFontWeight(self.0, weight);
        }
        self
    }
    /// Set whether the glyphs should be bolded or italicized.
    ///
    /// - style            The style.
    #[doc(alias = "ImpellerParagraphStyleSetFontStyle")]
    pub fn set_font_style(&mut self, style: FontStyle) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetFontStyle(self.0, style);
        }
        self
    }
    /// Set the font family.
    ///
    /// <https://api.flutter.dev/flutter/painting/TextStyle/fontFamily.html>
    ///
    /// - family_name      The family name.
    #[doc(alias = "ImpellerParagraphStyleSetFontFamily")]
    pub fn set_font_family(&mut self, family_name: &str) -> &mut Self {
        let family_name =
            std::ffi::CString::new(family_name).expect("failed to create Cstring from family name");
        unsafe {
            sys::ImpellerParagraphStyleSetFontFamily(self.0, family_name.as_ptr());
        }
        std::mem::drop(family_name);
        self
    }
    /// Set the font size.
    ///
    /// <https://api.flutter.dev/flutter/painting/TextStyle/fontSize.html>
    ///
    /// - size             The size.
    #[doc(alias = "ImpellerParagraphStyleSetFontSize")]
    pub fn set_font_size(&mut self, size: f32) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetFontSize(self.0, size);
        }
        self
    }
    /// The height of the text as a multiple of text size.
    ///
    /// <https://api.flutter.dev/flutter/painting/TextStyle/height.html>
    ///
    /// When height is 0.0, the line height will be determined by the
    /// font's metrics directly, which may differ from the font size.
    /// Otherwise the line height of the text will be a multiple of font
    /// size, and be exactly fontSize * height logical pixels tall.
    ///
    /// - height           The height.
    #[doc(alias = "ImpellerParagraphStyleSetHeight")]
    pub fn set_height(&mut self, height: f32) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetHeight(self.0, height);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Set the alignment of text within the paragraph.
    ///
    /// - align            The align.
    #[doc(alias = "ImpellerParagraphStyleSetTextAlignment")]
    pub fn set_text_alignment(&mut self, align: TextAlignment) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetTextAlignment(self.0, align);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Set the directionality of the text within the paragraph.
    ///
    /// - direction        The direction.
    #[doc(alias = "ImpellerParagraphStyleSetTextDirection")]
    pub fn set_text_direction(&mut self, direction: TextDirection) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetTextDirection(self.0, direction);
        }
        self
    }
    /// Set one of more text decorations on the paragraph. Decorations
    /// can be underlines, overlines, strikethroughs, etc.. The style of
    /// decorations can be set as well (dashed, dotted, wavy, etc..)
    ///
    /// A mask of `ImpellerTextDecorationType`s to enable.
    /// int types;
    /// The decoration color.
    ///   ImpellerColor color;
    /// The decoration style.
    ///   ImpellerTextDecorationStyle style;
    /// The multiplier applied to the default thickness of the font to use for the
    /// decoration.
    ///   float thickness_multiplier;
    #[doc(alias = "ImpellerParagraphStyleSetTextDecoration")]
    pub fn set_text_decoration(
        &mut self,
        decoration_type: TextDecorationType,
        color: &Color,
        style: TextDecorationStyle,
        thickness_multiplier: f32,
    ) -> &mut Self {
        let decoration = sys::ImpellerTextDecoration {
            types: decoration_type.bits(),
            style,
            color: *color,
            thickness_multiplier,
        };
        unsafe {
            sys::ImpellerParagraphStyleSetTextDecoration(self.0, &raw const decoration);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Set the maximum line count within the paragraph.
    ///
    /// - max_lines        The maximum lines.
    #[doc(alias = "ImpellerParagraphStyleSetMaxLines")]
    pub fn set_max_lines(&mut self, max_lines: u32) -> &mut Self {
        unsafe {
            sys::ImpellerParagraphStyleSetMaxLines(self.0, max_lines);
        }
        self
    }
    //------------------------------------------------------------------------------
    /// Set the paragraph locale.
    ///
    /// <https://api.flutter.dev/flutter/painting/TextStyle/locale.html>
    ///
    /// - locale           The locale.
    #[doc(alias = "ImpellerParagraphStyleSetLocale")]
    pub fn set_locale(&mut self, locale: &str) -> &mut Self {
        let locale = std::ffi::CString::new(locale).expect("failed to create Cstring from locale");
        unsafe {
            sys::ImpellerParagraphStyleSetLocale(self.0, locale.as_ptr());
        }
        std::mem::drop(locale);
        self
    }
    //------------------------------------------------------------------------------
    /// Set the UTF-8 string to use as the ellipsis. Pass nullptr to clear the setting to default.
    ///
    /// <https://api.flutter.dev/flutter/painting/TextStyle/ellipsis.html>
    ///
    /// - ellipsis         The ellipsis string UTF-8 data, or null.
    #[doc(alias = "ImpellerParagraphStyleSetEllipsis")]
    pub fn set_ellipsis(&mut self, ellipsis: Option<&str>) -> &mut Self {
        let ellipsis = ellipsis.map(|ellipsis| {
            std::ffi::CString::new(ellipsis).expect("failed to create cstr from ellipsis str")
        });
        unsafe {
            sys::ImpellerParagraphStyleSetEllipsis(
                self.0,
                ellipsis
                    .as_ref()
                    .map(|c| c.as_ptr())
                    .unwrap_or(std::ptr::null()),
            );
        }
        std::mem::drop(ellipsis);
        self
    }
}
/// Represents a two-dimensional path that is immutable and graphics context
/// agnostic.
///
/// <https://api.flutter.dev/flutter/dart-ui/Path-class.html>
///
/// <https://learn.microsoft.com/en-us/previous-versions/xamarin/xamarin-forms/user-interface/graphics/skiasharp/paths/paths>
///
/// <https://shopify.github.io/react-native-skia/docs/shapes/path>
///
/// Paths in Impeller consist of linear, cubic Bézier curve, and quadratic
/// Bézier curve segments. All other shapes are approximations using these
/// building blocks.
///
/// Paths are created using path builder that allow for the configuration of the
/// path segments, how they are filled, and/or stroked.
#[derive(Debug)]
#[repr(transparent)]
#[doc(alias = "ImpellerPath")]
pub struct Path(sys::ImpellerPath);
unsafe impl Send for Path {}
unsafe impl Sync for Path {}
impl Clone for Path {
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerPathRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for Path {
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerPathRelease(self.0);
        }
    }
}
impl Path {
    /// Get the bounds of the path.
    ///
    /// The bounds are conservative.
    /// That is, they may be larger than the actual shape of the path and could include the control points and isolated calls to move the cursor.
    #[doc(alias = "ImpellerPathGetBounds")]
    pub fn get_bounds(&self) -> Rect {
        let mut rect = sys::ImpellerRect::default();
        unsafe {
            sys::ImpellerPathGetBounds(self.0, &raw mut rect);
        }
        cast(rect)
    }
}
/// Path builders allow for the incremental building up of paths.
///
/// @see docs of [Path]
#[derive(Debug)]
#[repr(transparent)]
#[doc = "ImpellerPathBuilder"]
pub struct PathBuilder(sys::ImpellerPathBuilder);
unsafe impl Send for PathBuilder {}
unsafe impl Sync for PathBuilder {}
impl Drop for PathBuilder {
    #[doc(alias = "ImpellerPathBuilderRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerPathBuilderRelease(self.0);
        }
    }
}
impl Default for PathBuilder {
    /// Create a new path builder. Paths themselves are immutable.
    /// A builder builds these immutable paths.
    #[doc(alias = "ImpellerPathBuilderNew")]
    fn default() -> Self {
        let p = unsafe { sys::ImpellerPathBuilderNew() };
        assert!(!p.is_null());
        Self(p)
    }
}
impl PathBuilder {
    /// Move the cursor to the specified location.
    ///
    /// -  location  The location.
    #[doc = "ImpellerPathBuilderMoveTo"]
    pub fn move_to(&mut self, location: Point) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderMoveTo(self.0, cast_ref(&location));
        }
        self
    }
    /// Add a line segment from the current cursor location to the given
    /// location. The cursor location is updated to be at the endpoint.
    ///
    /// - location  The location.
    #[doc = "ImpellerPathBuilderLineTo"]
    pub fn line_to(&mut self, location: Point) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderLineTo(self.0, cast_ref(&location));
        }
        self
    }

    /// Add a quadratic curve from whose start point is the cursor to
    /// the specified end point using the a single control point.
    ///
    /// The new location of the cursor after this call is the end point.
    ///
    /// - control_point  The control point.
    /// - end_point      The end point.
    #[doc = "ImpellerPathBuilderQuadraticCurveTo"]
    pub fn quadratic_curve_to(&mut self, control_point: Point, end_point: Point) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderQuadraticCurveTo(
                self.0,
                cast_ref(&control_point),
                cast_ref(&end_point),
            );
        }
        self
    }
    /// Add a cubic curve whose start point is current cursor location
    /// to the specified end point using the two specified control
    /// points.
    ///
    /// The new location of the cursor after this call is the end point
    /// supplied.
    ///
    /// - control_point_1  The control point 1
    /// - control_point_2  The control point 2
    /// - end_point        The end point
    #[doc = "ImpellerPathBuilderCubicCurveTo"]
    pub fn cubic_curve_to(
        &mut self,
        control_point_1: Point,
        control_point_2: Point,
        end_point: Point,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderCubicCurveTo(
                self.0,
                cast_ref(&control_point_1),
                cast_ref(&control_point_2),
                cast_ref(&end_point),
            );
        }
        self
    }
    /// Adds a rectangle to the path.
    ///
    /// - rect     The rectangle.
    #[doc = "ImpellerPathBuilderAddRect"]
    pub fn add_rect(&mut self, rect: &Rect) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderAddRect(self.0, cast_ref(rect));
        }
        self
    }
    /// Add an arc to the path.
    ///
    /// - oval_bounds          The oval bounds.
    /// - start_angle_degrees  The start angle in degrees.
    /// - end_angle_degrees    The end angle in degrees.
    #[doc = "ImpellerPathBuilderAddArc"]
    pub fn add_arc(
        &mut self,
        oval_bounds: &Rect,
        start_angle_degrees: f32,
        end_angle_degrees: f32,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderAddArc(
                self.0,
                cast_ref(oval_bounds),
                start_angle_degrees,
                end_angle_degrees,
            );
        }
        self
    }

    /// Add an oval to the path.
    ///
    /// - oval_bounds  The oval bounds.
    #[doc = "ImpellerPathBuilderAddOval"]
    pub fn add_oval(&mut self, oval_bounds: &Rect) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderAddOval(self.0, cast_ref(oval_bounds));
        }
        self
    }
    /// Add a rounded rect with potentially non-uniform radii to the path.
    ///
    /// - oval_bounds     The oval bounds.
    /// - rounding_radii  The rounding radii.
    #[doc = "ImpellerPathBuilderAddRoundedRect"]
    pub fn add_rounded_rect(
        &mut self,
        oval_bounds: &Rect,
        rounding_radii: &RoundingRadii,
    ) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderAddRoundedRect(
                self.0,
                cast_ref(oval_bounds),
                &rounding_radii.into(),
            );
        }
        self
    }
    /// Close the path.
    #[doc = "ImpellerPathBuilderClose"]
    pub fn close(&mut self) -> &mut Self {
        unsafe {
            sys::ImpellerPathBuilderClose(self.0);
        }
        self
    }

    /// Create a new path by copying the existing built-up path. The
    /// existing path can continue being added to.
    ///
    /// - fill  The fill.
    ///
    /// @return     The impeller path.
    #[doc = "ImpellerPathBuilderCopyPathNew"]
    pub fn copy_path_new(&mut self, fill: FillType) -> Path {
        let p = unsafe { sys::ImpellerPathBuilderCopyPathNew(self.0, fill) };
        assert!(!p.is_null());
        Path(p)
    }
    /// Create a new path using the existing built-up path. The existing
    /// path builder now contains an empty path.
    ///
    /// - fill  The fill.
    ///
    /// @return     The impeller path.
    #[doc = "ImpellerPathBuilderTakePathNew"]
    pub fn take_path_new(&mut self, fill: FillType) -> Path {
        let p = unsafe { sys::ImpellerPathBuilderTakePathNew(self.0, fill) };
        assert!(!p.is_null());
        Path(p)
    }
}
/// A surface represents a render target for Impeller to direct the rendering
/// intent specified the form of display lists to.
///
/// Render targets are how Impeller API users perform Window System Integration
/// (WSI). Users wrap swapchain images as surfaces and draw display lists onto
/// these surfaces to present content.
///
/// Creating surfaces is typically platform and client-rendering-API specific.
///
/// This is an inherently "temporary" object. Just create one every frame and
/// destroy it after presenting.
#[derive(Debug)]
#[repr(transparent)]
#[doc = "ImpellerSurface"]
pub struct Surface(sys::ImpellerSurface);

impl Drop for Surface {
    #[doc(alias = "ImpellerSurfaceRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerSurfaceRelease(self.0);
        }
    }
}

impl Surface {
    /// Draw a display list onto the surface. The same display list can
    /// be drawn multiple times to different surfaces. BUT, you cannot
    /// draw multiple display lists to the same surface.
    ///
    /// To be specific, each call to [Surface::draw_display_list] will clear
    /// the contents of the surface. So, any previous drawing will be
    /// lost.
    ///
    /// @warning    In the OpenGL backend, Impeller will not make an effort to
    ///             preserve the OpenGL state that is current in the context.
    ///             Embedders that perform additional OpenGL operations in the
    ///             context should expect the reset state after control transitions
    ///             back to them. Key state to watch out for would be the viewports,
    ///             stencil rects, test toggles, resource (texture, framebuffer,
    ///             buffer) bindings, etc...
    ///
    /// - display_list  The display list to draw onto the surface.
    ///
    /// @return     If the display list could be drawn onto the surface.
    #[doc = "ImpellerSurfaceDrawDisplayList"]
    pub fn draw_display_list(&mut self, display_list: &DisplayList) -> Result<(), &'static str> {
        unsafe { sys::ImpellerSurfaceDrawDisplayList(self.0, display_list.0) }
            .then_some(())
            .ok_or("failed to draw to surface")
    }
    /// Present the surface to the underlying window system.
    ///
    /// This is for platforms like Vulkan which acquire a a surface from [VkSwapChain].
    ///
    /// For OpenGL, use your windowing library's `SwapBuffers`-like function.
    ///
    /// @return     Ok if the surface could be presented.
    #[doc = "ImpellerSurfacePresent"]
    pub fn present(self) -> Result<(), &'static str> {
        unsafe { sys::ImpellerSurfacePresent(self.0) }
            .then_some(())
            .ok_or("failed to present surface")
    }
}
/// A reference to a texture whose data is resident on the GPU. These can be
/// referenced in draw calls and paints.
///
/// Creating textures is extremely expensive. Creating a single one can
/// typically comfortably blow the frame budget of an application. Textures
/// should be created on background threads.
///
///
/// @warning    While textures themselves are thread safe, some context types
///             (like OpenGL) may need extra configuration to be able to operate
///             from multiple threads.
#[derive(Debug)]
#[repr(transparent)]
#[doc = "ImpellerTexture"]
pub struct Texture(sys::ImpellerTexture);
unsafe impl Sync for Texture {}
unsafe impl Send for Texture {}
impl Clone for Texture {
    #[doc(alias = "ImpellerTextureRetain")]
    fn clone(&self) -> Self {
        unsafe {
            sys::ImpellerTextureRetain(self.0);
        }
        Self(self.0)
    }
}
impl Drop for Texture {
    #[doc(alias = "ImpellerTextureRelease")]
    fn drop(&mut self) {
        unsafe {
            sys::ImpellerTextureRelease(self.0);
        }
    }
}
impl Texture {
    /// Get the OpenGL handle associated with this texture. If this is
    /// not an OpenGL texture, this method will always return 0.
    ///
    /// OpenGL handles are lazily created, this method will return
    /// GL_NONE if no OpenGL handle is available. To ensure that this
    /// call eagerly creates an OpenGL texture, call this on a thread
    /// where Impeller knows there is an OpenGL context available.
    ///
    /// @return     The OpenGL handle if one is available, GL_NONE otherwise.
    ///
    /// # Safety
    /// READ the docs that it may return GL_NONE (which may not be zero).
    /// use opengl constants to compare the return value properly.
    #[doc = "ImpellerTextureGetOpenGLHandle"]
    pub fn get_opengl_handle(&self) -> u64 {
        unsafe { sys::ImpellerTextureGetOpenGLHandle(self.0) }
    }
}

/// based on the size, it will calculate a suitable mipcount.
/// This function skips 1x1 mip levels because that's what flutter does.
pub fn flutter_mip_count(width: f32, height: f32) -> u32 {
    // https://github.com/flutter/engine/blob/main/impeller/geometry/size.h#L134

    let mut result = width.log2().ceil().max(height.log2().ceil()) as u32;
    // This check avoids creating 1x1 mip levels, which are both pointless
    // and cause rendering problems on some Adreno GPUs.
    // See:
    //      * https://github.com/flutter/flutter/issues/160441
    //      * https://github.com/flutter/flutter/issues/159876
    //      * https://github.com/flutter/flutter/issues/160587
    if result > 1 {
        result -= 1;
    }
    std::cmp::max(result, 1)
}

impl Color {
    /// A color with all components set to 0.
    pub const TRANSPARENT: Self = Self::new_srgba(0.0, 0.0, 0.0, 0.0);
    /// Create a new color with alpha set to 1.0
    pub const fn new_srgb(red: f32, green: f32, blue: f32) -> Self {
        Self::new_srgba(red, green, blue, 1.0)
    }
    /// Create a new color
    pub const fn new_srgba(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
        Self {
            red,
            green,
            blue,
            alpha,
            color_space: ColorSpace::SRGB,
        }
    }
    /// Set the alpha and return a new color
    pub const fn with_alpha(self, alpha: f32) -> Self {
        Self { alpha, ..self }
    }
}
bitflags::bitflags! {
    /// The types of text decoration to apply to text.
    pub struct TextDecorationType: std::ffi::c_int {
        /// No text decoration.
        const NONE = sys::TextDecorationType::None as std::ffi::c_int;
        /// An underline decoration.
        const UNDERLINE = sys::TextDecorationType::Underline as std::ffi::c_int;
        /// An overline decoration.
        const OVERLINE = sys::TextDecorationType::Overline as std::ffi::c_int;
        /// A strikethrough decoration.
        const LINETHROUGH = sys::TextDecorationType::LineThrough as std::ffi::c_int;
    }
}
/// Represents the rounding radii of a rounded rect.
///
/// Each point represents the X and Y radius of a corner.
#[repr(C)]
#[derive(Debug, Copy, Clone, Default)]
pub struct RoundingRadii {
    /// x and y radius of the top left corner.
    pub top_left: Point,
    /// x and y radius of the top right corner.
    pub top_right: Point,
    /// x and y radius of the bottom left corner.
    pub bottom_left: Point,
    /// x and y radius of the bottom right corner.
    pub bottom_right: Point,
}
impl From<&RoundingRadii> for sys::ImpellerRoundingRadii {
    fn from(value: &RoundingRadii) -> Self {
        Self {
            top_left: sys::ImpellerPoint {
                x: value.top_left.x,
                y: value.top_left.y,
            },
            top_right: sys::ImpellerPoint {
                x: value.top_right.x,
                y: value.top_right.y,
            },
            bottom_left: sys::ImpellerPoint {
                x: value.bottom_left.x,
                y: value.bottom_left.y,
            },
            bottom_right: sys::ImpellerPoint {
                x: value.bottom_right.x,
                y: value.bottom_right.y,
            },
        }
    }
}

impl sys::ImpellerMapping {
    /// A helper function to create a mapping from a boxed slice.
    ///
    /// This wraps `Box<[u8]>` in a `Box<Box<[u8]>>`, and leaks it.
    /// The leak is dropped inside the on_release callback. The userdata pointer returned
    /// can be used to access the original boxed slice.
    ///
    /// # Safety
    /// - The returned Self's on_release callback MUST be called with only the returned userdata pointer.
    /// - The allocator must be global, as we never know when or where the release callbacks can be called
    ///
    /// NOTE: We can probably simplify this using https://doc.rust-lang.org/std/boxed/struct.ThinBox.html on stabilization
    unsafe fn from_cow(contents: Cow<'static, [u8]>) -> (Self, *mut std::ffi::c_void) {
        let contents: Box<Cow<'static, [u8]>> = Box::new(contents);
        let data: *const u8 = contents.as_ptr();
        let length = contents.len() as u64;
        let user_data: *mut Cow<'static, [u8]> = Box::leak(contents);
        extern "C" fn boxed_cow_slice_dropper(on_release_user_data: *mut std::ffi::c_void) {
            let contents: Box<Cow<'static, [u8]>> =
                unsafe { Box::from_raw(on_release_user_data as *mut _) };
            drop(contents);
        }
        (
            sys::ImpellerMapping {
                data,
                length,
                on_release: Some(boxed_cow_slice_dropper),
            },
            user_data.cast(),
        )
    }
}
unsafe impl bytemuck::Zeroable for sys::ImpellerISize {}
unsafe impl bytemuck::Pod for sys::ImpellerISize {}
unsafe impl bytemuck::Zeroable for sys::ImpellerPoint {}
unsafe impl bytemuck::Pod for sys::ImpellerPoint {}
unsafe impl bytemuck::Zeroable for sys::ImpellerSize {}
unsafe impl bytemuck::Pod for sys::ImpellerSize {}
unsafe impl bytemuck::Zeroable for sys::ImpellerMatrix {}
unsafe impl bytemuck::Pod for sys::ImpellerMatrix {}
unsafe impl bytemuck::Zeroable for sys::ImpellerRect {}
unsafe impl bytemuck::Pod for sys::ImpellerRect {}
unsafe impl bytemuck::Zeroable for sys::ImpellerColor {}
unsafe impl bytemuck::Pod for sys::ImpellerColor {}

#[cfg(test)]
mod test {
    use super::*;
    #[test]
    fn test_version() {
        assert_eq!(
            ImpellerVersion::get_header_version().get_variant(),
            sys::IMPELLER_VERSION_VARIANT
        );
        assert_eq!(
            ImpellerVersion::get_linked_version().get_variant(),
            sys::IMPELLER_VERSION_VARIANT
        );
        assert_eq!(
            ImpellerVersion::get_header_version().get_major(),
            sys::IMPELLER_VERSION_MAJOR
        );
        assert_eq!(
            ImpellerVersion::get_linked_version().get_major(),
            sys::IMPELLER_VERSION_MAJOR
        );
        assert_eq!(
            ImpellerVersion::get_header_version().get_minor(),
            sys::IMPELLER_VERSION_MINOR
        );
        assert_eq!(
            ImpellerVersion::get_linked_version().get_minor(),
            sys::IMPELLER_VERSION_MINOR
        );
        assert_eq!(
            ImpellerVersion::get_header_version().get_patch(),
            sys::IMPELLER_VERSION_PATCH
        );
        assert_eq!(
            ImpellerVersion::get_linked_version().get_patch(),
            sys::IMPELLER_VERSION_PATCH
        );
    }
}