summaryrefslogtreecommitdiffstats
path: root/widget/gtk/gtk3drawing.cpp
blob: c8a39bfd5c1607e2f16730af259fbce02ea26a6a (plain)
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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/*
 * This file contains painting functions for each of the gtk2 widgets.
 * Adapted from the gtkdrawing.c, and gtk+2.0 source.
 */

#include <gtk/gtk.h>
#include <gdk/gdkprivate.h>
#include <string.h>
#include "gtkdrawing.h"
#include "mozilla/Assertions.h"
#include "mozilla/ScopeExit.h"
#include "prinrval.h"
#include "WidgetStyleCache.h"
#include "nsString.h"
#include "nsDebug.h"

#include <math.h>
#include <dlfcn.h>

static gboolean checkbox_check_state;
static gboolean notebook_has_tab_gap;

static ScrollbarGTKMetrics sScrollbarMetrics[2];
static ScrollbarGTKMetrics sActiveScrollbarMetrics[2];
static ToggleGTKMetrics sCheckboxMetrics;
static ToggleGTKMetrics sRadioMetrics;
static ToggleGTKMetrics sMenuRadioMetrics;
static ToggleGTKMetrics sMenuCheckboxMetrics;
static ToolbarGTKMetrics sToolbarMetrics;
static CSDWindowDecorationSize sToplevelWindowDecorationSize;
static CSDWindowDecorationSize sPopupWindowDecorationSize;

using mozilla::Span;

#define ARROW_UP 0
#define ARROW_DOWN G_PI
#define ARROW_RIGHT G_PI_2
#define ARROW_LEFT (G_PI + G_PI_2)

#if 0
// It's used for debugging only to compare Gecko widget style with
// the ones used by Gtk+ applications.
static void
style_path_print(GtkStyleContext *context)
{
    const GtkWidgetPath* path = gtk_style_context_get_path(context);

    static auto sGtkWidgetPathToStringPtr =
        (char * (*)(const GtkWidgetPath *))
        dlsym(RTLD_DEFAULT, "gtk_widget_path_to_string");

    fprintf(stderr, "Style path:\n%s\n\n", sGtkWidgetPathToStringPtr(path));
}
#endif

static GtkBorder operator-(const GtkBorder& first, const GtkBorder& second) {
  GtkBorder result;
  result.left = first.left - second.left;
  result.right = first.right - second.right;
  result.top = first.top - second.top;
  result.bottom = first.bottom - second.bottom;
  return result;
}

static GtkBorder operator+(const GtkBorder& first, const GtkBorder& second) {
  GtkBorder result;
  result.left = first.left + second.left;
  result.right = first.right + second.right;
  result.top = first.top + second.top;
  result.bottom = first.bottom + second.bottom;
  return result;
}

static GtkBorder operator+=(GtkBorder& first, const GtkBorder& second) {
  first.left += second.left;
  first.right += second.right;
  first.top += second.top;
  first.bottom += second.bottom;
  return first;
}

static gint moz_gtk_get_tab_thickness(GtkStyleContext* style);

static gint moz_gtk_menu_item_paint(WidgetNodeType widget, cairo_t* cr,
                                    GdkRectangle* rect, GtkWidgetState* state,
                                    GtkTextDirection direction);

static GtkBorder GetMarginBorderPadding(GtkStyleContext* aStyle);

static void Inset(GdkRectangle*, const GtkBorder&);

static void InsetByMargin(GdkRectangle*, GtkStyleContext* style);

static void moz_gtk_add_style_margin(GtkStyleContext* style, gint* left,
                                     gint* top, gint* right, gint* bottom) {
  GtkBorder margin;

  gtk_style_context_get_margin(style, gtk_style_context_get_state(style),
                               &margin);
  *left += margin.left;
  *right += margin.right;
  *top += margin.top;
  *bottom += margin.bottom;
}

static void moz_gtk_add_style_border(GtkStyleContext* style, gint* left,
                                     gint* top, gint* right, gint* bottom) {
  GtkBorder border;

  gtk_style_context_get_border(style, gtk_style_context_get_state(style),
                               &border);

  *left += border.left;
  *right += border.right;
  *top += border.top;
  *bottom += border.bottom;
}

static void moz_gtk_add_style_padding(GtkStyleContext* style, gint* left,
                                      gint* top, gint* right, gint* bottom) {
  GtkBorder padding;

  gtk_style_context_get_padding(style, gtk_style_context_get_state(style),
                                &padding);

  *left += padding.left;
  *right += padding.right;
  *top += padding.top;
  *bottom += padding.bottom;
}

static void moz_gtk_add_margin_border_padding(GtkStyleContext* style,
                                              gint* left, gint* top,
                                              gint* right, gint* bottom) {
  moz_gtk_add_style_margin(style, left, top, right, bottom);
  moz_gtk_add_style_border(style, left, top, right, bottom);
  moz_gtk_add_style_padding(style, left, top, right, bottom);
}

static void moz_gtk_add_border_padding(GtkStyleContext* style, gint* left,
                                       gint* top, gint* right, gint* bottom) {
  moz_gtk_add_style_border(style, left, top, right, bottom);
  moz_gtk_add_style_padding(style, left, top, right, bottom);
}

// In case there's an error in Gtk theme and preferred size is zero,
// return some sane values to pass mozilla automation tests.
// It should not happen in real-life.
#define MIN_WIDGET_SIZE 10
static void moz_gtk_sanity_preferred_size(GtkRequisition* requisition) {
  if (requisition->width <= 0) {
    requisition->width = MIN_WIDGET_SIZE;
  }
  if (requisition->height <= 0) {
    requisition->height = MIN_WIDGET_SIZE;
  }
}

// GetStateFlagsFromGtkWidgetState() can be safely used for the specific
// GtkWidgets that set both prelight and active flags.  For other widgets,
// either the GtkStateFlags or Gecko's GtkWidgetState need to be carefully
// adjusted to match GTK behavior.  Although GTK sets insensitive and focus
// flags in the generic GtkWidget base class, GTK adds prelight and active
// flags only to widgets that are expected to demonstrate prelight or active
// states.  This contrasts with HTML where any element may have :active and
// :hover states, and so Gecko's GtkStateFlags do not necessarily map to GTK
// flags.  Failure to restrict the flags in the same way as GTK can cause
// generic CSS selectors from some themes to unintentionally match elements
// that are not expected to change appearance on hover or mouse-down.
static GtkStateFlags GetStateFlagsFromGtkWidgetState(GtkWidgetState* state) {
  GtkStateFlags stateFlags = GTK_STATE_FLAG_NORMAL;

  if (state->disabled)
    stateFlags = GTK_STATE_FLAG_INSENSITIVE;
  else {
    if (state->depressed || state->active)
      stateFlags =
          static_cast<GtkStateFlags>(stateFlags | GTK_STATE_FLAG_ACTIVE);
    if (state->inHover)
      stateFlags =
          static_cast<GtkStateFlags>(stateFlags | GTK_STATE_FLAG_PRELIGHT);
    if (state->focused)
      stateFlags =
          static_cast<GtkStateFlags>(stateFlags | GTK_STATE_FLAG_FOCUSED);
    if (state->backdrop)
      stateFlags =
          static_cast<GtkStateFlags>(stateFlags | GTK_STATE_FLAG_BACKDROP);
  }

  return stateFlags;
}

static GtkStateFlags GetStateFlagsFromGtkTabFlags(GtkTabFlags flags) {
  return ((flags & MOZ_GTK_TAB_SELECTED) == 0) ? GTK_STATE_FLAG_NORMAL
                                               : GTK_STATE_FLAG_ACTIVE;
}

gint moz_gtk_init() {
  if (gtk_major_version > 3 ||
      (gtk_major_version == 3 && gtk_minor_version >= 14))
    checkbox_check_state = GTK_STATE_FLAG_CHECKED;
  else
    checkbox_check_state = GTK_STATE_FLAG_ACTIVE;

  moz_gtk_refresh();

  return MOZ_GTK_SUCCESS;
}

void moz_gtk_refresh() {
  if (gtk_check_version(3, 20, 0) != nullptr) {
    // Deprecated for Gtk >= 3.20+
    GtkStyleContext* style = GetStyleContext(MOZ_GTK_TAB_TOP);
    gtk_style_context_get_style(style, "has-tab-gap", &notebook_has_tab_gap,
                                NULL);
  } else {
    notebook_has_tab_gap = true;
  }

  sScrollbarMetrics[GTK_ORIENTATION_HORIZONTAL].initialized = false;
  sScrollbarMetrics[GTK_ORIENTATION_VERTICAL].initialized = false;
  sActiveScrollbarMetrics[GTK_ORIENTATION_HORIZONTAL].initialized = false;
  sActiveScrollbarMetrics[GTK_ORIENTATION_VERTICAL].initialized = false;
  sCheckboxMetrics.initialized = false;
  sRadioMetrics.initialized = false;
  sMenuCheckboxMetrics.initialized = false;
  sMenuRadioMetrics.initialized = false;
  sToolbarMetrics.initialized = false;
  sToplevelWindowDecorationSize.initialized = false;
  sPopupWindowDecorationSize.initialized = false;

  /* This will destroy all of our widgets */
  ResetWidgetCache();
}

static gint moz_gtk_get_focus_outline_size(GtkStyleContext* style,
                                           gint* focus_h_width,
                                           gint* focus_v_width) {
  GtkBorder border;
  gtk_style_context_get_border(style, gtk_style_context_get_state(style),
                               &border);
  *focus_h_width = border.left;
  *focus_v_width = border.top;
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_get_focus_outline_size(gint* focus_h_width, gint* focus_v_width) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_ENTRY);
  moz_gtk_get_focus_outline_size(style, focus_h_width, focus_v_width);
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_menuitem_get_horizontal_padding(gint* horizontal_padding) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_MENUITEM);
  gtk_style_context_get_style(style, "horizontal-padding", horizontal_padding,
                              nullptr);
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_checkmenuitem_get_horizontal_padding(gint* horizontal_padding) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_CHECKMENUITEM);
  gtk_style_context_get_style(style, "horizontal-padding", horizontal_padding,
                              nullptr);
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_button_get_default_overflow(gint* border_top, gint* border_left,
                                         gint* border_bottom,
                                         gint* border_right) {
  GtkBorder* default_outside_border;

  GtkStyleContext* style = GetStyleContext(MOZ_GTK_BUTTON);
  gtk_style_context_get_style(style, "default-outside-border",
                              &default_outside_border, NULL);

  if (default_outside_border) {
    *border_top = default_outside_border->top;
    *border_left = default_outside_border->left;
    *border_bottom = default_outside_border->bottom;
    *border_right = default_outside_border->right;
    gtk_border_free(default_outside_border);
  } else {
    *border_top = *border_left = *border_bottom = *border_right = 0;
  }
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_button_get_default_border(gint* border_top,
                                              gint* border_left,
                                              gint* border_bottom,
                                              gint* border_right) {
  GtkBorder* default_border;

  GtkStyleContext* style = GetStyleContext(MOZ_GTK_BUTTON);
  gtk_style_context_get_style(style, "default-border", &default_border, NULL);

  if (default_border) {
    *border_top = default_border->top;
    *border_left = default_border->left;
    *border_bottom = default_border->bottom;
    *border_right = default_border->right;
    gtk_border_free(default_border);
  } else {
    /* see gtkbutton.c */
    *border_top = *border_left = *border_bottom = *border_right = 1;
  }
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_splitter_get_metrics(gint orientation, gint* size) {
  GtkStyleContext* style;
  if (orientation == GTK_ORIENTATION_HORIZONTAL) {
    style = GetStyleContext(MOZ_GTK_SPLITTER_HORIZONTAL);
  } else {
    style = GetStyleContext(MOZ_GTK_SPLITTER_VERTICAL);
  }
  gtk_style_context_get_style(style, "handle_size", size, NULL);
  return MOZ_GTK_SUCCESS;
}

static void CalculateToolbarButtonMetrics(WidgetNodeType aAppearance,
                                          ToolbarButtonGTKMetrics* aMetrics) {
  gint iconWidth, iconHeight;
  if (!gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &iconWidth, &iconHeight)) {
    NS_WARNING("Failed to get Gtk+ icon size for titlebar button!");

    // Use some reasonable fallback size
    iconWidth = 16;
    iconHeight = 16;
  }

  GtkStyleContext* style = GetStyleContext(aAppearance);
  gint width = 0, height = 0;
  if (gtk_check_version(3, 20, 0) == nullptr) {
    gtk_style_context_get(style, gtk_style_context_get_state(style),
                          "min-width", &width, "min-height", &height, NULL);
  }

  // Cover cases when min-width/min-height is not set, it's invalid
  // or we're running on Gtk+ < 3.20.
  if (width < iconWidth) width = iconWidth;
  if (height < iconHeight) height = iconHeight;

  gint left = 0, top = 0, right = 0, bottom = 0;
  moz_gtk_add_border_padding(style, &left, &top, &right, &bottom);

  // Button size is calculated as min-width/height + border/padding.
  width += left + right;
  height += top + bottom;

  // Place icon at button center.
  aMetrics->iconXPosition = (width - iconWidth) / 2;
  aMetrics->iconYPosition = (height - iconHeight) / 2;

  aMetrics->minSizeWithBorderMargin.width = width;
  aMetrics->minSizeWithBorderMargin.height = height;
}

// We support LTR layout only here for now.
static void CalculateToolbarButtonSpacing(WidgetNodeType aAppearance,
                                          ToolbarButtonGTKMetrics* aMetrics) {
  GtkStyleContext* style = GetStyleContext(aAppearance);
  gtk_style_context_get_margin(style, gtk_style_context_get_state(style),
                               &aMetrics->buttonMargin);

  // Get titlebar spacing, a default one is 6 pixels (gtk/gtkheaderbar.c)
  gint buttonSpacing = 6;
  g_object_get(GetWidget(MOZ_GTK_HEADER_BAR), "spacing", &buttonSpacing,
               nullptr);

  // We apply spacing as a margin equaly to both adjacent buttons.
  buttonSpacing /= 2;

  if (!aMetrics->firstButton) {
    aMetrics->buttonMargin.left += buttonSpacing;
  }
  if (!aMetrics->lastButton) {
    aMetrics->buttonMargin.right += buttonSpacing;
  }

  aMetrics->minSizeWithBorderMargin.width +=
      aMetrics->buttonMargin.right + aMetrics->buttonMargin.left;
  aMetrics->minSizeWithBorderMargin.height +=
      aMetrics->buttonMargin.top + aMetrics->buttonMargin.bottom;
}

size_t GetGtkHeaderBarButtonLayout(Span<ButtonLayout> aButtonLayout,
                                   bool* aReversedButtonsPlacement) {
  gchar* decorationLayoutSetting = nullptr;
  GtkSettings* settings = gtk_settings_get_default();
  g_object_get(settings, "gtk-decoration-layout", &decorationLayoutSetting,
               nullptr);
  auto free = mozilla::MakeScopeExit([&] { g_free(decorationLayoutSetting); });

  // Use a default layout
  const gchar* decorationLayout = "menu:minimize,maximize,close";
  if (decorationLayoutSetting) {
    decorationLayout = decorationLayoutSetting;
  }

  // "minimize,maximize,close:" layout means buttons are on the opposite
  // titlebar side. close button is always there.
  if (aReversedButtonsPlacement) {
    const char* closeButton = strstr(decorationLayout, "close");
    const char* separator = strchr(decorationLayout, ':');
    *aReversedButtonsPlacement =
        closeButton && separator && closeButton < separator;
  }

  // We check what position a button string is stored in decorationLayout.
  //
  // decorationLayout gets its value from the GNOME preference:
  // org.gnome.desktop.vm.preferences.button-layout via the
  // gtk-decoration-layout property.
  //
  // Documentation of the gtk-decoration-layout property can be found here:
  // https://developer.gnome.org/gtk3/stable/GtkSettings.html#GtkSettings--gtk-decoration-layout
  if (aButtonLayout.IsEmpty()) {
    return 0;
  }

  nsDependentCSubstring layout(decorationLayout, strlen(decorationLayout));

  bool right = false;
  size_t activeButtons = 0;
  for (const auto& part : layout.Split(':')) {
    for (const auto& button : part.Split(',')) {
      if (button.EqualsLiteral("close")) {
        aButtonLayout[activeButtons++] = {MOZ_GTK_HEADER_BAR_BUTTON_CLOSE,
                                          right};
      } else if (button.EqualsLiteral("minimize")) {
        aButtonLayout[activeButtons++] = {MOZ_GTK_HEADER_BAR_BUTTON_MINIMIZE,
                                          right};
      } else if (button.EqualsLiteral("maximize")) {
        aButtonLayout[activeButtons++] = {MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE,
                                          right};
      }
      if (activeButtons == aButtonLayout.Length()) {
        return activeButtons;
      }
    }
    right = true;
  }
  return activeButtons;
}

static void EnsureToolbarMetrics(void) {
  if (!sToolbarMetrics.initialized) {
    // Make sure we have clean cache after theme reset, etc.
    memset(&sToolbarMetrics, 0, sizeof(sToolbarMetrics));

    // Calculate titlebar button visibility and positions.
    ButtonLayout aButtonLayout[TOOLBAR_BUTTONS];
    size_t activeButtonNums =
        GetGtkHeaderBarButtonLayout(mozilla::Span(aButtonLayout), nullptr);

    for (size_t i = 0; i < activeButtonNums; i++) {
      int buttonIndex =
          (aButtonLayout[i].mType - MOZ_GTK_HEADER_BAR_BUTTON_CLOSE);
      ToolbarButtonGTKMetrics* metrics = sToolbarMetrics.button + buttonIndex;
      metrics->visible = true;
      // Mark first button
      if (!i) {
        metrics->firstButton = true;
      }
      // Mark last button.
      if (i == (activeButtonNums - 1)) {
        metrics->lastButton = true;
      }

      CalculateToolbarButtonMetrics(aButtonLayout[i].mType, metrics);
      CalculateToolbarButtonSpacing(aButtonLayout[i].mType, metrics);
    }

    sToolbarMetrics.initialized = true;
  }
}

const ToolbarButtonGTKMetrics* GetToolbarButtonMetrics(
    WidgetNodeType aAppearance) {
  EnsureToolbarMetrics();

  int buttonIndex = (aAppearance - MOZ_GTK_HEADER_BAR_BUTTON_CLOSE);
  NS_ASSERTION(buttonIndex >= 0 && buttonIndex <= TOOLBAR_BUTTONS,
               "GetToolbarButtonMetrics(): Wrong titlebar button!");
  return sToolbarMetrics.button + buttonIndex;
}

static gint moz_gtk_window_paint(cairo_t* cr, GdkRectangle* rect,
                                 GtkTextDirection direction) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_WINDOW, direction);

  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_BACKGROUND);
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_style_context_restore(style);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_button_paint(cairo_t* cr, const GdkRectangle* rect,
                                 GtkWidgetState* state, GtkReliefStyle relief,
                                 GtkWidget* widget,
                                 GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style = gtk_widget_get_style_context(widget);
  gint x = rect->x, y = rect->y, width = rect->width, height = rect->height;

  gtk_widget_set_direction(widget, direction);

  gtk_style_context_save(style);
  StyleContextSetScale(style, state->scale);
  gtk_style_context_set_state(style, state_flags);

  if (state->isDefault && relief == GTK_RELIEF_NORMAL) {
    /* handle default borders both outside and inside the button */
    gint default_top, default_left, default_bottom, default_right;
    moz_gtk_button_get_default_overflow(&default_top, &default_left,
                                        &default_bottom, &default_right);
    x -= default_left;
    y -= default_top;
    width += default_left + default_right;
    height += default_top + default_bottom;
    gtk_render_background(style, cr, x, y, width, height);
    gtk_render_frame(style, cr, x, y, width, height);
    moz_gtk_button_get_default_border(&default_top, &default_left,
                                      &default_bottom, &default_right);
    x += default_left;
    y += default_top;
    width -= (default_left + default_right);
    height -= (default_top + default_bottom);
  } else if (relief != GTK_RELIEF_NONE || state->depressed ||
             (state_flags & GTK_STATE_FLAG_PRELIGHT)) {
    /* the following line can trigger an assertion (Crux theme)
       file ../../gdk/gdkwindow.c: line 1846 (gdk_window_clear_area):
       assertion `GDK_IS_WINDOW (window)' failed */
    gtk_render_background(style, cr, x, y, width, height);
    gtk_render_frame(style, cr, x, y, width, height);
  }

  if (state->focused) {
    GtkBorder border;
    gtk_style_context_get_border(style, state_flags, &border);
    x += border.left;
    y += border.top;
    width -= (border.left + border.right);
    height -= (border.top + border.bottom);
    gtk_render_focus(style, cr, x, y, width, height);
  }
  gtk_style_context_restore(style);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_header_bar_button_paint(cairo_t* cr,
                                            const GdkRectangle* aRect,
                                            GtkWidgetState* state,
                                            GtkReliefStyle relief,
                                            WidgetNodeType aIconWidgetType,
                                            GtkTextDirection direction) {
  WidgetNodeType buttonWidgetType =
      (aIconWidgetType == MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE_RESTORE)
          ? MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE
          : aIconWidgetType;

  GdkRectangle rect = *aRect;
  // We need to inset our calculated margin because it also
  // contains titlebar button spacing.
  const ToolbarButtonGTKMetrics* metrics =
      GetToolbarButtonMetrics(buttonWidgetType);
  Inset(&rect, metrics->buttonMargin);

  GtkWidget* buttonWidget = GetWidget(buttonWidgetType);
  moz_gtk_button_paint(cr, &rect, state, relief, buttonWidget, direction);

  GtkWidget* iconWidget =
      gtk_bin_get_child(GTK_BIN(GetWidget(aIconWidgetType)));
  cairo_surface_t* surface = GetWidgetIconSurface(iconWidget, state->scale);

  if (surface) {
    GtkStyleContext* style = gtk_widget_get_style_context(buttonWidget);
    GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);

    gtk_style_context_save(style);
    StyleContextSetScale(style, state->scale);
    gtk_style_context_set_state(style, state_flags);

    const ToolbarButtonGTKMetrics* metrics =
        GetToolbarButtonMetrics(buttonWidgetType);

    /* This is available since Gtk+ 3.10 as well as GtkHeaderBar */
    static auto sGtkRenderIconSurfacePtr =
        (void (*)(GtkStyleContext*, cairo_t*, cairo_surface_t*, gdouble,
                  gdouble))dlsym(RTLD_DEFAULT, "gtk_render_icon_surface");

    sGtkRenderIconSurfacePtr(style, cr, surface,
                             rect.x + metrics->iconXPosition,
                             rect.y + metrics->iconYPosition);
    gtk_style_context_restore(style);
  }

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_toggle_paint(cairo_t* cr, GdkRectangle* rect,
                                 GtkWidgetState* state, gboolean selected,
                                 gboolean inconsistent, gboolean isradio,
                                 GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  gint x, y, width, height;
  GtkStyleContext* style;

  // We need to call this before GetStyleContext, because otherwise we would
  // reset state flags
  const ToggleGTKMetrics* metrics =
      GetToggleMetrics(isradio ? MOZ_GTK_RADIOBUTTON : MOZ_GTK_CHECKBUTTON);
  // Clamp the rect and paint it center aligned in the rect.
  x = rect->x;
  y = rect->y;
  width = rect->width;
  height = rect->height;

  if (rect->width < rect->height) {
    y = rect->y + (rect->height - rect->width) / 2;
    height = rect->width;
  }

  if (rect->height < rect->width) {
    x = rect->x + (rect->width - rect->height) / 2;
    width = rect->height;
  }

  if (selected)
    state_flags =
        static_cast<GtkStateFlags>(state_flags | checkbox_check_state);

  if (inconsistent)
    state_flags =
        static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_INCONSISTENT);

  style = GetStyleContext(isradio ? MOZ_GTK_RADIOBUTTON : MOZ_GTK_CHECKBUTTON,
                          state->scale, direction, state_flags);

  if (gtk_check_version(3, 20, 0) == nullptr) {
    gtk_render_background(style, cr, x, y, width, height);
    gtk_render_frame(style, cr, x, y, width, height);
    // Indicator is inset by the toggle's padding and border.
    gint indicator_x = x + metrics->borderAndPadding.left;
    gint indicator_y = y + metrics->borderAndPadding.top;
    gint indicator_width = metrics->minSizeWithBorder.width -
                           metrics->borderAndPadding.left -
                           metrics->borderAndPadding.right;
    gint indicator_height = metrics->minSizeWithBorder.height -
                            metrics->borderAndPadding.top -
                            metrics->borderAndPadding.bottom;
    if (isradio) {
      gtk_render_option(style, cr, indicator_x, indicator_y, indicator_width,
                        indicator_height);
    } else {
      gtk_render_check(style, cr, indicator_x, indicator_y, indicator_width,
                       indicator_height);
    }
  } else {
    if (isradio) {
      gtk_render_option(style, cr, x, y, width, height);
    } else {
      gtk_render_check(style, cr, x, y, width, height);
    }
  }

  return MOZ_GTK_SUCCESS;
}

static gint calculate_button_inner_rect(GtkWidget* button,
                                        const GdkRectangle* rect,
                                        GdkRectangle* inner_rect,
                                        GtkTextDirection direction) {
  GtkStyleContext* style;
  GtkBorder border;
  GtkBorder padding = {0, 0, 0, 0};

  style = gtk_widget_get_style_context(button);

  /* This mirrors gtkbutton's child positioning */
  gtk_style_context_get_border(style, gtk_style_context_get_state(style),
                               &border);
  gtk_style_context_get_padding(style, gtk_style_context_get_state(style),
                                &padding);

  inner_rect->x = rect->x + border.left + padding.left;
  inner_rect->y = rect->y + padding.top + border.top;
  inner_rect->width =
      MAX(1, rect->width - padding.left - padding.right - border.left * 2);
  inner_rect->height =
      MAX(1, rect->height - padding.top - padding.bottom - border.top * 2);

  return MOZ_GTK_SUCCESS;
}

static gint calculate_arrow_rect(GtkWidget* arrow, GdkRectangle* rect,
                                 GdkRectangle* arrow_rect,
                                 GtkTextDirection direction) {
  /* defined in gtkarrow.c */
  gfloat arrow_scaling = 0.7;
  gfloat xalign, xpad;
  gint extent;
  gint mxpad, mypad;
  gfloat mxalign, myalign;
  GtkMisc* misc = GTK_MISC(arrow);

  gtk_style_context_get_style(gtk_widget_get_style_context(arrow),
                              "arrow_scaling", &arrow_scaling, NULL);

  gtk_misc_get_padding(misc, &mxpad, &mypad);
  extent = MIN((rect->width - mxpad * 2), (rect->height - mypad * 2)) *
           arrow_scaling;

  gtk_misc_get_alignment(misc, &mxalign, &myalign);

  xalign = direction == GTK_TEXT_DIR_LTR ? mxalign : 1.0 - mxalign;
  xpad = mxpad + (rect->width - extent) * xalign;

  arrow_rect->x = direction == GTK_TEXT_DIR_LTR ? floor(rect->x + xpad)
                                                : ceil(rect->x + xpad);
  arrow_rect->y = floor(rect->y + mypad + ((rect->height - extent) * myalign));

  arrow_rect->width = arrow_rect->height = extent;

  return MOZ_GTK_SUCCESS;
}

static MozGtkSize GetMinContentBox(GtkStyleContext* style) {
  GtkStateFlags state_flags = gtk_style_context_get_state(style);
  gint width, height;
  gtk_style_context_get(style, state_flags, "min-width", &width, "min-height",
                        &height, nullptr);
  return {width, height};
}

/**
 * Get minimum widget size as sum of margin, padding, border and
 * min-width/min-height.
 */
static void moz_gtk_get_widget_min_size(GtkStyleContext* style, int* width,
                                        int* height) {
  GtkStateFlags state_flags = gtk_style_context_get_state(style);
  gtk_style_context_get(style, state_flags, "min-height", height, "min-width",
                        width, nullptr);

  GtkBorder border, padding, margin;
  gtk_style_context_get_border(style, state_flags, &border);
  gtk_style_context_get_padding(style, state_flags, &padding);
  gtk_style_context_get_margin(style, state_flags, &margin);

  *width += border.left + border.right + margin.left + margin.right +
            padding.left + padding.right;
  *height += border.top + border.bottom + margin.top + margin.bottom +
             padding.top + padding.bottom;
}

static MozGtkSize GetMinMarginBox(GtkStyleContext* style) {
  gint width, height;
  moz_gtk_get_widget_min_size(style, &width, &height);
  return {width, height};
}

static void Inset(GdkRectangle* rect, const GtkBorder& aBorder) {
  rect->x += aBorder.left;
  rect->y += aBorder.top;
  rect->width -= aBorder.left + aBorder.right;
  rect->height -= aBorder.top + aBorder.bottom;
}

// Inset a rectangle by the margins specified in a style context.
static void InsetByMargin(GdkRectangle* rect, GtkStyleContext* style) {
  GtkBorder margin;
  gtk_style_context_get_margin(style, gtk_style_context_get_state(style),
                               &margin);
  Inset(rect, margin);
}

// Inset a rectangle by the border and padding specified in a style context.
static void InsetByBorderPadding(GdkRectangle* rect, GtkStyleContext* style) {
  GtkStateFlags state = gtk_style_context_get_state(style);
  GtkBorder padding, border;

  gtk_style_context_get_padding(style, state, &padding);
  Inset(rect, padding);
  gtk_style_context_get_border(style, state, &border);
  Inset(rect, border);
}

static gint moz_gtk_scrollbar_button_paint(cairo_t* cr,
                                           const GdkRectangle* aRect,
                                           GtkWidgetState* state,
                                           GtkScrollbarButtonFlags flags,
                                           GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GdkRectangle arrow_rect;
  gdouble arrow_angle;
  GtkStyleContext* style;
  gint arrow_displacement_x, arrow_displacement_y;

  GtkWidget* scrollbar = GetWidget(flags & MOZ_GTK_STEPPER_VERTICAL
                                       ? MOZ_GTK_SCROLLBAR_VERTICAL
                                       : MOZ_GTK_SCROLLBAR_HORIZONTAL);

  gtk_widget_set_direction(scrollbar, direction);

  if (flags & MOZ_GTK_STEPPER_VERTICAL) {
    arrow_angle = (flags & MOZ_GTK_STEPPER_DOWN) ? ARROW_DOWN : ARROW_UP;
  } else {
    arrow_angle = (flags & MOZ_GTK_STEPPER_DOWN) ? ARROW_RIGHT : ARROW_LEFT;
  }

  style = gtk_widget_get_style_context(scrollbar);

  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_BUTTON);
  StyleContextSetScale(style, state->scale);
  gtk_style_context_set_state(style, state_flags);
  if (arrow_angle == ARROW_RIGHT) {
    gtk_style_context_add_class(style, GTK_STYLE_CLASS_RIGHT);
  } else if (arrow_angle == ARROW_DOWN) {
    gtk_style_context_add_class(style, GTK_STYLE_CLASS_BOTTOM);
  } else if (arrow_angle == ARROW_LEFT) {
    gtk_style_context_add_class(style, GTK_STYLE_CLASS_LEFT);
  } else {
    gtk_style_context_add_class(style, GTK_STYLE_CLASS_TOP);
  }

  GdkRectangle rect = *aRect;
  if (gtk_check_version(3, 20, 0) == nullptr) {
    // The "trough-border" is not used since GTK 3.20.  The stepper margin
    // box occupies the full width of the "contents" gadget content box.
    InsetByMargin(&rect, style);
  } else {
    // Scrollbar button has to be inset by trough_border because its DOM
    // element is filling width of vertical scrollbar's track (or height
    // in case of horizontal scrollbars).
    GtkOrientation orientation = flags & MOZ_GTK_STEPPER_VERTICAL
                                     ? GTK_ORIENTATION_VERTICAL
                                     : GTK_ORIENTATION_HORIZONTAL;

    const ScrollbarGTKMetrics* metrics = GetScrollbarMetrics(orientation);
    if (flags & MOZ_GTK_STEPPER_VERTICAL) {
      rect.x += metrics->border.track.left;
      rect.width = metrics->size.thumb.width;
    } else {
      rect.y += metrics->border.track.top;
      rect.height = metrics->size.thumb.height;
    }
  }

  gtk_render_background(style, cr, rect.x, rect.y, rect.width, rect.height);
  gtk_render_frame(style, cr, rect.x, rect.y, rect.width, rect.height);

  arrow_rect.width = rect.width / 2;
  arrow_rect.height = rect.height / 2;

  gfloat arrow_scaling;
  gtk_style_context_get_style(style, "arrow-scaling", &arrow_scaling, NULL);

  gdouble arrow_size = MIN(rect.width, rect.height) * arrow_scaling;
  arrow_rect.x = rect.x + (rect.width - arrow_size) / 2;
  arrow_rect.y = rect.y + (rect.height - arrow_size) / 2;

  if (state_flags & GTK_STATE_FLAG_ACTIVE) {
    gtk_style_context_get_style(style, "arrow-displacement-x",
                                &arrow_displacement_x, "arrow-displacement-y",
                                &arrow_displacement_y, NULL);

    arrow_rect.x += arrow_displacement_x;
    arrow_rect.y += arrow_displacement_y;
  }

  gtk_render_arrow(style, cr, arrow_angle, arrow_rect.x, arrow_rect.y,
                   arrow_size);

  gtk_style_context_restore(style);

  return MOZ_GTK_SUCCESS;
}

static void moz_gtk_update_scrollbar_style(GtkStyleContext* style,
                                           WidgetNodeType widget,
                                           GtkTextDirection direction) {
  if (widget == MOZ_GTK_SCROLLBAR_HORIZONTAL) {
    gtk_style_context_add_class(style, GTK_STYLE_CLASS_BOTTOM);
  } else {
    if (direction == GTK_TEXT_DIR_LTR) {
      gtk_style_context_add_class(style, GTK_STYLE_CLASS_RIGHT);
      gtk_style_context_remove_class(style, GTK_STYLE_CLASS_LEFT);
    } else {
      gtk_style_context_add_class(style, GTK_STYLE_CLASS_LEFT);
      gtk_style_context_remove_class(style, GTK_STYLE_CLASS_RIGHT);
    }
  }
}

static void moz_gtk_draw_styled_frame(GtkStyleContext* style, cairo_t* cr,
                                      const GdkRectangle* aRect,
                                      bool drawFocus) {
  GdkRectangle rect = *aRect;

  InsetByMargin(&rect, style);

  gtk_render_background(style, cr, rect.x, rect.y, rect.width, rect.height);
  gtk_render_frame(style, cr, rect.x, rect.y, rect.width, rect.height);
  if (drawFocus) {
    gtk_render_focus(style, cr, rect.x, rect.y, rect.width, rect.height);
  }
}

static gint moz_gtk_scrollbar_trough_paint(WidgetNodeType widget, cairo_t* cr,
                                           const GdkRectangle* aRect,
                                           GtkWidgetState* state,
                                           GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GdkRectangle rect = *aRect;
  GtkStyleContext* style;

  if (gtk_get_minor_version() >= 20) {
    WidgetNodeType thumb = widget == MOZ_GTK_SCROLLBAR_TROUGH_VERTICAL
                               ? MOZ_GTK_SCROLLBAR_THUMB_VERTICAL
                               : MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL;
    MozGtkSize thumbSize = GetMinMarginBox(GetStyleContext(thumb));
    style = GetStyleContext(widget, state->scale, direction, state_flags);
    MozGtkSize trackSize = GetMinContentBox(style);
    trackSize.Include(thumbSize);
    trackSize += GetMarginBorderPadding(style);
    // Gecko's trough |aRect| fills available breadth, but GTK's trough is
    // centered in the contents_gadget.  The centering here round left
    // and up, like gtk_box_gadget_allocate_child().
    if (widget == MOZ_GTK_SCROLLBAR_TROUGH_VERTICAL) {
      rect.x += (rect.width - trackSize.width) / 2;
      rect.width = trackSize.width;
    } else {
      rect.y += (rect.height - trackSize.height) / 2;
      rect.height = trackSize.height;
    }
  } else {
    style = GetStyleContext(widget, state->scale, direction, state_flags);
  }

  moz_gtk_draw_styled_frame(style, cr, &rect, state->focused);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_scrollbar_paint(WidgetNodeType widget, cairo_t* cr,
                                    const GdkRectangle* rect,
                                    GtkWidgetState* state,
                                    GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style =
      GetStyleContext(widget, state->scale, direction, state_flags);

  moz_gtk_update_scrollbar_style(style, widget, direction);

  moz_gtk_draw_styled_frame(style, cr, rect, state->focused);

  style = GetStyleContext((widget == MOZ_GTK_SCROLLBAR_HORIZONTAL)
                              ? MOZ_GTK_SCROLLBAR_CONTENTS_HORIZONTAL
                              : MOZ_GTK_SCROLLBAR_CONTENTS_VERTICAL,
                          state->scale, direction, state_flags);
  moz_gtk_draw_styled_frame(style, cr, rect, state->focused);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_scrollbar_thumb_paint(WidgetNodeType widget, cairo_t* cr,
                                          const GdkRectangle* aRect,
                                          GtkWidgetState* state,
                                          GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style =
      GetStyleContext(widget, state->scale, direction, state_flags);

  GtkOrientation orientation = (widget == MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL)
                                   ? GTK_ORIENTATION_HORIZONTAL
                                   : GTK_ORIENTATION_VERTICAL;

  GdkRectangle rect = *aRect;

  const ScrollbarGTKMetrics* metrics =
      (state->depressed || state->active || state->inHover)
          ? GetActiveScrollbarMetrics(orientation)
          : GetScrollbarMetrics(orientation);
  Inset(&rect, metrics->margin.thumb);

  gtk_render_slider(style, cr, rect.x, rect.y, rect.width, rect.height,
                    orientation);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_inner_spin_paint(cairo_t* cr, GdkRectangle* rect,
                                     GtkWidgetState* state,
                                     GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_SPINBUTTON, state->scale, direction,
                      GetStateFlagsFromGtkWidgetState(state));

  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);

  /* hard code these values */
  GdkRectangle arrow_rect;
  arrow_rect.width = 6;
  arrow_rect.height = 6;

  // align spin to the left
  arrow_rect.x = rect->x;

  // up button
  arrow_rect.y = rect->y + (rect->height - arrow_rect.height) / 2 - 3;
  gtk_render_arrow(style, cr, ARROW_UP, arrow_rect.x, arrow_rect.y,
                   arrow_rect.width);

  // down button
  arrow_rect.y = rect->y + (rect->height - arrow_rect.height) / 2 + 3;
  gtk_render_arrow(style, cr, ARROW_DOWN, arrow_rect.x, arrow_rect.y,
                   arrow_rect.width);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_spin_paint(cairo_t* cr, GdkRectangle* rect,
                               GtkWidgetState* state,
                               GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_SPINBUTTON, state->scale, direction);
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_spin_updown_paint(cairo_t* cr, GdkRectangle* rect,
                                      gboolean isDown, GtkWidgetState* state,
                                      GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_SPINBUTTON, state->scale, direction,
                      GetStateFlagsFromGtkWidgetState(state));

  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);

  /* hard code these values */
  GdkRectangle arrow_rect;
  arrow_rect.width = 6;
  arrow_rect.height = 6;
  arrow_rect.x = rect->x + (rect->width - arrow_rect.width) / 2;
  arrow_rect.y = rect->y + (rect->height - arrow_rect.height) / 2;
  arrow_rect.y += isDown ? -1 : 1;

  gtk_render_arrow(style, cr, isDown ? ARROW_DOWN : ARROW_UP, arrow_rect.x,
                   arrow_rect.y, arrow_rect.width);

  return MOZ_GTK_SUCCESS;
}

/* See gtk_range_draw() for reference.
 */
static gint moz_gtk_scale_paint(cairo_t* cr, GdkRectangle* rect,
                                GtkWidgetState* state, GtkOrientation flags,
                                GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  gint x, y, width, height, min_width, min_height;
  GtkStyleContext* style;
  GtkBorder margin;

  moz_gtk_get_scale_metrics(flags, &min_width, &min_height);

  WidgetNodeType widget = (flags == GTK_ORIENTATION_HORIZONTAL)
                              ? MOZ_GTK_SCALE_TROUGH_HORIZONTAL
                              : MOZ_GTK_SCALE_TROUGH_VERTICAL;
  style = GetStyleContext(widget, state->scale, direction, state_flags);
  gtk_style_context_get_margin(style, state_flags, &margin);

  // Clamp the dimension perpendicular to the direction that the slider crosses
  // to the minimum size.
  if (flags == GTK_ORIENTATION_HORIZONTAL) {
    width = rect->width - (margin.left + margin.right);
    height = min_height - (margin.top + margin.bottom);
    x = rect->x + margin.left;
    y = rect->y + (rect->height - height) / 2;
  } else {
    width = min_width - (margin.left + margin.right);
    height = rect->height - (margin.top + margin.bottom);
    x = rect->x + (rect->width - width) / 2;
    y = rect->y + margin.top;
  }

  gtk_render_background(style, cr, x, y, width, height);
  gtk_render_frame(style, cr, x, y, width, height);

  if (state->focused)
    gtk_render_focus(style, cr, rect->x, rect->y, rect->width, rect->height);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_scale_thumb_paint(cairo_t* cr, GdkRectangle* rect,
                                      GtkWidgetState* state,
                                      GtkOrientation flags,
                                      GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style;
  gint thumb_width, thumb_height, x, y;

  /* determine the thumb size, and position the thumb in the center in the
   * opposite axis
   */
  if (flags == GTK_ORIENTATION_HORIZONTAL) {
    moz_gtk_get_scalethumb_metrics(GTK_ORIENTATION_HORIZONTAL, &thumb_width,
                                   &thumb_height);
    x = rect->x;
    y = rect->y + (rect->height - thumb_height) / 2;
  } else {
    moz_gtk_get_scalethumb_metrics(GTK_ORIENTATION_VERTICAL, &thumb_height,
                                   &thumb_width);
    x = rect->x + (rect->width - thumb_width) / 2;
    y = rect->y;
  }

  WidgetNodeType widget = (flags == GTK_ORIENTATION_HORIZONTAL)
                              ? MOZ_GTK_SCALE_THUMB_HORIZONTAL
                              : MOZ_GTK_SCALE_THUMB_VERTICAL;
  style = GetStyleContext(widget, state->scale, direction, state_flags);
  gtk_render_slider(style, cr, x, y, thumb_width, thumb_height, flags);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_gripper_paint(cairo_t* cr, GdkRectangle* rect,
                                  GtkWidgetState* state,
                                  GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_GRIPPER, state->scale, direction,
                      GetStateFlagsFromGtkWidgetState(state));
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_hpaned_paint(cairo_t* cr, GdkRectangle* rect,
                                 GtkWidgetState* state) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_SPLITTER_SEPARATOR_HORIZONTAL, state->scale,
                      GTK_TEXT_DIR_LTR, GetStateFlagsFromGtkWidgetState(state));
  gtk_render_handle(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_vpaned_paint(cairo_t* cr, GdkRectangle* rect,
                                 GtkWidgetState* state) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_SPLITTER_SEPARATOR_VERTICAL, state->scale,
                      GTK_TEXT_DIR_LTR, GetStateFlagsFromGtkWidgetState(state));
  gtk_render_handle(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

// See gtk_entry_draw() for reference.
static gint moz_gtk_entry_paint(cairo_t* cr, const GdkRectangle* aRect,
                                GtkWidgetState* state, GtkStyleContext* style,
                                WidgetNodeType widget) {
  // StyleAppearance::FocusOutline
  int draw_focus_outline_only = state->depressed;
  GdkRectangle rect = *aRect;

  if (draw_focus_outline_only) {
    // Inflate the given 'rect' with the focus outline size.
    gint h, v;
    moz_gtk_get_focus_outline_size(style, &h, &v);
    rect.x -= h;
    rect.width += 2 * h;
    rect.y -= v;
    rect.height += 2 * v;
  } else {
    gtk_render_background(style, cr, rect.x, rect.y, rect.width, rect.height);
  }

  // Paint the border, except for 'menulist-textfield' that isn't focused:
  if (widget != MOZ_GTK_DROPDOWN_ENTRY || state->focused) {
    gtk_render_frame(style, cr, rect.x, rect.y, rect.width, rect.height);
  }

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_text_view_paint(cairo_t* cr, GdkRectangle* aRect,
                                    GtkWidgetState* state,
                                    GtkTextDirection direction) {
  // GtkTextView and GtkScrolledWindow do not set active and prelight flags.
  // The use of focus with MOZ_GTK_SCROLLED_WINDOW here is questionable
  // because a parent widget will not have focus when its child GtkTextView
  // has focus, but perhaps this may help identify a focused textarea with
  // some themes as GtkTextView backgrounds do not typically render
  // differently with focus.
  GtkStateFlags state_flags = state->disabled  ? GTK_STATE_FLAG_INSENSITIVE
                              : state->focused ? GTK_STATE_FLAG_FOCUSED
                                               : GTK_STATE_FLAG_NORMAL;

  GtkStyleContext* style_frame = GetStyleContext(
      MOZ_GTK_SCROLLED_WINDOW, state->scale, direction, state_flags);
  gtk_render_frame(style_frame, cr, aRect->x, aRect->y, aRect->width,
                   aRect->height);

  GdkRectangle rect = *aRect;
  InsetByBorderPadding(&rect, style_frame);

  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_TEXT_VIEW, state->scale, direction, state_flags);
  gtk_render_background(style, cr, rect.x, rect.y, rect.width, rect.height);
  // There is a separate "text" window, which usually provides the
  // background behind the text.  However, this is transparent in Ambiance
  // for GTK 3.20, in which case the MOZ_GTK_TEXT_VIEW background is
  // visible.
  style = GetStyleContext(MOZ_GTK_TEXT_VIEW_TEXT, state->scale, direction,
                          state_flags);
  gtk_render_background(style, cr, rect.x, rect.y, rect.width, rect.height);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_treeview_paint(cairo_t* cr, GdkRectangle* rect,
                                   GtkWidgetState* state,
                                   GtkTextDirection direction) {
  gint xthickness, ythickness;
  GtkStyleContext* style;
  GtkStyleContext* style_tree;
  GtkStateFlags state_flags;
  GtkBorder border;

  /* only handle disabled and normal states, otherwise the whole background
   * area will be painted differently with other states */
  state_flags =
      state->disabled ? GTK_STATE_FLAG_INSENSITIVE : GTK_STATE_FLAG_NORMAL;

  style = GetStyleContext(MOZ_GTK_SCROLLED_WINDOW, state->scale, direction);
  gtk_style_context_get_border(style, state_flags, &border);
  xthickness = border.left;
  ythickness = border.top;

  style_tree = GetStyleContext(MOZ_GTK_TREEVIEW_VIEW, state->scale, direction);
  gtk_render_background(style_tree, cr, rect->x + xthickness,
                        rect->y + ythickness, rect->width - 2 * xthickness,
                        rect->height - 2 * ythickness);

  style = GetStyleContext(MOZ_GTK_SCROLLED_WINDOW, state->scale, direction);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_tree_header_cell_paint(cairo_t* cr,
                                           const GdkRectangle* aRect,
                                           GtkWidgetState* state,
                                           gboolean isSorted,
                                           GtkTextDirection direction) {
  moz_gtk_button_paint(cr, aRect, state, GTK_RELIEF_NORMAL,
                       GetWidget(MOZ_GTK_TREE_HEADER_CELL), direction);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_tree_header_sort_arrow_paint(cairo_t* cr,
                                                 GdkRectangle* rect,
                                                 GtkWidgetState* state,
                                                 GtkArrowType arrow_type,
                                                 GtkTextDirection direction) {
  GdkRectangle arrow_rect;
  gdouble arrow_angle;
  GtkStyleContext* style;

  /* hard code these values */
  arrow_rect.width = 11;
  arrow_rect.height = 11;
  arrow_rect.x = rect->x + (rect->width - arrow_rect.width) / 2;
  arrow_rect.y = rect->y + (rect->height - arrow_rect.height) / 2;
  style = GetStyleContext(MOZ_GTK_TREE_HEADER_SORTARROW, state->scale,
                          direction, GetStateFlagsFromGtkWidgetState(state));
  switch (arrow_type) {
    case GTK_ARROW_LEFT:
      arrow_angle = ARROW_LEFT;
      break;
    case GTK_ARROW_RIGHT:
      arrow_angle = ARROW_RIGHT;
      break;
    case GTK_ARROW_DOWN:
      arrow_angle = ARROW_DOWN;
      break;
    default:
      arrow_angle = ARROW_UP;
      break;
  }
  if (arrow_type != GTK_ARROW_NONE)
    gtk_render_arrow(style, cr, arrow_angle, arrow_rect.x, arrow_rect.y,
                     arrow_rect.width);
  return MOZ_GTK_SUCCESS;
}

/* See gtk_expander_paint() for reference.
 */
static gint moz_gtk_treeview_expander_paint(cairo_t* cr, GdkRectangle* rect,
                                            GtkWidgetState* state,
                                            GtkExpanderStyle expander_state,
                                            GtkTextDirection direction) {
  /* Because the frame we get is of the entire treeview, we can't get the
   * precise event state of one expander, thus rendering hover and active
   * feedback useless. */
  GtkStateFlags state_flags =
      state->disabled ? GTK_STATE_FLAG_INSENSITIVE : GTK_STATE_FLAG_NORMAL;

  if (state->inHover)
    state_flags =
        static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_PRELIGHT);
  if (state->selected)
    state_flags =
        static_cast<GtkStateFlags>(state_flags | GTK_STATE_FLAG_SELECTED);

  /* GTK_STATE_FLAG_ACTIVE controls expanded/colapsed state rendering
   * in gtk_render_expander()
   */
  if (expander_state == GTK_EXPANDER_EXPANDED)
    state_flags =
        static_cast<GtkStateFlags>(state_flags | checkbox_check_state);
  else
    state_flags =
        static_cast<GtkStateFlags>(state_flags & ~(checkbox_check_state));

  GtkStyleContext* style = GetStyleContext(
      MOZ_GTK_TREEVIEW_EXPANDER, state->scale, direction, state_flags);
  gtk_render_expander(style, cr, rect->x, rect->y, rect->width, rect->height);

  return MOZ_GTK_SUCCESS;
}

/* See gtk_separator_draw() for reference.
 */
static gint moz_gtk_combo_box_paint(cairo_t* cr, const GdkRectangle* aRect,
                                    GtkWidgetState* state,
                                    GtkTextDirection direction) {
  GdkRectangle arrow_rect, real_arrow_rect;
  gint separator_width;
  gboolean wide_separators;
  GtkStyleContext* style;
  GtkRequisition arrow_req;

  GtkWidget* comboBoxButton = GetWidget(MOZ_GTK_COMBOBOX_BUTTON);
  GtkWidget* comboBoxArrow = GetWidget(MOZ_GTK_COMBOBOX_ARROW);

  /* Also sets the direction on gComboBoxButtonWidget, which is then
   * inherited by the separator and arrow */
  moz_gtk_button_paint(cr, aRect, state, GTK_RELIEF_NORMAL, comboBoxButton,
                       direction);

  calculate_button_inner_rect(comboBoxButton, aRect, &arrow_rect, direction);
  /* Now arrow_rect contains the inner rect ; we want to correct the width
   * to what the arrow needs (see gtk_combo_box_size_allocate) */
  gtk_widget_get_preferred_size(comboBoxArrow, NULL, &arrow_req);
  moz_gtk_sanity_preferred_size(&arrow_req);

  if (direction == GTK_TEXT_DIR_LTR)
    arrow_rect.x += arrow_rect.width - arrow_req.width;
  arrow_rect.width = arrow_req.width;

  calculate_arrow_rect(comboBoxArrow, &arrow_rect, &real_arrow_rect, direction);

  style = GetStyleContext(MOZ_GTK_COMBOBOX_ARROW, state->scale);
  gtk_render_arrow(style, cr, ARROW_DOWN, real_arrow_rect.x, real_arrow_rect.y,
                   real_arrow_rect.width);

  /* If there is no separator in the theme, there's nothing left to do. */
  GtkWidget* widget = GetWidget(MOZ_GTK_COMBOBOX_SEPARATOR);
  if (!widget) return MOZ_GTK_SUCCESS;
  style = gtk_widget_get_style_context(widget);
  StyleContextSetScale(style, state->scale);
  gtk_style_context_get_style(style, "wide-separators", &wide_separators,
                              "separator-width", &separator_width, NULL);

  if (wide_separators) {
    if (direction == GTK_TEXT_DIR_LTR)
      arrow_rect.x -= separator_width;
    else
      arrow_rect.x += arrow_rect.width;

    gtk_render_frame(style, cr, arrow_rect.x, arrow_rect.y, separator_width,
                     arrow_rect.height);
  } else {
    if (direction == GTK_TEXT_DIR_LTR) {
      GtkBorder padding;
      GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
      gtk_style_context_get_padding(style, state_flags, &padding);
      arrow_rect.x -= padding.left;
    } else
      arrow_rect.x += arrow_rect.width;

    gtk_render_line(style, cr, arrow_rect.x, arrow_rect.y, arrow_rect.x,
                    arrow_rect.y + arrow_rect.height);
  }
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_arrow_paint(cairo_t* cr, GdkRectangle* rect,
                                GtkWidgetState* state, GtkArrowType arrow_type,
                                GtkTextDirection direction) {
  GdkRectangle arrow_rect;
  gdouble arrow_angle;

  if (direction == GTK_TEXT_DIR_RTL) {
    if (arrow_type == GTK_ARROW_LEFT) {
      arrow_type = GTK_ARROW_RIGHT;
    } else if (arrow_type == GTK_ARROW_RIGHT) {
      arrow_type = GTK_ARROW_LEFT;
    }
  }
  switch (arrow_type) {
    case GTK_ARROW_LEFT:
      arrow_angle = ARROW_LEFT;
      break;
    case GTK_ARROW_RIGHT:
      arrow_angle = ARROW_RIGHT;
      break;
    case GTK_ARROW_DOWN:
      arrow_angle = ARROW_DOWN;
      break;
    default:
      arrow_angle = ARROW_UP;
      break;
  }
  if (arrow_type == GTK_ARROW_NONE) return MOZ_GTK_SUCCESS;

  calculate_arrow_rect(GetWidget(MOZ_GTK_BUTTON_ARROW), rect, &arrow_rect,
                       direction);
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_BUTTON_ARROW, state->scale,
                                           direction, state_flags);
  gtk_render_arrow(style, cr, arrow_angle, arrow_rect.x, arrow_rect.y,
                   arrow_rect.width);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_combo_box_entry_button_paint(cairo_t* cr,
                                                 GdkRectangle* rect,
                                                 GtkWidgetState* state,
                                                 gboolean input_focus,
                                                 GtkTextDirection direction) {
  gint x_displacement, y_displacement;
  GdkRectangle arrow_rect, real_arrow_rect;
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style;

  GtkWidget* comboBoxEntry = GetWidget(MOZ_GTK_COMBOBOX_ENTRY_BUTTON);
  moz_gtk_button_paint(cr, rect, state, GTK_RELIEF_NORMAL, comboBoxEntry,
                       direction);
  calculate_button_inner_rect(comboBoxEntry, rect, &arrow_rect, direction);

  if (state_flags & GTK_STATE_FLAG_ACTIVE) {
    style = gtk_widget_get_style_context(comboBoxEntry);
    StyleContextSetScale(style, state->scale);
    gtk_style_context_get_style(style, "child-displacement-x", &x_displacement,
                                "child-displacement-y", &y_displacement, NULL);
    arrow_rect.x += x_displacement;
    arrow_rect.y += y_displacement;
  }

  calculate_arrow_rect(GetWidget(MOZ_GTK_COMBOBOX_ENTRY_ARROW), &arrow_rect,
                       &real_arrow_rect, direction);

  style = GetStyleContext(MOZ_GTK_COMBOBOX_ENTRY_ARROW, state->scale);
  gtk_render_arrow(style, cr, ARROW_DOWN, real_arrow_rect.x, real_arrow_rect.y,
                   real_arrow_rect.width);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_container_paint(cairo_t* cr, GdkRectangle* rect,
                                    GtkWidgetState* state,
                                    WidgetNodeType widget_type,
                                    GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style =
      GetStyleContext(widget_type, state->scale, direction, state_flags);
  /* this is for drawing a prelight box */
  if (state_flags & GTK_STATE_FLAG_PRELIGHT) {
    gtk_render_background(style, cr, rect->x, rect->y, rect->width,
                          rect->height);
  }

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_toggle_label_paint(cairo_t* cr, GdkRectangle* rect,
                                       GtkWidgetState* state, gboolean isradio,
                                       GtkTextDirection direction) {
  if (!state->focused) return MOZ_GTK_SUCCESS;

  GtkStyleContext* style = GetStyleContext(
      isradio ? MOZ_GTK_RADIOBUTTON_CONTAINER : MOZ_GTK_CHECKBUTTON_CONTAINER,
      state->scale, direction, GetStateFlagsFromGtkWidgetState(state));
  gtk_render_focus(style, cr, rect->x, rect->y, rect->width, rect->height);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_toolbar_paint(cairo_t* cr, GdkRectangle* rect,
                                  GtkWidgetState* state,
                                  GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_TOOLBAR, state->scale, direction);
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

/* See _gtk_toolbar_paint_space_line() for reference.
 */
static gint moz_gtk_toolbar_separator_paint(cairo_t* cr, GdkRectangle* rect,
                                            GtkWidgetState* state,
                                            GtkTextDirection direction) {
  gint separator_width;
  gint paint_width;
  gboolean wide_separators;

  /* Defined as constants in GTK+ 2.10.14 */
  const double start_fraction = 0.2;
  const double end_fraction = 0.8;

  GtkStyleContext* style = GetStyleContext(MOZ_GTK_TOOLBAR, state->scale);
  gtk_style_context_get_style(style, "wide-separators", &wide_separators,
                              "separator-width", &separator_width, NULL);

  style = GetStyleContext(MOZ_GTK_TOOLBAR_SEPARATOR, state->scale, direction);
  if (wide_separators) {
    if (separator_width > rect->width) separator_width = rect->width;

    gtk_render_frame(style, cr, rect->x + (rect->width - separator_width) / 2,
                     rect->y + rect->height * start_fraction, separator_width,
                     rect->height * (end_fraction - start_fraction));
  } else {
    GtkBorder padding;
    gtk_style_context_get_padding(style, gtk_style_context_get_state(style),
                                  &padding);

    paint_width = padding.left;
    if (paint_width > rect->width) paint_width = rect->width;

    gtk_render_line(style, cr, rect->x + (rect->width - paint_width) / 2,
                    rect->y + rect->height * start_fraction,
                    rect->x + (rect->width - paint_width) / 2,
                    rect->y + rect->height * end_fraction);
  }
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_tooltip_paint(cairo_t* cr, const GdkRectangle* aRect,
                                  GtkWidgetState* state,
                                  GtkTextDirection direction) {
  // Tooltip widget is made in GTK3 as following tree:
  // Tooltip window
  //   Horizontal Box
  //     Icon (not supported by Firefox)
  //     Label
  // Each element can be fully styled by CSS of GTK theme.
  // We have to draw all elements with appropriate offset and right dimensions.

  // Tooltip drawing
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_TOOLTIP, state->scale, direction);
  GdkRectangle rect = *aRect;
  gtk_render_background(style, cr, rect.x, rect.y, rect.width, rect.height);
  gtk_render_frame(style, cr, rect.x, rect.y, rect.width, rect.height);

  // Horizontal Box drawing
  //
  // The box element has hard-coded 6px margin-* GtkWidget properties, which
  // are added between the window dimensions and the CSS margin box of the
  // horizontal box.  The frame of the tooltip window is drawn in the
  // 6px margin.
  // For drawing Horizontal Box we have to inset drawing area by that 6px
  // plus its CSS margin.
  GtkStyleContext* boxStyle =
      GetStyleContext(MOZ_GTK_TOOLTIP_BOX, state->scale, direction);

  rect.x += 6;
  rect.y += 6;
  rect.width -= 12;
  rect.height -= 12;

  InsetByMargin(&rect, boxStyle);
  gtk_render_background(boxStyle, cr, rect.x, rect.y, rect.width, rect.height);
  gtk_render_frame(boxStyle, cr, rect.x, rect.y, rect.width, rect.height);

  // Label drawing
  InsetByBorderPadding(&rect, boxStyle);

  GtkStyleContext* labelStyle =
      GetStyleContext(MOZ_GTK_TOOLTIP_BOX_LABEL, state->scale, direction);
  moz_gtk_draw_styled_frame(labelStyle, cr, &rect, false);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_resizer_paint(cairo_t* cr, GdkRectangle* rect,
                                  GtkWidgetState* state,
                                  GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_RESIZER, state->scale, GTK_TEXT_DIR_LTR,
                      GetStateFlagsFromGtkWidgetState(state));

  // Workaround unico not respecting the text direction for resizers.
  // See bug 1174248.
  cairo_save(cr);
  if (direction == GTK_TEXT_DIR_RTL) {
    cairo_matrix_t mat;
    cairo_matrix_init_translate(&mat, 2 * rect->x + rect->width, 0);
    cairo_matrix_scale(&mat, -1, 1);
    cairo_transform(cr, &mat);
  }

  gtk_render_handle(style, cr, rect->x, rect->y, rect->width, rect->height);
  cairo_restore(cr);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_frame_paint(cairo_t* cr, GdkRectangle* rect,
                                GtkWidgetState* state,
                                GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_FRAME, state->scale, direction);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_progressbar_paint(cairo_t* cr, GdkRectangle* rect,
                                      GtkWidgetState* state,
                                      GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_PROGRESS_TROUGH, state->scale, direction);
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_progress_chunk_paint(cairo_t* cr, GdkRectangle* rect,
                                         GtkWidgetState* state,
                                         GtkTextDirection direction,
                                         WidgetNodeType widget) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_PROGRESS_CHUNK, state->scale, direction);

  if (widget == MOZ_GTK_PROGRESS_CHUNK_INDETERMINATE ||
      widget == MOZ_GTK_PROGRESS_CHUNK_VERTICAL_INDETERMINATE) {
    /**
     * The bar's size and the bar speed are set depending of the progress'
     * size. These could also be constant for all progress bars easily.
     */
    gboolean vertical =
        (widget == MOZ_GTK_PROGRESS_CHUNK_VERTICAL_INDETERMINATE);

    /* The size of the dimension we are going to use for the animation. */
    const gint progressSize = vertical ? rect->height : rect->width;

    /* The bar is using a fifth of the element size, based on GtkProgressBar
     * activity-blocks property. */
    const gint barSize = MAX(1, progressSize / 5);

    /* Represents the travel that has to be done for a complete cycle. */
    const gint travel = 2 * (progressSize - barSize);

    /* period equals to travel / pixelsPerMillisecond
     * where pixelsPerMillisecond equals progressSize / 1000.0.
     * This is equivalent to 1600. */
    static const guint period = 1600;
    const gint t = PR_IntervalToMilliseconds(PR_IntervalNow()) % period;
    const gint dx = travel * t / period;

    if (vertical) {
      rect->y += (dx < travel / 2) ? dx : travel - dx;
      rect->height = barSize;
    } else {
      rect->x += (dx < travel / 2) ? dx : travel - dx;
      rect->width = barSize;
    }
  }

  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_get_tab_thickness(GtkStyleContext* style) {
  if (!notebook_has_tab_gap)
    return 0; /* tabs do not overdraw the tabpanel border with "no gap" style */

  GtkBorder border;
  gtk_style_context_get_border(style, gtk_style_context_get_state(style),
                               &border);
  if (border.top < 2) return 2; /* some themes don't set ythickness correctly */

  return border.top;
}

gint moz_gtk_get_tab_thickness(WidgetNodeType aNodeType) {
  GtkStyleContext* style = GetStyleContext(aNodeType);
  int thickness = moz_gtk_get_tab_thickness(style);
  return thickness;
}

/* actual small tabs */
static gint moz_gtk_tab_paint(cairo_t* cr, GdkRectangle* rect,
                              GtkWidgetState* state, GtkTabFlags flags,
                              GtkTextDirection direction,
                              WidgetNodeType widget) {
  /* When the tab isn't selected, we just draw a notebook extension.
   * When it is selected, we overwrite the adjacent border of the tabpanel
   * touching the tab with a pierced border (called "the gap") to make the
   * tab appear physically attached to the tabpanel; see details below. */

  GtkStyleContext* style;
  GdkRectangle tabRect;
  GdkRectangle focusRect;
  GdkRectangle backRect;
  int initial_gap = 0;
  bool isBottomTab = (widget == MOZ_GTK_TAB_BOTTOM);

  style = GetStyleContext(widget, state->scale, direction,
                          GetStateFlagsFromGtkTabFlags(flags));
  tabRect = *rect;

  if (flags & MOZ_GTK_TAB_FIRST) {
    gtk_style_context_get_style(style, "initial-gap", &initial_gap, NULL);
    tabRect.width -= initial_gap;

    if (direction != GTK_TEXT_DIR_RTL) {
      tabRect.x += initial_gap;
    }
  }

  focusRect = backRect = tabRect;

  if (notebook_has_tab_gap) {
    if ((flags & MOZ_GTK_TAB_SELECTED) == 0) {
      /* Only draw the tab */
      gtk_render_extension(style, cr, tabRect.x, tabRect.y, tabRect.width,
                           tabRect.height,
                           isBottomTab ? GTK_POS_TOP : GTK_POS_BOTTOM);
    } else {
      /* Draw the tab and the gap
       * We want the gap to be positioned exactly on the tabpanel top
       * border; since tabbox.css may set a negative margin so that the tab
       * frame rect already overlaps the tabpanel frame rect, we need to take
       * that into account when drawing. To that effect, nsNativeThemeGTK
       * passes us this negative margin (bmargin in the graphic below) in the
       * lowest bits of |flags|.  We use it to set gap_voffset, the distance
       * between the top of the gap and the bottom of the tab (resp. the
       * bottom of the gap and the top of the tab when we draw a bottom tab),
       * while ensuring that the gap always touches the border of the tab,
       * i.e. 0 <= gap_voffset <= gap_height, to avoid surprinsing results
       * with big negative or positive margins.
       * Here is a graphical explanation in the case of top tabs:
       *             ___________________________
       *            /                           \
       *           |            T A B            |
       * ----------|. . . . . . . . . . . . . . .|----- top of tabpanel
       *           :    ^       bmargin          :  ^
       *           :    | (-negative margin,     :  |
       *  bottom   :    v  passed in flags)      :  |       gap_height
       *    of  -> :.............................:  |    (the size of the
       * the tab   .       part of the gap       .  |  tabpanel top border)
       *           .      outside of the tab     .  v
       * ----------------------------------------------
       *
       * To draw the gap, we use gtk_render_frame_gap(), see comment in
       * moz_gtk_tabpanels_paint(). This gap is made 3 * gap_height tall,
       * which should suffice to ensure that the only visible border is the
       * pierced one.  If the tab is in the middle, we make the box_gap begin
       * a bit to the left of the tab and end a bit to the right, adjusting
       * the gap position so it still is under the tab, because we want the
       * rendering of a gap in the middle of a tabpanel.  This is the role of
       * the gints gap_{l,r}_offset. On the contrary, if the tab is the
       * first, we align the start border of the box_gap with the start
       * border of the tab (left if LTR, right if RTL), by setting the
       * appropriate offset to 0.*/
      gint gap_loffset, gap_roffset, gap_voffset, gap_height;

      /* Get height needed by the gap */
      gap_height = moz_gtk_get_tab_thickness(style);

      /* Extract gap_voffset from the first bits of flags */
      gap_voffset = flags & MOZ_GTK_TAB_MARGIN_MASK;
      if (gap_voffset > gap_height) gap_voffset = gap_height;

      /* Set gap_{l,r}_offset to appropriate values */
      gap_loffset = gap_roffset = 20; /* should be enough */
      if (flags & MOZ_GTK_TAB_FIRST) {
        if (direction == GTK_TEXT_DIR_RTL)
          gap_roffset = initial_gap;
        else
          gap_loffset = initial_gap;
      }

      GtkStyleContext* panelStyle =
          GetStyleContext(MOZ_GTK_TABPANELS, state->scale, direction);

      if (isBottomTab) {
        /* Draw the tab on bottom */
        focusRect.y += gap_voffset;
        focusRect.height -= gap_voffset;

        gtk_render_extension(style, cr, tabRect.x, tabRect.y + gap_voffset,
                             tabRect.width, tabRect.height - gap_voffset,
                             GTK_POS_TOP);

        backRect.y += (gap_voffset - gap_height);
        backRect.height = gap_height;

        /* Draw the gap; erase with background color before painting in
         * case theme does not */
        gtk_render_background(panelStyle, cr, backRect.x, backRect.y,
                              backRect.width, backRect.height);
        cairo_save(cr);
        cairo_rectangle(cr, backRect.x, backRect.y, backRect.width,
                        backRect.height);
        cairo_clip(cr);

        gtk_render_frame_gap(panelStyle, cr, tabRect.x - gap_loffset,
                             tabRect.y + gap_voffset - 3 * gap_height,
                             tabRect.width + gap_loffset + gap_roffset,
                             3 * gap_height, GTK_POS_BOTTOM, gap_loffset,
                             gap_loffset + tabRect.width);
        cairo_restore(cr);
      } else {
        /* Draw the tab on top */
        focusRect.height -= gap_voffset;
        gtk_render_extension(style, cr, tabRect.x, tabRect.y, tabRect.width,
                             tabRect.height - gap_voffset, GTK_POS_BOTTOM);

        backRect.y += (tabRect.height - gap_voffset);
        backRect.height = gap_height;

        /* Draw the gap; erase with background color before painting in
         * case theme does not */
        gtk_render_background(panelStyle, cr, backRect.x, backRect.y,
                              backRect.width, backRect.height);

        cairo_save(cr);
        cairo_rectangle(cr, backRect.x, backRect.y, backRect.width,
                        backRect.height);
        cairo_clip(cr);

        gtk_render_frame_gap(panelStyle, cr, tabRect.x - gap_loffset,
                             tabRect.y + tabRect.height - gap_voffset,
                             tabRect.width + gap_loffset + gap_roffset,
                             3 * gap_height, GTK_POS_TOP, gap_loffset,
                             gap_loffset + tabRect.width);
        cairo_restore(cr);
      }
    }
  } else {
    gtk_render_background(style, cr, tabRect.x, tabRect.y, tabRect.width,
                          tabRect.height);
    gtk_render_frame(style, cr, tabRect.x, tabRect.y, tabRect.width,
                     tabRect.height);
  }

  if (state->focused) {
    /* Paint the focus ring */
    GtkBorder padding;
    gtk_style_context_get_padding(style, GetStateFlagsFromGtkWidgetState(state),
                                  &padding);

    focusRect.x += padding.left;
    focusRect.width -= (padding.left + padding.right);
    focusRect.y += padding.top;
    focusRect.height -= (padding.top + padding.bottom);

    gtk_render_focus(style, cr, focusRect.x, focusRect.y, focusRect.width,
                     focusRect.height);
  }

  return MOZ_GTK_SUCCESS;
}

/* tab area*/
static gint moz_gtk_tabpanels_paint(cairo_t* cr, GdkRectangle* rect,
                                    GtkWidgetState* state,
                                    GtkTextDirection direction) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_TABPANELS, state->scale, direction);
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  /*
   * The gap size is not needed in moz_gtk_tabpanels_paint because
   * the gap will be painted with the foreground tab in moz_gtk_tab_paint.
   *
   * However, if moz_gtk_tabpanels_paint just uses gtk_render_frame(),
   * the theme will think that there are no tabs and may draw something
   * different.Hence the trick of using two clip regions, and drawing the
   * gap outside each clip region, to get the correct frame for
   * a tabpanel with tabs.
   */
  /* left side */
  cairo_save(cr);
  cairo_rectangle(cr, rect->x, rect->y, rect->x + rect->width / 2,
                  rect->y + rect->height);
  cairo_clip(cr);
  gtk_render_frame_gap(style, cr, rect->x, rect->y, rect->width, rect->height,
                       GTK_POS_TOP, rect->width - 1, rect->width);
  cairo_restore(cr);

  /* right side */
  cairo_save(cr);
  cairo_rectangle(cr, rect->x + rect->width / 2, rect->y, rect->x + rect->width,
                  rect->y + rect->height);
  cairo_clip(cr);
  gtk_render_frame_gap(style, cr, rect->x, rect->y, rect->width, rect->height,
                       GTK_POS_TOP, 0, 1);
  cairo_restore(cr);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_tab_scroll_arrow_paint(cairo_t* cr, GdkRectangle* rect,
                                           GtkWidgetState* state,
                                           GtkArrowType arrow_type,
                                           GtkTextDirection direction) {
  GtkStyleContext* style;
  gdouble arrow_angle;
  gint arrow_size = MIN(rect->width, rect->height);
  gint x = rect->x + (rect->width - arrow_size) / 2;
  gint y = rect->y + (rect->height - arrow_size) / 2;

  if (direction == GTK_TEXT_DIR_RTL) {
    arrow_type =
        (arrow_type == GTK_ARROW_LEFT) ? GTK_ARROW_RIGHT : GTK_ARROW_LEFT;
  }
  switch (arrow_type) {
    case GTK_ARROW_LEFT:
      arrow_angle = ARROW_LEFT;
      break;
    case GTK_ARROW_RIGHT:
      arrow_angle = ARROW_RIGHT;
      break;
    case GTK_ARROW_DOWN:
      arrow_angle = ARROW_DOWN;
      break;
    default:
      arrow_angle = ARROW_UP;
      break;
  }
  if (arrow_type != GTK_ARROW_NONE) {
    style = GetStyleContext(MOZ_GTK_TAB_SCROLLARROW, state->scale, direction,
                            GetStateFlagsFromGtkWidgetState(state));
    gtk_render_arrow(style, cr, arrow_angle, x, y, arrow_size);
  }
  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_menu_bar_paint(cairo_t* cr, GdkRectangle* rect,
                                   GtkWidgetState* state,
                                   GtkTextDirection direction) {
  GtkStyleContext* style;

  GtkWidget* widget = GetWidget(MOZ_GTK_MENUBAR);
  gtk_widget_set_direction(widget, direction);

  style = gtk_widget_get_style_context(widget);
  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_MENUBAR);
  StyleContextSetScale(style, state->scale);

  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_style_context_restore(style);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_menu_popup_paint(cairo_t* cr, GdkRectangle* rect,
                                     GtkWidgetState* state,
                                     GtkTextDirection direction) {
  GtkStyleContext* style;

  GtkWidget* widget = GetWidget(MOZ_GTK_MENUPOPUP);
  gtk_widget_set_direction(widget, direction);

  // Draw a backing toplevel. This fixes themes that don't provide a menu
  // background, and depend on the GtkMenu's implementation window to provide
  // it.
  moz_gtk_window_paint(cr, rect, direction);

  style = gtk_widget_get_style_context(widget);
  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_MENU);
  StyleContextSetScale(style, state->scale);

  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_style_context_restore(style);

  return MOZ_GTK_SUCCESS;
}

// See gtk_menu_item_draw() for reference.
static gint moz_gtk_menu_separator_paint(cairo_t* cr, GdkRectangle* rect,
                                         GtkWidgetState* state,
                                         GtkTextDirection direction) {
  GtkWidgetState defaultState = {0};
  moz_gtk_menu_item_paint(MOZ_GTK_MENUSEPARATOR, cr, rect, &defaultState,
                          direction);

  if (gtk_get_minor_version() >= 20) return MOZ_GTK_SUCCESS;

  GtkStyleContext* style;
  gboolean wide_separators;
  gint separator_height;
  gint x, y, w;
  GtkBorder padding;

  style = GetStyleContext(MOZ_GTK_MENUSEPARATOR, state->scale, direction);
  gtk_style_context_get_padding(style, gtk_style_context_get_state(style),
                                &padding);

  x = rect->x;
  y = rect->y;
  w = rect->width;

  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_SEPARATOR);

  gtk_style_context_get_style(style, "wide-separators", &wide_separators,
                              "separator-height", &separator_height, NULL);

  if (wide_separators) {
    gtk_render_frame(style, cr, x + padding.left, y + padding.top,
                     w - padding.left - padding.right, separator_height);
  } else {
    gtk_render_line(style, cr, x + padding.left, y + padding.top,
                    x + w - padding.right - 1, y + padding.top);
  }

  gtk_style_context_restore(style);

  return MOZ_GTK_SUCCESS;
}

// See gtk_menu_item_draw() for reference.
static gint moz_gtk_menu_item_paint(WidgetNodeType widget, cairo_t* cr,
                                    GdkRectangle* rect, GtkWidgetState* state,
                                    GtkTextDirection direction) {
  gint x, y, w, h;
  guint minorVersion = gtk_get_minor_version();
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);

  // GTK versions prior to 3.8 render the background and frame only when not
  // a separator and in hover prelight.
  if (minorVersion < 8 && (widget == MOZ_GTK_MENUSEPARATOR ||
                           !(state_flags & GTK_STATE_FLAG_PRELIGHT)))
    return MOZ_GTK_SUCCESS;

  GtkStyleContext* style =
      GetStyleContext(widget, state->scale, direction, state_flags);

  if (minorVersion < 6) {
    // GTK+ 3.4 saves the style context and adds the menubar class to
    // menubar children, but does each of these only when drawing, not
    // during layout.
    gtk_style_context_save(style);
    if (widget == MOZ_GTK_MENUBARITEM) {
      gtk_style_context_add_class(style, GTK_STYLE_CLASS_MENUBAR);
    }
  }

  x = rect->x;
  y = rect->y;
  w = rect->width;
  h = rect->height;

  gtk_render_background(style, cr, x, y, w, h);
  gtk_render_frame(style, cr, x, y, w, h);

  if (minorVersion < 6) {
    gtk_style_context_restore(style);
  }

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_menu_arrow_paint(cairo_t* cr, GdkRectangle* rect,
                                     GtkWidgetState* state,
                                     GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_MENUITEM, state->scale, direction, state_flags);
  gtk_render_arrow(style, cr,
                   (direction == GTK_TEXT_DIR_LTR) ? ARROW_RIGHT : ARROW_LEFT,
                   rect->x, rect->y, rect->width);
  return MOZ_GTK_SUCCESS;
}

// For reference, see gtk_check_menu_item_size_allocate() in GTK versions after
// 3.20 and gtk_real_check_menu_item_draw_indicator() in earlier versions.
static gint moz_gtk_check_menu_item_paint(WidgetNodeType widgetType,
                                          cairo_t* cr, GdkRectangle* rect,
                                          GtkWidgetState* state,
                                          gboolean checked,
                                          GtkTextDirection direction) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style;
  gint indicator_size, horizontal_padding;
  gint x, y;

  moz_gtk_menu_item_paint(MOZ_GTK_MENUITEM, cr, rect, state, direction);

  if (checked) {
    state_flags =
        static_cast<GtkStateFlags>(state_flags | checkbox_check_state);
  }

  bool pre_3_20 = gtk_get_minor_version() < 20;
  gint offset;
  style = GetStyleContext(widgetType, state->scale, direction);
  gtk_style_context_get_style(style, "indicator-size", &indicator_size,
                              "horizontal-padding", &horizontal_padding, NULL);
  if (pre_3_20) {
    GtkBorder padding;
    gtk_style_context_get_padding(style, state_flags, &padding);
    offset = horizontal_padding + padding.left + 2;
  } else {
    GdkRectangle r = {0};
    InsetByMargin(&r, style);
    InsetByBorderPadding(&r, style);
    offset = r.x;
  }

  bool isRadio = (widgetType == MOZ_GTK_RADIOMENUITEM);
  WidgetNodeType indicatorType = isRadio ? MOZ_GTK_RADIOMENUITEM_INDICATOR
                                         : MOZ_GTK_CHECKMENUITEM_INDICATOR;
  const ToggleGTKMetrics* metrics = GetToggleMetrics(indicatorType);
  style = GetStyleContext(indicatorType, state->scale, direction, state_flags);

  if (direction == GTK_TEXT_DIR_RTL) {
    x = rect->width - indicator_size - offset;
  } else {
    x = rect->x + offset;
  }
  y = rect->y + (rect->height - indicator_size) / 2;

  gint indicator_width, indicator_height;
  indicator_width = indicator_height = indicator_size;
  if (!pre_3_20) {
    gtk_render_background(style, cr, x, y, indicator_size, indicator_size);
    gtk_render_frame(style, cr, x, y, indicator_size, indicator_size);
    x = x + metrics->borderAndPadding.left;
    y = y + metrics->borderAndPadding.top;
    indicator_width = metrics->minSizeWithBorder.width -
                      metrics->borderAndPadding.left -
                      metrics->borderAndPadding.right;
    indicator_height = metrics->minSizeWithBorder.height -
                       metrics->borderAndPadding.top -
                       metrics->borderAndPadding.bottom;
  }

  if (isRadio) {
    gtk_render_option(style, cr, x, y, indicator_width, indicator_height);
  } else {
    gtk_render_check(style, cr, x, y, indicator_width, indicator_height);
  }

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_info_bar_paint(cairo_t* cr, GdkRectangle* rect,
                                   GtkWidgetState* state) {
  GtkStyleContext* style =
      GetStyleContext(MOZ_GTK_INFO_BAR, state->scale, GTK_TEXT_DIR_LTR,
                      GetStateFlagsFromGtkWidgetState(state));
  gtk_render_background(style, cr, rect->x, rect->y, rect->width, rect->height);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width, rect->height);

  return MOZ_GTK_SUCCESS;
}

static gint moz_gtk_header_bar_paint(WidgetNodeType widgetType, cairo_t* cr,
                                     GdkRectangle* rect,
                                     GtkWidgetState* state) {
  GtkStateFlags state_flags = GetStateFlagsFromGtkWidgetState(state);
  GtkStyleContext* style =
      GetStyleContext(widgetType, state->scale, GTK_TEXT_DIR_NONE, state_flags);

// Some themes (Adwaita for instance) draws bold dark line at
// titlebar bottom. It does not fit well with Firefox tabs so
// draw with some extent to make the titlebar bottom part invisible.
#define TITLEBAR_EXTENT 4

  // We don't need to draw window decoration for MOZ_GTK_HEADER_BAR_MAXIMIZED,
  // i.e. when main window is maximized.
  if (widgetType == MOZ_GTK_HEADER_BAR) {
    GtkStyleContext* windowStyle =
        GetStyleContext(MOZ_GTK_HEADERBAR_WINDOW, state->scale);
    bool solidDecorations =
        gtk_style_context_has_class(windowStyle, "solid-csd");
    GtkStyleContext* decorationStyle =
        GetStyleContext(solidDecorations ? MOZ_GTK_WINDOW_DECORATION_SOLID
                                         : MOZ_GTK_WINDOW_DECORATION,
                        state->scale, GTK_TEXT_DIR_LTR, state_flags);

    gtk_render_background(decorationStyle, cr, rect->x, rect->y, rect->width,
                          rect->height + TITLEBAR_EXTENT);
    gtk_render_frame(decorationStyle, cr, rect->x, rect->y, rect->width,
                     rect->height + TITLEBAR_EXTENT);
  }

  gtk_render_background(style, cr, rect->x, rect->y, rect->width,
                        rect->height + TITLEBAR_EXTENT);
  gtk_render_frame(style, cr, rect->x, rect->y, rect->width,
                   rect->height + TITLEBAR_EXTENT);

  return MOZ_GTK_SUCCESS;
}

static GtkBorder GetMarginBorderPadding(GtkStyleContext* aStyle) {
  gint left = 0, top = 0, right = 0, bottom = 0;
  moz_gtk_add_margin_border_padding(aStyle, &left, &top, &right, &bottom);
  // narrowing conversions to gint16:
  GtkBorder result;
  result.left = left;
  result.right = right;
  result.top = top;
  result.bottom = bottom;
  return result;
}

gint moz_gtk_get_widget_border(WidgetNodeType widget, gint* left, gint* top,
                               gint* right, gint* bottom,
                               // NOTE: callers depend on direction being used
                               // only for MOZ_GTK_DROPDOWN widgets.
                               GtkTextDirection direction) {
  GtkWidget* w;
  GtkStyleContext* style;
  *left = *top = *right = *bottom = 0;

  switch (widget) {
    case MOZ_GTK_BUTTON:
    case MOZ_GTK_TOOLBAR_BUTTON: {
      style = GetStyleContext(MOZ_GTK_BUTTON);

      *left = *top = *right = *bottom = gtk_container_get_border_width(
          GTK_CONTAINER(GetWidget(MOZ_GTK_BUTTON)));

      if (widget == MOZ_GTK_TOOLBAR_BUTTON) {
        gtk_style_context_save(style);
        gtk_style_context_add_class(style, "image-button");
      }

      moz_gtk_add_style_padding(style, left, top, right, bottom);

      if (widget == MOZ_GTK_TOOLBAR_BUTTON) gtk_style_context_restore(style);

      moz_gtk_add_style_border(style, left, top, right, bottom);

      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_ENTRY:
    case MOZ_GTK_DROPDOWN_ENTRY: {
      style = GetStyleContext(widget);

      // XXX: Subtract 1 pixel from the padding to account for the default
      // padding in forms.css. See bug 1187385.
      *left = *top = *right = *bottom = -1;
      moz_gtk_add_border_padding(style, left, top, right, bottom);

      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_TEXT_VIEW:
    case MOZ_GTK_TREEVIEW: {
      style = GetStyleContext(MOZ_GTK_SCROLLED_WINDOW);
      moz_gtk_add_style_border(style, left, top, right, bottom);
      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_TREE_HEADER_CELL: {
      /* A Tree Header in GTK is just a different styled button
       * It must be placed in a TreeView for getting the correct style
       * assigned.
       * That is why the following code is the same as for MOZ_GTK_BUTTON.
       * */
      *left = *top = *right = *bottom = gtk_container_get_border_width(
          GTK_CONTAINER(GetWidget(MOZ_GTK_TREE_HEADER_CELL)));
      style = GetStyleContext(MOZ_GTK_TREE_HEADER_CELL);
      moz_gtk_add_border_padding(style, left, top, right, bottom);
      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_TREE_HEADER_SORTARROW:
      w = GetWidget(MOZ_GTK_TREE_HEADER_SORTARROW);
      break;
    case MOZ_GTK_DROPDOWN_ARROW:
      w = GetWidget(MOZ_GTK_COMBOBOX_ENTRY_BUTTON);
      break;
    case MOZ_GTK_DROPDOWN: {
      /* We need to account for the arrow on the dropdown, so text
       * doesn't come too close to the arrow, or in some cases spill
       * into the arrow. */
      gboolean wide_separators;
      gint separator_width;
      GtkRequisition arrow_req;
      GtkBorder border;

      *left = *top = *right = *bottom = gtk_container_get_border_width(
          GTK_CONTAINER(GetWidget(MOZ_GTK_COMBOBOX_BUTTON)));
      style = GetStyleContext(MOZ_GTK_COMBOBOX_BUTTON);
      moz_gtk_add_border_padding(style, left, top, right, bottom);

      /* If there is no separator, don't try to count its width. */
      separator_width = 0;
      GtkWidget* comboBoxSeparator = GetWidget(MOZ_GTK_COMBOBOX_SEPARATOR);
      if (comboBoxSeparator) {
        style = gtk_widget_get_style_context(comboBoxSeparator);
        gtk_style_context_get_style(style, "wide-separators", &wide_separators,
                                    "separator-width", &separator_width, NULL);

        if (!wide_separators) {
          gtk_style_context_get_border(
              style, gtk_style_context_get_state(style), &border);
          separator_width = border.left;
        }
      }

      gtk_widget_get_preferred_size(GetWidget(MOZ_GTK_COMBOBOX_ARROW), NULL,
                                    &arrow_req);
      moz_gtk_sanity_preferred_size(&arrow_req);

      if (direction == GTK_TEXT_DIR_RTL)
        *left += separator_width + arrow_req.width;
      else
        *right += separator_width + arrow_req.width;

      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_TABPANELS:
      w = GetWidget(MOZ_GTK_TABPANELS);
      break;
    case MOZ_GTK_PROGRESSBAR:
      w = GetWidget(MOZ_GTK_PROGRESSBAR);
      break;
    case MOZ_GTK_SPINBUTTON_ENTRY:
    case MOZ_GTK_SPINBUTTON_UP:
    case MOZ_GTK_SPINBUTTON_DOWN:
      w = GetWidget(MOZ_GTK_SPINBUTTON);
      break;
    case MOZ_GTK_SCALE_HORIZONTAL:
    case MOZ_GTK_SCALE_VERTICAL:
      w = GetWidget(widget);
      break;
    case MOZ_GTK_FRAME:
      w = GetWidget(MOZ_GTK_FRAME);
      break;
    case MOZ_GTK_CHECKBUTTON_CONTAINER:
    case MOZ_GTK_RADIOBUTTON_CONTAINER: {
      w = GetWidget(widget);
      style = gtk_widget_get_style_context(w);

      *left = *top = *right = *bottom =
          gtk_container_get_border_width(GTK_CONTAINER(w));
      moz_gtk_add_border_padding(style, left, top, right, bottom);
      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_MENUPOPUP:
      w = GetWidget(MOZ_GTK_MENUPOPUP);
      break;
    case MOZ_GTK_MENUBARITEM:
    case MOZ_GTK_MENUITEM:
    case MOZ_GTK_CHECKMENUITEM:
    case MOZ_GTK_RADIOMENUITEM: {
      // Bug 1274143 for MOZ_GTK_MENUBARITEM
      WidgetNodeType type =
          widget == MOZ_GTK_MENUBARITEM ? MOZ_GTK_MENUITEM : widget;
      style = GetStyleContext(type);

      if (gtk_get_minor_version() < 20) {
        moz_gtk_add_style_padding(style, left, top, right, bottom);
      } else {
        moz_gtk_add_margin_border_padding(style, left, top, right, bottom);
      }
      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_INFO_BAR:
      w = GetWidget(MOZ_GTK_INFO_BAR);
      break;
    case MOZ_GTK_TOOLTIP: {
      // In GTK 3 there are 6 pixels of additional margin around the box.
      // See details there:
      // https://github.com/GNOME/gtk/blob/5ea69a136bd7e4970b3a800390e20314665aaed2/gtk/ui/gtktooltipwindow.ui#L11
      *left = *right = *top = *bottom = 6;

      // We also need to add margin/padding/borders from Tooltip content.
      // Tooltip contains horizontal box, where icon and label is put.
      // We ignore icon as long as we don't have support for it.
      GtkStyleContext* boxStyle = GetStyleContext(MOZ_GTK_TOOLTIP_BOX);
      moz_gtk_add_margin_border_padding(boxStyle, left, top, right, bottom);

      GtkStyleContext* labelStyle = GetStyleContext(MOZ_GTK_TOOLTIP_BOX_LABEL);
      moz_gtk_add_margin_border_padding(labelStyle, left, top, right, bottom);

      return MOZ_GTK_SUCCESS;
    }
    case MOZ_GTK_HEADER_BAR_BUTTON_BOX: {
      style = GetStyleContext(MOZ_GTK_HEADER_BAR);
      moz_gtk_add_border_padding(style, left, top, right, bottom);
      *top = *bottom = 0;
      bool leftButtonsPlacement = false;
      GetGtkHeaderBarButtonLayout({}, &leftButtonsPlacement);
      if (direction == GTK_TEXT_DIR_RTL) {
        leftButtonsPlacement = !leftButtonsPlacement;
      }
      if (leftButtonsPlacement) {
        *right = 0;
      } else {
        *left = 0;
      }
      return MOZ_GTK_SUCCESS;
    }
    /* These widgets have no borders, since they are not containers. */
    case MOZ_GTK_CHECKBUTTON_LABEL:
    case MOZ_GTK_RADIOBUTTON_LABEL:
    case MOZ_GTK_SPLITTER_HORIZONTAL:
    case MOZ_GTK_SPLITTER_VERTICAL:
    case MOZ_GTK_CHECKBUTTON:
    case MOZ_GTK_RADIOBUTTON:
    case MOZ_GTK_SCROLLBAR_BUTTON:
    case MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL:
    case MOZ_GTK_SCROLLBAR_THUMB_VERTICAL:
    case MOZ_GTK_SCALE_THUMB_HORIZONTAL:
    case MOZ_GTK_SCALE_THUMB_VERTICAL:
    case MOZ_GTK_GRIPPER:
    case MOZ_GTK_PROGRESS_CHUNK:
    case MOZ_GTK_PROGRESS_CHUNK_INDETERMINATE:
    case MOZ_GTK_PROGRESS_CHUNK_VERTICAL_INDETERMINATE:
    case MOZ_GTK_TREEVIEW_EXPANDER:
    case MOZ_GTK_TOOLBAR_SEPARATOR:
    case MOZ_GTK_MENUSEPARATOR:
    case MOZ_GTK_HEADER_BAR:
    case MOZ_GTK_HEADER_BAR_MAXIMIZED:
    case MOZ_GTK_HEADER_BAR_BUTTON_CLOSE:
    case MOZ_GTK_HEADER_BAR_BUTTON_MINIMIZE:
    case MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE:
    case MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE_RESTORE:
    /* These widgets have no borders.*/
    case MOZ_GTK_INNER_SPIN_BUTTON:
    case MOZ_GTK_SPINBUTTON:
    case MOZ_GTK_WINDOW:
    case MOZ_GTK_RESIZER:
    case MOZ_GTK_MENUARROW:
    case MOZ_GTK_TOOLBARBUTTON_ARROW:
    case MOZ_GTK_TOOLBAR:
    case MOZ_GTK_MENUBAR:
    case MOZ_GTK_TAB_SCROLLARROW:
      return MOZ_GTK_SUCCESS;
    default:
      g_warning("Unsupported widget type: %d", widget);
      return MOZ_GTK_UNKNOWN_WIDGET;
  }
  /* TODO - we're still missing some widget implementations */
  if (w) {
    moz_gtk_add_style_border(gtk_widget_get_style_context(w), left, top, right,
                             bottom);
  }
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_get_tab_border(gint* left, gint* top, gint* right, gint* bottom,
                            GtkTextDirection direction, GtkTabFlags flags,
                            WidgetNodeType widget) {
  GtkStyleContext* style = GetStyleContext(widget, 1, direction,
                                           GetStateFlagsFromGtkTabFlags(flags));

  *left = *top = *right = *bottom = 0;
  moz_gtk_add_style_padding(style, left, top, right, bottom);

  // Gtk >= 3.20 does not use those styles
  if (gtk_check_version(3, 20, 0) != nullptr) {
    int tab_curvature;

    gtk_style_context_get_style(style, "tab-curvature", &tab_curvature, NULL);
    *left += tab_curvature;
    *right += tab_curvature;

    if (flags & MOZ_GTK_TAB_FIRST) {
      int initial_gap = 0;
      gtk_style_context_get_style(style, "initial-gap", &initial_gap, NULL);
      if (direction == GTK_TEXT_DIR_RTL)
        *right += initial_gap;
      else
        *left += initial_gap;
    }
  } else {
    GtkBorder margin;

    gtk_style_context_get_margin(style, gtk_style_context_get_state(style),
                                 &margin);
    *left += margin.left;
    *right += margin.right;

    if (flags & MOZ_GTK_TAB_FIRST) {
      style = GetStyleContext(MOZ_GTK_NOTEBOOK_HEADER, direction);
      gtk_style_context_get_margin(style, gtk_style_context_get_state(style),
                                   &margin);
      *left += margin.left;
      *right += margin.right;
    }
  }

  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_get_combo_box_entry_button_size(gint* width, gint* height) {
  /*
   * We get the requisition of the drop down button, which includes
   * all padding, border and focus line widths the button uses,
   * as well as the minimum arrow size and its padding
   * */
  GtkRequisition requisition;

  gtk_widget_get_preferred_size(GetWidget(MOZ_GTK_COMBOBOX_ENTRY_BUTTON), NULL,
                                &requisition);
  moz_gtk_sanity_preferred_size(&requisition);

  *width = requisition.width;
  *height = requisition.height;

  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_get_tab_scroll_arrow_size(gint* width, gint* height) {
  gint arrow_size;

  GtkStyleContext* style = GetStyleContext(MOZ_GTK_TABPANELS);
  gtk_style_context_get_style(style, "scroll-arrow-hlength", &arrow_size, NULL);

  *height = *width = arrow_size;

  return MOZ_GTK_SUCCESS;
}

void moz_gtk_get_arrow_size(WidgetNodeType widgetType, gint* width,
                            gint* height) {
  GtkWidget* widget;
  switch (widgetType) {
    case MOZ_GTK_DROPDOWN:
      widget = GetWidget(MOZ_GTK_COMBOBOX_ARROW);
      break;
    default:
      widget = GetWidget(MOZ_GTK_BUTTON_ARROW);
      break;
  }

  GtkRequisition requisition;
  gtk_widget_get_preferred_size(widget, NULL, &requisition);
  moz_gtk_sanity_preferred_size(&requisition);

  *width = requisition.width;
  *height = requisition.height;
}

gint moz_gtk_get_toolbar_separator_width(gint* size) {
  gboolean wide_separators;
  gint separator_width;
  GtkBorder border;

  GtkStyleContext* style = GetStyleContext(MOZ_GTK_TOOLBAR);
  gtk_style_context_get_style(style, "space-size", size, "wide-separators",
                              &wide_separators, "separator-width",
                              &separator_width, NULL);
  /* Just in case... */
  gtk_style_context_get_border(style, gtk_style_context_get_state(style),
                               &border);
  *size = MAX(*size, (wide_separators ? separator_width : border.left));
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_get_expander_size(gint* size) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_EXPANDER);
  gtk_style_context_get_style(style, "expander-size", size, NULL);
  return MOZ_GTK_SUCCESS;
}

gint moz_gtk_get_treeview_expander_size(gint* size) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_TREEVIEW);
  gtk_style_context_get_style(style, "expander-size", size, NULL);
  return MOZ_GTK_SUCCESS;
}

// See gtk_menu_item_draw() for reference.
gint moz_gtk_get_menu_separator_height(gint* size) {
  gboolean wide_separators;
  gint separator_height;
  GtkBorder padding;
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_MENUSEPARATOR);
  gtk_style_context_get_padding(style, gtk_style_context_get_state(style),
                                &padding);

  gtk_style_context_save(style);
  gtk_style_context_add_class(style, GTK_STYLE_CLASS_SEPARATOR);

  gtk_style_context_get_style(style, "wide-separators", &wide_separators,
                              "separator-height", &separator_height, NULL);

  gtk_style_context_restore(style);

  *size = padding.top + padding.bottom;
  *size += (wide_separators) ? separator_height : 1;

  return MOZ_GTK_SUCCESS;
}

void moz_gtk_get_entry_min_height(gint* min_content_height,
                                  gint* border_padding_height) {
  GtkStyleContext* style = GetStyleContext(MOZ_GTK_ENTRY);
  if (!gtk_check_version(3, 20, 0)) {
    gtk_style_context_get(style, gtk_style_context_get_state(style),
                          "min-height", min_content_height, nullptr);
  } else {
    *min_content_height = 0;
  }

  GtkBorder border;
  GtkBorder padding;
  gtk_style_context_get_border(style, gtk_style_context_get_state(style),
                               &border);
  gtk_style_context_get_padding(style, gtk_style_context_get_state(style),
                                &padding);

  *border_padding_height =
      (border.top + border.bottom + padding.top + padding.bottom);
}

void moz_gtk_get_scale_metrics(GtkOrientation orient, gint* scale_width,
                               gint* scale_height) {
  if (gtk_check_version(3, 20, 0) != nullptr) {
    WidgetNodeType widget = (orient == GTK_ORIENTATION_HORIZONTAL)
                                ? MOZ_GTK_SCALE_HORIZONTAL
                                : MOZ_GTK_SCALE_VERTICAL;

    gint thumb_length, thumb_height, trough_border;
    moz_gtk_get_scalethumb_metrics(orient, &thumb_length, &thumb_height);

    GtkStyleContext* style = GetStyleContext(widget);
    gtk_style_context_get_style(style, "trough-border", &trough_border, NULL);

    if (orient == GTK_ORIENTATION_HORIZONTAL) {
      *scale_width = thumb_length + trough_border * 2;
      *scale_height = thumb_height + trough_border * 2;
    } else {
      *scale_width = thumb_height + trough_border * 2;
      *scale_height = thumb_length + trough_border * 2;
    }
  } else {
    WidgetNodeType widget = (orient == GTK_ORIENTATION_HORIZONTAL)
                                ? MOZ_GTK_SCALE_TROUGH_HORIZONTAL
                                : MOZ_GTK_SCALE_TROUGH_VERTICAL;
    moz_gtk_get_widget_min_size(GetStyleContext(widget), scale_width,
                                scale_height);
  }
}

gint moz_gtk_get_scalethumb_metrics(GtkOrientation orient, gint* thumb_length,
                                    gint* thumb_height) {
  if (gtk_check_version(3, 20, 0) != nullptr) {
    WidgetNodeType widget = (orient == GTK_ORIENTATION_HORIZONTAL)
                                ? MOZ_GTK_SCALE_HORIZONTAL
                                : MOZ_GTK_SCALE_VERTICAL;
    GtkStyleContext* style = GetStyleContext(widget);
    gtk_style_context_get_style(style, "slider_length", thumb_length,
                                "slider_width", thumb_height, NULL);
  } else {
    WidgetNodeType widget = (orient == GTK_ORIENTATION_HORIZONTAL)
                                ? MOZ_GTK_SCALE_THUMB_HORIZONTAL
                                : MOZ_GTK_SCALE_THUMB_VERTICAL;
    GtkStyleContext* style = GetStyleContext(widget);

    gint min_width, min_height;
    GtkStateFlags state = gtk_style_context_get_state(style);
    gtk_style_context_get(style, state, "min-width", &min_width, "min-height",
                          &min_height, nullptr);
    GtkBorder margin;
    gtk_style_context_get_margin(style, state, &margin);
    gint margin_width = margin.left + margin.right;
    gint margin_height = margin.top + margin.bottom;

    // Negative margin of slider element also determines its minimal size
    // so use bigger of those two values.
    if (min_width < -margin_width) min_width = -margin_width;
    if (min_height < -margin_height) min_height = -margin_height;

    *thumb_length = min_width;
    *thumb_height = min_height;
  }

  return MOZ_GTK_SUCCESS;
}

static MozGtkSize SizeFromLengthAndBreadth(GtkOrientation aOrientation,
                                           gint aLength, gint aBreadth) {
  return aOrientation == GTK_ORIENTATION_HORIZONTAL
             ? MozGtkSize({aLength, aBreadth})
             : MozGtkSize({aBreadth, aLength});
}

const ToggleGTKMetrics* GetToggleMetrics(WidgetNodeType aWidgetType) {
  ToggleGTKMetrics* metrics;

  switch (aWidgetType) {
    case MOZ_GTK_RADIOBUTTON:
      metrics = &sRadioMetrics;
      break;
    case MOZ_GTK_CHECKBUTTON:
      metrics = &sCheckboxMetrics;
      break;
    case MOZ_GTK_RADIOMENUITEM_INDICATOR:
      metrics = &sMenuRadioMetrics;
      break;
    case MOZ_GTK_CHECKMENUITEM_INDICATOR:
      metrics = &sMenuCheckboxMetrics;
      break;
    default:
      MOZ_CRASH("Unsupported widget type for getting metrics");
      return nullptr;
  }

  metrics->initialized = true;
  if (gtk_check_version(3, 20, 0) == nullptr) {
    GtkStyleContext* style = GetStyleContext(aWidgetType);
    GtkStateFlags state_flags = gtk_style_context_get_state(style);
    gtk_style_context_get(style, state_flags, "min-height",
                          &(metrics->minSizeWithBorder.height), "min-width",
                          &(metrics->minSizeWithBorder.width), nullptr);
    // Fallback to indicator size if min dimensions are zero
    if (metrics->minSizeWithBorder.height == 0 ||
        metrics->minSizeWithBorder.width == 0) {
      gint indicator_size;
      gtk_widget_style_get(GetWidget(MOZ_GTK_CHECKBUTTON_CONTAINER),
                           "indicator_size", &indicator_size, nullptr);
      if (metrics->minSizeWithBorder.height == 0) {
        metrics->minSizeWithBorder.height = indicator_size;
      }
      if (metrics->minSizeWithBorder.width == 0) {
        metrics->minSizeWithBorder.width = indicator_size;
      }
    }

    GtkBorder border, padding;
    gtk_style_context_get_border(style, state_flags, &border);
    gtk_style_context_get_padding(style, state_flags, &padding);
    metrics->borderAndPadding.left = border.left + padding.left;
    metrics->borderAndPadding.right = border.right + padding.right;
    metrics->borderAndPadding.top = border.top + padding.top;
    metrics->borderAndPadding.bottom = border.bottom + padding.bottom;
    metrics->minSizeWithBorder.width +=
        metrics->borderAndPadding.left + metrics->borderAndPadding.right;
    metrics->minSizeWithBorder.height +=
        metrics->borderAndPadding.top + metrics->borderAndPadding.bottom;
  } else {
    gint indicator_size, indicator_spacing;
    gtk_widget_style_get(GetWidget(MOZ_GTK_CHECKBUTTON_CONTAINER),
                         "indicator_size", &indicator_size, "indicator_spacing",
                         &indicator_spacing, nullptr);
    metrics->minSizeWithBorder.width = metrics->minSizeWithBorder.height =
        indicator_size;
  }
  return metrics;
}

static void InitScrollbarMetrics(ScrollbarGTKMetrics* aMetrics,
                                 GtkOrientation aOrientation,
                                 GtkStateFlags aStateFlags) {
  WidgetNodeType scrollbar = aOrientation == GTK_ORIENTATION_HORIZONTAL
                                 ? MOZ_GTK_SCROLLBAR_HORIZONTAL
                                 : MOZ_GTK_SCROLLBAR_VERTICAL;

  gboolean backward, forward, secondary_backward, secondary_forward;
  GtkStyleContext* style =
      GetStyleContext(scrollbar, 1, GTK_TEXT_DIR_NONE, aStateFlags);
  gtk_style_context_get_style(
      style, "has-backward-stepper", &backward, "has-forward-stepper", &forward,
      "has-secondary-backward-stepper", &secondary_backward,
      "has-secondary-forward-stepper", &secondary_forward, nullptr);
  bool hasButtons =
      backward || forward || secondary_backward || secondary_forward;

  if (gtk_get_minor_version() < 20) {
    gint slider_width, trough_border, stepper_size, min_slider_size;

    gtk_style_context_get_style(style, "slider-width", &slider_width,
                                "trough-border", &trough_border, "stepper-size",
                                &stepper_size, "min-slider-length",
                                &min_slider_size, nullptr);

    aMetrics->size.thumb =
        SizeFromLengthAndBreadth(aOrientation, min_slider_size, slider_width);
    aMetrics->size.button =
        SizeFromLengthAndBreadth(aOrientation, stepper_size, slider_width);
    // overall scrollbar
    gint breadth = slider_width + 2 * trough_border;
    // Require room for the slider in the track if we don't have buttons.
    gint length = hasButtons ? 0 : min_slider_size + 2 * trough_border;
    aMetrics->size.scrollbar =
        SizeFromLengthAndBreadth(aOrientation, length, breadth);

    // Borders on the major axis are set on the outermost scrollbar
    // element to correctly position the buttons when
    // trough-under-steppers is true.
    // Borders on the minor axis are set on the track element so that it
    // receives mouse events, as in GTK.
    // Other borders have been zero-initialized.
    if (aOrientation == GTK_ORIENTATION_HORIZONTAL) {
      aMetrics->border.scrollbar.left = aMetrics->border.scrollbar.right =
          aMetrics->border.track.top = aMetrics->border.track.bottom =
              trough_border;
    } else {
      aMetrics->border.scrollbar.top = aMetrics->border.scrollbar.bottom =
          aMetrics->border.track.left = aMetrics->border.track.right =
              trough_border;
    }

    // We're done here for Gtk+ < 3.20...
    return;
  }

  // GTK version > 3.20
  // scrollbar
  aMetrics->border.scrollbar = GetMarginBorderPadding(style);

  WidgetNodeType contents, track, thumb;
  if (aOrientation == GTK_ORIENTATION_HORIZONTAL) {
    contents = MOZ_GTK_SCROLLBAR_CONTENTS_HORIZONTAL;
    track = MOZ_GTK_SCROLLBAR_TROUGH_HORIZONTAL;
    thumb = MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL;
  } else {
    contents = MOZ_GTK_SCROLLBAR_CONTENTS_VERTICAL;
    track = MOZ_GTK_SCROLLBAR_TROUGH_VERTICAL;
    thumb = MOZ_GTK_SCROLLBAR_THUMB_VERTICAL;
  }

  /* GetStyleContext() sets GtkStateFlags to the latest widget name
   * in css selector string. When we call:
   *
   *     GetStyleContext(thumb, GTK_STATE_FLAG_PRELIGHT)
   *
   * we get:
   *
   *    "scrollbar contents trough slider:hover"
   *
   * Some themes (Ubuntu Ambiance) styles trough/thumb by scrollbar,
   * the Gtk+ css rule looks like:
   *
   *    "scrollbar:hover contents trough slider"
   *
   *  So we need to apply GtkStateFlags to each widgets in style path.
   */

  // thumb
  style =
      CreateStyleContextWithStates(thumb, 1, GTK_TEXT_DIR_NONE, aStateFlags);
  aMetrics->size.thumb = GetMinMarginBox(style);
  gtk_style_context_get_margin(style, gtk_style_context_get_state(style),
                               &aMetrics->margin.thumb);
  g_object_unref(style);

  // track
  style =
      CreateStyleContextWithStates(track, 1, GTK_TEXT_DIR_NONE, aStateFlags);
  aMetrics->border.track = GetMarginBorderPadding(style);
  MozGtkSize trackMinSize = GetMinContentBox(style) + aMetrics->border.track;
  MozGtkSize trackSizeForThumb = aMetrics->size.thumb + aMetrics->border.track;
  g_object_unref(style);

  // button
  if (hasButtons) {
    style = CreateStyleContextWithStates(MOZ_GTK_SCROLLBAR_BUTTON, 1,
                                         GTK_TEXT_DIR_NONE, aStateFlags);
    aMetrics->size.button = GetMinMarginBox(style);
    g_object_unref(style);
  } else {
    aMetrics->size.button = {0, 0};
  }
  if (aOrientation == GTK_ORIENTATION_HORIZONTAL) {
    aMetrics->size.button.Rotate();
    // If the track is wider than necessary for the thumb, including when
    // the buttons will cause Gecko to expand the track to fill
    // available breadth, then add to the track border to prevent Gecko
    // from expanding the thumb to fill available breadth.
    gint extra = std::max(trackMinSize.height, aMetrics->size.button.height) -
                 trackSizeForThumb.height;
    if (extra > 0) {
      // If extra is odd, then the thumb is 0.5 pixels above
      // center as in gtk_range_compute_slider_position().
      aMetrics->border.track.top += extra / 2;
      aMetrics->border.track.bottom += extra - extra / 2;
      // Update size for change in border.
      trackSizeForThumb.height += extra;
    }
  } else {
    gint extra = std::max(trackMinSize.width, aMetrics->size.button.width) -
                 trackSizeForThumb.width;
    if (extra > 0) {
      // If extra is odd, then the thumb is 0.5 pixels to the left
      // of center as in gtk_range_compute_slider_position().
      aMetrics->border.track.left += extra / 2;
      aMetrics->border.track.right += extra - extra / 2;
      trackSizeForThumb.width += extra;
    }
  }

  style =
      CreateStyleContextWithStates(contents, 1, GTK_TEXT_DIR_NONE, aStateFlags);
  GtkBorder contentsBorder = GetMarginBorderPadding(style);
  g_object_unref(style);

  aMetrics->size.scrollbar =
      trackSizeForThumb + contentsBorder + aMetrics->border.scrollbar;
}

const ScrollbarGTKMetrics* GetScrollbarMetrics(GtkOrientation aOrientation) {
  auto metrics = &sScrollbarMetrics[aOrientation];
  if (!metrics->initialized) {
    InitScrollbarMetrics(metrics, aOrientation, GTK_STATE_FLAG_NORMAL);

    // We calculate thumb margin here because it's composited from
    // thumb class margin + difference margin between active and inactive
    // scrollbars. It's a workaround which alows us to emulate
    // overlay scrollbars for some Gtk+ themes (Ubuntu/Ambiance),
    // when an inactive scrollbar thumb is smaller than the active one.
    const ScrollbarGTKMetrics* metricsActive =
        GetActiveScrollbarMetrics(aOrientation);

    if (metrics->size.thumb < metricsActive->size.thumb) {
      metrics->margin.thumb +=
          (metrics->border.scrollbar + metrics->border.track) -
          (metricsActive->border.scrollbar + metricsActive->border.track);
    }

    metrics->initialized = true;
  }
  return metrics;
}

const ScrollbarGTKMetrics* GetActiveScrollbarMetrics(
    GtkOrientation aOrientation) {
  auto metrics = &sActiveScrollbarMetrics[aOrientation];
  if (!metrics->initialized) {
    InitScrollbarMetrics(metrics, aOrientation, GTK_STATE_FLAG_PRELIGHT);
    metrics->initialized = true;
  }
  return metrics;
}

/*
 * get_shadow_width() from gtkwindow.c is not public so we need
 * to implement it.
 */
void InitWindowDecorationSize(CSDWindowDecorationSize* sWindowDecorationSize,
                              bool aPopupWindow) {
  bool solidDecorations = gtk_style_context_has_class(
      GetStyleContext(MOZ_GTK_HEADERBAR_WINDOW, 1), "solid-csd");
  // solid-csd does not use frame extents, quit now.
  if (solidDecorations) {
    sWindowDecorationSize->decorationSize = {0, 0, 0, 0};
    return;
  }

  // Scale factor is applied later when decoration size is used for actual
  // gtk windows.
  GtkStyleContext* context = GetStyleContext(MOZ_GTK_WINDOW_DECORATION);

  /* Always sum border + padding */
  GtkBorder padding;
  GtkStateFlags state = gtk_style_context_get_state(context);
  gtk_style_context_get_border(context, state,
                               &sWindowDecorationSize->decorationSize);
  gtk_style_context_get_padding(context, state, &padding);
  sWindowDecorationSize->decorationSize += padding;

  // Available on GTK 3.20+.
  static auto sGtkRenderBackgroundGetClip = (void (*)(
      GtkStyleContext*, gdouble, gdouble, gdouble, gdouble,
      GdkRectangle*))dlsym(RTLD_DEFAULT, "gtk_render_background_get_clip");

  if (!sGtkRenderBackgroundGetClip) {
    return;
  }

  GdkRectangle clip;
  sGtkRenderBackgroundGetClip(context, 0, 0, 0, 0, &clip);

  GtkBorder extents;
  extents.top = -clip.y;
  extents.right = clip.width + clip.x;
  extents.bottom = clip.height + clip.y;
  extents.left = -clip.x;

  // Get shadow extents but combine with style margin; use the bigger value.
  // Margin is used for resize grip size - it's not present on
  // popup windows.
  if (!aPopupWindow) {
    GtkBorder margin;
    gtk_style_context_get_margin(context, state, &margin);

    extents.top = MAX(extents.top, margin.top);
    extents.right = MAX(extents.right, margin.right);
    extents.bottom = MAX(extents.bottom, margin.bottom);
    extents.left = MAX(extents.left, margin.left);
  }

  sWindowDecorationSize->decorationSize += extents;
}

GtkBorder GetCSDDecorationSize(bool aIsPopup) {
  auto metrics =
      aIsPopup ? &sPopupWindowDecorationSize : &sToplevelWindowDecorationSize;
  if (!metrics->initialized) {
    InitWindowDecorationSize(metrics, aIsPopup);
    metrics->initialized = true;
  }
  return metrics->decorationSize;
}

/* cairo_t *cr argument has to be a system-cairo. */
gint moz_gtk_widget_paint(WidgetNodeType widget, cairo_t* cr,
                          GdkRectangle* rect, GtkWidgetState* state, gint flags,
                          GtkTextDirection direction) {
  /* A workaround for https://bugzilla.gnome.org/show_bug.cgi?id=694086
   */
  cairo_new_path(cr);

  switch (widget) {
    case MOZ_GTK_BUTTON:
    case MOZ_GTK_TOOLBAR_BUTTON:
      if (state->depressed) {
        return moz_gtk_button_paint(cr, rect, state, (GtkReliefStyle)flags,
                                    GetWidget(MOZ_GTK_TOGGLE_BUTTON),
                                    direction);
      }
      return moz_gtk_button_paint(cr, rect, state, (GtkReliefStyle)flags,
                                  GetWidget(MOZ_GTK_BUTTON), direction);
    case MOZ_GTK_HEADER_BAR_BUTTON_CLOSE:
    case MOZ_GTK_HEADER_BAR_BUTTON_MINIMIZE:
    case MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE:
    case MOZ_GTK_HEADER_BAR_BUTTON_MAXIMIZE_RESTORE:
      return moz_gtk_header_bar_button_paint(
          cr, rect, state, (GtkReliefStyle)flags, widget, direction);
    case MOZ_GTK_CHECKBUTTON:
    case MOZ_GTK_RADIOBUTTON:
      return moz_gtk_toggle_paint(cr, rect, state,
                                  !!(flags & MOZ_GTK_WIDGET_CHECKED),
                                  !!(flags & MOZ_GTK_WIDGET_INCONSISTENT),
                                  (widget == MOZ_GTK_RADIOBUTTON), direction);
    case MOZ_GTK_SCROLLBAR_BUTTON:
      return moz_gtk_scrollbar_button_paint(
          cr, rect, state, (GtkScrollbarButtonFlags)flags, direction);
    case MOZ_GTK_SCROLLBAR_HORIZONTAL:
    case MOZ_GTK_SCROLLBAR_VERTICAL: {
      if (flags & MOZ_GTK_TRACK_OPAQUE) {
        GtkStyleContext* style = GetStyleContext(MOZ_GTK_WINDOW, direction);
        gtk_render_background(style, cr, rect->x, rect->y, rect->width,
                              rect->height);
      }
      if (gtk_check_version(3, 20, 0) == nullptr) {
        return moz_gtk_scrollbar_paint(widget, cr, rect, state, direction);
      }
      WidgetNodeType trough_widget = (widget == MOZ_GTK_SCROLLBAR_HORIZONTAL)
                                         ? MOZ_GTK_SCROLLBAR_TROUGH_HORIZONTAL
                                         : MOZ_GTK_SCROLLBAR_TROUGH_VERTICAL;
      return moz_gtk_scrollbar_trough_paint(trough_widget, cr, rect, state,
                                            direction);
    }
    case MOZ_GTK_SCROLLBAR_TROUGH_HORIZONTAL:
    case MOZ_GTK_SCROLLBAR_TROUGH_VERTICAL:
      if (gtk_check_version(3, 20, 0) == nullptr) {
        return moz_gtk_scrollbar_trough_paint(widget, cr, rect, state,
                                              direction);
      }
      break;
    case MOZ_GTK_SCROLLBAR_THUMB_HORIZONTAL:
    case MOZ_GTK_SCROLLBAR_THUMB_VERTICAL:
      return moz_gtk_scrollbar_thumb_paint(widget, cr, rect, state, direction);
    case MOZ_GTK_SCALE_HORIZONTAL:
    case MOZ_GTK_SCALE_VERTICAL:
      return moz_gtk_scale_paint(cr, rect, state, (GtkOrientation)flags,
                                 direction);
    case MOZ_GTK_SCALE_THUMB_HORIZONTAL:
    case MOZ_GTK_SCALE_THUMB_VERTICAL:
      return moz_gtk_scale_thumb_paint(cr, rect, state, (GtkOrientation)flags,
                                       direction);
    case MOZ_GTK_INNER_SPIN_BUTTON:
      return moz_gtk_inner_spin_paint(cr, rect, state, direction);
    case MOZ_GTK_SPINBUTTON:
      return moz_gtk_spin_paint(cr, rect, state, direction);
    case MOZ_GTK_SPINBUTTON_UP:
    case MOZ_GTK_SPINBUTTON_DOWN:
      return moz_gtk_spin_updown_paint(
          cr, rect, (widget == MOZ_GTK_SPINBUTTON_DOWN), state, direction);
    case MOZ_GTK_SPINBUTTON_ENTRY: {
      GtkStyleContext* style =
          GetStyleContext(MOZ_GTK_SPINBUTTON_ENTRY, state->scale, direction,
                          GetStateFlagsFromGtkWidgetState(state));
      return moz_gtk_entry_paint(cr, rect, state, style, widget);
    }
    case MOZ_GTK_GRIPPER:
      return moz_gtk_gripper_paint(cr, rect, state, direction);
    case MOZ_GTK_TREEVIEW:
      return moz_gtk_treeview_paint(cr, rect, state, direction);
    case MOZ_GTK_TREE_HEADER_CELL:
      return moz_gtk_tree_header_cell_paint(cr, rect, state, flags, direction);
    case MOZ_GTK_TREE_HEADER_SORTARROW:
      return moz_gtk_tree_header_sort_arrow_paint(
          cr, rect, state, (GtkArrowType)flags, direction);
    case MOZ_GTK_TREEVIEW_EXPANDER:
      return moz_gtk_treeview_expander_paint(
          cr, rect, state, (GtkExpanderStyle)flags, direction);
    case MOZ_GTK_ENTRY:
    case MOZ_GTK_DROPDOWN_ENTRY: {
      GtkStyleContext* style =
          GetStyleContext(widget, state->scale, direction,
                          GetStateFlagsFromGtkWidgetState(state));
      gint ret = moz_gtk_entry_paint(cr, rect, state, style, widget);
      return ret;
    }
    case MOZ_GTK_TEXT_VIEW:
      return moz_gtk_text_view_paint(cr, rect, state, direction);
    case MOZ_GTK_DROPDOWN:
      return moz_gtk_combo_box_paint(cr, rect, state, direction);
    case MOZ_GTK_DROPDOWN_ARROW:
      return moz_gtk_combo_box_entry_button_paint(cr, rect, state, flags,
                                                  direction);
    case MOZ_GTK_CHECKBUTTON_CONTAINER:
    case MOZ_GTK_RADIOBUTTON_CONTAINER:
      return moz_gtk_container_paint(cr, rect, state, widget, direction);
    case MOZ_GTK_CHECKBUTTON_LABEL:
    case MOZ_GTK_RADIOBUTTON_LABEL:
      return moz_gtk_toggle_label_paint(
          cr, rect, state, (widget == MOZ_GTK_RADIOBUTTON_LABEL), direction);
    case MOZ_GTK_TOOLBAR:
      return moz_gtk_toolbar_paint(cr, rect, state, direction);
    case MOZ_GTK_TOOLBAR_SEPARATOR:
      return moz_gtk_toolbar_separator_paint(cr, rect, state, direction);
    case MOZ_GTK_TOOLTIP:
      return moz_gtk_tooltip_paint(cr, rect, state, direction);
    case MOZ_GTK_FRAME:
      return moz_gtk_frame_paint(cr, rect, state, direction);
    case MOZ_GTK_RESIZER:
      return moz_gtk_resizer_paint(cr, rect, state, direction);
    case MOZ_GTK_PROGRESSBAR:
      return moz_gtk_progressbar_paint(cr, rect, state, direction);
    case MOZ_GTK_PROGRESS_CHUNK:
    case MOZ_GTK_PROGRESS_CHUNK_INDETERMINATE:
    case MOZ_GTK_PROGRESS_CHUNK_VERTICAL_INDETERMINATE:
      return moz_gtk_progress_chunk_paint(cr, rect, state, direction, widget);
    case MOZ_GTK_TAB_TOP:
    case MOZ_GTK_TAB_BOTTOM:
      return moz_gtk_tab_paint(cr, rect, state, (GtkTabFlags)flags, direction,
                               widget);
    case MOZ_GTK_TABPANELS:
      return moz_gtk_tabpanels_paint(cr, rect, state, direction);
    case MOZ_GTK_TAB_SCROLLARROW:
      return moz_gtk_tab_scroll_arrow_paint(cr, rect, state,
                                            (GtkArrowType)flags, direction);
    case MOZ_GTK_MENUBAR:
      return moz_gtk_menu_bar_paint(cr, rect, state, direction);
    case MOZ_GTK_MENUPOPUP:
      return moz_gtk_menu_popup_paint(cr, rect, state, direction);
    case MOZ_GTK_MENUSEPARATOR:
      return moz_gtk_menu_separator_paint(cr, rect, state, direction);
    case MOZ_GTK_MENUBARITEM:
    case MOZ_GTK_MENUITEM:
      return moz_gtk_menu_item_paint(widget, cr, rect, state, direction);
    case MOZ_GTK_MENUARROW:
      return moz_gtk_menu_arrow_paint(cr, rect, state, direction);
    case MOZ_GTK_TOOLBARBUTTON_ARROW:
      return moz_gtk_arrow_paint(cr, rect, state, (GtkArrowType)flags,
                                 direction);
    case MOZ_GTK_CHECKMENUITEM:
    case MOZ_GTK_RADIOMENUITEM:
      return moz_gtk_check_menu_item_paint(widget, cr, rect, state,
                                           (gboolean)flags, direction);
    case MOZ_GTK_SPLITTER_HORIZONTAL:
      return moz_gtk_vpaned_paint(cr, rect, state);
    case MOZ_GTK_SPLITTER_VERTICAL:
      return moz_gtk_hpaned_paint(cr, rect, state);
    case MOZ_GTK_WINDOW:
      return moz_gtk_window_paint(cr, rect, direction);
    case MOZ_GTK_INFO_BAR:
      return moz_gtk_info_bar_paint(cr, rect, state);
    case MOZ_GTK_HEADER_BAR:
    case MOZ_GTK_HEADER_BAR_MAXIMIZED:
      return moz_gtk_header_bar_paint(widget, cr, rect, state);
    default:
      g_warning("Unknown widget type: %d", widget);
  }

  return MOZ_GTK_UNKNOWN_WIDGET;
}

gint moz_gtk_shutdown() {
  /* This will destroy all of our widgets */
  ResetWidgetCache();

  return MOZ_GTK_SUCCESS;
}