summaryrefslogtreecommitdiff
path: root/gtk/gtkicontheme.c
blob: 820ef733481f86c381dcd324423e3ee883fdaefe (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
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
/* GtkIconTheme - a loader for icon themes
 * gtk-icon-theme.c Copyright (C) 2002, 2003 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <sys/types.h>
#include <sys/stat.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <glib.h>
#include <glib/gstdio.h>

#ifdef G_OS_WIN32
#ifndef S_ISDIR
#define S_ISDIR(mode) ((mode)&_S_IFDIR)
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shellapi.h>
#include "win32/gdkwin32.h"
#endif /* G_OS_WIN32 */

#include "gtkiconthemeprivate.h"
#include "gtkcsspalettevalueprivate.h"
#include "gtkcsscolorvalueprivate.h"
#include "gtkdebug.h"
#include "gtkiconcacheprivate.h"
#include "gtkintl.h"
#include "gtkmain.h"
#include "gtksettingsprivate.h"
#include "gtkstylecontextprivate.h"
#include "gtkprivate.h"
#include "gdkpixbufutilsprivate.h"
#include "gdk/gdktextureprivate.h"
#include "gdk/gdkprofilerprivate.h"

/* this is in case round() is not provided by the compiler, 
 * such as in the case of C89 compilers, like MSVC
 */
#include "fallback-c89.c"

/**
 * SECTION:gtkicontheme
 * @Short_description: Looking up icons by name
 * @Title: GtkIconTheme
 *
 * #GtkIconTheme provides a facility for looking up icons by name
 * and size. The main reason for using a name rather than simply
 * providing a filename is to allow different icons to be used
 * depending on what “icon theme” is selected
 * by the user. The operation of icon themes on Linux and Unix
 * follows the [Icon Theme Specification](http://www.freedesktop.org/Standards/icon-theme-spec)
 * There is a fallback icon theme, named `hicolor`, where applications
 * should install their icons, but additional icon themes can be installed
 * as operating system vendors and users choose.
 *
 * In many cases, named themes are used indirectly, via #GtkImage
 * rather than directly, but looking up icons
 * directly is also simple. The #GtkIconTheme object acts
 * as a database of all the icons in the current theme. You
 * can create new #GtkIconTheme objects, but it’s much more
 * efficient to use the standard icon theme for the #GdkDisplay
 * so that the icon information is shared with other people
 * looking up icons.
 * |[<!-- language="C" -->
 * GError *error = NULL;
 * GtkIconTheme *icon_theme;
 * GdkPaintable *paintable;
 *
 * icon_theme = gtk_icon_theme_get_default ();
 * paintable = gtk_icon_theme_load_icon (icon_theme,
 *                                       "my-icon-name", // icon name
 *                                       48, // icon size
 *                                       0,  // flags
 *                                       &error);
 * if (!paintable)
 *   {
 *     g_warning ("Couldn’t load icon: %s", error->message);
 *     g_error_free (error);
 *   }
 * else
 *   {
 *     // Use the icon
 *     g_object_unref (paintable);
 *   }
 * ]|
 */

#define FALLBACK_ICON_THEME "hicolor"

typedef enum
{
  ICON_THEME_DIR_FIXED,  
  ICON_THEME_DIR_SCALABLE,  
  ICON_THEME_DIR_THRESHOLD,
  ICON_THEME_DIR_UNTHEMED
} IconThemeDirType;

/* In reverse search order: */
typedef enum
{
  ICON_SUFFIX_NONE = 0,
  ICON_SUFFIX_XPM = 1 << 0,
  ICON_SUFFIX_SVG = 1 << 1,
  ICON_SUFFIX_PNG = 1 << 2,
  HAS_ICON_FILE = 1 << 3,
  ICON_SUFFIX_SYMBOLIC_PNG = 1 << 4
} IconSuffix;

#if 0
#define DEBUG_CACHE(args) g_print args
#else
#define DEBUG_CACHE(args)
#endif

#define LRU_CACHE_SIZE 100
#define MAX_LRU_TEXTURE_SIZE 128

typedef struct _GtkIconInfoClass    GtkIconInfoClass;
typedef struct _GtkIconThemeClass   GtkIconThemeClass;

/**
 * GtkIconTheme:
 *
 * Acts as a database of information about an icon theme.
 * Normally, you retrieve the icon theme for a particular
 * display using gtk_icon_theme_get_for_display() and it
 * will contain information about current icon theme for
 * that display, but you can also create a new #GtkIconTheme
 * object and set the icon theme name explicitly using
 * gtk_icon_theme_set_custom_theme().
 */
struct _GtkIconTheme
{
  GObject parent_instance;

  GHashTable *info_cache;

  GtkIconInfo *lru_cache[LRU_CACHE_SIZE];
  int lru_cache_next;

  gchar *current_theme;
  gchar **search_path;
  gint search_path_len;
  GList *resource_paths;

  guint custom_theme         : 1;
  guint is_display_singleton : 1;
  guint pixbuf_supports_svg  : 1;
  guint themes_valid         : 1;
  guint loading_themes       : 1;

  /* A list of all the themes needed to look up icons.
   * In search order, without duplicates
   */
  GList *themes;
  GHashTable *unthemed_icons;

  /* GdkDisplay for the icon theme (may be NULL) */
  GdkDisplay *display;

  /* time when we last stat:ed for theme changes */
  glong last_stat_time;
  GList *dir_mtimes;

  gulong theme_changed_idle;
};

struct _GtkIconThemeClass
{
  GObjectClass parent_class;

  void (* changed)  (GtkIconTheme *self);
};

typedef struct {
  gchar **icon_names;
  gint size;
  gint scale;
  GtkIconLookupFlags flags;
} IconInfoKey;

struct _GtkIconInfoClass
{
  GObjectClass parent_class;
};

/**
 * GtkIconInfo:
 *
 * Contains information found when looking up an icon in
 * an icon theme.
 */
struct _GtkIconInfo
{
  GObject parent_instance;

  /* Information about the source
   */
  IconInfoKey key;
  GtkIconTheme *in_cache;

  gchar *filename;
  GLoadableIcon *loadable;

  /* Cache pixbuf (if there is any) */
  GdkPixbuf *cache_pixbuf;

  /* Information about the directory where
   * the source was found
   */
  IconThemeDirType dir_type;
  gint dir_size;
  gint dir_scale;
  gint min_size;
  gint max_size;

  /* Parameters influencing the scaled icon
   */
  gint desired_size;
  gint desired_scale;
  guint forced_size     : 1;
  guint is_svg          : 1;
  guint is_resource     : 1;

  /* Cached information if we go ahead and try to load
   * the icon.
   */
  GdkTexture *texture;
  GError *load_error;
  gdouble unscaled_scale;
  gdouble scale;

  gint symbolic_width;
  gint symbolic_height;
};

typedef struct
{
  gchar *name;
  gchar *display_name;
  gchar *comment;

  /* In search order */
  GList *dirs;
} IconTheme;

typedef struct
{
  IconThemeDirType type;
  GQuark context;

  gint size;
  gint min_size;
  gint max_size;
  gint threshold;
  gint scale;
  gboolean is_resource;

  gchar *dir;
  gchar *subdir;
  gint subdir_index;
  
  GtkIconCache *cache;
  
  GHashTable *icons;
} IconThemeDir;

typedef struct
{
  gchar *svg_filename;
  gchar *no_svg_filename;
  gboolean is_resource;
} UnthemedIcon;

typedef struct 
{
  gchar *dir;
  time_t mtime;
  GtkIconCache *cache;
  gboolean exists;
} IconThemeDirMtime;

static void         gtk_icon_theme_finalize   (GObject          *object);
static void         theme_dir_destroy         (IconThemeDir     *dir);
static void         theme_destroy              (IconTheme       *theme);
static GtkIconInfo *theme_lookup_icon         (IconTheme        *theme,
                                               const gchar      *icon_name,
                                               gint              size,
                                               gint              scale,
                                               gboolean          allow_svg);
static void         theme_list_icons          (IconTheme        *theme,
                                               GHashTable       *icons,
                                               GQuark            context);
static gboolean     theme_has_icon            (IconTheme        *theme,
                                               const gchar      *icon_name);
static void         theme_subdir_load         (GtkIconTheme     *self,
                                               IconTheme        *theme,
                                               GKeyFile         *theme_file,
                                               gchar            *subdir);
static void         do_theme_change           (GtkIconTheme     *self);
static void         blow_themes               (GtkIconTheme     *self);
static gboolean     rescan_themes             (GtkIconTheme     *self);
static IconSuffix   theme_dir_get_icon_suffix (IconThemeDir     *dir,
                                               const gchar      *icon_name);
static GtkIconInfo *icon_info_new             (IconThemeDirType  type,
                                               gint              dir_size,
                                               gint              dir_scale);
static IconSuffix   suffix_from_name          (const gchar      *name);
static gboolean     icon_info_ensure_scale_and_texture (GtkIconInfo* icon_info);

static guint signal_changed = 0;

static guint
icon_info_key_hash (gconstpointer _key)
{
  const IconInfoKey *key = _key;
  guint h = 0;
  int i;
  for (i = 0; key->icon_names[i] != NULL; i++)
    h ^= g_str_hash (key->icon_names[i]);

  h ^= key->size * 0x10001;
  h ^= key->scale * 0x1000010;
  h ^= key->flags * 0x100000100;

  return h;
}

static gboolean
icon_info_key_equal (gconstpointer _a,
                     gconstpointer _b)
{
  const IconInfoKey *a = _a;
  const IconInfoKey *b = _b;
  int i;

  if (a->size != b->size)
    return FALSE;

  if (a->scale != b->scale)
    return FALSE;

  if (a->flags != b->flags)
    return FALSE;

  for (i = 0;
       a->icon_names[i] != NULL &&
       b->icon_names[i] != NULL; i++)
    {
      if (strcmp (a->icon_names[i], b->icon_names[i]) != 0)
        return FALSE;
    }

  return a->icon_names[i] == NULL && b->icon_names[i] == NULL;
}

G_DEFINE_TYPE (GtkIconTheme, gtk_icon_theme, G_TYPE_OBJECT)

static void
add_to_lru_cache (GtkIconInfo *info)
{
  GtkIconTheme *self = info->in_cache;

  if (!self)
    return;

  if (info->texture &&
      info->texture->width <= MAX_LRU_TEXTURE_SIZE &&
      info->texture->height <= MAX_LRU_TEXTURE_SIZE)
    {
      g_set_object (&self->lru_cache[self->lru_cache_next], info);
      self->lru_cache_next = (self->lru_cache_next + 1) % LRU_CACHE_SIZE;
    }
}

static void
clear_lru_cache (GtkIconTheme *self)
{
  int i;

  for (i = 0; i < LRU_CACHE_SIZE; i ++)
    g_clear_object (&self->lru_cache[i]);
}

/**
 * gtk_icon_theme_new:
 * 
 * Creates a new icon theme object. Icon theme objects are used
 * to lookup up an icon by name in a particular icon theme.
 * Usually, you’ll want to use gtk_icon_theme_get_default()
 * or gtk_icon_theme_get_for_display() rather than creating
 * a new icon theme object for scratch.
 * 
 * Returns: the newly created #GtkIconTheme object.
 */
GtkIconTheme *
gtk_icon_theme_new (void)
{
  return g_object_new (GTK_TYPE_ICON_THEME, NULL);
}

/**
 * gtk_icon_theme_get_default:
 * 
 * Gets the icon theme for the default display. See
 * gtk_icon_theme_get_for_display().
 *
 * Returns: (transfer none): A unique #GtkIconTheme associated with
 *     the default display. This icon theme is associated with
 *     the display and can be used as long as the display
 *     is open. Do not ref or unref it.
 */
GtkIconTheme *
gtk_icon_theme_get_default (void)
{
  return gtk_icon_theme_get_for_display (gdk_display_get_default ());
}

/**
 * gtk_icon_theme_get_for_display:
 * @display: a #GdkDisplay
 * 
 * Gets the icon theme object associated with @display; if this
 * function has not previously been called for the given
 * display, a new icon theme object will be created and
 * associated with the display. Icon theme objects are
 * fairly expensive to create, so using this function
 * is usually a better choice than calling than gtk_icon_theme_new()
 * and setting the display yourself; by using this function
 * a single icon theme object will be shared between users.
 *
 * Returns: (transfer none): A unique #GtkIconTheme associated with
 *  the given display. This icon theme is associated with
 *  the display and can be used as long as the display
 *  is open. Do not ref or unref it.
 */
GtkIconTheme *
gtk_icon_theme_get_for_display (GdkDisplay *display)
{
  GtkIconTheme *self;

  g_return_val_if_fail (GDK_IS_DISPLAY (display), NULL);

  self = g_object_get_data (G_OBJECT (display), "gtk-icon-theme");
  if (!self)
    {
      self = gtk_icon_theme_new ();
      gtk_icon_theme_set_display (self, display);

      self->is_display_singleton = TRUE;

      g_object_set_data (G_OBJECT (display), I_("gtk-icon-theme"), self);
    }

  return self;
}

static void
gtk_icon_theme_class_init (GtkIconThemeClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->finalize = gtk_icon_theme_finalize;

  /**
   * GtkIconTheme::changed:
   * @self: the icon theme
   *
   * Emitted when the current icon theme is switched or GTK+ detects
   * that a change has occurred in the contents of the current
   * icon theme.
   */
  signal_changed = g_signal_new (I_("changed"),
                                 G_TYPE_FROM_CLASS (klass),
                                 G_SIGNAL_RUN_LAST,
                                 G_STRUCT_OFFSET (GtkIconThemeClass, changed),
                                 NULL, NULL,
                                 NULL,
                                 G_TYPE_NONE, 0);
}


/* Callback when the display that the icon theme is attached
 * to is closed; unset the display, and if it’s the unique theme
 * for the display, drop the reference
 */
static void
display_closed (GdkDisplay   *display,
                gboolean      is_error,
                GtkIconTheme *self)
{
  gboolean was_display_singleton = self->is_display_singleton;

  if (was_display_singleton)
    {
      g_object_set_data (G_OBJECT (display), I_("gtk-icon-theme"), NULL);
      self->is_display_singleton = FALSE;
    }

  gtk_icon_theme_set_display (self, NULL);

  if (was_display_singleton)
    {
      g_object_unref (self);
    }
}

static void
update_current_theme (GtkIconTheme *self)
{
#define theme_changed(_old, _new) \
  ((_old && !_new) || (!_old && _new) || \
   (_old && _new && strcmp (_old, _new) != 0))

  if (!self->custom_theme)
    {
      gchar *theme = NULL;
      gboolean changed = FALSE;

      if (self->display)
        {
          GtkSettings *settings = gtk_settings_get_for_display (self->display);
          g_object_get (settings, "gtk-icon-theme-name", &theme, NULL);
        }

      if (theme_changed (self->current_theme, theme))
        {
          g_free (self->current_theme);
          self->current_theme = theme;
          changed = TRUE;
        }
      else
        g_free (theme);

      if (changed)
        do_theme_change (self);
    }
#undef theme_changed
}

/* Callback when the icon theme GtkSetting changes
 */
static void
theme_changed (GtkSettings  *settings,
               GParamSpec   *pspec,
               GtkIconTheme *self)
{
  update_current_theme (self);
}

static void
unset_display (GtkIconTheme *self)
{
  GtkSettings *settings;
  
  if (self->display)
    {
      settings = gtk_settings_get_for_display (self->display);
      
      g_signal_handlers_disconnect_by_func (self->display,
                                            (gpointer) display_closed,
                                            self);
      g_signal_handlers_disconnect_by_func (settings,
                                            (gpointer) theme_changed,
                                            self);

      self->display = NULL;
    }
}

/**
 * gtk_icon_theme_set_display:
 * @self: a #GtkIconTheme
 * @display: a #GdkDisplay
 * 
 * Sets the display for an icon theme; the display is used
 * to track the user’s currently configured icon theme,
 * which might be different for different displays.
 */
void
gtk_icon_theme_set_display (GtkIconTheme *self,
                            GdkDisplay   *display)
{
  GtkSettings *settings;

  g_return_if_fail (GTK_ICON_THEME (self));
  g_return_if_fail (display == NULL || GDK_IS_DISPLAY (display));

  unset_display (self);
  
  if (display)
    {
      settings = gtk_settings_get_for_display (display);
      
      self->display = display;
      
      g_signal_connect (display, "closed",
                        G_CALLBACK (display_closed), self);
      g_signal_connect (settings, "notify::gtk-icon-theme-name",
                        G_CALLBACK (theme_changed), self);
    }

  update_current_theme (self);
}

/* Checks whether a loader for SVG files has been registered
 * with GdkPixbuf.
 */
static gboolean
pixbuf_supports_svg (void)
{
  GSList *formats;
  GSList *tmp_list;
  static gint found_svg = -1;

  if (found_svg != -1)
    return found_svg;

  formats = gdk_pixbuf_get_formats ();

  found_svg = FALSE; 
  for (tmp_list = formats; tmp_list && !found_svg; tmp_list = tmp_list->next)
    {
      gchar **mime_types = gdk_pixbuf_format_get_mime_types (tmp_list->data);
      gchar **mime_type;
      
      for (mime_type = mime_types; *mime_type && !found_svg; mime_type++)
        {
          if (strcmp (*mime_type, "image/svg") == 0)
            found_svg = TRUE;
        }

      g_strfreev (mime_types);
    }

  g_slist_free (formats);
  
  return found_svg;
}

/* The icon info was removed from the icon_info_hash hash table */
static void
icon_info_uncached (GtkIconInfo *icon_info)
{
  DEBUG_CACHE (("removing %p (%s %d 0x%x) from cache (icon_them: %p)  (cache size %d)\n",
                icon_info,
                g_strjoinv (",", icon_info->key.icon_names),
                icon_info->key.size, icon_info->key.flags,
                self,
                icon_theme != NULL ? g_hash_table_size (self->info_cache) : 0));

  icon_info->in_cache = NULL;
}

static void
gtk_icon_theme_init (GtkIconTheme *self)
{
  const gchar * const *xdg_data_dirs;
  int i, j;

  self->info_cache = g_hash_table_new_full (icon_info_key_hash, icon_info_key_equal, NULL,
                                            (GDestroyNotify)icon_info_uncached);

  self->custom_theme = FALSE;

  xdg_data_dirs = g_get_system_data_dirs ();
  for (i = 0; xdg_data_dirs[i]; i++) ;

  self->search_path_len = 2 * i + 2;
  
  self->search_path = g_new (char *, self->search_path_len);
  
  i = 0;
  self->search_path[i++] = g_build_filename (g_get_user_data_dir (), "icons", NULL);
  self->search_path[i++] = g_build_filename (g_get_home_dir (), ".icons", NULL);
  
  for (j = 0; xdg_data_dirs[j]; j++) 
    self->search_path[i++] = g_build_filename (xdg_data_dirs[j], "icons", NULL);

  for (j = 0; xdg_data_dirs[j]; j++) 
    self->search_path[i++] = g_build_filename (xdg_data_dirs[j], "pixmaps", NULL);

  self->resource_paths = g_list_append (NULL, g_strdup ("/org/gtk/libgtk/icons/"));

  self->themes_valid = FALSE;
  self->themes = NULL;
  self->unthemed_icons = NULL;

  self->pixbuf_supports_svg = pixbuf_supports_svg ();
}

static void
free_dir_mtime (IconThemeDirMtime *dir_mtime)
{
  if (dir_mtime->cache)
    gtk_icon_cache_unref (dir_mtime->cache);

  g_free (dir_mtime->dir);
  g_slice_free (IconThemeDirMtime, dir_mtime);
}

static gboolean
theme_changed_idle (gpointer user_data)
{
  GtkIconTheme *self;

  self = GTK_ICON_THEME (user_data);

  g_signal_emit (self, signal_changed, 0);

  if (self->display && self->is_display_singleton)
    gtk_style_context_reset_widgets (self->display);

  self->theme_changed_idle = 0;

  return FALSE;
}

static void
queue_theme_changed (GtkIconTheme *self)
{
  if (!self->theme_changed_idle)
    {
      self->theme_changed_idle = g_idle_add_full (GTK_PRIORITY_RESIZE - 2,
                                                  theme_changed_idle,
                                                  self,
                                                  NULL);
      g_source_set_name_by_id (self->theme_changed_idle, "[gtk] theme_changed_idle");
    }
}

static void
do_theme_change (GtkIconTheme *self)
{
  g_hash_table_remove_all (self->info_cache);
  clear_lru_cache (self);

  if (!self->themes_valid)
    return;

  GTK_DISPLAY_NOTE (self->display, ICONTHEME,
            g_message ("change to icon theme \"%s\"", self->current_theme));
  blow_themes (self);

  queue_theme_changed (self);
}

static void
blow_themes (GtkIconTheme *self)
{
  if (self->themes_valid)
    {
      g_list_free_full (self->themes, (GDestroyNotify) theme_destroy);
      g_list_free_full (self->dir_mtimes, (GDestroyNotify) free_dir_mtime);
      g_hash_table_destroy (self->unthemed_icons);
    }
  self->themes = NULL;
  self->unthemed_icons = NULL;
  self->dir_mtimes = NULL;
  self->themes_valid = FALSE;
}

static void
gtk_icon_theme_finalize (GObject *object)
{
  GtkIconTheme *self = GTK_ICON_THEME (object);
  int i;

  g_hash_table_destroy (self->info_cache);

  if (self->theme_changed_idle)
    g_source_remove (self->theme_changed_idle);

  unset_display (self);

  g_free (self->current_theme);

  for (i = 0; i < self->search_path_len; i++)
    g_free (self->search_path[i]);
  g_free (self->search_path);

  g_list_free_full (self->resource_paths, g_free);

  blow_themes (self);
  clear_lru_cache (self);

  G_OBJECT_CLASS (gtk_icon_theme_parent_class)->finalize (object);
}

/**
 * gtk_icon_theme_set_search_path:
 * @self: a #GtkIconTheme
 * @path: (array length=n_elements) (element-type filename): array of
 *     directories that are searched for icon themes
 * @n_elements: number of elements in @path.
 * 
 * Sets the search path for the icon theme object. When looking
 * for an icon theme, GTK+ will search for a subdirectory of
 * one or more of the directories in @path with the same name
 * as the icon theme containing an index.theme file. (Themes from
 * multiple of the path elements are combined to allow themes to be
 * extended by adding icons in the user’s home directory.)
 *
 * In addition if an icon found isn’t found either in the current
 * icon theme or the default icon theme, and an image file with
 * the right name is found directly in one of the elements of
 * @path, then that image will be used for the icon name.
 * (This is legacy feature, and new icons should be put
 * into the fallback icon theme, which is called hicolor,
 * rather than directly on the icon path.)
 */
void
gtk_icon_theme_set_search_path (GtkIconTheme *self,
                                const gchar  *path[],
                                gint          n_elements)
{
  gint i;

  g_return_if_fail (GTK_IS_ICON_THEME (self));

  for (i = 0; i < self->search_path_len; i++)
    g_free (self->search_path[i]);

  g_free (self->search_path);

  self->search_path = g_new (gchar *, n_elements);
  self->search_path_len = n_elements;

  for (i = 0; i < self->search_path_len; i++)
    self->search_path[i] = g_strdup (path[i]);

  do_theme_change (self);
}

/**
 * gtk_icon_theme_get_search_path:
 * @self: a #GtkIconTheme
 * @path: (allow-none) (array length=n_elements) (element-type filename) (out):
 *     location to store a list of icon theme path directories or %NULL.
 *     The stored value should be freed with g_strfreev().
 * @n_elements: location to store number of elements in @path, or %NULL
 *
 * Gets the current search path. See gtk_icon_theme_set_search_path().
 */
void
gtk_icon_theme_get_search_path (GtkIconTheme  *self,
                                gchar        **path[],
                                gint          *n_elements)
{
  gint i;

  g_return_if_fail (GTK_IS_ICON_THEME (self));

  if (n_elements)
    *n_elements = self->search_path_len;
  
  if (path)
    {
      *path = g_new (gchar *, self->search_path_len + 1);
      for (i = 0; i < self->search_path_len; i++)
        (*path)[i] = g_strdup (self->search_path[i]);
      (*path)[i] = NULL;
    }
}

/**
 * gtk_icon_theme_append_search_path:
 * @self: a #GtkIconTheme
 * @path: (type filename): directory name to append to the icon path
 * 
 * Appends a directory to the search path. 
 * See gtk_icon_theme_set_search_path(). 
 */
void
gtk_icon_theme_append_search_path (GtkIconTheme *self,
                                   const gchar  *path)
{
  g_return_if_fail (GTK_IS_ICON_THEME (self));
  g_return_if_fail (path != NULL);

  self->search_path_len++;

  self->search_path = g_renew (gchar *, self->search_path, self->search_path_len);
  self->search_path[self->search_path_len-1] = g_strdup (path);

  do_theme_change (self);
}

/**
 * gtk_icon_theme_prepend_search_path:
 * @self: a #GtkIconTheme
 * @path: (type filename): directory name to prepend to the icon path
 * 
 * Prepends a directory to the search path. 
 * See gtk_icon_theme_set_search_path().
 */
void
gtk_icon_theme_prepend_search_path (GtkIconTheme *self,
                                    const gchar  *path)
{
  gint i;

  g_return_if_fail (GTK_IS_ICON_THEME (self));
  g_return_if_fail (path != NULL);

  self->search_path_len++;
  self->search_path = g_renew (gchar *, self->search_path, self->search_path_len);

  for (i = self->search_path_len - 1; i > 0; i--)
    self->search_path[i] = self->search_path[i - 1];
  
  self->search_path[0] = g_strdup (path);

  do_theme_change (self);
}

/**
 * gtk_icon_theme_add_resource_path:
 * @self: a #GtkIconTheme
 * @path: a resource path
 *
 * Adds a resource path that will be looked at when looking
 * for icons, similar to search paths.
 *
 * This function should be used to make application-specific icons
 * available as part of the icon theme.
 *
 * The resources are considered as part of the hicolor icon theme
 * and must be located in subdirectories that are defined in the
 * hicolor icon theme, such as `@path/16x16/actions/run.png`.
 * Icons that are directly placed in the resource path instead
 * of a subdirectory are also considered as ultimate fallback.
 */
void
gtk_icon_theme_add_resource_path (GtkIconTheme *self,
                                  const gchar  *path)
{
  g_return_if_fail (GTK_IS_ICON_THEME (self));
  g_return_if_fail (path != NULL);

  self->resource_paths = g_list_append (self->resource_paths, g_strdup (path));

  do_theme_change (self);
}

/**
 * gtk_icon_theme_set_custom_theme:
 * @self: a #GtkIconTheme
 * @theme_name: (allow-none): name of icon theme to use instead of
 *   configured theme, or %NULL to unset a previously set custom theme
 * 
 * Sets the name of the icon theme that the #GtkIconTheme object uses
 * overriding system configuration. This function cannot be called
 * on the icon theme objects returned from gtk_icon_theme_get_default()
 * and gtk_icon_theme_get_for_display().
 */
void
gtk_icon_theme_set_custom_theme (GtkIconTheme *self,
                                 const gchar  *theme_name)
{
  g_return_if_fail (GTK_IS_ICON_THEME (self));

  g_return_if_fail (!self->is_display_singleton);
  
  if (theme_name != NULL)
    {
      self->custom_theme = TRUE;
      if (!self->current_theme || strcmp (theme_name, self->current_theme) != 0)
        {
          g_free (self->current_theme);
          self->current_theme = g_strdup (theme_name);

          do_theme_change (self);
        }
    }
  else
    {
      if (self->custom_theme)
        {
          self->custom_theme = FALSE;
          update_current_theme (self);
        }
    }
}

static const gchar builtin_hicolor_index[] =
"[Icon Theme]\n"
"Name=Hicolor\n"
"Hidden=True\n"
"Directories=16x16/actions,16x16/status,22x22/actions,24x24/actions,24x24/status,32x32/actions,32x32/status,48x48/status,64x64/actions\n"
"[16x16/actions]\n"
"Size=16\n"
"Type=Threshold\n"
"[16x16/status]\n"
"Size=16\n"
"Type=Threshold\n"
"[22x22/actions]\n"
"Size=22\n"
"Type=Threshold\n"
"[24x24/actions]\n"
"Size=24\n"
"Type=Threshold\n"
"[24x24/status]\n"
"Size=24\n"
"Type=Threshold\n"
"[32x32/actions]\n"
"Size=32\n"
"Type=Threshold\n"
"[32x32/status]\n"
"Size=32\n"
"Type=Threshold\n"
"[48x48/status]\n"
"Size=48\n"
"Type=Threshold\n"
"[64x64/actions]\n"
"Size=64\n"
"Type=Threshold\n";

static void
insert_theme (GtkIconTheme *self,
              const gchar  *theme_name)
{
  gint i;
  GList *l;
  gchar **dirs;
  gchar **scaled_dirs;
  gchar **themes;
  IconTheme *theme = NULL;
  gchar *path;
  GKeyFile *theme_file;
  GError *error = NULL;
  IconThemeDirMtime *dir_mtime;
  GStatBuf stat_buf;

  for (l = self->themes; l != NULL; l = l->next)
    {
      theme = l->data;
      if (strcmp (theme->name, theme_name) == 0)
        return;
    }
  
  for (i = 0; i < self->search_path_len; i++)
    {
      path = g_build_filename (self->search_path[i],
                               theme_name,
                               NULL);
      dir_mtime = g_slice_new (IconThemeDirMtime);
      dir_mtime->cache = NULL;
      dir_mtime->dir = path;
      if (g_stat (path, &stat_buf) == 0 && S_ISDIR (stat_buf.st_mode)) {
        dir_mtime->mtime = stat_buf.st_mtime;
        dir_mtime->exists = TRUE;
      } else {
        dir_mtime->mtime = 0;
        dir_mtime->exists = FALSE;
      }

      self->dir_mtimes = g_list_prepend (self->dir_mtimes, dir_mtime);
    }

  theme_file = NULL;
  for (i = 0; i < self->search_path_len && !theme_file; i++)
    {
      path = g_build_filename (self->search_path[i],
                               theme_name,
                               "index.theme",
                               NULL);
      if (g_file_test (path, G_FILE_TEST_IS_REGULAR)) 
        {
          theme_file = g_key_file_new ();
          g_key_file_set_list_separator (theme_file, ',');
          if (!g_key_file_load_from_file (theme_file, path, 0, &error))
            {
              g_key_file_free (theme_file);
              theme_file = NULL;
              g_error_free (error);
              error = NULL;
            }
        }
      g_free (path);
    }

  if (theme_file || strcmp (theme_name, FALLBACK_ICON_THEME) == 0)
    {
      theme = g_new0 (IconTheme, 1);
      theme->name = g_strdup (theme_name);
      self->themes = g_list_prepend (self->themes, theme);
      if (!theme_file)
        {
          theme_file = g_key_file_new ();
          g_key_file_set_list_separator (theme_file, ',');
          g_key_file_load_from_data (theme_file, builtin_hicolor_index, -1, 0, NULL);
        }
    }

  if (theme_file == NULL)
    return;

  theme->display_name = 
    g_key_file_get_locale_string (theme_file, "Icon Theme", "Name", NULL, NULL);
  if (!theme->display_name)
    g_warning ("Theme file for %s has no name", theme_name);

  dirs = g_key_file_get_string_list (theme_file, "Icon Theme", "Directories", NULL, NULL);
  if (!dirs)
    {
      g_warning ("Theme file for %s has no directories", theme_name);
      self->themes = g_list_remove (self->themes, theme);
      g_free (theme->name);
      g_free (theme->display_name);
      g_free (theme);
      g_key_file_free (theme_file);
      return;
    }

  scaled_dirs = g_key_file_get_string_list (theme_file, "Icon Theme", "ScaledDirectories", NULL, NULL);

  theme->comment = 
    g_key_file_get_locale_string (theme_file, 
                                  "Icon Theme", "Comment",
                                  NULL, NULL);

  theme->dirs = NULL;
  for (i = 0; dirs[i] != NULL; i++)
    theme_subdir_load (self, theme, theme_file, dirs[i]);

  if (scaled_dirs)
    {
      for (i = 0; scaled_dirs[i] != NULL; i++)
        theme_subdir_load (self, theme, theme_file, scaled_dirs[i]);
    }
  g_strfreev (dirs);
  g_strfreev (scaled_dirs);

  theme->dirs = g_list_reverse (theme->dirs);

  themes = g_key_file_get_string_list (theme_file,
                                       "Icon Theme",
                                       "Inherits",
                                       NULL,
                                       NULL);
  if (themes)
    {
      for (i = 0; themes[i] != NULL; i++)
        insert_theme (self, themes[i]);
      
      g_strfreev (themes);
    }

  g_key_file_free (theme_file);
}

static void
free_unthemed_icon (UnthemedIcon *unthemed_icon)
{
  g_free (unthemed_icon->svg_filename);
  g_free (unthemed_icon->no_svg_filename);
  g_slice_free (UnthemedIcon, unthemed_icon);
}

static gchar *
strip_suffix (const gchar *filename)
{
  const gchar *dot;

  if (g_str_has_suffix (filename, ".symbolic.png"))
    return g_strndup (filename, strlen(filename)-13);

  dot = strrchr (filename, '.');

  if (dot == NULL)
    return g_strdup (filename);

  return g_strndup (filename, dot - filename);
}

static void
add_unthemed_icon (GtkIconTheme *self,
                   const gchar  *dir,
                   const gchar  *file,
                   gboolean      is_resource)
{
  IconSuffix new_suffix, old_suffix;
  gchar *abs_file;
  gchar *base_name;
  UnthemedIcon *unthemed_icon;

  new_suffix = suffix_from_name (file);

  if (new_suffix == ICON_SUFFIX_NONE)
    return;

  abs_file = g_build_filename (dir, file, NULL);
  base_name = strip_suffix (file);

  unthemed_icon = g_hash_table_lookup (self->unthemed_icons, base_name);

  if (unthemed_icon)
    {
      if (new_suffix == ICON_SUFFIX_SVG)
        {
          if (unthemed_icon->svg_filename)
            g_free (abs_file);
          else
            unthemed_icon->svg_filename = abs_file;
        }
      else
        {
          if (unthemed_icon->no_svg_filename)
            {
              old_suffix = suffix_from_name (unthemed_icon->no_svg_filename);
              if (new_suffix > old_suffix)
                {
                  g_free (unthemed_icon->no_svg_filename);
                  unthemed_icon->no_svg_filename = abs_file;
                }
              else
                g_free (abs_file);
            }
          else
            unthemed_icon->no_svg_filename = abs_file;
        }

      g_free (base_name);
    }
  else
    {
      unthemed_icon = g_slice_new0 (UnthemedIcon);

      unthemed_icon->is_resource = is_resource;

      if (new_suffix == ICON_SUFFIX_SVG)
        unthemed_icon->svg_filename = abs_file;
      else
        unthemed_icon->no_svg_filename = abs_file;

      /* takes ownership of base_name */
      g_hash_table_replace (self->unthemed_icons, base_name, unthemed_icon);
    }
}

static void
load_themes (GtkIconTheme *self)
{
  GDir *gdir;
  gint base;
  gchar *dir;
  const gchar *file;
  GTimeVal tv;
  IconThemeDirMtime *dir_mtime;
  GStatBuf stat_buf;
  GList *d;
  gint64 before = g_get_monotonic_time ();

  if (self->current_theme)
    insert_theme (self, self->current_theme);

  /* Always look in the Adwaita, gnome and hicolor icon themes.
   * Looking in hicolor is mandated by the spec, looking in Adwaita
   * and gnome is a pragmatic solution to prevent missing icons in
   * GTK+ applications when run under, e.g. KDE.
   */
#if 0
  insert_theme (self, DEFAULT_self);
  insert_theme (self, "gnome");
#endif
  insert_theme (self, FALLBACK_ICON_THEME);
  self->themes = g_list_reverse (self->themes);


  self->unthemed_icons = g_hash_table_new_full (g_str_hash, g_str_equal,
                                                g_free, (GDestroyNotify)free_unthemed_icon);

  for (base = 0; base < self->search_path_len; base++)
    {
      dir = self->search_path[base];

      dir_mtime = g_slice_new (IconThemeDirMtime);
      self->dir_mtimes = g_list_prepend (self->dir_mtimes, dir_mtime);
      
      dir_mtime->dir = g_strdup (dir);
      dir_mtime->mtime = 0;
      dir_mtime->exists = FALSE;
      dir_mtime->cache = NULL;

      if (g_stat (dir, &stat_buf) != 0 || !S_ISDIR (stat_buf.st_mode))
        continue;
      dir_mtime->mtime = stat_buf.st_mtime;
      dir_mtime->exists = TRUE;

      dir_mtime->cache = gtk_icon_cache_new_for_path (dir);
      if (dir_mtime->cache != NULL)
        continue;

      gdir = g_dir_open (dir, 0, NULL);
      if (gdir == NULL)
        continue;

      while ((file = g_dir_read_name (gdir)))
        add_unthemed_icon (self, dir, file, FALSE);

      g_dir_close (gdir);
    }
  self->dir_mtimes = g_list_reverse (self->dir_mtimes);

  for (d = self->resource_paths; d; d = d->next)
    {
      gchar **children;
      gint i;

      dir = d->data;
      children = g_resources_enumerate_children (dir, 0, NULL);
      if (!children)
        continue;

      for (i = 0; children[i]; i++)
        add_unthemed_icon (self, dir, children[i], TRUE);

      g_strfreev (children);
    }

  self->themes_valid = TRUE;
  
  g_get_current_time (&tv);
  self->last_stat_time = tv.tv_sec;

  GTK_DISPLAY_NOTE (self->display, ICONTHEME, {
    GList *l;
    GString *s;
    s = g_string_new ("Current icon themes ");
    for (l = self->themes; l; l = l->next)
      {
        IconTheme *theme = l->data;
        g_string_append (s, theme->name);
        g_string_append_c (s, ' ');
      }
    g_message ("%s", s->str);
    g_string_free (s, TRUE);
  });

  self->loading_themes = FALSE;
    gdk_profiler_add_mark (before * 1000, (g_get_monotonic_time () - before) * 1000, "icon theme load", self->current_theme);
}

static void
ensure_valid_themes (GtkIconTheme *self)
{
  GTimeVal tv;
  gboolean was_valid = self->themes_valid;

  if (self->loading_themes)
    return;
  self->loading_themes = TRUE;

  if (self->themes_valid)
    {
      g_get_current_time (&tv);

      if (ABS (tv.tv_sec - self->last_stat_time) > 5 &&
          rescan_themes (self))
        {
          g_hash_table_remove_all (self->info_cache);
          blow_themes (self);
          clear_lru_cache (self);
        }
    }

  if (!self->themes_valid)
    {
      load_themes (self);

      if (was_valid)
        queue_theme_changed (self);
    }
}

void
gtk_icon_theme_ensure_loaded (GtkIconTheme *self)
{
  ensure_valid_themes (self);
}

static inline gboolean
icon_name_is_symbolic (const gchar *icon_name,
                       int          icon_name_len)
{

  if (icon_name_len < 0)
    icon_name_len = strlen (icon_name);

  if (icon_name_len > strlen ("-symbolic"))
    {
      if (strcmp (icon_name + icon_name_len - strlen ("-symbolic"), "-symbolic") == 0)
        return TRUE;
    }

  if (icon_name_len > strlen ("-symbolic-ltr"))
    {
      if (strcmp (icon_name + icon_name_len - strlen ("-symbolic-ltr"), "-symbolic-ltr") == 0 ||
          strcmp (icon_name + icon_name_len - strlen ("-symbolic-rtl"), "-symbolic-rtl") == 0)
        return TRUE;
    }

  return FALSE;
}

static inline gboolean
icon_uri_is_symbolic (const gchar *icon_name,
                      int          icon_name_len)
{
  if (icon_name_len < 0)
    icon_name_len = strlen (icon_name);

  if (icon_name_len > strlen ("-symbolic.svg"))
    {
      if (strcmp (icon_name + icon_name_len - strlen ("-symbolic.svg"), "-symbolic.svg") == 0 ||
          strcmp (icon_name + icon_name_len - strlen (".symbolic.png"), ".symbolic.png") == 0)
        return TRUE;
    }

  if (icon_name_len > strlen ("-symbolic-ltr.svg"))
    {
      if (strcmp (icon_name + icon_name_len - strlen ("-symbolic.ltr.svg"), "-symbolic-ltr.svg") == 0 ||
          strcmp (icon_name + icon_name_len - strlen ("-symbolic.rtl.svg"), "-symbolic-rtl.svg") == 0)
        return TRUE;
    }

  return FALSE;
}

static GtkIconInfo *
real_choose_icon (GtkIconTheme       *self,
                  const gchar        *icon_names[],
                  gint                size,
                  gint                scale,
                  GtkIconLookupFlags  flags)
{
  GList *l;
  GtkIconInfo *icon_info = NULL;
  GtkIconInfo *unscaled_icon_info;
  UnthemedIcon *unthemed_icon = NULL;
  const gchar *icon_name = NULL;
  gboolean allow_svg;
  IconTheme *theme = NULL;
  gint i;
  IconInfoKey key;

  ensure_valid_themes (self);

  key.icon_names = (gchar **)icon_names;
  key.size = size;
  key.scale = scale;
  key.flags = flags;

  icon_info = g_hash_table_lookup (self->info_cache, &key);
  if (icon_info != NULL)
    {
      DEBUG_CACHE (("cache hit %p (%s %d 0x%x) (cache size %d)\n",
                    icon_info,
                    g_strjoinv (",", icon_info->key.icon_names),
                    icon_info->key.size, icon_info->key.flags,
                    g_hash_table_size (self->info_cache)));

      icon_info = g_object_ref (icon_info);

      /* Move item to front in LRU cache */
      add_to_lru_cache (icon_info);

      return icon_info;
    }

  if (flags & GTK_ICON_LOOKUP_NO_SVG)
    allow_svg = FALSE;
  else if (flags & GTK_ICON_LOOKUP_FORCE_SVG)
    allow_svg = TRUE;
  else
    allow_svg = self->pixbuf_supports_svg;

  /* This is used in the icontheme unit test */
  GTK_DISPLAY_NOTE (self->display, ICONTHEME,
            for (i = 0; icon_names[i]; i++)
              g_message ("\tlookup name: %s", icon_names[i]));

  /* For symbolic icons, do a search in all registered themes first;
   * a theme that inherits them from a parent theme might provide
   * an alternative full-color version, but still expect the symbolic icon
   * to show up instead.
   *
   * In other words: We prefer symbolic icons in inherited themes over
   * generic icons in the theme.
   */
  for (l = self->themes; l; l = l->next)
    {
      theme = l->data;
      for (i = 0; icon_names[i] && icon_name_is_symbolic (icon_names[i], -1); i++)
        {
          icon_name = icon_names[i];
          icon_info = theme_lookup_icon (theme, icon_name, size, scale, allow_svg);
          if (icon_info)
            goto out;
        }
    }

  for (l = self->themes; l; l = l->next)
    {
      theme = l->data;

      for (i = 0; icon_names[i]; i++)
        {
          icon_name = icon_names[i];
          icon_info = theme_lookup_icon (theme, icon_name, size, scale, allow_svg);
          if (icon_info)
            goto out;
        }
    }

  theme = NULL;

  for (i = 0; icon_names[i]; i++)
    {
      unthemed_icon = g_hash_table_lookup (self->unthemed_icons, icon_names[i]);
      if (unthemed_icon)
        break;
    }
#ifdef G_OS_WIN32
  /* Still not found an icon, check if reference to a Win32 resource */
  if (!unthemed_icon)
    {
      gchar **resources;
      HICON hIcon = NULL;
      
      resources = g_strsplit (icon_names[0], ",", 0);
      if (resources[0])
        {
          wchar_t *wfile = g_utf8_to_utf16 (resources[0], -1, NULL, NULL, NULL);
          ExtractIconExW (wfile, resources[1] ? atoi (resources[1]) : 0, &hIcon, NULL, 1);
          g_free (wfile);
        }
      
      if (hIcon)
        {
          icon_info = icon_info_new (ICON_THEME_DIR_UNTHEMED, size, 1);
          icon_info->cache_pixbuf = gdk_win32_icon_to_pixbuf_libgtk_only (hIcon, NULL, NULL);
          DestroyIcon (hIcon);
        }
      g_strfreev (resources);
    }
#endif

  if (unthemed_icon)
    {
      icon_info = icon_info_new (ICON_THEME_DIR_UNTHEMED, size, 1);

      /* A SVG icon, when allowed, beats out a XPM icon, but not a PNG icon */
      if (allow_svg &&
          unthemed_icon->svg_filename &&
          (!unthemed_icon->no_svg_filename ||
           suffix_from_name (unthemed_icon->no_svg_filename) < ICON_SUFFIX_PNG))
        icon_info->filename = g_strdup (unthemed_icon->svg_filename);
      else if (unthemed_icon->no_svg_filename)
        icon_info->filename = g_strdup (unthemed_icon->no_svg_filename);
      else
        {
          static gboolean warned_once = FALSE;

          if (!warned_once)
            {
              g_warning ("Found an icon but could not load it. "
                         "Most likely gdk-pixbuf does not provide SVG support.");
              warned_once = TRUE;
            }

          g_clear_object (&icon_info);
          goto out;
        }

      icon_info->is_svg = suffix_from_name (icon_info->filename) == ICON_SUFFIX_SVG;
      icon_info->is_resource = unthemed_icon->is_resource;
    }

 out:
  if (icon_info)
    {
      icon_info->desired_size = size;
      icon_info->desired_scale = scale;
      icon_info->forced_size = (flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0;

      /* In case we're not scaling the icon we want to reuse the exact same
       * size as a scale==1 lookup would be, rather than not scaling at all
       * and causing a different layout
       */
      icon_info->unscaled_scale = 1.0;
      if (scale != 1 && !icon_info->forced_size && theme != NULL)
        {
          unscaled_icon_info = theme_lookup_icon (theme, icon_name, size, 1, allow_svg);
          if (unscaled_icon_info)
            {
              icon_info->unscaled_scale =
                (gdouble) unscaled_icon_info->dir_size * scale / (icon_info->dir_size * icon_info->dir_scale);
              g_object_unref (unscaled_icon_info);
            }
        }

      icon_info->key.icon_names = g_strdupv ((char **)icon_names);
      icon_info->key.size = size;
      icon_info->key.scale = scale;
      icon_info->key.flags = flags;
      icon_info->in_cache = self;
      DEBUG_CACHE (("adding %p (%s %d 0x%x) to cache (cache size %d)\n",
                    icon_info,
                    g_strjoinv (",", icon_info->key.icon_names),
                    icon_info->key.size, icon_info->key.flags,
                    g_hash_table_size (self->info_cache)));
     g_hash_table_insert (self->info_cache, &icon_info->key, icon_info);
    }
  else
    {
      static gboolean check_for_default_theme = TRUE;
      gchar *default_theme_path;
      gboolean found = FALSE;

      if (check_for_default_theme)
        {
          check_for_default_theme = FALSE;

          for (i = 0; !found && i < self->search_path_len; i++)
            {
              default_theme_path = g_build_filename (self->search_path[i],
                                                     FALLBACK_ICON_THEME,
                                                     "index.theme",
                                                     NULL);
              found = g_file_test (default_theme_path, G_FILE_TEST_IS_REGULAR);
              g_free (default_theme_path);
            }

          if (!found)
            {
              g_warning ("Could not find the icon '%s'. The '%s' theme\n"
                         "was not found either, perhaps you need to install it.\n"
                         "You can get a copy from:\n"
                         "\t%s",
                         icon_names[0], FALLBACK_ICON_THEME, "http://icon-theme.freedesktop.org/releases");
            }
        }
    }

  return icon_info;
}

static void
icon_name_list_add_icon (GPtrArray   *icons,
                         const gchar *dir_suffix,
                         gchar       *icon_name)
{
  if (dir_suffix)
    g_ptr_array_add (icons, g_strconcat (icon_name, dir_suffix, NULL));
  g_ptr_array_add (icons, icon_name);
}

static GtkIconInfo *
choose_icon (GtkIconTheme       *self,
             const gchar        *icon_names[],
             gint                size,
             gint                scale,
             GtkIconLookupFlags  flags)
{
  gboolean has_regular = FALSE, has_symbolic = FALSE;
  GtkIconInfo *icon_info;
  GPtrArray *new_names;
  const gchar *dir_suffix;
  guint i;

  if (flags & GTK_ICON_LOOKUP_DIR_LTR)
    dir_suffix = "-ltr";
  else if (flags & GTK_ICON_LOOKUP_DIR_RTL)
    dir_suffix = "-rtl";
  else
    dir_suffix = NULL;

  for (i = 0; icon_names[i]; i++)
    {
      if (icon_name_is_symbolic (icon_names[i], -1))
        has_symbolic = TRUE;
      else
        has_regular = TRUE;
    }

  if ((flags & GTK_ICON_LOOKUP_FORCE_REGULAR) && has_symbolic)
    {
      new_names = g_ptr_array_new_with_free_func (g_free);
      for (i = 0; icon_names[i]; i++)
        {
          if (icon_name_is_symbolic (icon_names[i], -1))
            icon_name_list_add_icon (new_names, dir_suffix, g_strndup (icon_names[i], strlen (icon_names[i]) - strlen ("-symbolic")));
          else
            icon_name_list_add_icon (new_names, dir_suffix, g_strdup (icon_names[i]));
        }
      for (i = 0; icon_names[i]; i++)
        {
          if (icon_name_is_symbolic (icon_names[i], -1))
            icon_name_list_add_icon (new_names, dir_suffix, g_strdup (icon_names[i]));
        }
      g_ptr_array_add (new_names, NULL);

      icon_info = real_choose_icon (self,
                                    (const gchar **) new_names->pdata,
                                    size,
                                    scale,
                                    flags & ~(GTK_ICON_LOOKUP_FORCE_REGULAR | GTK_ICON_LOOKUP_FORCE_SYMBOLIC));

      g_ptr_array_free (new_names, TRUE);
    }
  else if ((flags & GTK_ICON_LOOKUP_FORCE_SYMBOLIC) && has_regular)
    {
      new_names = g_ptr_array_new_with_free_func (g_free);
      for (i = 0; icon_names[i]; i++)
        {
          if (!icon_name_is_symbolic (icon_names[i], -1))
            icon_name_list_add_icon (new_names, dir_suffix, g_strconcat (icon_names[i], "-symbolic", NULL));
          else
            icon_name_list_add_icon (new_names, dir_suffix, g_strdup (icon_names[i]));
        }
      for (i = 0; icon_names[i]; i++)
        {
          if (!icon_name_is_symbolic (icon_names[i], -1))
            icon_name_list_add_icon (new_names, dir_suffix, g_strdup (icon_names[i]));
        }
      g_ptr_array_add (new_names, NULL);

      icon_info = real_choose_icon (self,
                                    (const gchar **) new_names->pdata,
                                    size,
                                    scale,
                                    flags & ~(GTK_ICON_LOOKUP_FORCE_REGULAR | GTK_ICON_LOOKUP_FORCE_SYMBOLIC));

      g_ptr_array_free (new_names, TRUE);
    }
  else if (dir_suffix)
    {
      new_names = g_ptr_array_new_with_free_func (g_free);
      for (i = 0; icon_names[i]; i++)
        {
          icon_name_list_add_icon (new_names, dir_suffix, g_strdup (icon_names[i]));
        }
      g_ptr_array_add (new_names, NULL);

      icon_info = real_choose_icon (self,
                                    (const gchar **) new_names->pdata,
                                    size,
                                    scale,
                                    flags & ~(GTK_ICON_LOOKUP_FORCE_REGULAR | GTK_ICON_LOOKUP_FORCE_SYMBOLIC));

      g_ptr_array_free (new_names, TRUE);
    }
  else
    {
      icon_info = real_choose_icon (self,
                                    icon_names,
                                    size,
                                    scale,
                                    flags & ~(GTK_ICON_LOOKUP_FORCE_REGULAR | GTK_ICON_LOOKUP_FORCE_SYMBOLIC));
    }

  return icon_info;
}

/**
 * gtk_icon_theme_lookup_icon:
 * @self: a #GtkIconTheme
 * @icon_name: the name of the icon to lookup
 * @size: desired icon size
 * @flags: flags modifying the behavior of the icon lookup
 * 
 * Looks up a named icon and returns a #GtkIconInfo containing
 * information such as the filename of the icon. The icon
 * can then be rendered into a pixbuf using
 * gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon()
 * combines these two steps if all you need is the pixbuf.)
 *
 * When rendering on displays with high pixel densities you should not
 * use a @size multiplied by the scaling factor returned by functions
 * like gdk_surface_get_scale_factor(). Instead, you should use
 * gtk_icon_theme_lookup_icon_for_scale(), as the assets loaded
 * for a given scaling factor may be different.
 * 
 * Returns: (nullable) (transfer full): a #GtkIconInfo object
 *     containing information about the icon, or %NULL if the
 *     icon wasn’t found.
 */
GtkIconInfo *
gtk_icon_theme_lookup_icon (GtkIconTheme       *self,
                            const gchar        *icon_name,
                            gint                size,
                            GtkIconLookupFlags  flags)
{
  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (icon_name != NULL, NULL);
  g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
                        (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);

  GTK_DISPLAY_NOTE (self->display, ICONTHEME,
                    g_message ("looking up icon %s", icon_name));

  return gtk_icon_theme_lookup_icon_for_scale (self, icon_name,
                                               size, 1, flags);
}

/**
 * gtk_icon_theme_lookup_icon_for_scale:
 * @self: a #GtkIconTheme
 * @icon_name: the name of the icon to lookup
 * @size: desired icon size
 * @scale: the desired scale
 * @flags: flags modifying the behavior of the icon lookup
 *
 * Looks up a named icon for a particular window scale and returns a
 * #GtkIconInfo containing information such as the filename of the
 * icon. The icon can then be rendered into a pixbuf using
 * gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon() combines
 * these two steps if all you need is the pixbuf.)
 *
 * Returns: (nullable) (transfer full): a #GtkIconInfo object
 *     containing information about the icon, or %NULL if the
 *     icon wasn’t found.
 */
GtkIconInfo *
gtk_icon_theme_lookup_icon_for_scale (GtkIconTheme       *self,
                                      const gchar        *icon_name,
                                      gint                size,
                                      gint                scale,
                                      GtkIconLookupFlags  flags)
{
  GtkIconInfo *info;

  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (icon_name != NULL, NULL);
  g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
                        (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
  g_return_val_if_fail (scale >= 1, NULL);

  GTK_DISPLAY_NOTE (self->display, ICONTHEME,
                    g_message ("looking up icon %s for scale %d", icon_name, scale));

  if (flags & GTK_ICON_LOOKUP_GENERIC_FALLBACK)
    {
      gchar **names, **nonsymbolic_names;
      gint dashes, i;
      gchar *p, *nonsymbolic_icon_name;
      gboolean is_symbolic;
      int icon_name_len = strlen (icon_name);

      is_symbolic = icon_name_is_symbolic (icon_name, icon_name_len);
      if (is_symbolic)
        nonsymbolic_icon_name = g_strndup (icon_name, icon_name_len - strlen ("-symbolic"));
      else
        nonsymbolic_icon_name = g_strdup (icon_name);
 
      dashes = 0;
      for (p = (gchar *) nonsymbolic_icon_name; *p; p++)
        if (*p == '-')
          dashes++;

      nonsymbolic_names = g_new (gchar *, dashes + 2);
      nonsymbolic_names[0] = nonsymbolic_icon_name;

      for (i = 1; i <= dashes; i++)
        {
          nonsymbolic_names[i] = g_strdup (nonsymbolic_names[i - 1]);
          p = strrchr (nonsymbolic_names[i], '-');
          *p = '\0';
        }
      nonsymbolic_names[dashes + 1] = NULL;

      if (is_symbolic)
        {
          names = g_new (gchar *, 2 * dashes + 3);
          for (i = 0; nonsymbolic_names[i] != NULL; i++)
            {
              names[i] = g_strconcat (nonsymbolic_names[i], "-symbolic", NULL);
              names[dashes + 1 + i] = nonsymbolic_names[i];
            }

          names[dashes + 1 + i] = NULL;
          g_free (nonsymbolic_names);
        }
      else
        {
          names = nonsymbolic_names;
        }

      info = choose_icon (self, (const gchar **) names, size, scale, flags);

      g_strfreev (names);
    }
  else
    {
      const gchar *names[2];

      names[0] = icon_name;
      names[1] = NULL;

      info = choose_icon (self, names, size, scale, flags);
    }

  return info;
}

/**
 * gtk_icon_theme_choose_icon:
 * @self: a #GtkIconTheme
 * @icon_names: (array zero-terminated=1): %NULL-terminated array of
 *     icon names to lookup
 * @size: desired icon size
 * @flags: flags modifying the behavior of the icon lookup
 * 
 * Looks up a named icon and returns a #GtkIconInfo containing
 * information such as the filename of the icon. The icon
 * can then be rendered into a pixbuf using
 * gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon()
 * combines these two steps if all you need is the pixbuf.)
 *
 * If @icon_names contains more than one name, this function 
 * tries them all in the given order before falling back to 
 * inherited icon themes.
 * 
 * Returns: (nullable) (transfer full): a #GtkIconInfo object
 * containing information about the icon, or %NULL if the icon wasn’t
 * found.
 */
GtkIconInfo *
gtk_icon_theme_choose_icon (GtkIconTheme       *self,
                            const gchar        *icon_names[],
                            gint                size,
                            GtkIconLookupFlags  flags)
{
  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (icon_names != NULL, NULL);
  g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
                        (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
  g_warn_if_fail ((flags & GTK_ICON_LOOKUP_GENERIC_FALLBACK) == 0);

  return choose_icon (self, icon_names, size, 1, flags);
}

/**
 * gtk_icon_theme_choose_icon_for_scale:
 * @self: a #GtkIconTheme
 * @icon_names: (array zero-terminated=1): %NULL-terminated
 *     array of icon names to lookup
 * @size: desired icon size
 * @scale: desired scale
 * @flags: flags modifying the behavior of the icon lookup
 * 
 * Looks up a named icon for a particular window scale and returns
 * a #GtkIconInfo containing information such as the filename of the
 * icon. The icon can then be rendered into a pixbuf using
 * gtk_icon_info_load_icon(). (gtk_icon_theme_load_icon()
 * combines these two steps if all you need is the pixbuf.)
 *
 * If @icon_names contains more than one name, this function 
 * tries them all in the given order before falling back to 
 * inherited icon themes.
 * 
 * Returns: (nullable) (transfer full): a #GtkIconInfo object
 *     containing information about the icon, or %NULL if the
 *     icon wasn’t found.
 */
GtkIconInfo *
gtk_icon_theme_choose_icon_for_scale (GtkIconTheme       *self,
                                      const gchar        *icon_names[],
                                      gint                size,
                                      gint                scale,
                                      GtkIconLookupFlags  flags)
{
  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (icon_names != NULL, NULL);
  g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
                        (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
  g_return_val_if_fail (scale >= 1, NULL);
  g_warn_if_fail ((flags & GTK_ICON_LOOKUP_GENERIC_FALLBACK) == 0);

  return choose_icon (self, icon_names, size, scale, flags);
}


/* Error quark */
GQuark
gtk_icon_theme_error_quark (void)
{
  return g_quark_from_static_string ("gtk-icon-theme-error-quark");
}

/**
 * gtk_icon_theme_load_icon:
 * @self: a #GtkIconTheme
 * @icon_name: the name of the icon to lookup
 * @size: the desired icon size. The resulting icon may not be
 *     exactly this size; see gtk_icon_info_load_icon().
 * @flags: flags modifying the behavior of the icon lookup
 * @error: (allow-none): Location to store error information on failure,
 *     or %NULL.
 *
 * Looks up an icon in an icon theme, scales it to the given size
 * and renders it into a pixbuf. This is a convenience function;
 * if more details about the icon are needed, use
 * gtk_icon_theme_lookup_icon() followed by gtk_icon_info_load_icon().
 *
 * Note that you probably want to listen for icon theme changes and
 * update the icon. This is usually done by connecting to the
 * GtkWidget::style-set signal. If for some reason you do not want to
 * update the icon when the icon theme changes, you should consider
 * using gdk_pixbuf_copy() to make a private copy of the pixbuf
 * returned by this function. Otherwise GTK+ may need to keep the old
 * icon theme loaded, which would be a waste of memory.
 *
 * Returns: (nullable) (transfer full): the rendered icon; this may be
 *     a newly created icon or a new reference to an internal icon, so
 *     you must not modify the icon. Use g_object_unref() to release
 *     your reference to the icon. %NULL if the icon isn’t found.
 */
GdkPaintable *
gtk_icon_theme_load_icon (GtkIconTheme         *self,
                          const gchar          *icon_name,
                          gint                  size,
                          GtkIconLookupFlags    flags,
                          GError              **error)
{
  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (icon_name != NULL, NULL);
  g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
                        (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  return gtk_icon_theme_load_icon_for_scale (self, icon_name,
                                             size, 1, flags, error);
}

/**
 * gtk_icon_theme_load_icon_for_scale:
 * @self: a #GtkIconTheme
 * @icon_name: the name of the icon to lookup
 * @size: the desired icon size. The resulting icon may not be
 *     exactly this size; see gtk_icon_info_load_icon().
 * @scale: desired scale
 * @flags: flags modifying the behavior of the icon lookup
 * @error: (allow-none): Location to store error information on failure,
 *     or %NULL.
 *
 * Looks up an icon in an icon theme for a particular window scale,
 * scales it to the given size and renders it into a pixbuf. This is a
 * convenience function; if more details about the icon are needed,
 * use gtk_icon_theme_lookup_icon() followed by
 * gtk_icon_info_load_icon().
 *
 * Note that you probably want to listen for icon theme changes and
 * update the icon. This is usually done by connecting to the
 * GtkWidget::style-set signal. If for some reason you do not want to
 * update the icon when the icon theme changes, you should consider
 * using gdk_pixbuf_copy() to make a private copy of the pixbuf
 * returned by this function. Otherwise GTK+ may need to keep the old
 * icon theme loaded, which would be a waste of memory.
 *
 * Returns: (nullable) (transfer full): the rendered icon; this may be
 *     a newly created icon or a new reference to an internal icon, so
 *     you must not modify the icon. Use g_object_unref() to release
 *     your reference to the icon. %NULL if the icon isn’t found.
 */
GdkPaintable *
gtk_icon_theme_load_icon_for_scale (GtkIconTheme        *self,
                                    const gchar         *icon_name,
                                    gint                 size,
                                    gint                 scale,
                                    GtkIconLookupFlags   flags,
                                    GError             **error)
{
  GtkIconInfo *icon_info;
  GdkPaintable *paintable = NULL;

  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (icon_name != NULL, NULL);
  g_return_val_if_fail ((flags & GTK_ICON_LOOKUP_NO_SVG) == 0 ||
                        (flags & GTK_ICON_LOOKUP_FORCE_SVG) == 0, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);
  g_return_val_if_fail (scale >= 1, NULL);

  icon_info = gtk_icon_theme_lookup_icon_for_scale (self, icon_name, size, scale,
                                                    flags | GTK_ICON_LOOKUP_USE_BUILTIN);
  if (!icon_info)
    {
      g_set_error (error, GTK_ICON_THEME_ERROR,  GTK_ICON_THEME_NOT_FOUND,
                   _("Icon “%s” not present in theme %s"), icon_name, self->current_theme);
      return NULL;
    }

  paintable = gtk_icon_info_load_icon (icon_info, error);
  g_prefix_error (error, "Failed to load %s: ", icon_info->filename);
  g_object_unref (icon_info);

  return paintable;
}

/**
 * gtk_icon_theme_has_icon:
 * @self: a #GtkIconTheme
 * @icon_name: the name of an icon
 * 
 * Checks whether an icon theme includes an icon
 * for a particular name.
 * 
 * Returns: %TRUE if @self includes an
 *  icon for @icon_name.
 */
gboolean 
gtk_icon_theme_has_icon (GtkIconTheme *self,
                         const gchar  *icon_name)
{
  GList *l;

  g_return_val_if_fail (GTK_IS_ICON_THEME (self), FALSE);
  g_return_val_if_fail (icon_name != NULL, FALSE);

  ensure_valid_themes (self);

  for (l = self->dir_mtimes; l; l = l->next)
    {
      IconThemeDirMtime *dir_mtime = l->data;
      GtkIconCache *cache = dir_mtime->cache;
      
      if (cache && gtk_icon_cache_has_icon (cache, icon_name))
        return TRUE;
    }

  for (l = self->themes; l; l = l->next)
    {
      if (theme_has_icon (l->data, icon_name))
        return TRUE;
    }

  return FALSE;
}

static void
add_size (gpointer key,
          gpointer value,
          gpointer user_data)
{
  gint **res_p = user_data;

  **res_p = GPOINTER_TO_INT (key);

  (*res_p)++;
}

/**
 * gtk_icon_theme_get_icon_sizes:
 * @self: a #GtkIconTheme
 * @icon_name: the name of an icon
 * 
 * Returns an array of integers describing the sizes at which
 * the icon is available without scaling. A size of -1 means 
 * that the icon is available in a scalable format. The array 
 * is zero-terminated.
 * 
 * Returns: (array zero-terminated=1) (transfer full): A newly
 * allocated array describing the sizes at which the icon is
 * available. The array should be freed with g_free() when it is no
 * longer needed.
 */
gint *
gtk_icon_theme_get_icon_sizes (GtkIconTheme *self,
                               const gchar  *icon_name)
{
  GList *l, *d;
  GHashTable *sizes;
  gint *result, *r;
  guint suffix;  

  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  
  ensure_valid_themes (self);

  sizes = g_hash_table_new (g_direct_hash, g_direct_equal);

  for (l = self->themes; l; l = l->next)
    {
      IconTheme *theme = l->data;
      for (d = theme->dirs; d; d = d->next)
        {
          IconThemeDir *dir = d->data;

          if (dir->type != ICON_THEME_DIR_SCALABLE && g_hash_table_lookup_extended (sizes, GINT_TO_POINTER (dir->size), NULL, NULL))
            continue;

          suffix = theme_dir_get_icon_suffix (dir, icon_name);
          if (suffix != ICON_SUFFIX_NONE)
            {
              if (suffix == ICON_SUFFIX_SVG)
                g_hash_table_insert (sizes, GINT_TO_POINTER (-1), NULL);
              else
                g_hash_table_insert (sizes, GINT_TO_POINTER (dir->size), NULL);
            }
        }
    }

  r = result = g_new0 (gint, g_hash_table_size (sizes) + 1);

  g_hash_table_foreach (sizes, add_size, &r);
  g_hash_table_destroy (sizes);
  
  return result;
}

static void
add_key_to_hash (gpointer key,
                 gpointer value,
                 gpointer user_data)
{
  GHashTable *hash = user_data;

  g_hash_table_insert (hash, key, NULL);
}

static void
add_key_to_list (gpointer key,
                 gpointer value,
                 gpointer user_data)
{
  GList **list = user_data;

  *list = g_list_prepend (*list, g_strdup (key));
}

/**
 * gtk_icon_theme_list_icons:
 * @self: a #GtkIconTheme
 * @context: (allow-none): a string identifying a particular type of
 *           icon, or %NULL to list all icons.
 *
 * Lists the icons in the current icon theme. Only a subset
 * of the icons can be listed by providing a context string.
 * The set of values for the context string is system dependent,
 * but will typically include such values as “Applications” and
 * “MimeTypes”. Contexts are explained in the
 * [Icon Theme Specification](http://www.freedesktop.org/wiki/Specifications/icon-theme-spec).
 * The standard contexts are listed in the
 * [Icon Naming Specification](http://www.freedesktop.org/wiki/Specifications/icon-naming-spec).
 *
 * Returns: (element-type utf8) (transfer full): a #GList list
 *     holding the names of all the icons in the theme. You must
 *     first free each element in the list with g_free(), then
 *     free the list itself with g_list_free().
 */
GList *
gtk_icon_theme_list_icons (GtkIconTheme *self,
                           const gchar  *context)
{
  GHashTable *icons;
  GList *list, *l;
  GQuark context_quark;
  
  ensure_valid_themes (self);

  if (context)
    {
      context_quark = g_quark_try_string (context);

      if (!context_quark)
        return NULL;
    }
  else
    context_quark = 0;

  icons = g_hash_table_new (g_str_hash, g_str_equal);
  
  l = self->themes;
  while (l != NULL)
    {
      theme_list_icons (l->data, icons, context_quark);
      l = l->next;
    }

  if (context_quark == 0)
    g_hash_table_foreach (self->unthemed_icons,
                          add_key_to_hash,
                          icons);

  list = NULL;
  
  g_hash_table_foreach (icons,
                        add_key_to_list,
                        &list);

  g_hash_table_destroy (icons);
  
  return list;
}

static gboolean
rescan_themes (GtkIconTheme *self)
{
  IconThemeDirMtime *dir_mtime;
  GList *d;
  gint stat_res;
  GStatBuf stat_buf;
  GTimeVal tv;

  for (d = self->dir_mtimes; d != NULL; d = d->next)
    {
      dir_mtime = d->data;

      stat_res = g_stat (dir_mtime->dir, &stat_buf);

      /* dir mtime didn't change */
      if (stat_res == 0 && dir_mtime->exists &&
          S_ISDIR (stat_buf.st_mode) &&
          dir_mtime->mtime == stat_buf.st_mtime)
        continue;
      /* didn't exist before, and still doesn't */
      if (!dir_mtime->exists &&
          (stat_res != 0 || !S_ISDIR (stat_buf.st_mode)))
        continue;

      return TRUE;
    }

  g_get_current_time (&tv);
  self->last_stat_time = tv.tv_sec;

  return FALSE;
}

/**
 * gtk_icon_theme_rescan_if_needed:
 * @self: a #GtkIconTheme
 * 
 * Checks to see if the icon theme has changed; if it has, any
 * currently cached information is discarded and will be reloaded
 * next time @self is accessed.
 * 
 * Returns: %TRUE if the icon theme has changed and needed
 *     to be reloaded.
 */
gboolean
gtk_icon_theme_rescan_if_needed (GtkIconTheme *self)
{
  gboolean retval;

  g_return_val_if_fail (GTK_IS_ICON_THEME (self), FALSE);

  retval = rescan_themes (self);
  if (retval)
      do_theme_change (self);

  return retval;
}

static void
theme_destroy (IconTheme *theme)
{
  g_free (theme->display_name);
  g_free (theme->comment);
  g_free (theme->name);

  g_list_free_full (theme->dirs, (GDestroyNotify) theme_dir_destroy);
  
  g_free (theme);
}

static void
theme_dir_destroy (IconThemeDir *dir)
{
  if (dir->cache)
    gtk_icon_cache_unref (dir->cache);
  if (dir->icons)
    g_hash_table_destroy (dir->icons);
  
  g_free (dir->dir);
  g_free (dir->subdir);
  g_free (dir);
}

static int
theme_dir_size_difference (IconThemeDir *dir,
                           gint          size,
                           gint          scale)
{
  gint scaled_size, scaled_dir_size;
  gint min, max;

  scaled_size = size * scale;
  scaled_dir_size = dir->size * dir->scale;

  switch (dir->type)
    {
    case ICON_THEME_DIR_FIXED:
      return abs (scaled_size - scaled_dir_size);

    case ICON_THEME_DIR_SCALABLE:
      if (scaled_size < (dir->min_size * dir->scale))
        return (dir->min_size * dir->scale) - scaled_size;
      if (size > (dir->max_size * dir->scale))
        return scaled_size - (dir->max_size * dir->scale);
      return 0;

    case ICON_THEME_DIR_THRESHOLD:
      min = (dir->size - dir->threshold) * dir->scale;
      max = (dir->size + dir->threshold) * dir->scale;
      if (scaled_size < min)
        return min - scaled_size;
      if (scaled_size > max)
        return scaled_size - max;
      return 0;

    case ICON_THEME_DIR_UNTHEMED:
    default:
      g_assert_not_reached ();
      return 1000;
    }
}

static const gchar *
string_from_suffix (IconSuffix suffix)
{
  switch (suffix)
    {
    case ICON_SUFFIX_XPM:
      return ".xpm";
    case ICON_SUFFIX_SVG:
      return ".svg";
    case ICON_SUFFIX_PNG:
      return ".png";
    case ICON_SUFFIX_SYMBOLIC_PNG:
      return ".symbolic.png";
    case ICON_SUFFIX_NONE:
    case HAS_ICON_FILE:
    default:
      g_assert_not_reached();
      return NULL;
    }
}

static inline IconSuffix
suffix_from_name (const gchar *name)
{
  const gsize name_len = strlen (name);

  if (name_len > 4)
    {
      if (name_len > strlen (".symbolic.png"))
        {
          if (strcmp (name + name_len - strlen (".symbolic.png"), ".symbolic.png") == 0)
            return ICON_SUFFIX_SYMBOLIC_PNG;
        }

      if (strcmp (name + name_len - strlen (".png"), ".png") == 0)
        return ICON_SUFFIX_PNG;

      if (strcmp (name + name_len - strlen (".svg"), ".svg") == 0)
        return ICON_SUFFIX_SVG;

      if (strcmp (name + name_len - strlen (".xpm"), ".xpm") == 0)
        return ICON_SUFFIX_XPM;
    }

  return ICON_SUFFIX_NONE;
}

static IconSuffix
best_suffix (IconSuffix suffix,
             gboolean   allow_svg)
{
  if ((suffix & ICON_SUFFIX_SYMBOLIC_PNG) != 0)
    return ICON_SUFFIX_SYMBOLIC_PNG;
  else if ((suffix & ICON_SUFFIX_PNG) != 0)
    return ICON_SUFFIX_PNG;
  else if (allow_svg && ((suffix & ICON_SUFFIX_SVG) != 0))
    return ICON_SUFFIX_SVG;
  else if ((suffix & ICON_SUFFIX_XPM) != 0)
    return ICON_SUFFIX_XPM;
  else
    return ICON_SUFFIX_NONE;
}
 
static IconSuffix
theme_dir_get_icon_suffix (IconThemeDir *dir,
                           const gchar  *icon_name)
{
  IconSuffix suffix, symbolic_suffix;

  if (dir->cache)
    {
      int icon_name_len = strlen (icon_name);

      if (icon_name_is_symbolic (icon_name, icon_name_len))
        {
          /* Look for foo-symbolic.symbolic.png, as the cache only stores the ".png" suffix */
          char *icon_name_with_prefix = g_strconcat (icon_name, ".symbolic", NULL);
          symbolic_suffix = (IconSuffix)gtk_icon_cache_get_icon_flags (dir->cache,
                                                                        icon_name_with_prefix,
                                                                        dir->subdir_index);
          g_free (icon_name_with_prefix);

          if (symbolic_suffix & ICON_SUFFIX_PNG)
            suffix = ICON_SUFFIX_SYMBOLIC_PNG;
          else
            suffix = (IconSuffix)gtk_icon_cache_get_icon_flags (dir->cache,
                                                                icon_name,
                                                                dir->subdir_index);
        }
      else
        suffix = (IconSuffix)gtk_icon_cache_get_icon_flags (dir->cache,
                                                            icon_name,
                                                            dir->subdir_index);

      suffix = suffix & ~HAS_ICON_FILE;
    }
  else
    suffix = GPOINTER_TO_UINT (g_hash_table_lookup (dir->icons, icon_name));

  GTK_NOTE (ICONTHEME, g_message ("get icon suffix%s: %u", dir->cache ? " (cached)" : "", suffix));

  return suffix;
}

/* returns TRUE if dir_a is a better match */
static gboolean
compare_dir_matches (IconThemeDir *dir_a, gint difference_a,
                     IconThemeDir *dir_b, gint difference_b,
                     gint requested_size,
                     gint requested_scale)
{
  gint diff_a;
  gint diff_b;

  if (difference_a == 0)
    {
      if (difference_b != 0)
        return TRUE;
      
      /* a and b both exact matches */
    }
  else
    {
      /* If scaling, *always* prefer downscaling */
      if (dir_a->size >= requested_size &&
          dir_b->size < requested_size)
        return TRUE;

      if (dir_a->size < requested_size &&
          dir_b->size >= requested_size)
        return FALSE;
 
      /* Otherwise prefer the closest match */

      if (difference_a < difference_b)
        return TRUE;

      if (difference_a > difference_b)
        return FALSE;

      /* same pixel difference */
    }

  if (dir_a->scale == requested_scale &&
      dir_b->scale != requested_scale)
    return TRUE;

  if (dir_a->scale != requested_scale &&
      dir_b->scale == requested_scale)
    return FALSE;

  /* a and b both match the scale */

  if (dir_a->type != ICON_THEME_DIR_SCALABLE &&
      dir_b->type == ICON_THEME_DIR_SCALABLE)
    return TRUE;

  if (dir_a->type == ICON_THEME_DIR_SCALABLE &&
      dir_b->type != ICON_THEME_DIR_SCALABLE)
    return FALSE;
      
  /* a and b both are scalable */

  diff_a = abs (requested_size * requested_scale - dir_a->size * dir_a->scale);
  diff_b = abs (requested_size * requested_scale - dir_b->size * dir_b->scale);

  return diff_a <= diff_b;
}

static GtkIconInfo *
theme_lookup_icon (IconTheme   *theme,
                   const gchar *icon_name,
                   gint         size,
                   gint         scale,
                   gboolean     allow_svg)
{
  GList *dirs, *l;
  IconThemeDir *dir, *min_dir;
  gchar *file;
  gint min_difference, difference;
  IconSuffix suffix;
  IconSuffix min_suffix;

  min_difference = G_MAXINT;
  min_dir = NULL;

  dirs = theme->dirs;

  l = dirs;
  while (l != NULL)
    {
      dir = l->data;

      GTK_NOTE (ICONTHEME, g_message ("look up icon dir %s", dir->dir));
      suffix = theme_dir_get_icon_suffix (dir, icon_name);
      if (best_suffix (suffix, allow_svg) != ICON_SUFFIX_NONE)
        {
          difference = theme_dir_size_difference (dir, size, scale);
          if (min_dir == NULL ||
              compare_dir_matches (dir, difference,
                                   min_dir, min_difference,
                                   size, scale))
            {
              min_dir = dir;
              min_suffix = suffix;
              min_difference = difference;
            }
        }

      l = l->next;
    }

  if (min_dir)
    {
      GtkIconInfo *icon_info;

      icon_info = icon_info_new (min_dir->type, min_dir->size, min_dir->scale);
      icon_info->min_size = min_dir->min_size;
      icon_info->max_size = min_dir->max_size;

      suffix = min_suffix;
      suffix = best_suffix (suffix, allow_svg);
      g_assert (suffix != ICON_SUFFIX_NONE);

      if (min_dir->dir)
        {
          file = g_strconcat (icon_name, string_from_suffix (suffix), NULL);
          icon_info->filename = g_build_filename (min_dir->dir, file, NULL);

          icon_info->is_svg = suffix == ICON_SUFFIX_SVG;
          icon_info->is_resource = min_dir->is_resource;
          g_free (file);
        }
      else
        {
          icon_info->filename = NULL;
        }

      if (min_dir->cache)
        {
          icon_info->cache_pixbuf = gtk_icon_cache_get_icon (min_dir->cache, icon_name,
                                                              min_dir->subdir_index);
        }

      return icon_info;
    }

  return NULL;
}

static void
theme_list_icons (IconTheme  *theme, 
                  GHashTable *icons,
                  GQuark      context)
{
  GList *l = theme->dirs;
  IconThemeDir *dir;
  
  while (l != NULL)
    {
      dir = l->data;

      if (context == dir->context ||
          context == 0)
        {
          if (dir->cache)
            gtk_icon_cache_add_icons (dir->cache, dir->subdir, icons);
          else
            g_hash_table_foreach (dir->icons, add_key_to_hash, icons);
        }
      l = l->next;
    }
}

static gboolean
theme_has_icon (IconTheme   *theme,
                const gchar *icon_name)
{
  GList *l;

  for (l = theme->dirs; l; l = l->next)
    {
      IconThemeDir *dir = l->data;

      if (dir->cache)
        {
          if (gtk_icon_cache_has_icon (dir->cache, icon_name))
            return TRUE;
        }
      else
        {
          if (g_hash_table_lookup (dir->icons, icon_name) != NULL)
            return TRUE;
        }
    }

  return FALSE;
}

static GHashTable *
scan_directory (GtkIconTheme  *self,
                char          *full_dir)
{
  GDir *gdir;
  const gchar *name;
  GHashTable *icons = NULL;

  GTK_DISPLAY_NOTE (self->display, ICONTHEME,
                    g_message ("scanning directory %s", full_dir));

  gdir = g_dir_open (full_dir, 0, NULL);

  if (gdir == NULL)
    return NULL;

  while ((name = g_dir_read_name (gdir)))
    {
      gchar *base_name;
      IconSuffix suffix, hash_suffix;

      suffix = suffix_from_name (name);
      if (suffix == ICON_SUFFIX_NONE)
        continue;

      if (!icons)
        icons = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);

      base_name = strip_suffix (name);

      hash_suffix = GPOINTER_TO_INT (g_hash_table_lookup (icons, base_name));
      /* takes ownership of base_name */
      g_hash_table_replace (icons, base_name, GUINT_TO_POINTER (hash_suffix|suffix));
    }

  g_dir_close (gdir);

  return icons;
}

static void
theme_subdir_load (GtkIconTheme *self,
                   IconTheme    *theme,
                   GKeyFile     *theme_file,
                   gchar        *subdir)
{
  GList *d;
  gchar *type_string;
  IconThemeDir *dir;
  IconThemeDirType type;
  gchar *context_string;
  GQuark context;
  gint size;
  gint min_size;
  gint max_size;
  gint threshold;
  gchar *full_dir;
  GError *error = NULL;
  IconThemeDirMtime *dir_mtime;
  gint scale;

  size = g_key_file_get_integer (theme_file, subdir, "Size", &error);
  if (error)
    {
      g_error_free (error);
      g_warning ("Theme directory %s of theme %s has no size field\n", 
                 subdir, theme->name);
      return;
    }

  type = ICON_THEME_DIR_THRESHOLD;
  type_string = g_key_file_get_string (theme_file, subdir, "Type", NULL);
  if (type_string)
    {
      if (strcmp (type_string, "Fixed") == 0)
        type = ICON_THEME_DIR_FIXED;
      else if (strcmp (type_string, "Scalable") == 0)
        type = ICON_THEME_DIR_SCALABLE;
      else if (strcmp (type_string, "Threshold") == 0)
        type = ICON_THEME_DIR_THRESHOLD;

      g_free (type_string);
    }

  context = 0;
  context_string = g_key_file_get_string (theme_file, subdir, "Context", NULL);
  if (context_string)
    {
      context = g_quark_from_string (context_string);
      g_free (context_string);
    }

  if (g_key_file_has_key (theme_file, subdir, "MaxSize", NULL))
    max_size = g_key_file_get_integer (theme_file, subdir, "MaxSize", NULL);
  else
    max_size = size;

  if (g_key_file_has_key (theme_file, subdir, "MinSize", NULL))
    min_size = g_key_file_get_integer (theme_file, subdir, "MinSize", NULL);
  else
    min_size = size;

  if (g_key_file_has_key (theme_file, subdir, "Threshold", NULL))
    threshold = g_key_file_get_integer (theme_file, subdir, "Threshold", NULL);
  else
    threshold = 2;

  if (g_key_file_has_key (theme_file, subdir, "Scale", NULL))
    scale = g_key_file_get_integer (theme_file, subdir, "Scale", NULL);
  else
    scale = 1;

  for (d = self->dir_mtimes; d; d = d->next)
    {
      dir_mtime = (IconThemeDirMtime *)d->data;

      if (!dir_mtime->exists)
        continue; /* directory doesn't exist */

      full_dir = g_build_filename (dir_mtime->dir, subdir, NULL);

      /* First, see if we have a cache for the directory */
      if (dir_mtime->cache != NULL || g_file_test (full_dir, G_FILE_TEST_IS_DIR))
        {
          gboolean has_icons;
          GtkIconCache *dir_cache;
          GHashTable *icon_table = NULL;

          if (dir_mtime->cache == NULL)
            {
              /* This will return NULL if the cache doesn't exist or is outdated */
              dir_mtime->cache = gtk_icon_cache_new_for_path (dir_mtime->dir);
            }

          if (dir_mtime->cache != NULL)
            {
              dir_cache = dir_mtime->cache;
              has_icons = gtk_icon_cache_has_icons (dir_cache, subdir);
            }
          else
            {
              dir_cache = NULL;
              icon_table = scan_directory (self, full_dir);
              has_icons = icon_table != NULL;
            }

          if (!has_icons)
            {
              g_assert (!icon_table);
              g_free (full_dir);
              continue;
            }

          dir = g_new0 (IconThemeDir, 1);
          dir->type = type;
          dir->is_resource = FALSE;
          dir->context = context;
          dir->size = size;
          dir->min_size = min_size;
          dir->max_size = max_size;
          dir->threshold = threshold;
          dir->dir = full_dir;
          dir->subdir = g_strdup (subdir);
          dir->scale = scale;
          dir->icons = icon_table;

          if (dir_cache)
            {
              dir->cache = gtk_icon_cache_ref (dir_cache);
              dir->subdir_index = gtk_icon_cache_get_directory_index (dir->cache, dir->subdir);
            }
          else
            {
              dir_cache = NULL;
              dir->subdir_index = -1;
            }

          theme->dirs = g_list_prepend (theme->dirs, dir);
        }
      else
        g_free (full_dir);
    }

  if (strcmp (theme->name, FALLBACK_ICON_THEME) == 0)
    {
      for (d = self->resource_paths; d; d = d->next)
        {
          int i;
          char **children;

          /* Force a trailing / here, to avoid extra copies in GResource */
          full_dir = g_build_filename ((const gchar *)d->data, subdir, " ", NULL);
          full_dir[strlen (full_dir) - 1] = '\0';

          children = g_resources_enumerate_children (full_dir, 0, NULL);

          if (!children)
            {
              g_free (full_dir);
              continue;
            }

          dir = g_new0 (IconThemeDir, 1);
          dir->icons = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
          dir->type = type;
          dir->is_resource = TRUE;
          dir->context = context;
          dir->size = size;
          dir->min_size = min_size;
          dir->max_size = max_size;
          dir->threshold = threshold;
          dir->dir = full_dir;
          dir->subdir = g_strdup (subdir);
          dir->scale = scale;
          dir->cache = NULL;
          dir->subdir_index = -1;

          for (i = 0; children[i]; i++)
            {
              gchar *base_name;
              IconSuffix suffix, hash_suffix;

              suffix = suffix_from_name (children[i]);
              if (suffix == ICON_SUFFIX_NONE)
                continue;

              base_name = strip_suffix (children[i]);

              hash_suffix = GPOINTER_TO_INT (g_hash_table_lookup (dir->icons, base_name));
              /* takes ownership of base_name */
              g_hash_table_replace (dir->icons, base_name, GUINT_TO_POINTER (hash_suffix|suffix));
            }
          g_strfreev (children);

          if (g_hash_table_size (dir->icons) > 0)
            theme->dirs = g_list_prepend (theme->dirs, dir);
          else
            theme_dir_destroy (dir);
        }
    }
}

/*
 * GtkIconInfo
 */

G_DEFINE_TYPE (GtkIconInfo, gtk_icon_info, G_TYPE_OBJECT)

static void
gtk_icon_info_init (GtkIconInfo *icon_info)
{
  icon_info->scale = -1.;
}

static GtkIconInfo *
icon_info_new (IconThemeDirType type,
               gint             dir_size,
               gint             dir_scale)
{
  GtkIconInfo *icon_info;

  icon_info = g_object_new (GTK_TYPE_ICON_INFO, NULL);

  icon_info->dir_type = type;
  icon_info->dir_size = dir_size;
  icon_info->dir_scale = dir_scale;
  icon_info->unscaled_scale = 1.0;
  icon_info->is_svg = FALSE;
  icon_info->is_resource = FALSE;

  return icon_info;
}

/* This only copies whatever is needed to load the pixbuf,
 * so that we can do a load in a thread without affecting
 * the original IconInfo from the thread.
 */
static GtkIconInfo *
icon_info_dup (GtkIconInfo *icon_info)
{
  GtkIconInfo *dup;

  dup = icon_info_new (icon_info->dir_type, icon_info->dir_size, icon_info->dir_scale);

  dup->filename = g_strdup (icon_info->filename);
  dup->is_svg = icon_info->is_svg;

  if (icon_info->loadable)
    dup->loadable = g_object_ref (icon_info->loadable);
  if (icon_info->texture)
    dup->texture = g_object_ref (icon_info->texture);

  if (icon_info->cache_pixbuf)
    dup->cache_pixbuf = g_object_ref (icon_info->cache_pixbuf);

  dup->scale = icon_info->scale;
  dup->unscaled_scale = icon_info->unscaled_scale;
  dup->desired_size = icon_info->desired_size;
  dup->desired_scale = icon_info->desired_scale;
  dup->forced_size = icon_info->forced_size;
  dup->is_resource = icon_info->is_resource;
  dup->min_size = icon_info->min_size;
  dup->max_size = icon_info->max_size;
  dup->symbolic_width = icon_info->symbolic_width;
  dup->symbolic_height = icon_info->symbolic_height;

  return dup;
}

static void
gtk_icon_info_finalize (GObject *object)
{
  GtkIconInfo *icon_info = (GtkIconInfo *) object;

  if (icon_info->in_cache)
    g_hash_table_remove (icon_info->in_cache->info_cache, &icon_info->key);

  g_strfreev (icon_info->key.icon_names);

  g_free (icon_info->filename);

  g_clear_object (&icon_info->loadable);
  g_clear_object (&icon_info->texture);
  g_clear_object (&icon_info->cache_pixbuf);
  g_clear_error (&icon_info->load_error);

  G_OBJECT_CLASS (gtk_icon_info_parent_class)->finalize (object);
}

static void
gtk_icon_info_class_init (GtkIconInfoClass *klass)
{
  GObjectClass *gobject_class = G_OBJECT_CLASS (klass);

  gobject_class->finalize = gtk_icon_info_finalize;
}

/**
 * gtk_icon_info_get_base_size:
 * @self: a #GtkIconInfo
 * 
 * Gets the base size for the icon. The base size
 * is a size for the icon that was specified by
 * the icon theme creator. This may be different
 * than the actual size of image;
 * These icons will be given
 * the same base size as the larger icons to which
 * they are attached.
 *
 * Note that for scaled icons the base size does
 * not include the base scale.
 *
 * Returns: the base size, or 0, if no base
 *     size is known for the icon.
 */
gint
gtk_icon_info_get_base_size (GtkIconInfo *icon_info)
{
  g_return_val_if_fail (icon_info != NULL, 0);

  return icon_info->dir_size;
}

/**
 * gtk_icon_info_get_base_scale:
 * @self: a #GtkIconInfo
 *
 * Gets the base scale for the icon. The base scale is a scale
 * for the icon that was specified by the icon theme creator.
 * For instance an icon drawn for a high-dpi monitor with window
 * scale 2 for a base size of 32 will be 64 pixels tall and have
 * a base scale of 2.
 *
 * Returns: the base scale
 */
gint
gtk_icon_info_get_base_scale (GtkIconInfo *icon_info)
{
  g_return_val_if_fail (icon_info != NULL, 0);

  return icon_info->dir_scale;
}

/**
 * gtk_icon_info_get_filename:
 * @self: a #GtkIconInfo
 * 
 * Gets the filename for the icon. If the %GTK_ICON_LOOKUP_USE_BUILTIN
 * flag was passed to gtk_icon_theme_lookup_icon(), there may be no
 * filename if a builtin icon is returned; in this case, you should
 * use gtk_icon_info_get_builtin_pixbuf().
 * 
 * Returns: (nullable) (type filename): the filename for the icon, or %NULL
 *     if gtk_icon_info_get_builtin_pixbuf() should be used instead.
 *     The return value is owned by GTK+ and should not be modified
 *     or freed.
 */
const gchar *
gtk_icon_info_get_filename (GtkIconInfo *icon_info)
{
  g_return_val_if_fail (icon_info != NULL, NULL);

  return icon_info->filename;
}

/**
 * gtk_icon_info_is_symbolic:
 * @self: a #GtkIconInfo
 *
 * Checks if the icon is symbolic or not. This currently uses only
 * the file name and not the file contents for determining this.
 * This behaviour may change in the future.
 *
 * Returns: %TRUE if the icon is symbolic, %FALSE otherwise
 */
gboolean
gtk_icon_info_is_symbolic (GtkIconInfo *icon_info)
{
  g_return_val_if_fail (GTK_IS_ICON_INFO (icon_info), FALSE);

  return icon_info->filename != NULL &&
         icon_uri_is_symbolic (icon_info->filename, -1);
}

/* If this returns TRUE, its safe to call icon_info_ensure_scale_and_texture
 * without blocking
 */
static gboolean
icon_info_get_pixbuf_ready (GtkIconInfo *icon_info)
{
  if (icon_info->texture)
    return TRUE;

  if (icon_info->load_error)
    return TRUE;

  return FALSE;
}

static GLoadableIcon *
icon_info_get_loadable (GtkIconInfo *icon_info)
{
  GFile *file;
  GLoadableIcon *loadable;

  if (icon_info->loadable)
    return g_object_ref (icon_info->loadable);

  if (icon_info->is_resource)
    {
      char *uri = g_strconcat ("resource://", icon_info->filename, NULL);
      file = g_file_new_for_uri (uri);
      g_free (uri);
    }
  else
    file = g_file_new_for_path (icon_info->filename);

  loadable = G_LOADABLE_ICON (g_file_icon_new (file));

  g_object_unref (file);

  return loadable;
}

/* This function contains the complicated logic for deciding
 * on the size at which to load the icon and loading it at
 * that size.
 */
static gboolean
icon_info_ensure_scale_and_texture (GtkIconInfo *icon_info)
{
  gint image_width, image_height, image_size;
  gint scaled_desired_size;
  GdkPixbuf *source_pixbuf;
  gdouble dir_scale;

  if (icon_info->texture)
    return TRUE;

  if (icon_info->load_error)
    return FALSE;

  scaled_desired_size = icon_info->desired_size * icon_info->desired_scale;

  dir_scale = icon_info->dir_scale;

  /* In many cases, the scale can be determined without actual access
   * to the icon file. This is generally true when we have a size
   * for the directory where the icon is; the image size doesn't
   * matter in that case.
   */
  if (icon_info->forced_size ||
      icon_info->dir_type == ICON_THEME_DIR_UNTHEMED)
    icon_info->scale = -1;
  else if (icon_info->dir_type == ICON_THEME_DIR_FIXED ||
           icon_info->dir_type == ICON_THEME_DIR_THRESHOLD)
    icon_info->scale = icon_info->unscaled_scale;
  else if (icon_info->dir_type == ICON_THEME_DIR_SCALABLE)
    {
      /* For svg icons, treat scalable directories as if they had
       * a Scale=<desired_scale> entry. In particular, this means
       * spinners that are restriced to size 32 will loaded at size
       * up to 64 with Scale=2.
       */
      if (icon_info->is_svg)
        dir_scale = icon_info->desired_scale;

      if (scaled_desired_size < icon_info->min_size * dir_scale)
        icon_info->scale = (gdouble) icon_info->min_size / (gdouble) icon_info->dir_size;
      else if (scaled_desired_size > icon_info->max_size * dir_scale)
        icon_info->scale = (gdouble) icon_info->max_size / (gdouble) icon_info->dir_size;
      else
        icon_info->scale = (gdouble) scaled_desired_size / (icon_info->dir_size * dir_scale);
    }

  gdk_profiler_add_mark (g_get_monotonic_time () * 1000, 0, "icon load", icon_info->filename);

  /* At this point, we need to actually get the icon; either from the
   * builtin image or by loading the file
   */
  source_pixbuf = NULL;
  if (icon_info->cache_pixbuf)
    source_pixbuf = g_object_ref (icon_info->cache_pixbuf);
  else if (icon_info->is_resource)
    {
      if (icon_info->is_svg)
        {
          gint size;

          if (icon_info->forced_size || icon_info->dir_type == ICON_THEME_DIR_UNTHEMED)
            size = scaled_desired_size;
          else
            size = icon_info->dir_size * dir_scale * icon_info->scale;

          if (gtk_icon_info_is_symbolic (icon_info))
            source_pixbuf = gtk_make_symbolic_pixbuf_from_resource (icon_info->filename,
                                                                    size, size,
                                                                    icon_info->desired_scale,
                                                                    &icon_info->load_error);
          else if (size == 0)
            source_pixbuf = _gdk_pixbuf_new_from_resource_scaled (icon_info->filename,
                                                                  "svg",
                                                                  icon_info->desired_scale,
                                                                  &icon_info->load_error);
          else
            source_pixbuf = _gdk_pixbuf_new_from_resource_at_scale (icon_info->filename,
                                                                    "svg",
                                                                    size, size, TRUE,
                                                                    &icon_info->load_error);
        }
      else
        source_pixbuf = _gdk_pixbuf_new_from_resource (icon_info->filename,
                                                       "png",
                                                       &icon_info->load_error);
    }
  else
    {
      GLoadableIcon *loadable;
      GInputStream *stream;

      loadable = icon_info_get_loadable (icon_info);
      stream = g_loadable_icon_load (loadable,
                                     scaled_desired_size,
                                     NULL, NULL,
                                     &icon_info->load_error);
      g_object_unref (loadable);

      if (stream)
        {
          /* SVG icons are a special case - we just immediately scale them
           * to the desired size
           */
          if (icon_info->is_svg)
            {
              gint size;

              if (icon_info->forced_size || icon_info->dir_type == ICON_THEME_DIR_UNTHEMED)
                size = scaled_desired_size;
              else
                size = icon_info->dir_size * dir_scale * icon_info->scale;

              if (gtk_icon_info_is_symbolic (icon_info))
                source_pixbuf = gtk_make_symbolic_pixbuf_from_path (icon_info->filename,
                                                                    size, size,
                                                                    icon_info->desired_scale,
                                                                    &icon_info->load_error);
              else if (size == 0)
                source_pixbuf = _gdk_pixbuf_new_from_stream_scaled (stream,
                                                                    "svg",
                                                                    icon_info->desired_scale,
                                                                    NULL,
                                                                    &icon_info->load_error);
              else
                source_pixbuf = _gdk_pixbuf_new_from_stream_at_scale (stream,
                                                                      "svg",
                                                                      size, size,
                                                                      TRUE, NULL,
                                                                     &icon_info->load_error);
            }
          else
            source_pixbuf = _gdk_pixbuf_new_from_stream (stream,
                                                         "png",
                                                         NULL,
                                                         &icon_info->load_error);
          g_object_unref (stream);
        }
    }

  if (!source_pixbuf)
    {
      static gboolean warn_about_load_failure = TRUE;

      if (warn_about_load_failure)
        {
          const char *path;

          if (icon_info->filename)
            path = icon_info->filename;
          else if (G_IS_FILE (icon_info->loadable))
            path = g_file_peek_path (G_FILE (icon_info->loadable));
          else
            path = "icon theme";

          g_warning ("Could not load a pixbuf from %s.\n"
                     "This may indicate that pixbuf loaders or the mime database could not be found.",
                     path);

          warn_about_load_failure = FALSE;
        }

      return FALSE;
    }

  /* Do scale calculations that depend on the image size
   */
  image_width = gdk_pixbuf_get_width (source_pixbuf);
  image_height = gdk_pixbuf_get_height (source_pixbuf);
  image_size = MAX (image_width, image_height);

  if (icon_info->is_svg)
    icon_info->scale = image_size / 1000.;
  else if (icon_info->scale < 0.0)
    {
      if (image_size > 0 && scaled_desired_size > 0)
        icon_info->scale = (gdouble)scaled_desired_size / (gdouble)image_size;
      else
        icon_info->scale = 1.0;

      if (icon_info->dir_type == ICON_THEME_DIR_UNTHEMED && 
          !icon_info->forced_size)
        icon_info->scale = MIN (icon_info->scale, 1.0);
    }

  if (icon_info->is_svg ||
      icon_info->scale == 1.0)
    {
      icon_info->texture = gdk_texture_new_for_pixbuf (source_pixbuf);
      g_object_unref (source_pixbuf);
    }
  else
    {
      GdkPixbuf *scaled = gdk_pixbuf_scale_simple (source_pixbuf,
                                                   MAX (1, 0.5 + image_width * icon_info->scale),
                                                   MAX (1, 0.5 + image_height * icon_info->scale),
                                                   GDK_INTERP_BILINEAR);
      icon_info->texture = gdk_texture_new_for_pixbuf (scaled);
      g_object_unref (scaled);
      g_object_unref (source_pixbuf);
    }

  g_assert (icon_info->texture != NULL);
  add_to_lru_cache (icon_info);

  return TRUE;
}

/**
 * gtk_icon_info_load_icon:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @error: (allow-none): location to store error information on failure,
 *     or %NULL.
 *
 * Renders an icon previously looked up in an icon theme using
 * gtk_icon_theme_lookup_icon(); the size will be based on the size
 * passed to gtk_icon_theme_lookup_icon(). Note that the resulting
 * pixbuf may not be exactly this size; an icon theme may have icons
 * that differ slightly from their nominal sizes, and in addition GTK+
 * will avoid scaling icons that it considers sufficiently close to the
 * requested size or for which the source image would have to be scaled
 * up too far. (This maintains sharpness.). This behaviour can be changed
 * by passing the %GTK_ICON_LOOKUP_FORCE_SIZE flag when obtaining
 * the #GtkIconInfo. If this flag has been specified, the pixbuf
 * returned by this function will be scaled to the exact size.
 *
 * Returns: (transfer full) (nullable): the rendered icon.
 *   Use g_object_unref() to release your reference to the icon.
 */
GdkPaintable *
gtk_icon_info_load_icon (GtkIconInfo *icon_info,
                         GError     **error)
{
  g_return_val_if_fail (icon_info != NULL, NULL);
  g_return_val_if_fail (error == NULL || *error == NULL, NULL);

  if (!icon_info->texture)
    {
      icon_info_ensure_scale_and_texture (icon_info);

      /* Still no texture -> error */
      if (!icon_info->texture)
        {
          if (icon_info->load_error)
            {
              if (error)
                *error = g_error_copy (icon_info->load_error);
            }
          else
            {
              g_set_error_literal (error,
                                   GTK_ICON_THEME_ERROR,
                                   GTK_ICON_THEME_NOT_FOUND,
                                   _("Failed to load icon"));
            }

          return NULL;
        }
    }

  return GDK_PAINTABLE (g_object_ref (icon_info->texture));
}

static void
load_icon_thread  (GTask        *task,
                   gpointer      source_object,
                   gpointer      task_data,
                   GCancellable *cancellable)
{
  GtkIconInfo *dup = task_data;

  (void)icon_info_ensure_scale_and_texture (dup);
  g_task_return_pointer (task, NULL, NULL);
}

/**
 * gtk_icon_info_load_icon_async:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @cancellable: (allow-none): optional #GCancellable object, %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the
 *     request is satisfied
 * @user_data: (closure): the data to pass to callback function
 *
 * Asynchronously load, render and scale an icon previously looked up
 * from the icon theme using gtk_icon_theme_lookup_icon().
 *
 * For more details, see gtk_icon_info_load_icon() which is the synchronous
 * version of this call.
 */
void
gtk_icon_info_load_icon_async (GtkIconInfo         *icon_info,
                               GCancellable        *cancellable,
                               GAsyncReadyCallback  callback,
                               gpointer             user_data)
{
  GTask *task;

  task = g_task_new (icon_info, cancellable, callback, user_data);

  if (icon_info_get_pixbuf_ready (icon_info))
    {
      GError *error = NULL;
      GdkPaintable *paintable = gtk_icon_info_load_icon (icon_info, &error);

      if (paintable == NULL)
        g_task_return_error (task, error);
      else
        g_task_return_pointer (task, paintable, g_object_unref);
    }
  else
    {
      GtkIconInfo *dup = icon_info_dup (icon_info);
      g_task_set_task_data (task, dup, g_object_unref);
      g_task_run_in_thread (task, load_icon_thread);
    }

  g_object_unref (task);
}

/**
 * gtk_icon_info_load_icon_finish:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @res: a #GAsyncResult
 * @error: (allow-none): location to store error information on failure,
 *     or %NULL.
 *
 * Finishes an async icon load, see gtk_icon_info_load_icon_async().
 *
 * Returns: (transfer full): the rendered icon; this may be a newly
 *     created icon or a new reference to an internal icon, so you must
 *     not modify the icon. Use g_object_unref() to release your reference
 *     to the icon.
 */
GdkPaintable *
gtk_icon_info_load_icon_finish (GtkIconInfo   *icon_info,
                                GAsyncResult  *result,
                                GError       **error)
{
  GTask *task = G_TASK (result);
  GtkIconInfo *dup;

  g_return_val_if_fail (g_task_is_valid (result, icon_info), NULL);

  dup = g_task_get_task_data (task);
  if (dup == NULL || g_task_had_error (task))
    return g_task_propagate_pointer (task, error);

  /* We ran the thread and it was not cancelled */

  /* Check if someone else updated the icon_info in between */
  if (!icon_info_get_pixbuf_ready (icon_info))
    {
      /* If not, copy results from dup back to icon_info */
      icon_info->scale = dup->scale;
      g_clear_object (&icon_info->texture);
      if (dup->texture)
        icon_info->texture = g_object_ref (dup->texture);
      g_clear_error (&icon_info->load_error);
      if (dup->load_error)
        icon_info->load_error = g_error_copy (dup->load_error);
    }

  g_assert (icon_info_get_pixbuf_ready (icon_info));

  /* This is now guaranteed to not block */
  return gtk_icon_info_load_icon (icon_info, error);
}

static GdkPixbuf *
gtk_icon_info_load_symbolic_png (GtkIconInfo    *icon_info,
                                 const GdkRGBA  *fg,
                                 const GdkRGBA  *success_color,
                                 const GdkRGBA  *warning_color,
                                 const GdkRGBA  *error_color,
                                 GError        **error)
{
  GdkRGBA fg_default = { 0.7450980392156863, 0.7450980392156863, 0.7450980392156863, 1.0};
  GdkRGBA success_default = { 0.3046921492332342,0.6015716792553597, 0.023437857633325704, 1.0};
  GdkRGBA warning_default = {0.9570458533607996, 0.47266346227206835, 0.2421911955443656, 1.0 };
  GdkRGBA error_default = { 0.796887159533074, 0 ,0, 1.0 };
  GdkPixbuf *pixbuf;
  GdkPixbuf *colored;

  if (!icon_info_ensure_scale_and_texture (icon_info))
    {
      if (icon_info->load_error)
        {
          if (error)
            *error = g_error_copy (icon_info->load_error);
        }
      else
        {
          g_set_error_literal (error,
                               GTK_ICON_THEME_ERROR,
                               GTK_ICON_THEME_NOT_FOUND,
                               _("Failed to load icon"));
        }

      return NULL;
    }

  pixbuf = gdk_pixbuf_get_from_texture (icon_info->texture);
  colored = gtk_color_symbolic_pixbuf (pixbuf,
                                       fg ? fg : &fg_default,
                                       success_color ? success_color : &success_default,
                                       warning_color ? warning_color : &warning_default,
                                       error_color ? error_color : &error_default);
  g_object_unref (pixbuf);
  return colored;
}

#define MAX_RGB_STRING_LENGTH (3 + 1 + ((3 + 1) * 3) + 1 + 1)
static inline void
rgba_to_string_noalpha (const GdkRGBA *rgba,
                        char          *buff)
{
  /* gdk_rgba_to_string inlined in here for the alpha == 1 case,
   * and g_strdup_printf replaced with g_snprintf */
  g_snprintf (buff,
              MAX_RGB_STRING_LENGTH,
              "rgb(%d,%d,%d)",
              (int)(0.5 + CLAMP (rgba->red, 0., 1.) * 255.),
              (int)(0.5 + CLAMP (rgba->green, 0., 1.) * 255.),
              (int)(0.5 + CLAMP (rgba->blue, 0., 1.) * 255.));
}

static GdkPixbuf *
gtk_icon_info_load_symbolic_svg (GtkIconInfo    *icon_info,
                                 const GdkRGBA  *fg,
                                 const GdkRGBA  *success_color,
                                 const GdkRGBA  *warning_color,
                                 const GdkRGBA  *error_color,
                                 GError        **error)
{
  GInputStream *stream;
  GdkPixbuf *pixbuf;
  char css_fg[MAX_RGB_STRING_LENGTH];
  char css_warning[MAX_RGB_STRING_LENGTH] = "rgb(245,121,62)";
  char css_success[MAX_RGB_STRING_LENGTH] = "rgb(78,154,6)";
  char css_error[MAX_RGB_STRING_LENGTH] = "rgb(204,0,0)";
  gchar *svg_data;
  gchar *width;
  gchar *height;
  char *escaped_file_data;
  double alpha;
  gchar alphastr[G_ASCII_DTOSTR_BUF_SIZE];

  alpha = fg->alpha;

  rgba_to_string_noalpha (fg, css_fg);

  if (warning_color)
    rgba_to_string_noalpha (warning_color, css_warning);

  if (error_color)
    rgba_to_string_noalpha (error_color, css_error);

  if (success_color)
    rgba_to_string_noalpha (success_color, css_success);

  if (icon_info->is_resource)
    {
      GBytes *bytes;
      const char *data;
      gsize file_len;

      bytes = g_resources_lookup_data (icon_info->filename, G_RESOURCE_LOOKUP_FLAGS_NONE, error);
      if (bytes == NULL)
        return NULL;
      data = g_bytes_get_data (bytes, &file_len);
      escaped_file_data = g_base64_encode ((guchar *) data, file_len);
      g_bytes_unref (bytes);
    }
  else
    {
      char *file_data;
      gsize file_len;

      if (!g_file_get_contents (icon_info->filename, &file_data, &file_len, error))
        return NULL;
      escaped_file_data = g_base64_encode ((guchar *) file_data, file_len);
      g_free (file_data);
    }

  if (!icon_info_ensure_scale_and_texture (icon_info))
    {
      g_propagate_error (error, icon_info->load_error);
      icon_info->load_error = NULL;
      g_free (escaped_file_data);
      return NULL;
    }

  if (icon_info->symbolic_width == 0 ||
      icon_info->symbolic_height == 0)
    {
      /* Fetch size from the original icon */
      if (icon_info->is_resource)
        pixbuf = gdk_pixbuf_new_from_resource (icon_info->filename, error);
      else
        pixbuf = gdk_pixbuf_new_from_file (icon_info->filename, error);

      if (!pixbuf)
        {
          g_free (escaped_file_data);
          return NULL;
        }

      icon_info->symbolic_width = gdk_pixbuf_get_width (pixbuf);
      icon_info->symbolic_height = gdk_pixbuf_get_height (pixbuf);
      g_object_unref (pixbuf);
    }

  GTK_NOTE (ICONTHEME, {
  int symbolic_size = MAX (icon_info->symbolic_width, icon_info->symbolic_height);
  if (icon_info->dir_type == ICON_THEME_DIR_UNTHEMED)
    g_message ("Symbolic icon %s is not in an icon theme directory",
               icon_info->key.icon_names ? icon_info->key.icon_names[0] : icon_info->filename);
  else if (icon_info->dir_size * icon_info->dir_scale != symbolic_size)
    g_message ("Symbolic icon %s of size %d is in an icon theme directory of size %d",
               icon_info->key.icon_names ? icon_info->key.icon_names[0] : icon_info->filename,
               symbolic_size,
               icon_info->dir_size * icon_info->dir_scale);
  });

  width = g_strdup_printf ("%d", icon_info->symbolic_width);
  height = g_strdup_printf ("%d", icon_info->symbolic_height);

  g_ascii_dtostr (alphastr, G_ASCII_DTOSTR_BUF_SIZE, CLAMP (alpha, 0, 1));

  svg_data = g_strconcat ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
                      "<svg version=\"1.1\"\n"
                      "     xmlns=\"http://www.w3.org/2000/svg\"\n"
                      "     xmlns:xi=\"http://www.w3.org/2001/XInclude\"\n"
                      "     width=\"", width, "\"\n"
                      "     height=\"", height, "\">\n"
                      "  <style type=\"text/css\">\n"
                      "    rect,path,ellipse,circle,polygon {\n"
                      "      fill: ", css_fg," !important;\n"
                      "    }\n"
                      "    .warning {\n"
                      "      fill: ", css_warning, " !important;\n"
                      "    }\n"
                      "    .error {\n"
                      "      fill: ", css_error ," !important;\n"
                      "    }\n"
                      "    .success {\n"
                      "      fill: ", css_success, " !important;\n"
                      "    }\n"
                      "  </style>\n"
                      "  <g opacity=\"", alphastr, "\" ><xi:include href=\"data:text/xml;base64,", escaped_file_data, "\"/></g>\n"
                      "</svg>",
                      NULL);
  g_free (escaped_file_data);
  g_free (width);
  g_free (height);

  stream = g_memory_input_stream_new_from_data (svg_data, -1, g_free);
  pixbuf = _gdk_pixbuf_new_from_stream_at_scale (stream,
                                                 "svg",
                                                gdk_texture_get_width (icon_info->texture),
                                                gdk_texture_get_height (icon_info->texture),
                                                TRUE,
                                                NULL,
                                                error);
  g_object_unref (stream);

  return pixbuf;
}


static GdkPixbuf *
gtk_icon_info_load_symbolic_internal (GtkIconInfo    *icon_info,
                                      const GdkRGBA  *fg,
                                      const GdkRGBA  *success_color,
                                      const GdkRGBA  *warning_color,
                                      const GdkRGBA  *error_color,
                                      GError        **error)
{
  GdkPixbuf *pixbuf;

  if (g_str_has_suffix (icon_info->filename, ".symbolic.png"))
    pixbuf = gtk_icon_info_load_symbolic_png (icon_info, fg, success_color, warning_color, error_color, error);
  else
    pixbuf = gtk_icon_info_load_symbolic_svg (icon_info, fg, success_color, warning_color, error_color, error);

  return pixbuf;
}

/**
 * gtk_icon_info_load_symbolic:
 * @self: a #GtkIconInfo
 * @fg: a #GdkRGBA representing the foreground color of the icon
 * @success_color: (allow-none): a #GdkRGBA representing the warning color
 *     of the icon or %NULL to use the default color
 * @warning_color: (allow-none): a #GdkRGBA representing the warning color
 *     of the icon or %NULL to use the default color
 * @error_color: (allow-none): a #GdkRGBA representing the error color
 *     of the icon or %NULL to use the default color (allow-none)
 * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
 *     loaded icon was a symbolic one and whether the @fg color was
 *     applied to it.
 * @error: (allow-none): location to store error information on failure,
 *     or %NULL.
 *
 * Loads an icon, modifying it to match the system colours for the foreground,
 * success, warning and error colors provided. If the icon is not a symbolic
 * one, the function will return the result from gtk_icon_info_load_icon().
 *
 * This allows loading symbolic icons that will match the system theme.
 *
 * Unless you are implementing a widget, you will want to use
 * g_themed_icon_new_with_default_fallbacks() to load the icon.
 *
 * As implementation details, the icon loaded needs to be of SVG type,
 * contain the “symbolic” term as the last component of the icon name,
 * and use the “fg”, “success”, “warning” and “error” CSS styles in the
 * SVG file itself.
 *
 * See the [Symbolic Icons Specification](http://www.freedesktop.org/wiki/SymbolicIcons)
 * for more information about symbolic icons.
 *
 * Returns: (transfer full): a #GdkPixbuf representing the loaded icon
 */
GdkPaintable *
gtk_icon_info_load_symbolic (GtkIconInfo    *icon_info,
                             const GdkRGBA  *fg,
                             const GdkRGBA  *success_color,
                             const GdkRGBA  *warning_color,
                             const GdkRGBA  *error_color,
                             gboolean       *was_symbolic,
                             GError        **error)
{
  GdkPixbuf *pixbuf;
  gboolean is_symbolic;

  g_return_val_if_fail (icon_info != NULL, NULL);
  g_return_val_if_fail (fg != NULL, NULL);

  is_symbolic = gtk_icon_info_is_symbolic (icon_info);

  if (was_symbolic)
    *was_symbolic = is_symbolic;

  if (!is_symbolic)
    return gtk_icon_info_load_icon (icon_info, error);

  pixbuf = gtk_icon_info_load_symbolic_internal (icon_info,
                                                 fg, success_color,
                                                 warning_color, error_color,
                                                 error);

  if (pixbuf)
    {
      GdkTexture *texture = gdk_texture_new_for_pixbuf (pixbuf);
      g_object_unref (pixbuf);

      return GDK_PAINTABLE (texture);
    }

  return NULL;
}

void
gtk_icon_theme_lookup_symbolic_colors (GtkCssStyle *style,
                                       GdkRGBA     *color_out,
                                       GdkRGBA     *success_out,
                                       GdkRGBA     *warning_out,
                                       GdkRGBA     *error_out)
{
  GtkCssValue *palette, *color;
  const GdkRGBA *lookup;

  color = gtk_css_style_get_value (style, GTK_CSS_PROPERTY_COLOR);
  palette = gtk_css_style_get_value (style, GTK_CSS_PROPERTY_ICON_PALETTE);
  *color_out = *gtk_css_color_value_get_rgba (color);

  lookup = gtk_css_palette_value_get_color (palette, "success");
  if (lookup)
    *success_out = *lookup;
  else
    *success_out = *color_out;

  lookup = gtk_css_palette_value_get_color (palette, "warning");
  if (lookup)
    *warning_out = *lookup;
  else
    *warning_out = *color_out;

  lookup = gtk_css_palette_value_get_color (palette, "error");
  if (lookup)
    *error_out = *lookup;
  else
    *error_out = *color_out;
}

/**
 * gtk_icon_info_load_symbolic_for_context:
 * @self: a #GtkIconInfo
 * @context: a #GtkStyleContext
 * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
 *     loaded icon was a symbolic one and whether the foreground color was
 *     applied to it.
 * @error: (allow-none): location to store error information on failure,
 *     or %NULL.
 *
 * Loads an icon, modifying it to match the system colors for the foreground,
 * success, warning and error colors provided. If the icon is not a symbolic
 * one, the function will return the result from gtk_icon_info_load_icon().
 * This function uses the regular foreground color and the symbolic colors
 * with the names “success_color”, “warning_color” and “error_color” from
 * the context.
 *
 * This allows loading symbolic icons that will match the system theme.
 *
 * See gtk_icon_info_load_symbolic() for more details.
 *
 * Returns: (transfer full) (nullable): a #GdkPixbuf representing the loaded icon
 *   or %NULL If the icon could not be loaded
 */
GdkPaintable *
gtk_icon_info_load_symbolic_for_context (GtkIconInfo      *icon_info,
                                         GtkStyleContext  *context,
                                         gboolean         *was_symbolic,
                                         GError          **error)
{
  GdkRGBA fg;
  GdkRGBA success_color;
  GdkRGBA warning_color;
  GdkRGBA error_color;
  gboolean is_symbolic;
  GdkPixbuf *pixbuf;

  g_return_val_if_fail (icon_info != NULL, NULL);
  g_return_val_if_fail (context != NULL, NULL);

  is_symbolic = gtk_icon_info_is_symbolic (icon_info);

  if (was_symbolic)
    *was_symbolic = is_symbolic;

  if (!is_symbolic)
    return gtk_icon_info_load_icon (icon_info, error);

  gtk_icon_theme_lookup_symbolic_colors (gtk_style_context_lookup_style (context),
                                         &fg, &success_color,
                                         &warning_color, &error_color);

  pixbuf = gtk_icon_info_load_symbolic_internal (icon_info,
                                                 &fg, &success_color,
                                                 &warning_color, &error_color,
                                                 error);

  if (pixbuf)
    {
      GdkTexture *texture = gdk_texture_new_for_pixbuf (pixbuf);
      g_object_unref (pixbuf);

      return GDK_PAINTABLE (texture);
    }

  return NULL;
}

typedef struct {
  guint is_symbolic : 1;
  guint success_color_set : 1;
  guint warning_color_set : 1;
  guint error_color_set : 1;
  guint fg_set : 1;
  GtkIconInfo *dup;
  GdkRGBA fg;
  GdkRGBA success_color;
  GdkRGBA warning_color;
  GdkRGBA error_color;
} AsyncSymbolicData;

static void
async_symbolic_data_free (AsyncSymbolicData *data)
{
  if (data->dup)
    g_object_unref (data->dup);
  g_slice_free (AsyncSymbolicData, data);
}

static void
async_load_no_symbolic_cb (GObject      *source_object,
                           GAsyncResult *res,
                           gpointer      user_data)
{
  GtkIconInfo *icon_info = GTK_ICON_INFO (source_object);
  GTask *task = user_data;
  GError *error = NULL;
  GdkPaintable *paintable;

  paintable = gtk_icon_info_load_icon_finish (icon_info, res, &error);
  if (paintable == NULL)
    g_task_return_error (task, error);
  else
    g_task_return_pointer (task, paintable, g_object_unref);
  g_object_unref (task);
}

static void
load_symbolic_icon_thread  (GTask        *task,
                            gpointer      source_object,
                            gpointer      task_data,
                            GCancellable *cancellable)
{
  AsyncSymbolicData *data = task_data;
  GError *error;
  GdkPixbuf *pixbuf;

  error = NULL;
  pixbuf = gtk_icon_info_load_symbolic_internal (data->dup,
                                                 data->fg_set ? &data->fg : NULL,
                                                 data->success_color_set ? &data->success_color : NULL,
                                                 data->warning_color_set ? &data->warning_color : NULL,
                                                 data->error_color_set ? &data->error_color : NULL,
                                                 &error);
  if (pixbuf == NULL)
    g_task_return_error (task, error);
  else
    g_task_return_pointer (task, pixbuf, g_object_unref);
}

/**
 * gtk_icon_info_load_symbolic_async:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @fg: a #GdkRGBA representing the foreground color of the icon
 * @success_color: (allow-none): a #GdkRGBA representing the warning color
 *     of the icon or %NULL to use the default color
 * @warning_color: (allow-none): a #GdkRGBA representing the warning color
 *     of the icon or %NULL to use the default color
 * @error_color: (allow-none): a #GdkRGBA representing the error color
 *     of the icon or %NULL to use the default color (allow-none)
 * @cancellable: (allow-none): optional #GCancellable object,
 *     %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the
 *     request is satisfied
 * @user_data: (closure): the data to pass to callback function
 *
 * Asynchronously load, render and scale a symbolic icon previously looked up
 * from the icon theme using gtk_icon_theme_lookup_icon().
 *
 * For more details, see gtk_icon_info_load_symbolic() which is the synchronous
 * version of this call.
 */
void
gtk_icon_info_load_symbolic_async (GtkIconInfo          *icon_info,
                                   const GdkRGBA        *fg,
                                   const GdkRGBA        *success_color,
                                   const GdkRGBA        *warning_color,
                                   const GdkRGBA        *error_color,
                                   GCancellable         *cancellable,
                                   GAsyncReadyCallback   callback,
                                   gpointer              user_data)
{
  GTask *task;
  AsyncSymbolicData *data;

  g_return_if_fail (icon_info != NULL);
  g_return_if_fail (fg != NULL);

  task = g_task_new (icon_info, cancellable, callback, user_data);

  data = g_slice_new0 (AsyncSymbolicData);
  g_task_set_task_data (task, data, (GDestroyNotify) async_symbolic_data_free);

  data->is_symbolic = gtk_icon_info_is_symbolic (icon_info);

  if (!data->is_symbolic)
    {
      gtk_icon_info_load_icon_async (icon_info, cancellable, async_load_no_symbolic_cb, g_object_ref (task));
    }
  else
    {
      if (fg)
        {
          data->fg = *fg;
          data->fg_set = TRUE;
        }

      if (success_color)
        {
          data->success_color = *success_color;
          data->success_color_set = TRUE;
        }

      if (warning_color)
        {
          data->warning_color = *warning_color;
          data->warning_color_set = TRUE;
        }

      if (error_color)
        {
          data->error_color = *error_color;
          data->error_color_set = TRUE;
        }

      data->dup = icon_info_dup (icon_info);
      g_task_run_in_thread (task, load_symbolic_icon_thread);
    }
  g_object_unref (task);
}

/**
 * gtk_icon_info_load_symbolic_finish:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @res: a #GAsyncResult
 * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
 *     loaded icon was a symbolic one and whether the @fg color was
 *     applied to it.
 * @error: (allow-none): location to store error information on failure,
 *     or %NULL.
 *
 * Finishes an async icon load, see gtk_icon_info_load_symbolic_async().
 *
 * Returns: (transfer full): the rendered icon;
 *  Use g_object_unref() to release your reference
 *  to the icon.
 */
GdkPaintable *
gtk_icon_info_load_symbolic_finish (GtkIconInfo   *icon_info,
                                    GAsyncResult  *result,
                                    gboolean      *was_symbolic,
                                    GError       **error)
{
  GTask *task = G_TASK (result);
  AsyncSymbolicData *data = g_task_get_task_data (task);
  GdkPixbuf *pixbuf;
  GdkTexture *texture;

  if (was_symbolic)
    *was_symbolic = data->is_symbolic;

  if (data->dup && !g_task_had_error (task))
    {
      pixbuf = g_task_propagate_pointer (task, NULL);

      g_assert (pixbuf != NULL); /* we checked for !had_error above */
    }
  else
    {
      pixbuf = g_task_propagate_pointer (task, error);
    }

  texture = gdk_texture_new_for_pixbuf (pixbuf);
  g_object_unref (pixbuf);

  return GDK_PAINTABLE (texture);
}

/**
 * gtk_icon_info_load_symbolic_for_context_async:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @context: a #GtkStyleContext
 * @cancellable: (allow-none): optional #GCancellable object,
 *     %NULL to ignore
 * @callback: (scope async): a #GAsyncReadyCallback to call when the
 *     request is satisfied
 * @user_data: (closure): the data to pass to callback function
 *
 * Asynchronously load, render and scale a symbolic icon previously
 * looked up from the icon theme using gtk_icon_theme_lookup_icon().
 *
 * For more details, see gtk_icon_info_load_symbolic_for_context()
 * which is the synchronous version of this call.
 */
void
gtk_icon_info_load_symbolic_for_context_async (GtkIconInfo         *icon_info,
                                               GtkStyleContext     *context,
                                               GCancellable        *cancellable,
                                               GAsyncReadyCallback  callback,
                                               gpointer             user_data)
{
  GdkRGBA fg;
  GdkRGBA success_color;
  GdkRGBA warning_color;
  GdkRGBA error_color;

  g_return_if_fail (icon_info != NULL);
  g_return_if_fail (context != NULL);

  gtk_icon_theme_lookup_symbolic_colors (gtk_style_context_lookup_style (context),
                                         &fg, &success_color,
                                         &warning_color, &error_color);

  gtk_icon_info_load_symbolic_async (icon_info,
                                     &fg, &success_color,
                                     &warning_color, &error_color,
                                     cancellable, callback, user_data);
}

/**
 * gtk_icon_info_load_symbolic_for_context_finish:
 * @self: a #GtkIconInfo from gtk_icon_theme_lookup_icon()
 * @res: a #GAsyncResult
 * @was_symbolic: (out) (allow-none): a #gboolean, returns whether the
 *     loaded icon was a symbolic one and whether the @fg color was
 *     applied to it.
 * @error: (allow-none): location to store error information on failure,
 *     or %NULL.
 *
 * Finishes an async icon load, see gtk_icon_info_load_symbolic_for_context_async().
 *
 * Returns: (transfer full): the rendered icon; this may be a newly
 *     created icon or a new reference to an internal icon, so you must
 *     not modify the icon. Use g_object_unref() to release your reference
 *     to the icon.
 */
GdkPaintable *
gtk_icon_info_load_symbolic_for_context_finish (GtkIconInfo   *icon_info,
                                                GAsyncResult  *result,
                                                gboolean      *was_symbolic,
                                                GError       **error)
{
  return gtk_icon_info_load_symbolic_finish (icon_info, result, was_symbolic, error);
}

/**
 * gtk_icon_theme_lookup_by_gicon:
 * @self: a #GtkIconTheme
 * @icon: the #GIcon to look up
 * @size: desired icon size
 * @flags: flags modifying the behavior of the icon lookup
 * 
 * Looks up an icon and returns a #GtkIconInfo containing information
 * such as the filename of the icon. The icon can then be rendered
 * into a pixbuf using gtk_icon_info_load_icon().
 *
 * When rendering on displays with high pixel densities you should not
 * use a @size multiplied by the scaling factor returned by functions
 * like gdk_surface_get_scale_factor(). Instead, you should use
 * gtk_icon_theme_lookup_by_gicon_for_scale(), as the assets loaded
 * for a given scaling factor may be different.
 *
 * Returns: (nullable) (transfer full): a #GtkIconInfo containing
 *     information about the icon, or %NULL if the icon wasn’t
 *     found. Unref with g_object_unref()
 */
GtkIconInfo *
gtk_icon_theme_lookup_by_gicon (GtkIconTheme       *self,
                                GIcon              *icon,
                                gint                size,
                                GtkIconLookupFlags  flags)
{
  return gtk_icon_theme_lookup_by_gicon_for_scale (self, icon,
                                                   size, 1, flags);
}

static GtkIconInfo *
gtk_icon_info_new_for_file (GFile *file,
                            gint   size,
                            gint   scale)
{
  GtkIconInfo *info;

  info = icon_info_new (ICON_THEME_DIR_UNTHEMED, size, 1);
  info->loadable = G_LOADABLE_ICON (g_file_icon_new (file));
  info->is_resource = g_file_has_uri_scheme (file, "resource");

  if (info->is_resource)
    {
      gchar *uri;

      uri = g_file_get_uri (file);
      info->filename = g_strdup (uri + 11); /* resource:// */
      g_free (uri);
    }
  else
    {
      info->filename = g_file_get_path (file);
    }

  info->is_svg = suffix_from_name (info->filename) == ICON_SUFFIX_SVG;

 info->desired_size = size;
 info->desired_scale = scale;
 info->forced_size = FALSE;

 return info;
}

static GtkIconInfo *
gtk_icon_info_new_for_pixbuf (GtkIconTheme *icon_theme,
                              GdkPixbuf    *pixbuf)
{
  GtkIconInfo *info;

  info = icon_info_new (ICON_THEME_DIR_UNTHEMED, 0, 1);
  info->texture = gdk_texture_new_for_pixbuf (pixbuf);
  info->scale = 1.0;

  return info;
}

/**
 * gtk_icon_theme_lookup_by_gicon_for_scale:
 * @self: a #GtkIconTheme
 * @icon: the #GIcon to look up
 * @size: desired icon size
 * @scale: the desired scale
 * @flags: flags modifying the behavior of the icon lookup
 *
 * Looks up an icon and returns a #GtkIconInfo containing information
 * such as the filename of the icon. The icon can then be rendered into
 * a pixbuf using gtk_icon_info_load_icon().
 *
 * Returns: (nullable) (transfer full): a #GtkIconInfo containing
 *     information about the icon, or %NULL if the icon wasn’t
 *     found. Unref with g_object_unref()
 */
GtkIconInfo *
gtk_icon_theme_lookup_by_gicon_for_scale (GtkIconTheme       *self,
                                          GIcon              *icon,
                                          gint                size,
                                          gint                scale,
                                          GtkIconLookupFlags  flags)
{
  GtkIconInfo *info;

  g_return_val_if_fail (GTK_IS_ICON_THEME (self), NULL);
  g_return_val_if_fail (G_IS_ICON (icon), NULL);
  g_warn_if_fail ((flags & GTK_ICON_LOOKUP_GENERIC_FALLBACK) == 0);

  if (GDK_IS_PIXBUF (icon))
    {
      GdkPixbuf *pixbuf;

      pixbuf = GDK_PIXBUF (icon);

      if ((flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0)
        {
          gint width, height, max;
          gdouble pixbuf_scale;

          width = gdk_pixbuf_get_width (pixbuf);
          height = gdk_pixbuf_get_height (pixbuf);
          max = MAX (width, height);
          pixbuf_scale = (gdouble) size * scale / (gdouble) max;

           if (pixbuf_scale != 1.0)
             {
              GdkPixbuf *scaled;
              scaled = gdk_pixbuf_scale_simple (pixbuf,
                                                0.5 + width * pixbuf_scale,
                                                0.5 + height * pixbuf_scale,
                                                GDK_INTERP_BILINEAR);

              info = gtk_icon_info_new_for_pixbuf (self, scaled);
              g_object_unref (scaled);
             }
           else
             {
              info = gtk_icon_info_new_for_pixbuf (self, pixbuf);
             }
        }
      else
        {
          info = gtk_icon_info_new_for_pixbuf (self, pixbuf);
        }

      return info;
    }
  else if (G_IS_FILE_ICON (icon))
    {
      GFile *file = g_file_icon_get_file (G_FILE_ICON (icon));

      info = gtk_icon_info_new_for_file (file, size, scale);
      info->forced_size = (flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0;

      return info;
    }
  else if (G_IS_LOADABLE_ICON (icon))
    {
      info = icon_info_new (ICON_THEME_DIR_UNTHEMED, size, 1);
      info->loadable = G_LOADABLE_ICON (g_object_ref (icon));
      info->is_svg = FALSE;
      info->desired_size = size;
      info->desired_scale = scale;
      info->forced_size = (flags & GTK_ICON_LOOKUP_FORCE_SIZE) != 0;

      return info;
    }
  else if (G_IS_THEMED_ICON (icon))
    {
      const gchar **names;

      names = (const gchar **)g_themed_icon_get_names (G_THEMED_ICON (icon));
      info = gtk_icon_theme_choose_icon_for_scale (self, names, size, scale, flags);

      return info;
    }

  return NULL;
}