xemacs-beta / src / glyphs.c

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
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
/* Generic glyph/image implementation + display tables
   Copyright (C) 1994, 1995 Board of Trustees, University of Illinois
   Copyright (C) 1995 Tinker Systems
   Copyright (C) 1995, 1996, 2000, 2001, 2002, 2004, 2005 Ben Wing
   Copyright (C) 1995 Sun Microsystems
   Copyright (C) 1998, 1999, 2000 Andy Piper
   Copyright (C) 2007, 2010 Didier Verna

This file is part of XEmacs.

XEmacs is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any
later version.

XEmacs 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 General Public License
for more details.

You should have received a copy of the GNU General Public License
along with XEmacs; see the file COPYING.  If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.  */

/* Synched up with: Not in FSF. */

/* This file mostly written by Ben Wing, with some code by Chuck Thompson.
   Heavily modified / rewritten by Andy Piper.

   Earliest glyph support, Jamie Zawinski for 19.8?
   subwindow support added by Chuck Thompson
   additional XPM support added by Chuck Thompson
   initial X-Face support added by Stig
   Majorly rewritten/restructured by Ben Wing, including creation of
   glyph and image-instance objects, for 19.12/19.13
   GIF/JPEG/etc. support originally in this file -- see glyph-eimage.c
   Pointer/icon overhaul, more restructuring by Ben Wing for 19.14
   Many changes for color work and optimizations by Jareth Hein for 21.0
   Switch of GIF/JPEG/PNG to new EImage intermediate code by Jareth Hein for 21.0
   TIFF code by Jareth Hein for 21.0
   Generalization for ms-windows by Andy Piper for 21.0
   TODO:
   Convert images.el to C and stick it in here?
 */

#include <config.h>
#include "lisp.h"

#include "blocktype.h"
#include "buffer.h"
#include "chartab.h"
#include "device-impl.h"
#include "elhash.h"
#include "faces.h"
#include "frame-impl.h"
#include "glyphs.h"
#include "gui.h"
#include "insdel.h"
#include "fontcolor-impl.h"
#include "opaque.h"
#include "rangetab.h"
#include "redisplay.h"
#include "specifier.h"
#include "window.h"

#include "sysfile.h"

#if defined (HAVE_XPM) && !defined (HAVE_GTK)
#include <X11/xpm.h>
#endif

Lisp_Object Qimage_conversion_error;

Lisp_Object Qglyphp, Qcontrib_p, Qbaseline;
Lisp_Object Qbuffer_glyph_p, Qpointer_glyph_p, Qicon_glyph_p;
Lisp_Object Qnothing_image_instance_p, Qtext_image_instance_p;
Lisp_Object Qmono_pixmap_image_instance_p;
Lisp_Object Qcolor_pixmap_image_instance_p;
Lisp_Object Qpointer_image_instance_p;
Lisp_Object Qsubwindow_image_instance_p;
Lisp_Object Qwidget_image_instance_p;
Lisp_Object Qconst_glyph_variable;
Lisp_Object Qmono_pixmap, Qcolor_pixmap, Qsubwindow;
Lisp_Object Q_file, Q_face, Q_pixel_width, Q_pixel_height;
Lisp_Object Qformatted_string;
Lisp_Object Vcurrent_display_table;
Lisp_Object Vtruncation_glyph, Vcontinuation_glyph, Voctal_escape_glyph;
Lisp_Object Vcontrol_arrow_glyph, Vinvisible_text_glyph, Vhscroll_glyph;
Lisp_Object Vxemacs_logo;
Lisp_Object Vthe_nothing_vector;
Lisp_Object Vimage_instantiator_format_list;
Lisp_Object Vimage_instance_type_list;
Lisp_Object Vglyph_type_list;

int disable_animated_pixmaps;
static Lisp_Object Vimage_instance_hash_table_test;

DEFINE_IMAGE_INSTANTIATOR_FORMAT (nothing);
DEFINE_IMAGE_INSTANTIATOR_FORMAT (inherit);
DEFINE_IMAGE_INSTANTIATOR_FORMAT (string);
DEFINE_IMAGE_INSTANTIATOR_FORMAT (formatted_string);
DEFINE_IMAGE_INSTANTIATOR_FORMAT (subwindow);
DEFINE_IMAGE_INSTANTIATOR_FORMAT (text);
DEFINE_IMAGE_INSTANTIATOR_FORMAT (pointer);

#ifdef HAVE_WINDOW_SYSTEM
DEFINE_IMAGE_INSTANTIATOR_FORMAT (xbm);
Lisp_Object Qxbm;

Lisp_Object Q_mask_file, Q_mask_data, Q_hotspot_x, Q_hotspot_y;
Lisp_Object Q_foreground, Q_background;
#ifndef BitmapSuccess
#define BitmapSuccess           0
#define BitmapOpenFailed        1
#define BitmapFileInvalid       2
#define BitmapNoMemory          3
#endif
#endif

#ifdef HAVE_XFACE
DEFINE_IMAGE_INSTANTIATOR_FORMAT (xface);
Lisp_Object Qxface;
#endif

#ifdef HAVE_XPM
DEFINE_IMAGE_INSTANTIATOR_FORMAT (xpm);
Lisp_Object Qxpm;
Lisp_Object Q_color_symbols;
#endif

typedef struct image_instantiator_format_entry image_instantiator_format_entry;
struct image_instantiator_format_entry
{
  Lisp_Object symbol;
  Lisp_Object device;
  struct image_instantiator_methods *meths;
};

typedef struct
{
  Dynarr_declare (struct image_instantiator_format_entry);
} image_instantiator_format_entry_dynarr;

/* This contains one entry per format, per device it's defined on. */
image_instantiator_format_entry_dynarr *
  the_image_instantiator_format_entry_dynarr;

static Lisp_Object allocate_image_instance (Lisp_Object governing_domain,
					    Lisp_Object parent,
					    Lisp_Object instantiator);
static void image_validate (Lisp_Object instantiator);
static void glyph_property_was_changed (Lisp_Object glyph,
					Lisp_Object property,
					Lisp_Object locale);
static void set_image_instance_dirty_p (Lisp_Object instance, int dirty);
static void register_ignored_expose (struct frame* f, int x, int y, int width, int height);
static void cache_subwindow_instance_in_frame_maybe (Lisp_Object instance);
static void update_image_instance (Lisp_Object image_instance,
				   Lisp_Object instantiator);
/* Unfortunately windows and X are different. In windows BeginPaint()
   will prevent WM_PAINT messages being generated so it is unnecessary
   to register exposures as they will not occur. Under X they will
   always occur. */
int hold_ignored_expose_registration;

EXFUN (Fimage_instance_type, 1);
EXFUN (Fglyph_type, 1);
EXFUN (Fnext_window, 4);


/****************************************************************************
 *                          Image Instantiators                             *
 ****************************************************************************/

struct image_instantiator_methods *
decode_device_ii_format (Lisp_Object device, Lisp_Object format,
			 Error_Behavior errb)
{
  int i;

  if (!SYMBOLP (format))
    {
      if (ERRB_EQ (errb, ERROR_ME))
	CHECK_SYMBOL (format);
      return 0;
    }

  for (i = 0; i < Dynarr_length (the_image_instantiator_format_entry_dynarr);
       i++)
    {
      if ( EQ (format,
	       Dynarr_at (the_image_instantiator_format_entry_dynarr, i).
	       symbol) )
	{
	  Lisp_Object d = Dynarr_at (the_image_instantiator_format_entry_dynarr, i).
	    device;
	  if ((NILP (d) && NILP (device))
	      ||
	      (!NILP (device) &&
	       EQ (CONSOLE_TYPE (XCONSOLE
				 (DEVICE_CONSOLE (XDEVICE (device)))), d)))
	    return Dynarr_at (the_image_instantiator_format_entry_dynarr, i).meths;
	}
    }

  maybe_invalid_argument ("Invalid image-instantiator format", format,
			  Qimage, errb);

  return 0;
}

struct image_instantiator_methods *
decode_image_instantiator_format (Lisp_Object format, Error_Behavior errb)
{
  return decode_device_ii_format (Qnil, format, errb);
}

static int
valid_image_instantiator_format_p (Lisp_Object format, Lisp_Object locale)
{
  int i;
  struct image_instantiator_methods* meths =
    decode_image_instantiator_format (format, ERROR_ME_NOT);
  Lisp_Object contype = Qnil;
  /* mess with the locale */
  if (!NILP (locale) && SYMBOLP (locale))
    contype = locale;
  else
    {
      struct console* console = decode_console (locale);
      contype = console ? CONSOLE_TYPE (console) : locale;
    }
  /* nothing is valid in all locales */
  if (EQ (format, Qnothing))
    return 1;
  /* reject unknown formats */
  else if (NILP (contype) || !meths)
    return 0;

  for (i = 0; i < Dynarr_length (meths->consoles); i++)
    if (EQ (contype, Dynarr_at (meths->consoles, i).symbol))
      return 1;
  return 0;
}

DEFUN ("valid-image-instantiator-format-p", Fvalid_image_instantiator_format_p,
       1, 2, 0, /*
Given an IMAGE-INSTANTIATOR-FORMAT, return non-nil if it is valid.
If LOCALE is non-nil then the format is checked in that locale.
If LOCALE is nil the current console is used.

Valid formats are some subset of `nothing', `string', `formatted-string',
`xpm', `xbm', `xface', `gif', `jpeg', `png', `tiff', `cursor-font', `font',
`autodetect', `subwindow', `inherit', `mswindows-resource', `bmp',
`native-layout', `layout', `label', `tab-control', `tree-view',
`progress-gauge', `scrollbar', `combo-box', `edit-field', `button',
`widget', `pointer', and `text', depending on how XEmacs was compiled.
*/
       (image_instantiator_format, locale))
{
  return valid_image_instantiator_format_p (image_instantiator_format,
					    locale) ?
    Qt : Qnil;
}

DEFUN ("image-instantiator-format-list", Fimage_instantiator_format_list,
       0, 0, 0, /*
Return a list of valid image-instantiator formats.
*/
       ())
{
  return Fcopy_sequence (Vimage_instantiator_format_list);
}

void
add_entry_to_device_ii_format_list (Lisp_Object device, Lisp_Object symbol,
				    struct image_instantiator_methods *meths)
{
  struct image_instantiator_format_entry entry;

  entry.symbol = symbol;
  entry.device = device;
  entry.meths = meths;
  Dynarr_add (the_image_instantiator_format_entry_dynarr, entry);
  if (NILP (memq_no_quit (symbol, Vimage_instantiator_format_list)))
    Vimage_instantiator_format_list =
      Fcons (symbol, Vimage_instantiator_format_list);
}

void
add_entry_to_image_instantiator_format_list (Lisp_Object symbol,
					     struct
					     image_instantiator_methods *meths)
{
  add_entry_to_device_ii_format_list (Qnil, symbol, meths);
}

static Lisp_Object *
get_image_conversion_list (Lisp_Object console_type)
{
  return &decode_console_type (console_type, ERROR_ME)->image_conversion_list;
}

DEFUN ("set-console-type-image-conversion-list", Fset_console_type_image_conversion_list,
       2, 2, 0, /*
Set the image-conversion-list for consoles of the given CONSOLE-TYPE.
The image-conversion-list specifies how image instantiators that
are strings should be interpreted.  Each element of the list should be
a list of two elements (a regular expression string and a vector) or
a list of three elements (the preceding two plus an integer index into
the vector).  The string is converted to the vector associated with the
first matching regular expression.  If a vector index is specified, the
string itself is substituted into that position in the vector.

Note: The conversion above is applied when the image instantiator is
added to an image specifier, not when the specifier is actually
instantiated.  Therefore, changing the image-conversion-list only affects
newly-added instantiators.  Existing instantiators in glyphs and image
specifiers will not be affected.
*/
       (console_type, list))
{
  Lisp_Object *imlist = get_image_conversion_list (console_type);

  /* Check the list to make sure that it only has valid entries. */

  EXTERNAL_LIST_LOOP_2 (mapping, list)
    {
      /* Mapping form should be (STRING VECTOR) or (STRING VECTOR INTEGER) */
      if (!CONSP (mapping) ||
	  !CONSP (XCDR (mapping)) ||
	  (!NILP (XCDR (XCDR (mapping))) &&
	   (!CONSP (XCDR (XCDR (mapping))) ||
	    !NILP (XCDR (XCDR (XCDR (mapping)))))))
	invalid_argument ("Invalid mapping form", mapping);
      else
	{
	  Lisp_Object regexp = XCAR (mapping);
	  Lisp_Object typevec = XCAR (XCDR (mapping));
	  Lisp_Object pos = Qnil;
	  Lisp_Object newvec;
	  struct gcpro gcpro1;

	  CHECK_STRING (regexp);
	  CHECK_VECTOR (typevec);
	  if (!NILP (XCDR (XCDR (mapping))))
	    {
	      pos = XCAR (XCDR (XCDR (mapping)));
	      CHECK_INT (pos);
	      if (XINT (pos) < 0 ||
		  XINT (pos) >= XVECTOR_LENGTH (typevec))
		args_out_of_range_3
		  (pos, Qzero, make_int (XVECTOR_LENGTH (typevec) - 1));
	    }

	  newvec = Fcopy_sequence (typevec);
	  if (INTP (pos))
	    XVECTOR_DATA (newvec)[XINT (pos)] = regexp;
	  GCPRO1 (newvec);
	  image_validate (newvec);
	  UNGCPRO;
	}
    }

  *imlist = Fcopy_tree (list, Qt);
  return list;
}

DEFUN ("console-type-image-conversion-list", Fconsole_type_image_conversion_list,
       1, 1, 0, /*
Return the image-conversion-list for devices of the given CONSOLE-TYPE.
The image-conversion-list specifies how to interpret image string
instantiators for the specified console type.  See
`set-console-type-image-conversion-list' for a description of its syntax.
*/
       (console_type))
{
  return Fcopy_tree (*get_image_conversion_list (console_type), Qt);
}

/* Process a string instantiator according to the image-conversion-list for
   CONSOLE_TYPE.  Returns a vector. */

static Lisp_Object
process_image_string_instantiator (Lisp_Object data,
				   Lisp_Object console_type,
				   int dest_mask)
{
  Lisp_Object tail;

  LIST_LOOP (tail, *get_image_conversion_list (console_type))
    {
      Lisp_Object mapping = XCAR (tail);
      Lisp_Object regexp = XCAR (mapping);
      Lisp_Object typevec = XCAR (XCDR (mapping));

      /* if the result is of a type that can't be instantiated
	 (e.g. a string when we're dealing with a pointer glyph),
	 skip it. */
      if (!(dest_mask &
	    IIFORMAT_METH (decode_image_instantiator_format
			   (INSTANTIATOR_TYPE (typevec), ERROR_ME),
			   possible_dest_types, ())))
	continue;
      if (fast_string_match (regexp, 0, data, 0, -1, 0, ERROR_ME, 0) >= 0)
	{
	  if (!NILP (XCDR (XCDR (mapping))))
	    {
	      int pos = XINT (XCAR (XCDR (XCDR (mapping))));
	      Lisp_Object newvec = Fcopy_sequence (typevec);
	      XVECTOR_DATA (newvec)[pos] = data;
	      return newvec;
	    }
	  else
	    return typevec;
	}
    }

  /* Oh well. */
  invalid_argument ("Unable to interpret glyph instantiator",
		       data);

  RETURN_NOT_REACHED (Qnil);
}

Lisp_Object
find_keyword_in_vector_or_given (Lisp_Object vector, Lisp_Object keyword,
				 Lisp_Object default_)
{
  Lisp_Object *elt;
  int instantiator_len;

  elt = XVECTOR_DATA (vector);
  instantiator_len = XVECTOR_LENGTH (vector);

  elt++;
  instantiator_len--;

  while (instantiator_len > 0)
    {
      if (EQ (elt[0], keyword))
	return elt[1];
      elt += 2;
      instantiator_len -= 2;
    }

  return default_;
}

Lisp_Object
find_keyword_in_vector (Lisp_Object vector, Lisp_Object keyword)
{
  return find_keyword_in_vector_or_given (vector, keyword, Qnil);
}

static Lisp_Object
find_instantiator_differences (Lisp_Object new_, Lisp_Object old)
{
  Lisp_Object alist = Qnil;
  Lisp_Object *elt = XVECTOR_DATA (new_);
  Lisp_Object *old_elt = XVECTOR_DATA (old);
  int len = XVECTOR_LENGTH (new_);
  struct gcpro gcpro1;

  /* If the vector length has changed then consider everything
     changed. We could try and figure out what properties have
     disappeared or been added, but this code is only used as an
     optimization anyway so lets not bother. */
  if (len != XVECTOR_LENGTH (old))
    return new_;

  GCPRO1 (alist);

  for (len -= 2; len >= 1; len -= 2)
    {
      /* Keyword comparisons can be done with eq, the value must be
	 done with equal.
	 #### Note that this does not optimize re-ordering. */
      if (!EQ (elt[len], old_elt[len])
	  || !internal_equal (elt[len+1], old_elt[len+1], 0))
	alist = Fcons (Fcons (elt[len], elt[len+1]), alist);
     }

  {
    Lisp_Object result = alist_to_tagged_vector (elt[0], alist);
    free_alist (alist);
    RETURN_UNGCPRO (result);
  }
}

DEFUN ("set-instantiator-property", Fset_instantiator_property,
       3, 3, 0, /*
Destructively set the property KEYWORD of INSTANTIATOR to VALUE.
If the property is not set then it is added to a copy of the
instantiator and the new instantiator returned.
Use `set-glyph-image' on glyphs to register instantiator changes.  */
       (instantiator, keyword, value))
{
  Lisp_Object *elt;
  int len;

  CHECK_VECTOR (instantiator);
  if (!KEYWORDP (keyword))
    invalid_argument ("instantiator property must be a keyword", keyword);

  elt = XVECTOR_DATA (instantiator);
  len = XVECTOR_LENGTH (instantiator);

  for (len -= 2; len >= 1; len -= 2)
    {
      if (EQ (elt[len], keyword))
	{
	  elt[len+1] = value;
	  break;
	}
    }

  /* Didn't find it so add it. */
  if (len < 1)
  {
    Lisp_Object alist = Qnil, result;
    struct gcpro gcpro1;

    GCPRO1 (alist);
    alist = tagged_vector_to_alist (instantiator);
    alist = Fcons (Fcons (keyword, value), alist);
    result = alist_to_tagged_vector (elt[0], alist);
    free_alist (alist);
    RETURN_UNGCPRO (result);
  }

  return instantiator;
}

void
check_valid_string (Lisp_Object data)
{
  CHECK_STRING (data);
}

void
check_valid_vector (Lisp_Object data)
{
  CHECK_VECTOR (data);
}

void
check_valid_face (Lisp_Object data)
{
  Fget_face (data);
}

void
check_valid_int (Lisp_Object data)
{
  CHECK_INT (data);
}

void
file_or_data_must_be_present (Lisp_Object instantiator)
{
  if (NILP (find_keyword_in_vector (instantiator, Q_file)) &&
      NILP (find_keyword_in_vector (instantiator, Q_data)))
    sferror ("Must supply either :file or :data",
			 instantiator);
}

void
data_must_be_present (Lisp_Object instantiator)
{
  if (NILP (find_keyword_in_vector (instantiator, Q_data)))
    sferror ("Must supply :data", instantiator);
}

static void
face_must_be_present (Lisp_Object instantiator)
{
  if (NILP (find_keyword_in_vector (instantiator, Q_face)))
    sferror ("Must supply :face", instantiator);
}

/* utility function useful in retrieving data from a file. */

Lisp_Object
make_string_from_file (Lisp_Object file)
{
  /* This function can call lisp */
  int count = specpdl_depth ();
  Lisp_Object temp_buffer;
  struct gcpro gcpro1;
  Lisp_Object data;

  specbind (Qinhibit_quit, Qt);
  record_unwind_protect (Fset_buffer, Fcurrent_buffer ());
  temp_buffer = Fget_buffer_create (build_ascstring (" *pixmap conversion*"));
  GCPRO1 (temp_buffer);
  set_buffer_internal (XBUFFER (temp_buffer));
  Ferase_buffer (Qnil);
  specbind (intern ("format-alist"), Qnil);
  Finsert_file_contents_internal (file, Qnil, Qnil, Qnil, Qnil, Qnil, Qnil);
  data = Fbuffer_substring (Qnil, Qnil, Qnil);
  unbind_to (count);
  UNGCPRO;
  return data;
}

/* The following two functions are provided to make it easier for
   the normalize methods to work with keyword-value vectors.
   Hash tables are kind of heavyweight for this purpose.
   (If vectors were resizable, we could avoid this problem;
   but they're not.) An alternative approach that might be
   more efficient but require more work is to use a type of
   assoc-Dynarr and provide primitives for deleting elements out
   of it. (However, you'd also have to add an unwind-protect
   to make sure the Dynarr got freed in case of an error in
   the normalization process.) */

Lisp_Object
tagged_vector_to_alist (Lisp_Object vector)
{
  Lisp_Object *elt = XVECTOR_DATA (vector);
  int len = XVECTOR_LENGTH (vector);
  Lisp_Object result = Qnil;

  assert (len & 1);
  for (len -= 2; len >= 1; len -= 2)
    result = Fcons (Fcons (elt[len], elt[len+1]), result);

  return result;
}

Lisp_Object
alist_to_tagged_vector (Lisp_Object tag, Lisp_Object alist)
{
  int len = 1 + 2 * XINT (Flength (alist));
  Lisp_Object *elt = alloca_array (Lisp_Object, len);
  int i;
  Lisp_Object rest;

  i = 0;
  elt[i++] = tag;
  LIST_LOOP (rest, alist)
    {
      Lisp_Object pair = XCAR (rest);
      elt[i] = XCAR (pair);
      elt[i+1] = XCDR (pair);
      i += 2;
    }

  return Fvector (len, elt);
}

#ifdef ERROR_CHECK_GLYPHS
static int
check_instance_cache_mapper (Lisp_Object UNUSED (key), Lisp_Object value,
			     void *flag_closure)
{
  /* This function can GC */
  /* value can be nil; we cache failures as well as successes */
  if (!NILP (value))
    {
      Lisp_Object window;
      window = GET_LISP_FROM_VOID (flag_closure);
      assert (EQ (XIMAGE_INSTANCE_DOMAIN (value), window));
    }

  return 0;
}

void
check_window_subwindow_cache (struct window* w)
{
  Lisp_Object window = wrap_window (w);


  assert (!NILP (w->subwindow_instance_cache));
  elisp_maphash (check_instance_cache_mapper,
		 w->subwindow_instance_cache,
		 STORE_LISP_IN_VOID (window));
}

void
check_image_instance_structure (Lisp_Object instance)
{
  /* Weird nothing images exist at startup when the console is
     deleted. */
  if (!NOTHING_IMAGE_INSTANCEP (instance))
    {
      assert (DOMAIN_LIVE_P (instance));
      assert (VECTORP (XIMAGE_INSTANCE_INSTANTIATOR (instance)));
    }
  if (WINDOWP (XIMAGE_INSTANCE_DOMAIN (instance)))
    check_window_subwindow_cache
      (XWINDOW (XIMAGE_INSTANCE_DOMAIN (instance)));
}
#endif

/* Determine what kind of domain governs the image instance.
   Verify that the given domain is at least as specific, and extract
   the governing domain from it. */
static Lisp_Object
get_image_instantiator_governing_domain (Lisp_Object instantiator,
					 Lisp_Object domain)
{
  int governing_domain;

  struct image_instantiator_methods *meths =
    decode_image_instantiator_format (INSTANTIATOR_TYPE (instantiator),
				      ERROR_ME);
  governing_domain = IIFORMAT_METH_OR_GIVEN (meths, governing_domain, (),
					     GOVERNING_DOMAIN_DEVICE);

  if (governing_domain == GOVERNING_DOMAIN_WINDOW
      && NILP (DOMAIN_WINDOW (domain)))
    invalid_argument_2
      ("Domain for this instantiator must be resolvable to a window",
       instantiator, domain);
  else if (governing_domain == GOVERNING_DOMAIN_FRAME
	   && NILP (DOMAIN_FRAME (domain)))
    invalid_argument_2
      ("Domain for this instantiator must be resolvable to a frame",
       instantiator, domain);

  if (governing_domain == GOVERNING_DOMAIN_WINDOW)
    domain = DOMAIN_WINDOW (domain);
  else if (governing_domain == GOVERNING_DOMAIN_FRAME)
    domain = DOMAIN_FRAME (domain);
  else if (governing_domain == GOVERNING_DOMAIN_DEVICE)
    domain = DOMAIN_DEVICE (domain);
  else
    ABORT ();

  return domain;
}

Lisp_Object
normalize_image_instantiator (Lisp_Object instantiator,
			      Lisp_Object contype,
			      Lisp_Object dest_mask)
{
  if (IMAGE_INSTANCEP (instantiator))
    return instantiator;

  if (STRINGP (instantiator))
    instantiator = process_image_string_instantiator (instantiator, contype,
						      XINT (dest_mask));
  /* Subsequent validation will pick this up. */
  if (!VECTORP (instantiator))
    return instantiator;
  /* We have to always store the actual pixmap data and not the
     filename even though this is a potential memory pig.  We have to
     do this because it is quite possible that we will need to
     instantiate a new instance of the pixmap and the file will no
     longer exist (e.g. w3 pixmaps are almost always from temporary
     files). */
  {
    struct gcpro gcpro1;
    struct image_instantiator_methods *meths;

    GCPRO1 (instantiator);

    meths = decode_image_instantiator_format (INSTANTIATOR_TYPE (instantiator),
					      ERROR_ME);
    RETURN_UNGCPRO (IIFORMAT_METH_OR_GIVEN (meths, normalize,
					    (instantiator, contype, dest_mask),
					    instantiator));
  }
}

static Lisp_Object
instantiate_image_instantiator (Lisp_Object governing_domain,
				Lisp_Object domain,
				Lisp_Object instantiator,
				Lisp_Object pointer_fg, Lisp_Object pointer_bg,
				int dest_mask, Lisp_Object glyph)
{
  Lisp_Object ii = allocate_image_instance (governing_domain,
					    IMAGE_INSTANCEP (domain) ?
					    domain : glyph, instantiator);
  Lisp_Image_Instance* p = XIMAGE_INSTANCE (ii);
  struct image_instantiator_methods *meths, *device_meths;
  struct gcpro gcpro1;

  GCPRO1 (ii);
  if (!valid_image_instantiator_format_p (INSTANTIATOR_TYPE (instantiator),
					  DOMAIN_DEVICE (governing_domain)))
    invalid_argument
      ("Image instantiator format is invalid in this locale.",
       instantiator);

  meths = decode_image_instantiator_format (INSTANTIATOR_TYPE (instantiator),
					    ERROR_ME);
  MAYBE_IIFORMAT_METH (meths, instantiate, (ii, instantiator, pointer_fg,
					    pointer_bg, dest_mask, domain));

  /* Now do device specific instantiation. */
  device_meths = decode_device_ii_format (DOMAIN_DEVICE (governing_domain),
					  INSTANTIATOR_TYPE (instantiator),
					  ERROR_ME_NOT);

  if (!HAS_IIFORMAT_METH_P (meths, instantiate)
      && (!device_meths || !HAS_IIFORMAT_METH_P (device_meths, instantiate)))
    invalid_argument
      ("Don't know how to instantiate this image instantiator?",
       instantiator);

  /* In general native window system methods will require sane
     geometry values, thus the instance needs to have been laid-out
     before they get called. */
  image_instance_layout (ii, XIMAGE_INSTANCE_WIDTH (ii),
			 XIMAGE_INSTANCE_HEIGHT (ii),
			 IMAGE_UNCHANGED_GEOMETRY,
			 IMAGE_UNCHANGED_GEOMETRY, domain);

  MAYBE_IIFORMAT_METH (device_meths, instantiate, (ii, instantiator, pointer_fg,
						   pointer_bg, dest_mask, domain));
  /* Do post instantiation. */
  MAYBE_IIFORMAT_METH (meths, post_instantiate, (ii, instantiator, domain));
  MAYBE_IIFORMAT_METH (device_meths, post_instantiate, (ii, instantiator, domain));

  /* We're done. */
  IMAGE_INSTANCE_INITIALIZED (p) = 1;
  /* Now that we're done verify that we really are laid out. */
  if (IMAGE_INSTANCE_LAYOUT_CHANGED (p))
    image_instance_layout (ii, XIMAGE_INSTANCE_WIDTH (ii),
			   XIMAGE_INSTANCE_HEIGHT (ii),
			   IMAGE_UNCHANGED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY, domain);

  /* We *must* have a clean image at this point. */
  IMAGE_INSTANCE_TEXT_CHANGED (p) = 0;
  IMAGE_INSTANCE_SIZE_CHANGED (p) = 0;
  IMAGE_INSTANCE_LAYOUT_CHANGED (p) = 0;
  IMAGE_INSTANCE_DIRTYP (p) = 0;

  assert ( XIMAGE_INSTANCE_HEIGHT (ii) >= 0
	   && XIMAGE_INSTANCE_WIDTH (ii) >= 0 );

  ERROR_CHECK_IMAGE_INSTANCE (ii);

  RETURN_UNGCPRO (ii);
}


/****************************************************************************
 *                          Image-Instance Object                           *
 ****************************************************************************/

Lisp_Object Qimage_instancep;

/* %%#### KKCC: Don't yet handle the equivalent of setting the device field
   of image instances w/dead devices to nil. */

static const struct memory_description text_image_instance_description_1 [] = {
  { XD_LISP_OBJECT, offsetof (struct text_image_instance, string) },
  { XD_END }
};

static const struct sized_memory_description text_image_instance_description = {
  sizeof (struct text_image_instance), text_image_instance_description_1
};

static const struct memory_description pixmap_image_instance_description_1 [] = {
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, hotspot_x) },
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, hotspot_x) },
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, filename) },
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, mask_filename) },
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, fg) },
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, bg) },
  { XD_LISP_OBJECT, offsetof (struct pixmap_image_instance, auxdata) },
  { XD_END }
};

static const struct sized_memory_description pixmap_image_instance_description = {
  sizeof (struct pixmap_image_instance), pixmap_image_instance_description_1
};

static const struct memory_description subwindow_image_instance_description_1 [] = {
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, face) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, type) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, props) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, items) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, pending_items) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, children) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, width) },
  { XD_LISP_OBJECT, offsetof (struct subwindow_image_instance, height) },
  { XD_END }
};

static const struct sized_memory_description subwindow_image_instance_description = {
  sizeof (struct subwindow_image_instance), subwindow_image_instance_description_1
};

static const struct memory_description image_instance_data_description_1 [] = {
  { XD_BLOCK_ARRAY, IMAGE_TEXT,
    1, { &text_image_instance_description } },
  { XD_BLOCK_ARRAY, IMAGE_MONO_PIXMAP,
    1, { &pixmap_image_instance_description } },
  { XD_BLOCK_ARRAY, IMAGE_COLOR_PIXMAP,
    1, { &pixmap_image_instance_description } },
  { XD_BLOCK_ARRAY, IMAGE_WIDGET,
    1, { &subwindow_image_instance_description } },
  { XD_END }
};

static const struct sized_memory_description image_instance_data_description = {
  0, image_instance_data_description_1
};

static const struct memory_description image_instance_description[] = {
  { XD_INT, offsetof (struct Lisp_Image_Instance, type) },
  { XD_LISP_OBJECT, offsetof (Lisp_Image_Instance, domain) },
  { XD_LISP_OBJECT, offsetof (Lisp_Image_Instance, device) },
  { XD_LISP_OBJECT, offsetof (Lisp_Image_Instance, name) },
  { XD_LISP_OBJECT, offsetof (Lisp_Image_Instance, parent) },
  { XD_LISP_OBJECT, offsetof (Lisp_Image_Instance, instantiator) },
  { XD_UNION, offsetof (struct Lisp_Image_Instance, u),
    XD_INDIRECT (0, 0), { &image_instance_data_description } },
  { XD_END }
};

static Lisp_Object
mark_image_instance (Lisp_Object obj)
{
  Lisp_Image_Instance *i = XIMAGE_INSTANCE (obj);

  /* #### I want to check the instance here, but there are way too
     many instances of the instance being marked while the domain is
     dead. For instance you can get marked through an event when using
     callback_ex.*/
#if 0
  ERROR_CHECK_IMAGE_INSTANCE (obj);
#endif

  mark_object (i->name);
  mark_object (i->instantiator);
  /* #### Is this legal in marking? We may get in the situation where the
     domain has been deleted - making the instance unusable. It seems
     better to remove the domain so that it can be finalized. */
  if (!DOMAIN_LIVE_P (i->domain))
    i->domain = Qnil;
  else
    mark_object (i->domain);

  /* We don't mark the glyph reference since that would create a
     circularity preventing GC. Ditto the instantiator. */
  switch (IMAGE_INSTANCE_TYPE (i))
    {
    case IMAGE_TEXT:
      mark_object (IMAGE_INSTANCE_TEXT_STRING (i));
      break;
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
      mark_object (IMAGE_INSTANCE_PIXMAP_FILENAME (i));
      mark_object (IMAGE_INSTANCE_PIXMAP_MASK_FILENAME (i));
      mark_object (IMAGE_INSTANCE_PIXMAP_HOTSPOT_X (i));
      mark_object (IMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (i));
      mark_object (IMAGE_INSTANCE_PIXMAP_FG (i));
      mark_object (IMAGE_INSTANCE_PIXMAP_BG (i));
      break;

    case IMAGE_WIDGET:
      mark_object (IMAGE_INSTANCE_WIDGET_TYPE (i));
      mark_object (IMAGE_INSTANCE_WIDGET_PROPS (i));
      mark_object (IMAGE_INSTANCE_SUBWINDOW_FACE (i));
      mark_object (IMAGE_INSTANCE_WIDGET_ITEMS (i));
      mark_object (IMAGE_INSTANCE_LAYOUT_CHILDREN (i));
      mark_object (IMAGE_INSTANCE_WIDGET_PENDING_ITEMS (i));
      mark_object (IMAGE_INSTANCE_WIDGET_HEIGHT_SUBR (i));
      mark_object (IMAGE_INSTANCE_WIDGET_WIDTH_SUBR (i));
    case IMAGE_SUBWINDOW:
      break;

    default:
      break;
    }

  /* The image may have been previously finalized (yes that's weird,
     see Fdelete_frame() and mark_window_as_deleted()), in which case
     the domain will be nil, so cope with this. */
  if (!NILP (IMAGE_INSTANCE_DEVICE (i)))
    MAYBE_DEVMETH (XDEVICE (IMAGE_INSTANCE_DEVICE (i)),
		   mark_image_instance, (i));

  return i->device;
}

static void
print_image_instance (Lisp_Object obj, Lisp_Object printcharfun,
		      int escapeflag)
{
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (obj);

  if (print_readably)
    printing_unreadable_lisp_object (obj, 0);
  write_fmt_string_lisp (printcharfun, "#<image-instance (%s) ", 1,
			 Fimage_instance_type (obj));
  if (!NILP (ii->name))
    write_fmt_string_lisp (printcharfun, "%S ", 1, ii->name);
  write_fmt_string_lisp (printcharfun, "on %s ", 1, ii->domain);
  switch (IMAGE_INSTANCE_TYPE (ii))
    {
    case IMAGE_NOTHING:
      break;

    case IMAGE_TEXT:
      print_internal (IMAGE_INSTANCE_TEXT_STRING (ii), printcharfun, 1);
      break;

    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      if (STRINGP (IMAGE_INSTANCE_PIXMAP_FILENAME (ii)))
	{
	  Ibyte *s;
	  Lisp_Object filename = IMAGE_INSTANCE_PIXMAP_FILENAME (ii);
	  s = qxestrrchr (XSTRING_DATA (filename), '/');
	  if (s)
	    print_internal (build_istring (s + 1), printcharfun, 1);
	  else
	    print_internal (filename, printcharfun, 1);
	}
      if (IMAGE_INSTANCE_PIXMAP_DEPTH (ii) > 1)
	write_fmt_string (printcharfun, " %dx%dx%d",
			  IMAGE_INSTANCE_PIXMAP_WIDTH (ii),
			  IMAGE_INSTANCE_PIXMAP_HEIGHT (ii),
			  IMAGE_INSTANCE_PIXMAP_DEPTH (ii));
      else
	write_fmt_string (printcharfun, " %dx%d",
			  IMAGE_INSTANCE_PIXMAP_WIDTH (ii),
			  IMAGE_INSTANCE_PIXMAP_HEIGHT (ii));
      if (!NILP (IMAGE_INSTANCE_PIXMAP_HOTSPOT_X (ii)) ||
	  !NILP (IMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (ii)))
	{
	  write_ascstring (printcharfun, " @");
	  if (!NILP (IMAGE_INSTANCE_PIXMAP_HOTSPOT_X (ii)))
	    write_fmt_string (printcharfun, "%ld",
			      XINT (IMAGE_INSTANCE_PIXMAP_HOTSPOT_X (ii)));
	  else
	    write_ascstring (printcharfun, "??");
	  write_ascstring (printcharfun, ",");
	  if (!NILP (IMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (ii)))
	    write_fmt_string (printcharfun, "%ld",
			      XINT (IMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (ii)));
	  else
	    write_ascstring (printcharfun, "??");
	}
      if (!NILP (IMAGE_INSTANCE_PIXMAP_FG (ii)) ||
	  !NILP (IMAGE_INSTANCE_PIXMAP_BG (ii)))
	{
	  write_ascstring (printcharfun, " (");
	  if (!NILP (IMAGE_INSTANCE_PIXMAP_FG (ii)))
	    {
	      print_internal
		(XCOLOR_INSTANCE
		 (IMAGE_INSTANCE_PIXMAP_FG (ii))->name, printcharfun, 0);
	    }
	  write_ascstring (printcharfun, "/");
	  if (!NILP (IMAGE_INSTANCE_PIXMAP_BG (ii)))
	    {
	      print_internal
		(XCOLOR_INSTANCE
		 (IMAGE_INSTANCE_PIXMAP_BG (ii))->name, printcharfun, 0);
	    }
	  write_ascstring (printcharfun, ")");
	}
      break;

    case IMAGE_WIDGET:
      print_internal (IMAGE_INSTANCE_WIDGET_TYPE (ii), printcharfun, 0);

      if (GUI_ITEMP (IMAGE_INSTANCE_WIDGET_ITEM (ii)))
	write_fmt_string_lisp (printcharfun, " %S", 1,
			       IMAGE_INSTANCE_WIDGET_TEXT (ii));

      if (!NILP (IMAGE_INSTANCE_WIDGET_FACE (ii)))
	write_fmt_string_lisp (printcharfun, " face=%s", 1,
			       IMAGE_INSTANCE_WIDGET_FACE (ii));
      /* fallthrough */

    case IMAGE_SUBWINDOW:
      write_fmt_string (printcharfun, " %dx%d", IMAGE_INSTANCE_WIDTH (ii),
			IMAGE_INSTANCE_HEIGHT (ii));

      /* This is stolen from frame.c.  Subwindows are strange in that they
	 are specific to a particular frame so we want to print in their
	 description what that frame is. */

      write_ascstring (printcharfun, " on #<");
      {
	struct frame* f  = XFRAME (IMAGE_INSTANCE_FRAME (ii));

	if (!FRAME_LIVE_P (f))
	  write_ascstring (printcharfun, "dead");
	else
	  write_ascstring (printcharfun,
			  DEVICE_TYPE_NAME (XDEVICE (FRAME_DEVICE (f))));
      }
      write_ascstring (printcharfun, "-frame>");
      write_fmt_string (printcharfun, " 0x%p",
			IMAGE_INSTANCE_SUBWINDOW_ID (ii));

      break;

    default:
      ABORT ();
    }

  MAYBE_DEVMETH (DOMAIN_XDEVICE (ii->domain), print_image_instance,
		 (ii, printcharfun, escapeflag));
  write_fmt_string (printcharfun, " 0x%x>", LISP_OBJECT_UID (obj));
}

static void
finalize_image_instance (Lisp_Object obj)
{
  Lisp_Image_Instance *i = XIMAGE_INSTANCE (obj);

  /* objects like this exist at dump time, so don't bomb out. */
  if (IMAGE_INSTANCE_TYPE (i) == IMAGE_NOTHING
      ||
      NILP (IMAGE_INSTANCE_DEVICE (i)))
    return;

  /* We can't use the domain here, because it might have
     disappeared. */
  MAYBE_DEVMETH (XDEVICE (IMAGE_INSTANCE_DEVICE (i)),
		 finalize_image_instance, (i));

  /* Make sure we don't try this twice. */
  IMAGE_INSTANCE_DEVICE (i) = Qnil;
}

static int
image_instance_equal (Lisp_Object obj1, Lisp_Object obj2, int depth,
		      int UNUSED (foldcase))
{
  Lisp_Image_Instance *i1 = XIMAGE_INSTANCE (obj1);
  Lisp_Image_Instance *i2 = XIMAGE_INSTANCE (obj2);

  ERROR_CHECK_IMAGE_INSTANCE (obj1);
  ERROR_CHECK_IMAGE_INSTANCE (obj2);

  if (!EQ (IMAGE_INSTANCE_DOMAIN (i1),
	   IMAGE_INSTANCE_DOMAIN (i2))
      || IMAGE_INSTANCE_TYPE (i1) != IMAGE_INSTANCE_TYPE (i2)
      || IMAGE_INSTANCE_WIDTH (i1) != IMAGE_INSTANCE_WIDTH (i2)
      || IMAGE_INSTANCE_MARGIN_WIDTH (i1) !=
      IMAGE_INSTANCE_MARGIN_WIDTH (i2)
      || IMAGE_INSTANCE_HEIGHT (i1) != IMAGE_INSTANCE_HEIGHT (i2)
      || IMAGE_INSTANCE_XOFFSET (i1) != IMAGE_INSTANCE_XOFFSET (i2)
      || IMAGE_INSTANCE_YOFFSET (i1) != IMAGE_INSTANCE_YOFFSET (i2))
    return 0;
  if (!internal_equal (IMAGE_INSTANCE_NAME (i1), IMAGE_INSTANCE_NAME (i2),
		       depth + 1))
    return 0;
  if (!internal_equal (IMAGE_INSTANCE_INSTANTIATOR (i1),
		       IMAGE_INSTANCE_INSTANTIATOR (i2),
		       depth + 1))
    return 0;

  switch (IMAGE_INSTANCE_TYPE (i1))
    {
    case IMAGE_NOTHING:
      break;

    case IMAGE_TEXT:
      if (!internal_equal (IMAGE_INSTANCE_TEXT_STRING (i1),
			   IMAGE_INSTANCE_TEXT_STRING (i2),
			   depth + 1))
	return 0;
      break;

    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      if (!(IMAGE_INSTANCE_PIXMAP_DEPTH (i1) ==
	    IMAGE_INSTANCE_PIXMAP_DEPTH (i2) &&
	    IMAGE_INSTANCE_PIXMAP_SLICE (i1) ==
	    IMAGE_INSTANCE_PIXMAP_SLICE (i2) &&
	    EQ (IMAGE_INSTANCE_PIXMAP_HOTSPOT_X (i1),
		IMAGE_INSTANCE_PIXMAP_HOTSPOT_X (i2)) &&
	    EQ (IMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (i1),
		IMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (i2)) &&
	    internal_equal (IMAGE_INSTANCE_PIXMAP_FILENAME (i1),
			    IMAGE_INSTANCE_PIXMAP_FILENAME (i2),
			    depth + 1) &&
	    internal_equal (IMAGE_INSTANCE_PIXMAP_MASK_FILENAME (i1),
			    IMAGE_INSTANCE_PIXMAP_MASK_FILENAME (i2),
			    depth + 1)))
	return 0;
      break;

    case IMAGE_WIDGET:
      if (!(EQ (IMAGE_INSTANCE_WIDGET_TYPE (i1),
		IMAGE_INSTANCE_WIDGET_TYPE (i2))
	    && IMAGE_INSTANCE_SUBWINDOW_ID (i1) ==
	    IMAGE_INSTANCE_SUBWINDOW_ID (i2)
	    &&
	    EQ (IMAGE_INSTANCE_WIDGET_FACE (i1),
		IMAGE_INSTANCE_WIDGET_TYPE (i2))
	    && internal_equal (IMAGE_INSTANCE_WIDGET_ITEMS (i1),
			       IMAGE_INSTANCE_WIDGET_ITEMS (i2),
			       depth + 1)
	    && internal_equal (IMAGE_INSTANCE_LAYOUT_CHILDREN (i1),
			       IMAGE_INSTANCE_LAYOUT_CHILDREN (i2),
			       depth + 1)
	    && internal_equal (IMAGE_INSTANCE_WIDGET_PROPS (i1),
			       IMAGE_INSTANCE_WIDGET_PROPS (i2),
			       depth + 1)
	    && internal_equal (IMAGE_INSTANCE_WIDGET_WIDTH_SUBR (i1),
			       IMAGE_INSTANCE_WIDGET_WIDTH_SUBR (i2),
			       depth + 1)
	    && internal_equal (IMAGE_INSTANCE_WIDGET_HEIGHT_SUBR (i1),
			       IMAGE_INSTANCE_WIDGET_HEIGHT_SUBR (i2),
			       depth + 1)
	    ))
	return 0;
      break;

    case IMAGE_SUBWINDOW:
      if (!(IMAGE_INSTANCE_SUBWINDOW_ID (i1) ==
	    IMAGE_INSTANCE_SUBWINDOW_ID (i2)))
	return 0;
      break;

    default:
      ABORT ();
    }

  return DEVMETH_OR_GIVEN (DOMAIN_XDEVICE (i1->domain),
			   image_instance_equal, (i1, i2, depth), 1);
}

/* Image instance domain manipulators. We can't error check in these
   otherwise we get into infinite recursion. */
Lisp_Object
image_instance_device (Lisp_Object instance)
{
  return XIMAGE_INSTANCE_DEVICE (instance);
}

Lisp_Object
image_instance_frame (Lisp_Object instance)
{
  return XIMAGE_INSTANCE_FRAME (instance);
}

Lisp_Object
image_instance_window (Lisp_Object instance)
{
  return DOMAIN_WINDOW (XIMAGE_INSTANCE_DOMAIN (instance));
}

int
image_instance_live_p (Lisp_Object instance)
{
  return DOMAIN_LIVE_P (XIMAGE_INSTANCE_DOMAIN (instance));
}

static Hashcode
image_instance_hash (Lisp_Object obj, int depth, Boolint UNUSED (equalp))
{
  Lisp_Image_Instance *i = XIMAGE_INSTANCE (obj);
  Hashcode hash = HASH5 (LISP_HASH (IMAGE_INSTANCE_DOMAIN (i)),
			  IMAGE_INSTANCE_WIDTH (i),
			  IMAGE_INSTANCE_MARGIN_WIDTH (i),
			  IMAGE_INSTANCE_HEIGHT (i),
			  internal_hash (IMAGE_INSTANCE_INSTANTIATOR (i),
					 depth + 1, 0));

  ERROR_CHECK_IMAGE_INSTANCE (obj);

  switch (IMAGE_INSTANCE_TYPE (i))
    {
    case IMAGE_NOTHING:
      break;

    case IMAGE_TEXT:
      hash = HASH2 (hash, internal_hash (IMAGE_INSTANCE_TEXT_STRING (i),
					 depth + 1, 0));
      break;

    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      hash = HASH4 (hash, IMAGE_INSTANCE_PIXMAP_DEPTH (i),
		    IMAGE_INSTANCE_PIXMAP_SLICE (i),
		    internal_hash (IMAGE_INSTANCE_PIXMAP_FILENAME (i),
				   depth + 1, 0));
      break;

    case IMAGE_WIDGET:
      /* We need the hash to be equivalent to what should be
	 displayed. */
      hash = HASH5 (hash,
		    LISP_HASH (IMAGE_INSTANCE_WIDGET_TYPE (i)),
		    internal_hash (IMAGE_INSTANCE_WIDGET_PROPS (i),
                                   depth + 1, 0),
		    internal_hash (IMAGE_INSTANCE_WIDGET_ITEMS (i),
                                   depth + 1, 0),
		    internal_hash (IMAGE_INSTANCE_LAYOUT_CHILDREN (i),
				   depth + 1, 0));
    case IMAGE_SUBWINDOW:
      hash = HASH2 (hash, (EMACS_INT) IMAGE_INSTANCE_SUBWINDOW_ID (i));
      break;

    default:
      ABORT ();
    }

  return HASH2 (hash, DEVMETH_OR_GIVEN
		(XDEVICE (image_instance_device (obj)),
		 image_instance_hash, (i, depth),
		 0));
}

DEFINE_NODUMP_LISP_OBJECT ("image-instance", image_instance,
			   mark_image_instance, print_image_instance,
			   finalize_image_instance, image_instance_equal,
			   image_instance_hash,
			   image_instance_description,
			   Lisp_Image_Instance);

static Lisp_Object
allocate_image_instance (Lisp_Object governing_domain, Lisp_Object parent,
			 Lisp_Object instantiator)
{
  Lisp_Object obj = ALLOC_NORMAL_LISP_OBJECT (image_instance);
  Lisp_Image_Instance *lp = XIMAGE_INSTANCE (obj);

  /* It's not possible to simply keep a record of the domain in which
     the instance was instantiated. This is because caching may mean
     that the domain becomes invalid but the instance remains
     valid. However, the only truly relevant domain is the domain in
     which the instance is cached since this is the one that will be
     common to the instances. */
  lp->domain = governing_domain;
  /* The cache domain is not quite sufficient since the domain can get
     deleted before the image instance does. We need to know the
     domain device in order to finalize the image instance
     properly. We therefore record the device also. */
  lp->device = DOMAIN_DEVICE (governing_domain);
  lp->type = IMAGE_NOTHING;
  lp->name = Qnil;
  lp->width = IMAGE_UNSPECIFIED_GEOMETRY;
  lp->height = IMAGE_UNSPECIFIED_GEOMETRY;
  lp->parent = parent;
  lp->instantiator = instantiator;
  /* So that layouts get done. */
  lp->layout_changed = 1;

  MARK_GLYPHS_CHANGED;

  return obj;
}

static enum image_instance_type
decode_image_instance_type (Lisp_Object type, Error_Behavior errb)
{
  if (ERRB_EQ (errb, ERROR_ME))
    CHECK_SYMBOL (type);

  if (EQ (type, Qnothing))      return IMAGE_NOTHING;
  if (EQ (type, Qtext))         return IMAGE_TEXT;
  if (EQ (type, Qmono_pixmap))  return IMAGE_MONO_PIXMAP;
  if (EQ (type, Qcolor_pixmap)) return IMAGE_COLOR_PIXMAP;
  if (EQ (type, Qpointer))      return IMAGE_POINTER;
  if (EQ (type, Qsubwindow))    return IMAGE_SUBWINDOW;
  if (EQ (type, Qwidget))    return IMAGE_WIDGET;

  maybe_invalid_constant ("Invalid image-instance type", type,
			     Qimage, errb);

  return IMAGE_UNKNOWN; /* not reached */
}

static Lisp_Object
encode_image_instance_type (enum image_instance_type type)
{
  switch (type)
    {
    case IMAGE_NOTHING:      return Qnothing;
    case IMAGE_TEXT:         return Qtext;
    case IMAGE_MONO_PIXMAP:  return Qmono_pixmap;
    case IMAGE_COLOR_PIXMAP: return Qcolor_pixmap;
    case IMAGE_POINTER:      return Qpointer;
    case IMAGE_SUBWINDOW:    return Qsubwindow;
    case IMAGE_WIDGET:    return Qwidget;
    default:
      ABORT ();
    }

  return Qnil; /* not reached */
}

static int
decode_image_instance_type_list (Lisp_Object list)
{
  int mask = 0;

  if (NILP (list))
    return ~0;

  if (!CONSP (list))
    {
      enum image_instance_type type =
	decode_image_instance_type (list, ERROR_ME);
      return image_instance_type_to_mask (type);
    }

  {
    EXTERNAL_LIST_LOOP_2 (elt, list)
      {
	enum image_instance_type type =
	  decode_image_instance_type (elt, ERROR_ME);
	mask |= image_instance_type_to_mask (type);
      }
  }

  return mask;
}

static Lisp_Object
encode_image_instance_type_list (int mask)
{
  int count = 0;
  Lisp_Object result = Qnil;

  while (mask)
    {
      count++;
      if (mask & 1)
	result = Fcons (encode_image_instance_type
			((enum image_instance_type) count), result);
      mask >>= 1;
    }

  return Fnreverse (result);
}

DOESNT_RETURN
incompatible_image_types (Lisp_Object instantiator, int given_dest_mask,
			  int desired_dest_mask)
{
  signal_error_1
    (Qinvalid_argument,
     list2
     (emacs_sprintf_string_lisp
      ("No compatible image-instance types given: wanted one of %s, got %s",
       Qnil, 2, encode_image_instance_type_list (desired_dest_mask),
       encode_image_instance_type_list (given_dest_mask)),
      instantiator));
}

static int
valid_image_instance_type_p (Lisp_Object type)
{
  return !NILP (memq_no_quit (type, Vimage_instance_type_list));
}

DEFUN ("valid-image-instance-type-p", Fvalid_image_instance_type_p, 1, 1, 0, /*
Given an IMAGE-INSTANCE-TYPE, return non-nil if it is valid.
Valid types are some subset of `nothing', `text', `mono-pixmap',
`color-pixmap', `pointer', `subwindow', and `widget', depending on how
XEmacs was compiled.
*/
       (image_instance_type))
{
  return valid_image_instance_type_p (image_instance_type) ? Qt : Qnil;
}

DEFUN ("image-instance-type-list", Fimage_instance_type_list, 0, 0, 0, /*
Return a list of valid image-instance types.
*/
       ())
{
  return Fcopy_sequence (Vimage_instance_type_list);
}

Error_Behavior
decode_error_behavior_flag (Lisp_Object noerror)
{
  if (NILP (noerror))        return ERROR_ME;
  else if (EQ (noerror, Qt)) return ERROR_ME_NOT;
  else if (EQ (noerror, Qdebug)) return ERROR_ME_DEBUG_WARN;
  else                       return ERROR_ME_WARN;
}

Lisp_Object
encode_error_behavior_flag (Error_Behavior errb)
{
  if (ERRB_EQ (errb, ERROR_ME))
    return Qnil;
  else if (ERRB_EQ (errb, ERROR_ME_NOT))
    return Qt;
  else if (ERRB_EQ (errb, ERROR_ME_DEBUG_WARN))
    return Qdebug;
  else
    {
      assert (ERRB_EQ (errb, ERROR_ME_WARN));
      return Qwarning;
    }
}

/* Recurse up the hierarchy looking for the topmost glyph. This means
   that instances in layouts will inherit face properties from their
   parent. */
Lisp_Object image_instance_parent_glyph (Lisp_Image_Instance* ii)
{
  if (IMAGE_INSTANCEP (IMAGE_INSTANCE_PARENT (ii)))
    {
      return image_instance_parent_glyph
	(XIMAGE_INSTANCE (IMAGE_INSTANCE_PARENT (ii)));
    }
  return IMAGE_INSTANCE_PARENT (ii);
}

static Lisp_Object
make_image_instance_1 (Lisp_Object data, Lisp_Object domain,
		       Lisp_Object dest_types)
{
  Lisp_Object ii;
  struct gcpro gcpro1;
  int dest_mask;
  Lisp_Object governing_domain;

  if (IMAGE_INSTANCEP (data))
    invalid_argument ("Image instances not allowed here", data);
  image_validate (data);
  domain = decode_domain (domain);
  /* instantiate_image_instantiator() will abort if given an
     image instance ... */
  dest_mask = decode_image_instance_type_list (dest_types);
  data = normalize_image_instantiator (data,
				       DEVICE_TYPE (DOMAIN_XDEVICE (domain)),
				       make_int (dest_mask));
  GCPRO1 (data);
  /* After normalizing the data, it's always either an image instance (which
     we filtered out above) or a vector. */
  if (EQ (INSTANTIATOR_TYPE (data), Qinherit))
    invalid_argument ("Inheritance not allowed here", data);
  governing_domain =
    get_image_instantiator_governing_domain (data, domain);
  ii = instantiate_image_instantiator (governing_domain, domain, data,
				       Qnil, Qnil, dest_mask, Qnil);
  RETURN_UNGCPRO (ii);
}

DEFUN ("make-image-instance", Fmake_image_instance, 1, 4, 0, /*
Return a new `image-instance' object.

Image-instance objects encapsulate the way a particular image (pixmap,
etc.) is displayed on a particular device.  In most circumstances, you
do not need to directly create image instances; use a glyph instead.
However, it may occasionally be useful to explicitly create image
instances, if you want more control over the instantiation process.

DATA is an image instantiator, which describes the image; see
`make-image-specifier' for a description of the allowed values.

DEST-TYPES should be a list of allowed image instance types that can
be generated.  The recognized image instance types are

`nothing'
  Nothing is displayed.
`text'
  Displayed as text.  The foreground and background colors and the
  font of the text are specified independent of the pixmap.  Typically
  these attributes will come from the face of the surrounding text,
  unless a face is specified for the glyph in which the image appears.
`mono-pixmap'
  Displayed as a mono pixmap (a pixmap with only two colors where the
  foreground and background can be specified independent of the pixmap;
  typically the pixmap assumes the foreground and background colors of
  the text around it, unless a face is specified for the glyph in which
  the image appears).
`color-pixmap'
  Displayed as a color pixmap.
`pointer'
  Used as the mouse pointer for a window.
`subwindow'
  A child window that is treated as an image.  This allows (e.g.)
  another program to be responsible for drawing into the window.
`widget'
  A child window that contains a window-system widget, e.g. a push
  button, text field, or slider.

The DEST-TYPES list is unordered.  If multiple destination types are
possible for a given instantiator, the "most natural" type for the
instantiator's format is chosen. (For XBM, the most natural types are
`mono-pixmap', followed by `color-pixmap', followed by `pointer'.  For
the other normal image formats, the most natural types are
`color-pixmap', followed by `mono-pixmap', followed by `pointer'.  For
the string and formatted-string formats, the most natural types are
`text', followed by `mono-pixmap' (not currently implemented),
followed by `color-pixmap' (not currently implemented).  For MS
Windows resources, the most natural type for pointer resources is
`pointer', and for the others it's `color-pixmap'.  The other formats
can only be instantiated as one type. (If you want to control more
specifically the order of the types into which an image is
instantiated, just call `make-image-instance' repeatedly until it
succeeds, passing less and less preferred destination types each
time.)

See `make-image-specifier' for a description of the different image
instantiator formats.

If DEST-TYPES is omitted, all possible types are allowed.

DOMAIN specifies the domain to which the image instance will be attached.
This domain is termed the \"governing domain\".  The type of the governing
domain depends on the image instantiator format. (Although, more correctly,
it should probably depend on the image instance type.) For example, pixmap
image instances are specific to a device, but widget image instances are
specific to a particular XEmacs window because in order to display such a
widget when two windows onto the same buffer want to display the widget,
two separate underlying widgets must be created. (That's because a widget
is actually a child window-system window, and all window-system windows have
a unique existence on the screen.) This means that the governing domain for
a pixmap image instance will be some device (most likely, the only existing
device), whereas the governing domain for a widget image instance will be
some XEmacs window.

If you specify an overly general DOMAIN (e.g. a frame when a window was
wanted), an error is signaled.  If you specify an overly specific DOMAIN
\(e.g. a window when a device was wanted), the corresponding general domain
is fetched and used instead.  For `make-image-instance', it makes no
difference whether you specify an overly specific domain or the properly
general domain derived from it.  However, it does matter when creating an
image instance by instantiating a specifier or glyph (e.g. with
`glyph-image-instance'), because the more specific domain causes spec lookup
to start there and proceed to more general domains. (It would also matter
when creating an image instance with an instantiator format of `inherit',
but we currently disallow this. #### We should fix this.)

If omitted, DOMAIN defaults to the selected window.

NOERROR controls what happens when the image cannot be generated.
If nil, an error message is generated.  If t, no messages are
generated and this function returns nil.  If anything else, a warning
message is generated and this function returns nil.
*/
       (data, domain, dest_types, noerror))
{
  Error_Behavior errb = decode_error_behavior_flag (noerror);

  return call_with_suspended_errors ((lisp_fn_t) make_image_instance_1,
				     Qnil, Qimage, errb,
				     3, data, domain, dest_types);
}

DEFUN ("image-instance-p", Fimage_instance_p, 1, 1, 0, /*
Return non-nil if OBJECT is an image instance.
*/
       (object))
{
  return IMAGE_INSTANCEP (object) ? Qt : Qnil;
}

DEFUN ("image-instance-type", Fimage_instance_type, 1, 1, 0, /*
Return the type of the given image instance.
The return value will be one of `nothing', `text', `mono-pixmap',
`color-pixmap', `pointer', `subwindow', or `widget'.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);
  return encode_image_instance_type (XIMAGE_INSTANCE_TYPE (image_instance));
}

DEFUN ("image-instance-name", Fimage_instance_name, 1, 1, 0, /*
Return the name of the given image instance.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  return XIMAGE_INSTANCE_NAME (image_instance);
}

DEFUN ("image-instance-instantiator", Fimage_instance_instantiator, 1, 1, 0, /*
Return the instantiator that was used to create the image instance.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  return XIMAGE_INSTANCE_INSTANTIATOR (image_instance);
}

DEFUN ("image-instance-domain", Fimage_instance_domain, 1, 1, 0, /*
Return the governing domain of the given image instance.
The governing domain of an image instance is the domain that the image
instance is specific to.  It is NOT necessarily the domain that was
given to the call to `specifier-instance' that resulted in the creation
of this image instance.  See `make-image-instance' for more information
on governing domains.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  return XIMAGE_INSTANCE_DOMAIN (image_instance);
}

DEFUN ("image-instance-string", Fimage_instance_string, 1, 1, 0, /*
Return the string of the given image instance.
This will only be non-nil for text image instances and widgets.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  if (XIMAGE_INSTANCE_TYPE (image_instance) == IMAGE_TEXT)
    return XIMAGE_INSTANCE_TEXT_STRING (image_instance);
  else if (XIMAGE_INSTANCE_TYPE (image_instance) == IMAGE_WIDGET)
    return XIMAGE_INSTANCE_WIDGET_TEXT (image_instance);
  else
    return Qnil;
}

DEFUN ("image-instance-property", Fimage_instance_property, 2, 2, 0, /*
Return the given property of the given image instance.
Returns nil if the property or the property method do not exist for
the image instance in the domain.
*/
       (image_instance, prop))
{
  Lisp_Image_Instance* ii;
  Lisp_Object type, ret;
  struct image_instantiator_methods* meths;

  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);
  CHECK_SYMBOL (prop);
  ii = XIMAGE_INSTANCE (image_instance);

  /* ... then try device specific methods ... */
  type = encode_image_instance_type (IMAGE_INSTANCE_TYPE (ii));
  meths = decode_device_ii_format (image_instance_device (image_instance),
				   type, ERROR_ME_NOT);
  if (meths && HAS_IIFORMAT_METH_P (meths, property)
      &&
      !UNBOUNDP (ret =  IIFORMAT_METH (meths, property, (image_instance, prop))))
    {
      return ret;
    }
  /* ... then format specific methods ... */
  meths = decode_device_ii_format (Qnil, type, ERROR_ME_NOT);
  if (meths && HAS_IIFORMAT_METH_P (meths, property)
      &&
      !UNBOUNDP (ret = IIFORMAT_METH (meths, property, (image_instance, prop))))
    {
      return ret;
    }
  /* ... then fail */
  return Qnil;
}

DEFUN ("image-instance-file-name", Fimage_instance_file_name, 1, 1, 0, /*
Return the file name from which IMAGE-INSTANCE was read, if known.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return XIMAGE_INSTANCE_PIXMAP_FILENAME (image_instance);

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-mask-file-name", Fimage_instance_mask_file_name, 1, 1, 0, /*
Return the file name from which IMAGE-INSTANCE's mask was read, if known.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return XIMAGE_INSTANCE_PIXMAP_MASK_FILENAME (image_instance);

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-depth", Fimage_instance_depth, 1, 1, 0, /*
Return the depth of the image instance.
This is 0 for a bitmap, or a positive integer for a pixmap.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return make_int (XIMAGE_INSTANCE_PIXMAP_DEPTH (image_instance));

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-height", Fimage_instance_height, 1, 1, 0, /*
Return the height of the image instance, in pixels.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
    case IMAGE_SUBWINDOW:
    case IMAGE_WIDGET:
      return make_int (XIMAGE_INSTANCE_HEIGHT (image_instance));

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-width", Fimage_instance_width, 1, 1, 0, /*
Return the width of the image instance, in pixels.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
    case IMAGE_SUBWINDOW:
    case IMAGE_WIDGET:
      return make_int (XIMAGE_INSTANCE_WIDTH (image_instance));

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-hotspot-x", Fimage_instance_hotspot_x, 1, 1, 0, /*
Return the X coordinate of the image instance's hotspot, if known.
This is a point relative to the origin of the pixmap.  When an image is
 used as a mouse pointer, the hotspot is the point on the image that sits
 over the location that the pointer points to.  This is, for example, the
 tip of the arrow or the center of the crosshairs.
This will always be nil for a non-pointer image instance.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return XIMAGE_INSTANCE_PIXMAP_HOTSPOT_X (image_instance);

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-hotspot-y", Fimage_instance_hotspot_y, 1, 1, 0, /*
Return the Y coordinate of the image instance's hotspot, if known.
This is a point relative to the origin of the pixmap.  When an image is
 used as a mouse pointer, the hotspot is the point on the image that sits
 over the location that the pointer points to.  This is, for example, the
 tip of the arrow or the center of the crosshairs.
This will always be nil for a non-pointer image instance.
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return XIMAGE_INSTANCE_PIXMAP_HOTSPOT_Y (image_instance);

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-foreground", Fimage_instance_foreground, 1, 1, 0, /*
Return the foreground color of IMAGE-INSTANCE, if applicable.
This will be a color instance or nil. (It will only be non-nil for
colorized mono pixmaps and for pointers.)
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return XIMAGE_INSTANCE_PIXMAP_FG (image_instance);

    case IMAGE_WIDGET:
      return FACE_FOREGROUND (
			      XIMAGE_INSTANCE_WIDGET_FACE (image_instance),
			      XIMAGE_INSTANCE_FRAME
			      (image_instance));

    default:
      return Qnil;
    }
}

DEFUN ("image-instance-background", Fimage_instance_background, 1, 1, 0, /*
Return the background color of IMAGE-INSTANCE, if applicable.
This will be a color instance or nil. (It will only be non-nil for
colorized mono pixmaps and for pointers.)
*/
       (image_instance))
{
  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  switch (XIMAGE_INSTANCE_TYPE (image_instance))
    {
    case IMAGE_MONO_PIXMAP:
    case IMAGE_COLOR_PIXMAP:
    case IMAGE_POINTER:
      return XIMAGE_INSTANCE_PIXMAP_BG (image_instance);

    case IMAGE_WIDGET:
      return FACE_BACKGROUND (
			      XIMAGE_INSTANCE_WIDGET_FACE (image_instance),
			      XIMAGE_INSTANCE_FRAME
			      (image_instance));

    default:
      return Qnil;
    }
}


DEFUN ("colorize-image-instance", Fcolorize_image_instance, 3, 3, 0, /*
Make the image instance be displayed in the given colors.
This function returns a new image instance that is exactly like the
specified one except that (if possible) the foreground and background
colors and as specified.  Currently, this only does anything if the image
instance is a mono pixmap; otherwise, the same image instance is returned.
*/
       (image_instance, foreground, background))
{
  Lisp_Object new_;
  Lisp_Object device;

  CHECK_IMAGE_INSTANCE (image_instance);
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);
  CHECK_COLOR_INSTANCE (foreground);
  CHECK_COLOR_INSTANCE (background);

  device = image_instance_device (image_instance);
  if (!HAS_DEVMETH_P (XDEVICE (device), colorize_image_instance))
    return image_instance;

  /* #### There should be a copy_image_instance(), which calls a
     device-specific method to copy the window-system subobject. */
  new_ = allocate_image_instance (XIMAGE_INSTANCE_DOMAIN (image_instance),
				 Qnil, Qnil);
  copy_lisp_object (new_, image_instance);
  /* note that if this method returns non-zero, this method MUST
     copy any window-system resources, so that when one image instance is
     freed, the other one is not hosed. */
  if (!DEVMETH (XDEVICE (device), colorize_image_instance, (new_, foreground,
							    background)))
    return image_instance;
  return new_;
}


/************************************************************************/
/*                              Geometry calculations                   */
/************************************************************************/

/* Find out desired geometry of the image instance. If there is no
   special function then just return the width and / or height. */
void
image_instance_query_geometry (Lisp_Object image_instance,
			       int* width, int* height,
			       enum image_instance_geometry disp,
			       Lisp_Object domain)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (image_instance);
  Lisp_Object type;
  struct image_instantiator_methods* meths;
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  type = encode_image_instance_type (IMAGE_INSTANCE_TYPE (ii));
  meths = decode_device_ii_format (Qnil, type, ERROR_ME_NOT);

  if (meths && HAS_IIFORMAT_METH_P (meths, query_geometry))
    {
      IIFORMAT_METH (meths, query_geometry, (image_instance, width, height,
					     disp, domain));
    }
  else
    {
      if (width)
	*width = IMAGE_INSTANCE_WIDTH (ii);
      if (height)
	*height = IMAGE_INSTANCE_HEIGHT (ii);
    }
}

/* Layout the image instance using the provided dimensions. Layout
   widgets are going to do different kinds of calculations to
   determine what size to give things so we could make the layout
   function relatively simple to take account of that. An alternative
   approach is to consider separately the two cases, one where you
   don't mind what size you have (normal widgets) and one where you
   want to specify something (layout widgets). */
void
image_instance_layout (Lisp_Object image_instance,
		       int width, int height,
		       int xoffset, int yoffset,
		       Lisp_Object domain)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (image_instance);
  Lisp_Object type;
  struct image_instantiator_methods* meths;

  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  /* Nothing is as nothing does. */
  if (NOTHING_IMAGE_INSTANCEP (image_instance))
    return;

  /* We don't want carefully calculated offsets to be mucked up by
     random layouts. */
  if (xoffset != IMAGE_UNCHANGED_GEOMETRY)
    XIMAGE_INSTANCE_XOFFSET (image_instance) = xoffset;
  if (yoffset != IMAGE_UNCHANGED_GEOMETRY)
    XIMAGE_INSTANCE_YOFFSET (image_instance) = yoffset;

  assert (XIMAGE_INSTANCE_YOFFSET (image_instance) >= 0
	  && XIMAGE_INSTANCE_XOFFSET (image_instance) >= 0);

  /* If geometry is unspecified then get some reasonable values for it. */
  if (width == IMAGE_UNSPECIFIED_GEOMETRY
      ||
      height == IMAGE_UNSPECIFIED_GEOMETRY)
    {
      int dwidth = IMAGE_UNSPECIFIED_GEOMETRY;
      int dheight = IMAGE_UNSPECIFIED_GEOMETRY;
      /* Get the desired geometry. */
      image_instance_query_geometry (image_instance,
				     &dwidth, &dheight,
				     IMAGE_DESIRED_GEOMETRY,
				     domain);
      /* Compare with allowed geometry. */
      if (width == IMAGE_UNSPECIFIED_GEOMETRY)
	width = dwidth;
      if (height == IMAGE_UNSPECIFIED_GEOMETRY)
	height = dheight;
    }

  /* If we don't have sane values then we cannot layout at this point and
     must just return. */
  if (width == IMAGE_UNSPECIFIED_GEOMETRY
      ||
      height == IMAGE_UNSPECIFIED_GEOMETRY)
      return;

  /* At this point width and height should contain sane values. Thus
     we set the glyph geometry and lay it out. */
  if (IMAGE_INSTANCE_WIDTH (ii) != width
      ||
      IMAGE_INSTANCE_HEIGHT (ii) != height)
    {
      IMAGE_INSTANCE_SIZE_CHANGED (ii) = 1;
    }

  IMAGE_INSTANCE_WIDTH (ii) = width;
  IMAGE_INSTANCE_HEIGHT (ii) = height;

  type = encode_image_instance_type (IMAGE_INSTANCE_TYPE (ii));
  meths = decode_device_ii_format (Qnil, type, ERROR_ME_NOT);

  MAYBE_IIFORMAT_METH (meths, layout,
		       (image_instance, width, height, xoffset, yoffset,
			domain));
  /* Do not clear the dirty flag here - redisplay will do this for
     us at the end. */
  IMAGE_INSTANCE_LAYOUT_CHANGED (ii) = 0;
}

/* Update an image instance from its changed instantiator. */
static void
update_image_instance (Lisp_Object image_instance,
		       Lisp_Object instantiator)
{
  struct image_instantiator_methods* meths;
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (image_instance);

  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  if (NOTHING_IMAGE_INSTANCEP (image_instance))
    return;

  assert (!internal_equal (IMAGE_INSTANCE_INSTANTIATOR (ii), instantiator, 0)
	  || (internal_equal (IMAGE_INSTANCE_INSTANTIATOR (ii), instantiator, 0)
	   && internal_equal (IMAGE_INSTANCE_INSTANTIATOR (ii), instantiator, -10)));

  /* If the instantiator is identical then do nothing. We must use
     equal here because the specifier code copies the instantiator. */
  if (!internal_equal (IMAGE_INSTANCE_INSTANTIATOR (ii), instantiator, 0))
    {
      /* Extract the changed properties so that device / format
	 methods only have to cope with these. We assume that
	 normalization has already been done. */
      Lisp_Object diffs = find_instantiator_differences
	(instantiator,
	 IMAGE_INSTANCE_INSTANTIATOR (ii));
      Lisp_Object type = encode_image_instance_type
	(IMAGE_INSTANCE_TYPE (ii));
      struct gcpro gcpro1;
      GCPRO1 (diffs);

      /* try device specific methods first ... */
      meths = decode_device_ii_format (image_instance_device (image_instance),
				       type, ERROR_ME_NOT);
      MAYBE_IIFORMAT_METH (meths, update, (image_instance, diffs));
      /* ... then format specific methods ... */
      meths = decode_device_ii_format (Qnil, type, ERROR_ME_NOT);
      MAYBE_IIFORMAT_METH (meths, update, (image_instance, diffs));

      /* Instance and therefore glyph has changed so mark as dirty.
	 If we don't do this output optimizations will assume the
	 glyph is unchanged. */
      set_image_instance_dirty_p (image_instance, 1);
      /* Structure has changed. */
      IMAGE_INSTANCE_LAYOUT_CHANGED (ii) = 1;

      UNGCPRO;
    }
  /* We should now have a consistent instantiator so keep a record of
     it. It is important that we don't actually update the window
     system widgets here - we must do that when redisplay tells us
     to.

     #### should we delay doing this until the display is up-to-date
     also? */
  IMAGE_INSTANCE_INSTANTIATOR (ii) = instantiator;
}

/*
 * Mark image instance in W as dirty if (a) W's faces have changed and
 * (b) GLYPH_OR_II instance in W is a string.
 *
 * Return non-zero if instance has been marked dirty.
 */
int
invalidate_glyph_geometry_maybe (Lisp_Object glyph_or_ii, struct window* w)
{
  if (XFRAME(WINDOW_FRAME(w))->faces_changed)
    {
      Lisp_Object image = glyph_or_ii;

      if (GLYPHP (glyph_or_ii))
	{
	  Lisp_Object window = wrap_window (w);

	  image = glyph_image_instance (glyph_or_ii, window,
					ERROR_ME_DEBUG_WARN, 1);
	}

      if (TEXT_IMAGE_INSTANCEP (image))
	{
	  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (image);
	  IMAGE_INSTANCE_DIRTYP (ii) = 1;
	  IMAGE_INSTANCE_LAYOUT_CHANGED (ii) = 1;
	  if (GLYPHP (glyph_or_ii))
	    XGLYPH_DIRTYP (glyph_or_ii) = 1;
	  return 1;
	}
    }

  return 0;
}


/************************************************************************/
/*                              error helpers                           */
/************************************************************************/
DOESNT_RETURN
signal_image_error (const Ascbyte *reason, Lisp_Object frob)
{
  signal_error (Qimage_conversion_error, reason, frob);
}

DOESNT_RETURN
signal_image_error_2 (const Ascbyte *reason, Lisp_Object frob0,
		      Lisp_Object frob1)
{
  signal_error_2 (Qimage_conversion_error, reason, frob0, frob1);
}

DOESNT_RETURN
signal_double_image_error (const Ascbyte *reason1, const Ascbyte *reason2,
			   Lisp_Object data)
{
  signal_error_1 (Qimage_conversion_error,
		list3 (build_msg_string (reason1),
		       build_msg_string (reason2),
		       data));
}

DOESNT_RETURN
signal_double_image_error_2 (const Ascbyte *reason1, const Ascbyte *reason2,
			     Lisp_Object data1, Lisp_Object data2)
{
  signal_error_1 (Qimage_conversion_error,
		list4 (build_msg_string (reason1),
		       build_msg_string (reason2),
		       data1, data2));
}

/****************************************************************************
 *                                  nothing                                 *
 ****************************************************************************/

static int
nothing_possible_dest_types (void)
{
  return IMAGE_NOTHING_MASK;
}

static void
nothing_instantiate (Lisp_Object image_instance, Lisp_Object instantiator,
		     Lisp_Object UNUSED (pointer_fg),
		     Lisp_Object UNUSED (pointer_bg),
		     int dest_mask, Lisp_Object UNUSED (domain))
{
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (image_instance);

  if (dest_mask & IMAGE_NOTHING_MASK)
    {
      IMAGE_INSTANCE_TYPE (ii) = IMAGE_NOTHING;
      IMAGE_INSTANCE_HEIGHT (ii) = 0;
      IMAGE_INSTANCE_WIDTH (ii) = 0;
    }
  else
    incompatible_image_types (instantiator, dest_mask, IMAGE_NOTHING_MASK);
}


/****************************************************************************
 *                                  inherit                                 *
 ****************************************************************************/

static void
inherit_validate (Lisp_Object instantiator)
{
  face_must_be_present (instantiator);
}

static Lisp_Object
inherit_normalize (Lisp_Object inst, Lisp_Object UNUSED (console_type),
		   Lisp_Object UNUSED (dest_mask))
{
  Lisp_Object face;

  assert (XVECTOR_LENGTH (inst) == 3);
  face = XVECTOR_DATA (inst)[2];
  if (!FACEP (face))
    inst = vector3 (Qinherit, Q_face, Fget_face (face));
  return inst;
}

static int
inherit_possible_dest_types (void)
{
  return IMAGE_MONO_PIXMAP_MASK;
}

static void
inherit_instantiate (Lisp_Object UNUSED (image_instance),
		     Lisp_Object UNUSED (instantiator),
		     Lisp_Object UNUSED (pointer_fg),
		     Lisp_Object UNUSED (pointer_bg),
		     int UNUSED (dest_mask), Lisp_Object UNUSED (domain))
{
  /* handled specially in image_instantiate */
  ABORT ();
}


/****************************************************************************
 *                                  string                                  *
 ****************************************************************************/

static void
string_validate (Lisp_Object instantiator)
{
  data_must_be_present (instantiator);
}

static int
string_possible_dest_types (void)
{
  return IMAGE_TEXT_MASK;
}

/* Called from autodetect_instantiate() */
void
string_instantiate (Lisp_Object image_instance, Lisp_Object instantiator,
		    Lisp_Object UNUSED (pointer_fg),
		    Lisp_Object UNUSED (pointer_bg),
		    int dest_mask, Lisp_Object domain)
{
  Lisp_Object string = find_keyword_in_vector (instantiator, Q_data);
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (image_instance);

  assert (!NILP (string));

  /* Should never get here with a domain other than a window. */
#ifndef NDEBUG
  /* Work Around for an Intel Compiler 7.0 internal error */
  /* assert (WINDOWP (DOMAIN_WINDOW (domain))); internal error: 0_5086 */
  {
    Lisp_Object w = DOMAIN_WINDOW (domain);
    assert (WINDOWP (w));
  }
#endif

  if (dest_mask & IMAGE_TEXT_MASK)
    {
      IMAGE_INSTANCE_TYPE (ii) = IMAGE_TEXT;
      IMAGE_INSTANCE_TEXT_STRING (ii) = string;
    }
  else
    incompatible_image_types (instantiator, dest_mask, IMAGE_TEXT_MASK);
}

/* Sort out the size of the text that is being displayed. Calculating
   it dynamically allows us to change the text and still see
   everything. Note that the following methods are for text not string
   since that is what the instantiated type is. The first method is a
   helper that is used elsewhere for calculating text geometry. */
void
query_string_geometry (Lisp_Object string, Lisp_Object face,
		       int* width, int* height, int* descent, Lisp_Object domain)
{
  struct font_metric_info fm;
  unsigned char charsets[NUM_LEADING_BYTES];
  struct face_cachel cachel;
  struct face_cachel *the_cachel;
  Lisp_Object window = DOMAIN_WINDOW (domain);
  Lisp_Object frame  = DOMAIN_FRAME  (domain);

  CHECK_STRING (string);

  /* Compute height */
  if (height)
    {
      /* Compute string metric info */
      find_charsets_in_ibyte_string (charsets,
				       XSTRING_DATA   (string),
				       XSTRING_LENGTH (string));

      /* Fallback to the default face if none was provided. */
      if (!NILP (face))
	{
	  reset_face_cachel (&cachel);
	  update_face_cachel_data (&cachel,
				   /* #### NOTE: in fact, I'm not sure if it's
				      #### possible to *not* get a window
				      #### here, but you never know...
				      #### -- dvl */
				   NILP (window) ? frame : window,
				   face);
	  the_cachel = &cachel;
	}
      else
	the_cachel = WINDOW_FACE_CACHEL (DOMAIN_XWINDOW (domain),
					 DEFAULT_INDEX);

      ensure_face_cachel_complete (the_cachel, domain, charsets);
      face_cachel_charset_font_metric_info (the_cachel, charsets, &fm);

      *height = fm.ascent + fm.descent;
      /* #### descent only gets set if we query the height as well. */
      if (descent)
	*descent = fm.descent;
    }

  /* Compute width */
  if (width)
    *width = redisplay_text_width_string (domain,
					  NILP (face) ? Vdefault_face : face,
					  0, string, 0, -1);
}

Lisp_Object
query_string_font (Lisp_Object string, Lisp_Object face, Lisp_Object domain)
{
  unsigned char charsets[NUM_LEADING_BYTES];
  struct face_cachel cachel;
  int i;
  Lisp_Object window = DOMAIN_WINDOW (domain);
  Lisp_Object frame  = DOMAIN_FRAME  (domain);

  /* Compute string font info */
  find_charsets_in_ibyte_string (charsets,
				 XSTRING_DATA   (string),
				 XSTRING_LENGTH (string));

  reset_face_cachel (&cachel);
  update_face_cachel_data (&cachel, NILP (window) ? frame : window, face);
  ensure_face_cachel_complete (&cachel, domain, charsets);

  for (i = 0; i < NUM_LEADING_BYTES; i++)
    if (charsets[i])
      return FACE_CACHEL_FONT
	((&cachel), charset_by_leading_byte (i + MIN_LEADING_BYTE));

  return Qnil;			/* NOT REACHED */
}

static void
text_query_geometry (Lisp_Object image_instance,
		     int* width, int* height,
		     enum image_instance_geometry UNUSED (disp),
		     Lisp_Object domain)
{
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (image_instance);
  int descent = 0;

  query_string_geometry (IMAGE_INSTANCE_TEXT_STRING (ii),
			 IMAGE_INSTANCE_FACE (ii),
			 width, height, &descent, domain);

  /* The descent gets set as a side effect of querying the
     geometry. */
  IMAGE_INSTANCE_TEXT_DESCENT (ii) = descent;
}

/* set the properties of a string */
static void
text_update (Lisp_Object image_instance, Lisp_Object instantiator)
{
  Lisp_Object val = find_keyword_in_vector (instantiator, Q_data);

  if (!NILP (val))
    {
      CHECK_STRING (val);
      XIMAGE_INSTANCE_TEXT_STRING (image_instance) = val;
    }
}


/****************************************************************************
 *                             formatted-string                             *
 ****************************************************************************/

static void
formatted_string_validate (Lisp_Object instantiator)
{
  data_must_be_present (instantiator);
}

static int
formatted_string_possible_dest_types (void)
{
  return IMAGE_TEXT_MASK;
}

static void
formatted_string_instantiate (Lisp_Object image_instance,
			      Lisp_Object instantiator,
			      Lisp_Object pointer_fg, Lisp_Object pointer_bg,
			      int dest_mask, Lisp_Object domain)
{
  /* #### implement this */
  warn_when_safe (Qunimplemented, Qnotice,
		  "`formatted-string' not yet implemented; assuming `string'");

  string_instantiate (image_instance, instantiator,
		      pointer_fg, pointer_bg, dest_mask, domain);
}


/************************************************************************/
/*                        pixmap file functions                         */
/************************************************************************/

/* - If INSTANTIATOR refers to inline data, or there is no file keyword, we
     have nothing to do, so return Qt.
   - If INSTANTIATOR refers to data in a file, return the full filename
     if it exists; otherwise, return '(filename), meaning "file not found".
   - If there is no locate_pixmap_file method for this console, return Qnil.

   FILE_KEYWORD and DATA_KEYWORD are symbols specifying the
   keywords used to look up the file and inline data,
   respectively, in the instantiator.  These would be Q_file and Q_data,
   Q_mask_file or Q_mask_data. */

Lisp_Object
potential_pixmap_file_instantiator (Lisp_Object instantiator,
				    Lisp_Object file_keyword,
				    Lisp_Object data_keyword,
				    Lisp_Object console_type)
{
  Lisp_Object file;
  Lisp_Object data;

  assert (VECTORP (instantiator));

  data = find_keyword_in_vector (instantiator, data_keyword);
  file = find_keyword_in_vector (instantiator, file_keyword);

  if (!NILP (file) && NILP (data))
    {
      struct console_methods *meths
	= decode_console_type(console_type, ERROR_ME);

      if (HAS_CONTYPE_METH_P (meths, locate_pixmap_file))
	{
	  Lisp_Object retval
	    = CONTYPE_METH (meths, locate_pixmap_file, (file));

	  if (!NILP (retval))
	    return retval;
	  else
	    return Fcons (file, Qnil); /* should have been file */
	}
      else /* method unavailable */
	return Qnil;
    }

  return Qt;
}

Lisp_Object
simple_image_type_normalize (Lisp_Object inst, Lisp_Object console_type,
			     Lisp_Object image_type_tag)
{
  /* This function can call lisp */
  Lisp_Object file = Qnil;
  struct gcpro gcpro1, gcpro2;
  Lisp_Object alist = Qnil;

  GCPRO2 (file, alist);

  /* Now, convert any file data into inline data.  At the end of this,
     `data' will contain the inline data (if any) or Qnil, and `file'
     will contain the name this data was derived from (if known) or
     Qnil.

     Note that if we cannot generate any regular inline data, we
     skip out. */

  file = potential_pixmap_file_instantiator (inst, Q_file, Q_data,
					     console_type);

  if (NILP (file)) /* normalization impossible for the console type */
    RETURN_UNGCPRO (Qnil);

  if (CONSP (file)) /* failure locating filename */
    signal_double_image_error ("Opening pixmap file",
			       "no such file or directory",
			       Fcar (file));

  if (EQ (file, Qt)) /* no conversion necessary */
    RETURN_UNGCPRO (inst);

  alist = tagged_vector_to_alist (inst);

  {
    Lisp_Object data = make_string_from_file (file);
    alist = remassq_no_quit (Q_file, alist);
    /* there can't be a :data at this point. */
    alist = Fcons (Fcons (Q_file, file),
		   Fcons (Fcons (Q_data, data), alist));
  }

  {
    Lisp_Object result = alist_to_tagged_vector (image_type_tag, alist);
    free_alist (alist);
    RETURN_UNGCPRO (result);
  }
}


#ifdef HAVE_WINDOW_SYSTEM
/**********************************************************************
 *                             XBM                                    *
 **********************************************************************/

/* Check if DATA represents a valid inline XBM spec (i.e. a list
   of (width height bits), with checking done on the dimensions).
   If not, signal an error. */

static void
check_valid_xbm_inline (Lisp_Object data)
{
  Lisp_Object width, height, bits, args[2];

  if (!CONSP (data) ||
      !CONSP (XCDR (data)) ||
      !CONSP (XCDR (XCDR (data))) ||
      !NILP (XCDR (XCDR (XCDR (data)))))
    sferror ("Must be list of 3 elements", data);

  width  = XCAR (data);
  height = XCAR (XCDR (data));
  bits   = XCAR (XCDR (XCDR (data)));

  CHECK_STRING (bits);

  if (!NATNUMP (width))
    invalid_argument ("Width must be a natural number", width);

  if (!NATNUMP (height))
    invalid_argument ("Height must be a natural number", height);

  args[0] = width;
  args[1] = height;

  args[0] = Ftimes (countof (args), args);
  args[1] = make_integer (8);

  args[0] = Fquo (countof (args), args);
  args[1] = make_integer (string_char_length (bits));

  if (!NILP (Fgtr (countof (args), args)))
    invalid_argument ("data is too short for width and height",
			 vector3 (width, height, bits));
}

/* Validate method for XBM's. */

static void
xbm_validate (Lisp_Object instantiator)
{
  file_or_data_must_be_present (instantiator);
}

/* Given a filename that is supposed to contain XBM data, return
   the inline representation of it as (width height bits).  Return
   the hotspot through XHOT and YHOT, if those pointers are not 0.
   If there is no hotspot, XHOT and YHOT will contain -1.

   If the function fails:

   -- if OK_IF_DATA_INVALID is set and the data was invalid,
      return Qt.
   -- maybe return an error, or return Qnil.
 */

#ifdef HAVE_X_WINDOWS
#include <X11/Xlib.h>
#else
#define XFree(data) free(data)
#endif

Lisp_Object
bitmap_to_lisp_data (Lisp_Object name, int *xhot, int *yhot,
		     int ok_if_data_invalid)
{
  int w, h;
  Binbyte *data;
  int result;

  result = read_bitmap_data_from_file (name, &w, &h, &data, xhot, yhot);

  if (result == BitmapSuccess)
    {
      Lisp_Object retval;
      int len = (w + 7) / 8 * h;

      retval = list3 (make_int (w), make_int (h),
		      make_extstring ((Extbyte *) data, len, Qbinary));
      XFree (data);
      return retval;
    }

  switch (result)
    {
    case BitmapOpenFailed:
      {
	/* should never happen */
	signal_double_image_error ("Opening bitmap file",
				   "no such file or directory",
				   name);
      }
    case BitmapFileInvalid:
      {
	if (ok_if_data_invalid)
	  return Qt;
	signal_double_image_error ("Reading bitmap file",
				   "invalid data in file",
				   name);
      }
    case BitmapNoMemory:
      {
	signal_double_image_error ("Reading bitmap file",
				   "out of memory",
				   name);
      }
    default:
      {
	signal_double_image_error_2 ("Reading bitmap file",
				     "unknown error code",
				     make_int (result), name);
      }
    }

  return Qnil; /* not reached */
}

/* This function attempts to find implicit mask files by appending "Mask" or
   "msk" to the original bitmap file name. This is more or less standard: a
   number of bitmaps in /usr/include/X11/bitmaps use it. */
Lisp_Object
xbm_mask_file_munging (Lisp_Object alist, Lisp_Object file,
		       Lisp_Object mask_file, Lisp_Object console_type)
{
  /* Let's try to find an implicit mask file if we have neither an explicit
     mask file name, nor inline mask data. Note that no errors are reported in
     case of failure because the mask file we're looking for might not
     exist. */ 
  if (EQ (mask_file, Qt) && NILP (assq_no_quit (Q_mask_data, alist)))
    {
      assert (!EQ (file, Qt) && !EQ (file, Qnil));
      mask_file = MAYBE_LISP_CONTYPE_METH
	(decode_console_type(console_type, ERROR_ME),
	 locate_pixmap_file, (concat2 (file, build_ascstring ("Mask"))));
      if (NILP (mask_file))
	mask_file = MAYBE_LISP_CONTYPE_METH
	  (decode_console_type(console_type, ERROR_ME),
	   locate_pixmap_file, (concat2 (file, build_ascstring ("msk"))));
    }

  /* We got a mask file, either explicitely or from the search above. */
  if (!NILP (mask_file))
    {
      Lisp_Object mask_data;

      assert (!EQ (mask_file, Qt));

      mask_data = bitmap_to_lisp_data (mask_file, 0, 0, 0);
      alist = remassq_no_quit (Q_mask_file, alist);
      /* there can't be a :mask-data at this point. */
      alist = Fcons (Fcons (Q_mask_file, mask_file),
		     Fcons (Fcons (Q_mask_data, mask_data), alist));
    }

  return alist;
}

/* Normalize method for XBM's. */

static Lisp_Object
xbm_normalize (Lisp_Object inst, Lisp_Object console_type,
	       Lisp_Object UNUSED (dest_mask))
{
  Lisp_Object file = Qnil, mask_file = Qnil, alist = Qnil;
  struct gcpro gcpro1, gcpro2, gcpro3;

  GCPRO3 (file, mask_file, alist);

  /* Now, convert any file data into inline data for both the regular
     data and the mask data.  At the end of this, `data' will contain
     the inline data (if any) or Qnil, and `file' will contain
     the name this data was derived from (if known) or Qnil.
     Likewise for `mask_file' and `mask_data'.

     Note that if we cannot generate any regular inline data, we
     skip out. */

  file = potential_pixmap_file_instantiator (inst, Q_file, Q_data,
					     console_type);
  mask_file = potential_pixmap_file_instantiator (inst, Q_mask_file,
						  Q_mask_data, console_type);

  /* No locate_pixmap_file method for this console type, so we can't get a
     file (neither a mask file BTW). */
  if (NILP (file))
    RETURN_UNGCPRO (Qnil);

  if (CONSP (file)) /* failure locating filename */
    signal_double_image_error ("Opening bitmap file",
			       "no such file or directory",
			       Fcar (file));

  if (CONSP (mask_file)) /* failure locating filename */
    signal_double_image_error ("Opening bitmap mask file",
			       "no such file or directory",
			       Fcar (mask_file));

  if (EQ (file, Qt) && EQ (mask_file, Qt)) /* no conversion necessary */
    RETURN_UNGCPRO (inst);

  alist = tagged_vector_to_alist (inst);

  if (!EQ (file, Qt))
    {
      int xhot, yhot;
      Lisp_Object data = bitmap_to_lisp_data (file, &xhot, &yhot, 0);
      alist = remassq_no_quit (Q_file, alist);
      /* there can't be a :data at this point. */
      alist = Fcons (Fcons (Q_file, file),
		     Fcons (Fcons (Q_data, data), alist));

      if (xhot != -1 && NILP (assq_no_quit (Q_hotspot_x, alist)))
	alist = Fcons (Fcons (Q_hotspot_x, make_int (xhot)),
		       alist);
      if (yhot != -1 && NILP (assq_no_quit (Q_hotspot_y, alist)))
	alist = Fcons (Fcons (Q_hotspot_y, make_int (yhot)),
		       alist);
    }

  alist = xbm_mask_file_munging (alist, file, mask_file, console_type);

  {
    Lisp_Object result = alist_to_tagged_vector (Qxbm, alist);
    free_alist (alist);
    RETURN_UNGCPRO (result);
  }
}


static int
xbm_possible_dest_types (void)
{
  return
    IMAGE_MONO_PIXMAP_MASK  |
    IMAGE_COLOR_PIXMAP_MASK |
    IMAGE_POINTER_MASK;
}

#endif


#ifdef HAVE_XFACE
/**********************************************************************
 *                             X-Face                                 *
 **********************************************************************/

static void
xface_validate (Lisp_Object instantiator)
{
  file_or_data_must_be_present (instantiator);
}

static Lisp_Object
xface_normalize (Lisp_Object inst, Lisp_Object console_type,
		 Lisp_Object UNUSED (dest_mask))
{
  Lisp_Object file = Qnil, mask_file = Qnil, alist = Qnil;
  struct gcpro gcpro1, gcpro2, gcpro3;

  GCPRO3 (file, mask_file, alist);

  /* Now, convert any file data into inline data for both the regular
     data and the mask data.  At the end of this, `data' will contain
     the inline data (if any) or Qnil, and `file' will contain
     the name this data was derived from (if known) or Qnil.
     Likewise for `mask_file' and `mask_data'.

     Note that if we cannot generate any regular inline data, we
     skip out. */

  file = potential_pixmap_file_instantiator (inst, Q_file, Q_data,
					     console_type);
  mask_file = potential_pixmap_file_instantiator (inst, Q_mask_file,
						  Q_mask_data, console_type);

  /* No locate_pixmap_file method for this console type, so we can't get a
     file (neither a mask file BTW). */
  if (NILP (file))
    RETURN_UNGCPRO (Qnil);

  if (CONSP (file)) /* failure locating filename */
    signal_double_image_error ("Opening face file",
			       "no such file or directory",
			       Fcar (file));

  if (CONSP (mask_file)) /* failure locating filename */
    signal_double_image_error ("Opening face mask file",
			       "no such file or directory",
			       Fcar (mask_file));

  if (EQ (file, Qt) && EQ (mask_file, Qt)) /* no conversion necessary */
    RETURN_UNGCPRO (inst);

  alist = tagged_vector_to_alist (inst);

  if (!EQ (file, Qt))
    {
      Lisp_Object data = make_string_from_file (file);
      alist = remassq_no_quit (Q_file, alist);
      /* there can't be a :data at this point. */
      alist = Fcons (Fcons (Q_file, file),
		     Fcons (Fcons (Q_data, data), alist));
    }

  alist = xbm_mask_file_munging (alist, file, mask_file, console_type);

  {
    Lisp_Object result = alist_to_tagged_vector (Qxface, alist);
    free_alist (alist);
    RETURN_UNGCPRO (result);
  }
}

static int
xface_possible_dest_types (void)
{
  return
    IMAGE_MONO_PIXMAP_MASK  |
    IMAGE_COLOR_PIXMAP_MASK |
    IMAGE_POINTER_MASK;
}

#endif /* HAVE_XFACE */


#ifdef HAVE_XPM

/**********************************************************************
 *                             XPM                                    *
 **********************************************************************/

#ifdef HAVE_GTK
/* Gtk has to be gratuitously different, eh? */
Lisp_Object
pixmap_to_lisp_data (Lisp_Object name, int UNUSED (ok_if_data_invalid))
{
  return (make_string_from_file (name));
}
#else
Lisp_Object
pixmap_to_lisp_data (Lisp_Object name, int ok_if_data_invalid)
{
  Ascbyte **data;
  int result;
  Extbyte *fname = 0;
  Ibyte *resolved;

  LISP_PATHNAME_RESOLVE_LINKS (name, resolved);
  fname = ITEXT_TO_EXTERNAL (resolved, Qfile_name);
  result = XpmReadFileToData (fname, &data);

  if (result == XpmSuccess)
    {
      Lisp_Object retval = Qnil;
      struct buffer *old_buffer = current_buffer;
      Lisp_Object temp_buffer =
	Fget_buffer_create (build_ascstring (" *pixmap conversion*"));
      int elt;
      int height, width, ncolors;
      struct gcpro gcpro1, gcpro2, gcpro3;
      int speccount = specpdl_depth ();

      GCPRO3 (name, retval, temp_buffer);

      specbind (Qinhibit_quit, Qt);
      set_buffer_internal (XBUFFER (temp_buffer));
      Ferase_buffer (Qnil);

      buffer_insert_ascstring (current_buffer, "/* XPM */\r");
      buffer_insert_ascstring (current_buffer, "static char *pixmap[] = {\r");

      sscanf (data[0], "%d %d %d", &height, &width, &ncolors);
      for (elt = 0; elt <= width + ncolors; elt++)
	{
	  buffer_insert_ascstring (current_buffer, "\"");
	  buffer_insert_ascstring (current_buffer, data[elt]);

	  if (elt < width + ncolors)
	    buffer_insert_ascstring (current_buffer, "\",\r");
	  else
	    buffer_insert_ascstring (current_buffer, "\"};\r");
	}

      retval = Fbuffer_substring (Qnil, Qnil, Qnil);
      XpmFree (data);

      set_buffer_internal (old_buffer);
      unbind_to (speccount);

      RETURN_UNGCPRO (retval);
    }

  switch (result)
    {
    case XpmFileInvalid:
      {
	if (ok_if_data_invalid)
	  return Qt;
	signal_image_error ("invalid XPM data in file", name);
      }
    case XpmNoMemory:
      {
	signal_double_image_error ("Reading pixmap file",
				   "out of memory", name);
      }
    case XpmOpenFailed:
      {
	/* should never happen? */
	signal_double_image_error ("Opening pixmap file",
				   "no such file or directory", name);
      }
    default:
      {
	signal_double_image_error_2 ("Parsing pixmap file",
				     "unknown error code",
				     make_int (result), name);
	break;
      }
    }

  return Qnil; /* not reached */
}
#endif /* !HAVE_GTK */

static void
check_valid_xpm_color_symbols (Lisp_Object data)
{
  Lisp_Object rest;

  for (rest = data; !NILP (rest); rest = XCDR (rest))
    {
      if (!CONSP (rest) ||
	  !CONSP (XCAR (rest)) ||
	  !STRINGP (XCAR (XCAR (rest))) ||
	  (!STRINGP (XCDR (XCAR (rest))) &&
	   !COLOR_SPECIFIERP (XCDR (XCAR (rest)))))
	sferror ("Invalid color symbol alist", data);
    }
}

static void
xpm_validate (Lisp_Object instantiator)
{
  file_or_data_must_be_present (instantiator);
}

Lisp_Object Vxpm_color_symbols;

Lisp_Object
evaluate_xpm_color_symbols (void)
{
  Lisp_Object rest, results = Qnil;
  struct gcpro gcpro1, gcpro2;

  GCPRO2 (rest, results);
  for (rest = Vxpm_color_symbols; !NILP (rest); rest = XCDR (rest))
    {
      Lisp_Object name, value, cons;

      CHECK_CONS (rest);
      cons = XCAR (rest);
      CHECK_CONS (cons);
      name = XCAR (cons);
      CHECK_STRING (name);
      value = XCDR (cons);
      CHECK_CONS (value);
      value = XCAR (value);
      value = IGNORE_MULTIPLE_VALUES (Feval (value));
      if (NILP (value))
	continue;
      if (!STRINGP (value) && !COLOR_SPECIFIERP (value))
	invalid_argument
	  ("Result from xpm-color-symbols eval must be nil, string, or color",
	   value);
      results = Fcons (Fcons (name, value), results);
    }
  UNGCPRO;			/* no more evaluation */
  return results;
}

static Lisp_Object
xpm_normalize (Lisp_Object inst, Lisp_Object console_type,
	       Lisp_Object UNUSED (dest_mask))
{
  Lisp_Object file = Qnil;
  Lisp_Object color_symbols;
  struct gcpro gcpro1, gcpro2;
  Lisp_Object alist = Qnil;

  GCPRO2 (file, alist);

  /* Now, convert any file data into inline data.  At the end of this,
     `data' will contain the inline data (if any) or Qnil, and
     `file' will contain the name this data was derived from (if
     known) or Qnil.

     Note that if we cannot generate any regular inline data, we
     skip out. */

  file = potential_pixmap_file_instantiator (inst, Q_file, Q_data,
					     console_type);

  if (NILP (file)) /* normalization impossible for the console type */
    RETURN_UNGCPRO (Qnil);

  if (CONSP (file)) /* failure locating filename */
    signal_double_image_error ("Opening pixmap file",
			       "no such file or directory",
			       Fcar (file));

  color_symbols = find_keyword_in_vector_or_given (inst, Q_color_symbols,
						   Qunbound);

  if (EQ (file, Qt) && !UNBOUNDP (color_symbols))
    /* no conversion necessary */
    RETURN_UNGCPRO (inst);

  alist = tagged_vector_to_alist (inst);

  if (!NILP (file) && !EQ (file, Qt))
    {
      Lisp_Object data = pixmap_to_lisp_data (file, 0);
      alist = remassq_no_quit (Q_file, alist);
      /* there can't be a :data at this point. */
      alist = Fcons (Fcons (Q_file, file),
		     Fcons (Fcons (Q_data, data), alist));
    }

  if (UNBOUNDP (color_symbols))
    {
      color_symbols = evaluate_xpm_color_symbols ();
      alist = Fcons (Fcons (Q_color_symbols, color_symbols),
		     alist);
    }

  {
    Lisp_Object result = alist_to_tagged_vector (Qxpm, alist);
    free_alist (alist);
    RETURN_UNGCPRO (result);
  }
}

static int
xpm_possible_dest_types (void)
{
  return
    IMAGE_MONO_PIXMAP_MASK  |
    IMAGE_COLOR_PIXMAP_MASK |
    IMAGE_POINTER_MASK;
}

#endif /* HAVE_XPM */


/****************************************************************************
 *                         Image Specifier Object                           *
 ****************************************************************************/

static const struct memory_description image_specifier_description[] = {
  { XD_LISP_OBJECT, offsetof (struct image_specifier, attachee) },
  { XD_LISP_OBJECT, offsetof (struct image_specifier, attachee_property) },
  { XD_END }
};

DEFINE_SPECIFIER_TYPE_WITH_DATA (image);

static void
image_create (Lisp_Object obj)
{
  Lisp_Specifier *image = XIMAGE_SPECIFIER (obj);

  IMAGE_SPECIFIER_ALLOWED (image) = ~0; /* all are allowed */
  IMAGE_SPECIFIER_ATTACHEE (image) = Qnil;
  IMAGE_SPECIFIER_ATTACHEE_PROPERTY (image) = Qnil;
}

static void
image_mark (Lisp_Object obj)
{
  Lisp_Specifier *image = XIMAGE_SPECIFIER (obj);

  mark_object (IMAGE_SPECIFIER_ATTACHEE (image));
  mark_object (IMAGE_SPECIFIER_ATTACHEE_PROPERTY (image));
}

static int
instantiator_eq_equal (const Hash_Table_Test *UNUSED (http),
                       Lisp_Object obj1, Lisp_Object obj2)
{
  if (EQ (obj1, obj2))
    return 1;

  else if (CONSP (obj1) && CONSP (obj2))
    {
      return instantiator_eq_equal (NULL, XCAR (obj1), XCAR (obj2))
	&& instantiator_eq_equal (NULL, XCDR (obj1), XCDR (obj2));
    }
  return 0;
}

static Hashcode
instantiator_eq_hash (const Hash_Table_Test *UNUSED (http), Lisp_Object obj)
{
  if (CONSP (obj))
    {
      /* no point in worrying about tail recursion, since we're not
	 going very deep */
      return HASH2 (instantiator_eq_hash (NULL, XCAR (obj)),
		    instantiator_eq_hash (NULL, XCDR (obj)));
    }
  return LISP_HASH (obj);
}

/* We need a special hash table for storing image instances. */
Lisp_Object
make_image_instance_cache_hash_table (void)
{
  return make_general_lisp_hash_table (Vimage_instance_hash_table_test, 30,
                                       -1.0, -1.0,
                                       HASH_TABLE_KEY_CAR_VALUE_WEAK);
}

static Lisp_Object
image_instantiate_cache_result (Lisp_Object locative)
{
  /* locative = (instance instantiator . subtable)

     So we are using the instantiator as the key and the instance as
     the value. Since the hashtable is key-weak this means that the
     image instance will stay around as long as the instantiator stays
     around. The instantiator is stored in the `image' slot of the
     glyph, so as long as the glyph is marked the instantiator will be
     as well and hence the cached image instance also.*/
  Fputhash (XCAR (XCDR (locative)), XCAR (locative), XCDR (XCDR (locative)));
  free_cons (XCDR (locative));
  free_cons (locative);
  return Qnil;
}

/* Given a specification for an image, return an instance of
   the image which matches the given instantiator and which can be
   displayed in the given domain. */

static Lisp_Object
image_instantiate (Lisp_Object specifier, Lisp_Object UNUSED (matchspec),
		   Lisp_Object domain, Lisp_Object instantiator,
		   Lisp_Object depth, int no_fallback)
{
  Lisp_Object glyph = IMAGE_SPECIFIER_ATTACHEE (XIMAGE_SPECIFIER (specifier));
  int dest_mask = XIMAGE_SPECIFIER_ALLOWED (specifier);
  int pointerp = dest_mask & image_instance_type_to_mask (IMAGE_POINTER);

  if (IMAGE_INSTANCEP (instantiator))
    {
      /* make sure that the image instance's governing domain and type are
	 matching. */
      Lisp_Object governing_domain = XIMAGE_INSTANCE_DOMAIN (instantiator);

      if ((DEVICEP (governing_domain)
	   && EQ (governing_domain, DOMAIN_DEVICE (domain)))
	  || (FRAMEP (governing_domain)
	      && EQ (governing_domain, DOMAIN_FRAME (domain)))
	  || (WINDOWP (governing_domain)
	      && EQ (governing_domain, DOMAIN_WINDOW (domain))))
	{
	  int mask =
	    image_instance_type_to_mask (XIMAGE_INSTANCE_TYPE (instantiator));
	  if (mask & dest_mask)
	    return instantiator;
	  else
	    invalid_argument ("Type of image instance not allowed here",
				 instantiator);
	}
      else
	invalid_argument_2 ("Wrong domain for image instance",
			       instantiator, domain);
    }
  /* How ugly !! An image instanciator that uses a kludgy syntax to snarf in
     face properties. There's a design flaw here. -- didier */
  else if (VECTORP (instantiator)
	   && EQ (INSTANTIATOR_TYPE (instantiator), Qinherit))
    {
      assert (XVECTOR_LENGTH (instantiator) == 3);
      return (FACE_PROPERTY_INSTANCE
	      (Fget_face (XVECTOR_DATA (instantiator)[2]),
	       Qbackground_pixmap, domain, no_fallback, depth));
    }
  else
    {
      Lisp_Object instance = Qnil;
      Lisp_Object subtable = Qnil;
      /* #### Should this be GCPRO'd? */
      Lisp_Object hash_key = Qnil;
      Lisp_Object pointer_fg = Qnil;
      Lisp_Object pointer_bg = Qnil;
      Lisp_Object governing_domain =
	get_image_instantiator_governing_domain (instantiator, domain);
      struct gcpro gcpro1;

      GCPRO1 (instance);

      /* We have to put subwindow, widget and text image instances in
	 a per-window cache so that we can see the same glyph in
	 different windows. We use governing_domain to determine the type
	 of image_instance that will be created. */

      if (pointerp)
	{
	  pointer_fg = FACE_FOREGROUND (Vpointer_face, domain);
	  pointer_bg = FACE_BACKGROUND (Vpointer_face, domain);
	  hash_key = list4 (glyph, INSTANTIATOR_TYPE (instantiator),
			    pointer_fg, pointer_bg);
	}
      else
	/* We cannot simply key on the glyph since fallbacks could use
	   the same glyph but have a totally different instantiator
	   type. Thus we key on the glyph and the type (but not any
	   other parts of the instantiator. */
	hash_key = list2 (glyph, INSTANTIATOR_TYPE (instantiator));

      /* First look in the device cache. */
      if (DEVICEP (governing_domain))
	{
	  subtable = Fgethash (make_int (dest_mask),
			       XDEVICE (governing_domain)->
			       image_instance_cache,
			       Qunbound);
	  if (UNBOUNDP (subtable))
	    {
	      /* For the image instance cache, we do comparisons with
		 EQ rather than with EQUAL, as we do for color and
		 font names.  The reasons are:

		 1) pixmap data can be very long, and thus the hashing
		 and comparing will take awhile.

		 2) It's not so likely that we'll run into things that
		 are EQUAL but not EQ (that can happen a lot with
		 faces, because their specifiers are copied around);
		 but pixmaps tend not to be in faces.

		 However, if the image-instance could be a pointer, we
		 have to use EQUAL because we massaged the
		 instantiator into a cons3 also containing the
		 foreground and background of the pointer face.  */
	      subtable = make_image_instance_cache_hash_table ();

	      Fputhash (make_int (dest_mask), subtable,
			XDEVICE (governing_domain)->image_instance_cache);
	      instance = Qunbound;
	    }
	  else
	    {
	      instance = Fgethash (hash_key, subtable, Qunbound);
	    }
	}
      else if (WINDOWP (governing_domain))
	{
	  /* Subwindows have a per-window cache and have to be treated
	     differently. */
	  instance =
	    Fgethash (hash_key,
		      XWINDOW (governing_domain)->subwindow_instance_cache,
		      Qunbound);
	}
      else
	ABORT ();	/* We're not allowed anything else currently. */

      /* If we don't have an instance at this point then create
	 one. */
      if (UNBOUNDP (instance))
	{
	  Lisp_Object locative =
	    noseeum_cons (Qnil,
			  noseeum_cons (hash_key,
					DEVICEP (governing_domain) ? subtable
					: XWINDOW (governing_domain)
					->subwindow_instance_cache));
	  int speccount = specpdl_depth ();

	  /* Make sure we cache the failures, too.  Use an
	     unwind-protect to catch such errors.  If we fail, the
	     unwind-protect records nil in the hash table.  If we
	     succeed, we change the car of the locative to the
	     resulting instance, which gets recorded instead. */
	  record_unwind_protect (image_instantiate_cache_result,
				 locative);
	  instance =
	    instantiate_image_instantiator (governing_domain,
					    domain, instantiator,
					    pointer_fg, pointer_bg,
					    dest_mask, glyph);

	  /* We need a per-frame cache for redisplay. */
	  cache_subwindow_instance_in_frame_maybe (instance);

	  Fsetcar (locative, instance);
#ifdef ERROR_CHECK_GLYPHS
	  if (image_instance_type_to_mask (XIMAGE_INSTANCE_TYPE (instance))
	      & (IMAGE_SUBWINDOW_MASK | IMAGE_WIDGET_MASK))
	      assert (EQ (XIMAGE_INSTANCE_FRAME (instance),
			  DOMAIN_FRAME (domain)));
#endif
	  unbind_to (speccount);
#ifdef ERROR_CHECK_GLYPHS
	  if (image_instance_type_to_mask (XIMAGE_INSTANCE_TYPE (instance))
	      & (IMAGE_SUBWINDOW_MASK | IMAGE_WIDGET_MASK))
	    assert (EQ (Fgethash (hash_key,
				  XWINDOW (governing_domain)
				  ->subwindow_instance_cache,
				  Qunbound), instance));
#endif
	}
      else if (NILP (instance))
	gui_error ("Can't instantiate image (probably cached)", instantiator);
      /* We found an instance. However, because we are using the glyph
	 as the hash key instead of the instantiator, the current
	 instantiator may not be the same as the original. Thus we
	 must update the instance based on the new
	 instantiator. Preserving instance identity like this is
	 important to stop excessive window system widget creation and
	 deletion - and hence flashing. */
      else
	{
	  /* #### This function should be able to cope with *all*
	     changes to the instantiator, but currently only copes
	     with the most used properties. This means that it is
	     possible to make changes that don't get reflected in the
	     display. */
	  update_image_instance (instance, instantiator);
	  free_list (hash_key);
	}

#ifdef ERROR_CHECK_GLYPHS
      if (image_instance_type_to_mask (XIMAGE_INSTANCE_TYPE (instance))
	  & (IMAGE_SUBWINDOW_MASK | IMAGE_WIDGET_MASK))
	assert (EQ (XIMAGE_INSTANCE_FRAME (instance),
		    DOMAIN_FRAME (domain)));
#endif
      ERROR_CHECK_IMAGE_INSTANCE (instance);
      RETURN_UNGCPRO (instance);
    }

  ABORT ();
  return Qnil; /* not reached */
}

/* Validate an image instantiator. */

static void
image_validate (Lisp_Object instantiator)
{
  if (IMAGE_INSTANCEP (instantiator) || STRINGP (instantiator))
    return;
  else if (VECTORP (instantiator))
    {
      Lisp_Object *elt = XVECTOR_DATA (instantiator);
      int instantiator_len = XVECTOR_LENGTH (instantiator);
      struct image_instantiator_methods *meths;
      Lisp_Object already_seen = Qnil;
      struct gcpro gcpro1;
      int i;

      if (instantiator_len < 1)
	sferror ("Vector length must be at least 1",
			     instantiator);

      meths = decode_image_instantiator_format (elt[0], ERROR_ME);
      if (!(instantiator_len & 1))
	sferror
	  ("Must have alternating keyword/value pairs", instantiator);

      GCPRO1 (already_seen);

      for (i = 1; i < instantiator_len; i += 2)
	{
	  Lisp_Object keyword = elt[i];
	  Lisp_Object value = elt[i+1];
	  int j;

	  CHECK_SYMBOL (keyword);
	  if (!SYMBOL_IS_KEYWORD (keyword))
	    invalid_argument ("Symbol must begin with a colon", keyword);

	  for (j = 0; j < Dynarr_length (meths->keywords); j++)
	    if (EQ (keyword, Dynarr_at (meths->keywords, j).keyword))
	      break;

	  if (j == Dynarr_length (meths->keywords))
	    invalid_argument ("Unrecognized keyword", keyword);

	  if (!Dynarr_at (meths->keywords, j).multiple_p)
	    {
	      if (!NILP (memq_no_quit (keyword, already_seen)))
		sferror
		  ("Keyword may not appear more than once", keyword);
	      already_seen = Fcons (keyword, already_seen);
	    }

	  (Dynarr_at (meths->keywords, j).validate) (value);
	}

      UNGCPRO;

      MAYBE_IIFORMAT_METH (meths, validate, (instantiator));
    }
  else
    invalid_argument ("Must be string or vector", instantiator);
}

static void
image_after_change (Lisp_Object specifier, Lisp_Object locale)
{
  Lisp_Object attachee =
    IMAGE_SPECIFIER_ATTACHEE (XIMAGE_SPECIFIER (specifier));
  Lisp_Object property =
    IMAGE_SPECIFIER_ATTACHEE_PROPERTY (XIMAGE_SPECIFIER (specifier));
  if (FACEP (attachee))
    {
      face_property_was_changed (attachee, property, locale);
      if (BUFFERP (locale))
	XBUFFER (locale)->buffer_local_face_property = 1;
    }
  else if (GLYPHP (attachee))
    glyph_property_was_changed (attachee, property, locale);
}

void
set_image_attached_to (Lisp_Object obj, Lisp_Object face_or_glyph,
		       Lisp_Object property)
{
  Lisp_Specifier *image = XIMAGE_SPECIFIER (obj);

  IMAGE_SPECIFIER_ATTACHEE (image) = face_or_glyph;
  IMAGE_SPECIFIER_ATTACHEE_PROPERTY (image) = property;
}

static Lisp_Object
image_going_to_add (Lisp_Object specifier, Lisp_Object UNUSED (locale),
		    Lisp_Object tag_set, Lisp_Object instantiator)
{
  Lisp_Object possible_console_types = Qnil;
  Lisp_Object rest;
  Lisp_Object retlist = Qnil;
  struct gcpro gcpro1, gcpro2;

  LIST_LOOP (rest, Vconsole_type_list)
    {
      Lisp_Object contype = XCAR (rest);
      if (!NILP (memq_no_quit (contype, tag_set)))
	possible_console_types = Fcons (contype, possible_console_types);
    }

  if (XINT (Flength (possible_console_types)) > 1)
    /* two conflicting console types specified */
    return Qnil;

  if (NILP (possible_console_types))
    possible_console_types = Vconsole_type_list;

  GCPRO2 (retlist, possible_console_types);

  LIST_LOOP (rest, possible_console_types)
    {
      Lisp_Object contype = XCAR (rest);
      Lisp_Object newinst = call_with_suspended_errors
	((lisp_fn_t) normalize_image_instantiator,
	 Qnil, Qimage, ERROR_ME_DEBUG_WARN, 3, instantiator, contype,
	 make_int (XIMAGE_SPECIFIER_ALLOWED (specifier)));

      if (!NILP (newinst))
	{
	  Lisp_Object newtag;
	  if (NILP (memq_no_quit (contype, tag_set)))
	    newtag = Fcons (contype, tag_set);
	  else
	    newtag = tag_set;
	  retlist = Fcons (Fcons (newtag, newinst), retlist);
	}
    }

  UNGCPRO;

  return retlist;
}

/* Copy an image instantiator. We can't use Fcopy_tree since widgets
   may contain circular references which would send Fcopy_tree into
   infloop death. */
static Lisp_Object
image_copy_vector_instantiator (Lisp_Object instantiator)
{
  int i;
  struct image_instantiator_methods *meths;
  Lisp_Object *elt;
  int instantiator_len;

  CHECK_VECTOR (instantiator);

  instantiator = Fcopy_sequence (instantiator);
  elt = XVECTOR_DATA (instantiator);
  instantiator_len = XVECTOR_LENGTH (instantiator);

  meths = decode_image_instantiator_format (elt[0], ERROR_ME);

  for (i = 1; i < instantiator_len; i += 2)
    {
      int j;
      Lisp_Object keyword = elt[i];
      Lisp_Object value = elt[i+1];

      /* Find the keyword entry. */
      for (j = 0; j < Dynarr_length (meths->keywords); j++)
	{
	  if (EQ (keyword, Dynarr_at (meths->keywords, j).keyword))
	    break;
	}

      /* Only copy keyword values that should be copied. */
      if (Dynarr_at (meths->keywords, j).copy_p
	  &&
	  (CONSP (value) || VECTORP (value)))
	{
	  elt [i+1] = Fcopy_tree (value, Qt);
	}
    }

  return instantiator;
}

static Lisp_Object
image_copy_instantiator (Lisp_Object arg)
{
  if (CONSP (arg))
    {
      Lisp_Object rest;
      rest = arg = Fcopy_sequence (arg);
      while (CONSP (rest))
	{
	  Lisp_Object elt = XCAR (rest);
	  if (CONSP (elt))
	    XCAR (rest) = Fcopy_tree (elt, Qt);
	  else if (VECTORP (elt))
	    XCAR (rest) = image_copy_vector_instantiator (elt);
	  if (VECTORP (XCDR (rest))) /* hack for (a b . [c d]) */
	    XCDR (rest) = Fcopy_tree (XCDR (rest), Qt);
	  rest = XCDR (rest);
	}
    }
  else if (VECTORP (arg))
    {
      arg = image_copy_vector_instantiator (arg);
    }
  return arg;
}

DEFUN ("image-specifier-p", Fimage_specifier_p, 1, 1, 0, /*
Return non-nil if OBJECT is an image specifier.
See `make-image-specifier' for a description of image instantiators.
*/
       (object))
{
  return IMAGE_SPECIFIERP (object) ? Qt : Qnil;
}


/****************************************************************************
 *                             Glyph Object                                 *
 ****************************************************************************/

static Lisp_Object
mark_glyph (Lisp_Object obj)
{
  Lisp_Glyph *glyph = XGLYPH (obj);

  mark_object (glyph->image);
  mark_object (glyph->contrib_p);
  mark_object (glyph->baseline);
  mark_object (glyph->face);

  return glyph->plist;
}

static void
print_glyph (Lisp_Object obj, Lisp_Object printcharfun,
	     int UNUSED (escapeflag))
{
  Lisp_Glyph *glyph = XGLYPH (obj);

  if (print_readably)
    printing_unreadable_lisp_object (obj, 0);

  write_fmt_string_lisp (printcharfun, "#<glyph (%s", 1, Fglyph_type (obj));
  write_fmt_string_lisp (printcharfun, ") %S", 1, glyph->image);
  write_fmt_string (printcharfun, "0x%x>", LISP_OBJECT_UID (obj));
}

/* Glyphs are equal if all of their display attributes are equal.  We
   don't compare names or doc-strings, because that would make equal
   be eq.

   This isn't concerned with "unspecified" attributes, that's what
   #'glyph-differs-from-default-p is for. */
static int
glyph_equal (Lisp_Object obj1, Lisp_Object obj2, int depth,
	     int UNUSED (foldcase))
{
  Lisp_Glyph *g1 = XGLYPH (obj1);
  Lisp_Glyph *g2 = XGLYPH (obj2);

  depth++;

  return (internal_equal (g1->image,     g2->image,     depth) &&
	  internal_equal (g1->contrib_p, g2->contrib_p, depth) &&
	  internal_equal (g1->baseline,  g2->baseline,  depth) &&
	  internal_equal (g1->face,      g2->face,      depth) &&
	  !plists_differ (g1->plist,     g2->plist, 0, 0, depth + 1, 0));
}

static Hashcode
glyph_hash (Lisp_Object obj, int depth, Boolint UNUSED (equalp))
{
  depth++;

  /* No need to hash all of the elements; that would take too long.
     Just hash the most common ones. */
  return HASH2 (internal_hash (XGLYPH (obj)->image, depth, 0),
		internal_hash (XGLYPH (obj)->face,  depth, 0));
}

static Lisp_Object
glyph_getprop (Lisp_Object obj, Lisp_Object prop)
{
  Lisp_Glyph *g = XGLYPH (obj);

  if (EQ (prop, Qimage))     return g->image;
  if (EQ (prop, Qcontrib_p)) return g->contrib_p;
  if (EQ (prop, Qbaseline))  return g->baseline;
  if (EQ (prop, Qface))      return g->face;

  return external_plist_get (&g->plist, prop, 0, ERROR_ME);
}

static int
glyph_putprop (Lisp_Object obj, Lisp_Object prop, Lisp_Object value)
{
  if (EQ (prop, Qimage)     ||
      EQ (prop, Qcontrib_p) ||
      EQ (prop, Qbaseline))
    return 0;

  if (EQ (prop, Qface))
    {
      XGLYPH (obj)->face = Fget_face (value);
      return 1;
    }

  external_plist_put (&XGLYPH (obj)->plist, prop, value, 0, ERROR_ME);
  return 1;
}

static int
glyph_remprop (Lisp_Object obj, Lisp_Object prop)
{
  if (EQ (prop, Qimage)     ||
      EQ (prop, Qcontrib_p) ||
      EQ (prop, Qbaseline))
    return -1;

  if (EQ (prop, Qface))
    {
      XGLYPH (obj)->face = Qnil;
      return 1;
    }

  return external_remprop (&XGLYPH (obj)->plist, prop, 0, ERROR_ME);
}

static Lisp_Object
glyph_plist (Lisp_Object obj)
{
  Lisp_Glyph *glyph = XGLYPH (obj);
  Lisp_Object result = glyph->plist;

  result = cons3 (Qface,      glyph->face,      result);
  result = cons3 (Qbaseline,  glyph->baseline,  result);
  result = cons3 (Qcontrib_p, glyph->contrib_p, result);
  result = cons3 (Qimage,     glyph->image,     result);

  return result;
}

static const struct memory_description glyph_description[] = {
  { XD_LISP_OBJECT, offsetof (Lisp_Glyph, image) },
  { XD_LISP_OBJECT, offsetof (Lisp_Glyph, contrib_p) },
  { XD_LISP_OBJECT, offsetof (Lisp_Glyph, baseline) },
  { XD_LISP_OBJECT, offsetof (Lisp_Glyph, face) },
  { XD_LISP_OBJECT, offsetof (Lisp_Glyph, plist) },
  { XD_END }
};

DEFINE_DUMPABLE_LISP_OBJECT ("glyph", glyph,
			     mark_glyph, print_glyph, 0,
			     glyph_equal, glyph_hash,
			     glyph_description,
			     Lisp_Glyph);

Lisp_Object
allocate_glyph (enum glyph_type type,
		void (*after_change) (Lisp_Object glyph, Lisp_Object property,
				      Lisp_Object locale))
{
  /* This function can GC */
  Lisp_Object obj = ALLOC_NORMAL_LISP_OBJECT (glyph);
  Lisp_Glyph *g = XGLYPH (obj);

  g->type = type;
  g->image = Fmake_specifier (Qimage); /* This function can GC */
  g->dirty = 0;
  switch (g->type)
    {
    case GLYPH_BUFFER:
      XIMAGE_SPECIFIER_ALLOWED (g->image) =
	IMAGE_NOTHING_MASK | IMAGE_TEXT_MASK
	| IMAGE_MONO_PIXMAP_MASK | IMAGE_COLOR_PIXMAP_MASK
	| IMAGE_SUBWINDOW_MASK | IMAGE_WIDGET_MASK;
      break;
    case GLYPH_POINTER:
      XIMAGE_SPECIFIER_ALLOWED (g->image) =
	IMAGE_NOTHING_MASK | IMAGE_POINTER_MASK;
      break;
    case GLYPH_ICON:
      XIMAGE_SPECIFIER_ALLOWED (g->image) =
	IMAGE_NOTHING_MASK | IMAGE_MONO_PIXMAP_MASK
	| IMAGE_COLOR_PIXMAP_MASK;
      break;
    default:
      ABORT ();
    }

  /* I think Fmake_specifier can GC.  I think set_specifier_fallback can GC. */
  /* We're getting enough reports of odd behavior in this area it seems */
  /* best to GCPRO everything. */
  {
    Lisp_Object tem1 = list1 (Fcons (Qnil, Vthe_nothing_vector));
    Lisp_Object tem2 = list1 (Fcons (Qnil, Qt));
    Lisp_Object tem3 = list1 (Fcons (Qnil, Qnil));
    struct gcpro gcpro1, gcpro2, gcpro3, gcpro4;

    GCPRO4 (obj, tem1, tem2, tem3);

    set_specifier_fallback (g->image, tem1);
    g->contrib_p = Fmake_specifier (Qboolean);
    set_specifier_fallback (g->contrib_p, tem2);
    /* #### should have a specifier for the following */
    g->baseline = Fmake_specifier (Qgeneric);
    set_specifier_fallback (g->baseline, tem3);
    g->face = Qnil;
    g->plist = Qnil;
    g->after_change = after_change;

    set_image_attached_to (g->image, obj, Qimage);
    UNGCPRO;
  }

  return obj;
}

static enum glyph_type
decode_glyph_type (Lisp_Object type, Error_Behavior errb)
{
  if (NILP (type))
    return GLYPH_BUFFER;

  if (ERRB_EQ (errb, ERROR_ME))
    CHECK_SYMBOL (type);

  if (EQ (type, Qbuffer))  return GLYPH_BUFFER;
  if (EQ (type, Qpointer)) return GLYPH_POINTER;
  if (EQ (type, Qicon))    return GLYPH_ICON;

  maybe_invalid_constant ("Invalid glyph type", type, Qimage, errb);

  return GLYPH_UNKNOWN;
}

static int
valid_glyph_type_p (Lisp_Object type)
{
  return !NILP (memq_no_quit (type, Vglyph_type_list));
}

DEFUN ("valid-glyph-type-p", Fvalid_glyph_type_p, 1, 1, 0, /*
Given a GLYPH-TYPE, return non-nil if it is valid.
Valid types are `buffer', `pointer', and `icon'.
*/
       (glyph_type))
{
  return valid_glyph_type_p (glyph_type) ? Qt : Qnil;
}

DEFUN ("glyph-type-list", Fglyph_type_list, 0, 0, 0, /*
Return a list of valid glyph types.
*/
       ())
{
  return Fcopy_sequence (Vglyph_type_list);
}

DEFUN ("make-glyph-internal", Fmake_glyph_internal, 0, 1, 0, /*
Create and return a new uninitialized glyph of type TYPE.

TYPE specifies the type of the glyph; this should be one of `buffer',
`pointer', or `icon', and defaults to `buffer'.  The type of the glyph
specifies in which contexts the glyph can be used, and controls the
allowable image types into which the glyph's image can be
instantiated.

`buffer' glyphs can be used as the begin-glyph or end-glyph of an
extent, in the modeline, and in the toolbar.  Their image can be
instantiated as `nothing', `mono-pixmap', `color-pixmap', `text',
and `subwindow'.

`pointer' glyphs can be used to specify the mouse pointer.  Their
image can be instantiated as `pointer'.

`icon' glyphs can be used to specify the icon used when a frame is
iconified.  Their image can be instantiated as `mono-pixmap' and
`color-pixmap'.
*/
       (type))
{
  enum glyph_type typeval = decode_glyph_type (type, ERROR_ME);
  return allocate_glyph (typeval, 0);
}

DEFUN ("glyphp", Fglyphp, 1, 1, 0, /*
Return non-nil if OBJECT is a glyph.

A glyph is an object used for pixmaps, widgets and the like.  It is used
in begin-glyphs and end-glyphs attached to extents, in marginal and textual
annotations, in overlay arrows (overlay-arrow-* variables), in toolbar
buttons, and the like.  Much more detailed information can be found at
`make-glyph'.  Its image is described using an image specifier --
see `make-image-specifier'.  See also `make-image-instance' for further
information.
*/
       (object))
{
  return GLYPHP (object) ? Qt : Qnil;
}

DEFUN ("glyph-type", Fglyph_type, 1, 1, 0, /*
Return the type of the given glyph.
The return value will be one of `buffer', `pointer', or `icon'.
*/
       (glyph))
{
  CHECK_GLYPH (glyph);
  switch (XGLYPH_TYPE (glyph))
    {
    default: ABORT ();
    case GLYPH_BUFFER:  return Qbuffer;
    case GLYPH_POINTER: return Qpointer;
    case GLYPH_ICON:    return Qicon;
    }
}

Lisp_Object
glyph_image_instance (Lisp_Object glyph, Lisp_Object domain,
		      Error_Behavior errb, int no_quit)
{
  Lisp_Object specifier = GLYPH_IMAGE (XGLYPH (glyph));

  /* This can never return Qunbound.  All glyphs have `nothing' as
     a fallback. */
  Lisp_Object image_instance = specifier_instance (specifier, Qunbound,
						   domain, errb, no_quit, 0,
						   Qzero);
  assert (!UNBOUNDP (image_instance));
  ERROR_CHECK_IMAGE_INSTANCE (image_instance);

  return image_instance;
}

static Lisp_Object
glyph_image_instance_maybe (Lisp_Object glyph_or_image, Lisp_Object window)
{
  Lisp_Object instance = glyph_or_image;

  if (GLYPHP (glyph_or_image))
    instance = glyph_image_instance (glyph_or_image, window,
				     ERROR_ME_DEBUG_WARN, 1);

  return instance;
}

inline static int
image_instance_needs_layout (Lisp_Object instance)
{
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (instance);

  if (IMAGE_INSTANCE_DIRTYP (ii) && IMAGE_INSTANCE_LAYOUT_CHANGED (ii))
    {
      return 1;
    }
  else
    {
      Lisp_Object iif = IMAGE_INSTANCE_FRAME (ii);
      return FRAMEP (iif) && XFRAME (iif)->size_changed;
    }
}

/*****************************************************************************
 glyph_width

 Return the width of the given GLYPH on the given WINDOW.
 Calculations are done based on recursively querying the geometry of
 the associated image instances.
 ****************************************************************************/
unsigned short
glyph_width (Lisp_Object glyph_or_image, Lisp_Object domain)
{
  Lisp_Object instance = glyph_image_instance_maybe (glyph_or_image,
						     domain);
  if (!IMAGE_INSTANCEP (instance))
    return 0;

  if (image_instance_needs_layout (instance))
    image_instance_layout (instance, IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY, domain);

  return XIMAGE_INSTANCE_WIDTH (instance);
}

DEFUN ("glyph-width", Fglyph_width, 1, 2, 0, /*
Return the width of GLYPH on WINDOW.
This may not be exact as it does not take into account all of the context
that redisplay will.
*/
       (glyph, window))
{
  window = wrap_window (decode_window (window));
  CHECK_GLYPH (glyph);

  return make_int (glyph_width (glyph, window));
}

unsigned short
glyph_ascent (Lisp_Object glyph_or_image, Lisp_Object domain)
{
  Lisp_Object instance = glyph_image_instance_maybe (glyph_or_image,
						     domain);
  if (!IMAGE_INSTANCEP (instance))
    return 0;

  if (image_instance_needs_layout (instance))
    image_instance_layout (instance, IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY, domain);

  if (XIMAGE_INSTANCE_TYPE (instance) == IMAGE_TEXT)
    return XIMAGE_INSTANCE_TEXT_ASCENT (instance);
  else
    return XIMAGE_INSTANCE_HEIGHT (instance);
}

unsigned short
glyph_descent (Lisp_Object glyph_or_image, Lisp_Object domain)
{
  Lisp_Object instance = glyph_image_instance_maybe (glyph_or_image,
						     domain);
  if (!IMAGE_INSTANCEP (instance))
    return 0;

  if (image_instance_needs_layout (instance))
    image_instance_layout (instance, IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY, domain);

  if (XIMAGE_INSTANCE_TYPE (instance) ==  IMAGE_TEXT)
    return XIMAGE_INSTANCE_TEXT_DESCENT (instance);
  else
    return 0;
}

/* strictly a convenience function. */
unsigned short
glyph_height (Lisp_Object glyph_or_image, Lisp_Object domain)
{
  Lisp_Object instance = glyph_image_instance_maybe (glyph_or_image,
						     domain);

  if (!IMAGE_INSTANCEP (instance))
    return 0;

  if (image_instance_needs_layout (instance))
    image_instance_layout (instance, IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNSPECIFIED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY,
			   IMAGE_UNCHANGED_GEOMETRY, domain);

  return XIMAGE_INSTANCE_HEIGHT (instance);
}

DEFUN ("glyph-ascent", Fglyph_ascent, 1, 2, 0, /*
Return the ascent value of GLYPH on WINDOW.
This may not be exact as it does not take into account all of the context
that redisplay will.
*/
       (glyph, window))
{
  window = wrap_window (decode_window (window));
  CHECK_GLYPH (glyph);

  return make_int (glyph_ascent (glyph, window));
}

DEFUN ("glyph-descent", Fglyph_descent, 1, 2, 0, /*
Return the descent value of GLYPH on WINDOW.
This may not be exact as it does not take into account all of the context
that redisplay will.
*/
       (glyph, window))
{
  window = wrap_window (decode_window (window));
  CHECK_GLYPH (glyph);

  return make_int (glyph_descent (glyph, window));
}

/* This is redundant but I bet a lot of people expect it to exist. */
DEFUN ("glyph-height", Fglyph_height, 1, 2, 0, /*
Return the height of GLYPH on WINDOW.
This may not be exact as it does not take into account all of the context
that redisplay will.
*/
       (glyph, window))
{
  window = wrap_window (decode_window (window));
  CHECK_GLYPH (glyph);

  return make_int (glyph_height (glyph, window));
}

static void
set_glyph_dirty_p (Lisp_Object glyph_or_image, Lisp_Object window, int dirty)
{
  Lisp_Object instance = glyph_or_image;

  if (!NILP (glyph_or_image))
    {
      if (GLYPHP (glyph_or_image))
	{
	  instance = glyph_image_instance (glyph_or_image, window,
					   ERROR_ME_DEBUG_WARN, 1);
	  XGLYPH_DIRTYP (glyph_or_image) = dirty;
	}

      if (!IMAGE_INSTANCEP (instance))
	return;

      XIMAGE_INSTANCE_DIRTYP (instance) = dirty;
    }
}

static void
set_image_instance_dirty_p (Lisp_Object instance, int dirty)
{
  if (IMAGE_INSTANCEP (instance))
    {
      XIMAGE_INSTANCE_DIRTYP (instance) = dirty;
      /* Now cascade up the hierarchy. */
      set_image_instance_dirty_p (XIMAGE_INSTANCE_PARENT (instance),
				  dirty);
    }
  else if (GLYPHP (instance))
    {
      XGLYPH_DIRTYP (instance) = dirty;
    }
}

/* #### do we need to cache this info to speed things up? */

Lisp_Object
glyph_baseline (Lisp_Object glyph, Lisp_Object domain)
{
  if (!GLYPHP (glyph))
    return Qnil;
  else
    {
      Lisp_Object retval =
	specifier_instance_no_quit (GLYPH_BASELINE (XGLYPH (glyph)),
				    /* #### look into error flag */
				    Qunbound, domain, ERROR_ME_DEBUG_WARN,
				    0, Qzero);
      if (!NILP (retval) && !INTP (retval))
	retval = Qnil;
      else if (INTP (retval))
	{
	  if (XINT (retval) < 0)
	    retval = Qzero;
	  if (XINT (retval) > 100)
	    retval = make_int (100);
	}
      return retval;
    }
}

Lisp_Object
glyph_face (Lisp_Object glyph, Lisp_Object UNUSED (domain))
{
  /* #### Domain parameter not currently used but it will be */
  return GLYPHP (glyph) ? GLYPH_FACE (XGLYPH (glyph)) : Qnil;
}

int
glyph_contrib_p (Lisp_Object glyph, Lisp_Object domain)
{
  if (!GLYPHP (glyph))
    return 0;
  else
    return !NILP (specifier_instance_no_quit
		  (GLYPH_CONTRIB_P (XGLYPH (glyph)), Qunbound, domain,
		   /* #### look into error flag */
		   ERROR_ME_DEBUG_WARN, 0, Qzero));
}

static void
glyph_property_was_changed (Lisp_Object glyph, Lisp_Object property,
			    Lisp_Object locale)
{
  if (XGLYPH (glyph)->after_change)
    (XGLYPH (glyph)->after_change) (glyph, property, locale);
}

void
glyph_query_geometry (Lisp_Object glyph_or_image, int* width, int* height,
		      enum image_instance_geometry disp, Lisp_Object domain)
{
  Lisp_Object instance = glyph_or_image;

  if (GLYPHP (glyph_or_image))
    instance = glyph_image_instance (glyph_or_image, domain,
				     ERROR_ME_DEBUG_WARN, 1);

  image_instance_query_geometry (instance, width, height, disp, domain);
}

void
glyph_do_layout (Lisp_Object glyph_or_image, int width, int height,
	      int xoffset, int yoffset, Lisp_Object domain)
{
  Lisp_Object instance = glyph_or_image;

  if (GLYPHP (glyph_or_image))
    instance = glyph_image_instance (glyph_or_image, domain,
				     ERROR_ME_DEBUG_WARN, 1);

  image_instance_layout (instance, width, height, xoffset, yoffset, domain);
}


/*****************************************************************************
 *                          glyph cachel functions                           *
 *****************************************************************************/

#define NUM_PRECACHED_GLYPHS 6
#define LOOP_OVER_PRECACHED_GLYPHS			\
  FROB (Vcontinuation_glyph, CONT_GLYPH_INDEX)		\
  FROB (Vtruncation_glyph, TRUN_GLYPH_INDEX)		\
  FROB (Vhscroll_glyph, HSCROLL_GLYPH_INDEX)		\
  FROB (Vcontrol_arrow_glyph, CONTROL_GLYPH_INDEX)	\
  FROB (Voctal_escape_glyph, OCT_ESC_GLYPH_INDEX)	\
  FROB (Vinvisible_text_glyph, INVIS_GLYPH_INDEX)


/* #### All of this is 95% copied from face cachels.  Consider
  consolidating.

  Why do we need glyph_cachels? Simply because a glyph_cachel captures
  per-window information about a particular glyph. A glyph itself is
  not created in any particular context, so if we were to rely on a
  glyph to tell us about its dirtiness we would not be able to reset
  the dirty flag after redisplaying it as it may exist in other
  contexts. When we have redisplayed we need to know which glyphs to
  reset the dirty flags on - the glyph_cachels give us a nice list we
  can iterate through doing this.  */
void
mark_glyph_cachels (glyph_cachel_dynarr *elements)
{
  int elt;

  if (!elements)
    return;

  for (elt = 0; elt < Dynarr_length (elements); elt++)
    {
      struct glyph_cachel *cachel = Dynarr_atp (elements, elt);
      mark_object (cachel->glyph);
    }
}

static void
update_glyph_cachel_data (struct window *w, Lisp_Object glyph,
			  struct glyph_cachel *cachel)
{
  if (!cachel->updated || NILP (cachel->glyph) || !EQ (cachel->glyph, glyph)
      || XGLYPH_DIRTYP (cachel->glyph)
      || XFRAME(WINDOW_FRAME(w))->faces_changed)
    {
      Lisp_Object window, instance;

      window = wrap_window (w);

      cachel->glyph   = glyph;
      /* Speed things up slightly by grabbing the glyph instantiation
	 and passing it to the size functions. */
      instance = glyph_image_instance (glyph, window, ERROR_ME_DEBUG_WARN, 1);

      if (!IMAGE_INSTANCEP (instance))
	return;

      /* Mark text instance of the glyph dirty if faces have changed,
	 because its geometry might have changed. */
      invalidate_glyph_geometry_maybe (instance, w);

      /* #### Do the following 2 lines buy us anything? --kkm */
      XGLYPH_DIRTYP (glyph) = XIMAGE_INSTANCE_DIRTYP (instance);
      cachel->dirty   = XGLYPH_DIRTYP (glyph);
      cachel->width   = glyph_width   (instance, window);
      cachel->ascent  = glyph_ascent  (instance, window);
      cachel->descent = glyph_descent (instance, window);
    }

  cachel->updated = 1;
}

static void
add_glyph_cachel (struct window *w, Lisp_Object glyph)
{
  struct glyph_cachel new_cachel;

  xzero (new_cachel);
  new_cachel.glyph = Qnil;

  update_glyph_cachel_data (w, glyph, &new_cachel);
  Dynarr_add (w->glyph_cachels, new_cachel);
}

#ifdef ERROR_CHECK_GLYPHS

/* The precached glyphs should always occur in slots 0 - 5, with each glyph in the
   slot reserved for it.  Meanwhile any other glyphs should always occur in slots
   6 or greater. */
static void
verify_glyph_index (Lisp_Object glyph, glyph_index idx)
{
  if (0)
    ;
#define FROB(glyph_obj, gindex)			\
  else if (EQ (glyph, glyph_obj))		\
    assert (gindex == idx);
  LOOP_OVER_PRECACHED_GLYPHS
  else
    assert (idx >= NUM_PRECACHED_GLYPHS);
#undef FROB
}

#endif /* ERROR_CHECK_GLYPHS */

glyph_index
get_glyph_cachel_index (struct window *w, Lisp_Object glyph)
{
  int elt;

  if (noninteractive)
    return 0;

  for (elt = 0; elt < Dynarr_length (w->glyph_cachels); elt++)
    {
      struct glyph_cachel *cachel =
	Dynarr_atp (w->glyph_cachels, elt);

      if (EQ (cachel->glyph, glyph) && !NILP (glyph))
	{
#ifdef ERROR_CHECK_GLYPHS
	  verify_glyph_index (glyph, elt);
#endif /* ERROR_CHECK_GLYPHS */
	  update_glyph_cachel_data (w, glyph, cachel);
	  return elt;
	}
    }

  /* If we didn't find the glyph, add it and then return its index. */
  add_glyph_cachel (w, glyph);
  return elt;
}

void
reset_glyph_cachels (struct window *w)
{
  Dynarr_reset (w->glyph_cachels);
#define FROB(glyph_obj, gindex)			\
  get_glyph_cachel_index (w, glyph_obj);
  LOOP_OVER_PRECACHED_GLYPHS
#undef FROB
}

void
mark_glyph_cachels_as_not_updated (struct window *w)
{
  int elt;

  /* A previous bug resulted from the glyph cachels never getting reset
     in the minibuffer window after creation, and another glyph added before
     we got a chance to add the six normal glyphs that should go first, and
     we got called with only one glyph present. */
  assert (Dynarr_length (w->glyph_cachels) >= NUM_PRECACHED_GLYPHS);
  /* We need to have a dirty flag to tell if the glyph has changed.
     We can check to see if each glyph variable is actually a
     completely different glyph, though. */
#define FROB(glyph_obj, gindex)						\
  update_glyph_cachel_data (w, glyph_obj,				\
			    Dynarr_atp (w->glyph_cachels, gindex));
  LOOP_OVER_PRECACHED_GLYPHS
#undef FROB

  for (elt = 0; elt < Dynarr_length (w->glyph_cachels); elt++)
    {
      Dynarr_atp (w->glyph_cachels, elt)->updated = 0;
    }
}

/* Unset the dirty bit on all the glyph cachels that have it. */
void
mark_glyph_cachels_as_clean (struct window* w)
{
  int elt;
  Lisp_Object window = wrap_window (w);

  for (elt = 0; elt < Dynarr_length (w->glyph_cachels); elt++)
    {
      struct glyph_cachel *cachel = Dynarr_atp (w->glyph_cachels, elt);
      cachel->dirty = 0;
      set_glyph_dirty_p (cachel->glyph, window, 0);
    }
}

#ifdef MEMORY_USAGE_STATS

int
compute_glyph_cachel_usage (glyph_cachel_dynarr *glyph_cachels,
			    struct usage_stats *ustats)
{
  int total = 0;

  if (glyph_cachels)
    total += Dynarr_memory_usage (glyph_cachels, ustats);

  return total;
}

#endif /* MEMORY_USAGE_STATS */



/*****************************************************************************
 *                        subwindow cachel functions                         *
 *****************************************************************************/
/* Subwindows are curious in that you have to physically unmap them to
   not display them. It is problematic deciding what to do in
   redisplay. We have two caches - a per-window instance cache that
   keeps track of subwindows on a window, these are linked to their
   instantiator in the hashtable and when the instantiator goes away
   we want the instance to go away also. However we also have a
   per-frame instance cache that we use to determine if a subwindow is
   obscuring an area that we want to clear. We need to be able to flip
   through this quickly so a hashtable is not suitable hence the
   subwindow_cachels. This is a weak list so unreference instances
   will get deleted properly. */

/* redisplay in general assumes that drawing something will erase
   what was there before. unfortunately this does not apply to
   subwindows that need to be specifically unmapped in order to
   disappear. we take a brute force approach - on the basis that its
   cheap - and unmap all subwindows in a display line */

/* Put new instances in the frame subwindow cache. This is less costly than
   doing it every time something gets mapped, and deleted instances will be
   removed automatically. */
static void
cache_subwindow_instance_in_frame_maybe (Lisp_Object instance)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (instance);
  if (!NILP (DOMAIN_FRAME (IMAGE_INSTANCE_DOMAIN (ii))))
    {
      struct frame* f = DOMAIN_XFRAME (IMAGE_INSTANCE_DOMAIN (ii));
      XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f))
	= Fcons (instance, XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f)));
    }
}

/* Unmap and finalize all subwindow instances in the frame cache. This
   is necessary because GC will not guarantee the order things get
   deleted in and moreover, frame finalization deletes the window
   system windows before deleting XEmacs windows, and hence
   subwindows.  */
int
unmap_subwindow_instance_cache_mapper (Lisp_Object UNUSED (key),
				       Lisp_Object value, void* finalize)
{
  /* value can be nil; we cache failures as well as successes */
  if (!NILP (value))
    {
      struct frame* f = XFRAME (XIMAGE_INSTANCE_FRAME (value));
      unmap_subwindow (value);
      if (finalize)
	{
	  /* In case GC doesn't catch up fast enough, remove from the frame
	     cache also. Otherwise code that checks the sanity of the instance
	     will fail. */
	  XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f))
	    = delq_no_quit (value,
			    XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f)));
	  finalize_image_instance (value);
	}
    }
  return 0;
}

static void
finalize_all_subwindow_instances (struct window *w)
{
  if (!NILP (w->next))   finalize_all_subwindow_instances (XWINDOW (w->next));
  if (!NILP (w->vchild)) finalize_all_subwindow_instances (XWINDOW (w->vchild));
  if (!NILP (w->hchild)) finalize_all_subwindow_instances (XWINDOW (w->hchild));

  elisp_maphash (unmap_subwindow_instance_cache_mapper,
		 w->subwindow_instance_cache, (void*)1);
}

void
free_frame_subwindow_instances (struct frame* f)
{
  /* Make sure all instances are finalized. We have to do this via the
     instance cache since some instances may be extant but not
     displayed (and hence not in the frame cache). */
  finalize_all_subwindow_instances (XWINDOW (f->root_window));
}

/* Unmap all instances in the frame cache. */
void
reset_frame_subwindow_instance_cache (struct frame* f)
{
  Lisp_Object rest;

  LIST_LOOP (rest, XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f)))
    {
      Lisp_Object value = XCAR (rest);
      unmap_subwindow (value);
    }
}

/*****************************************************************************
 *                           subwindow exposure ignorance                    *
 *****************************************************************************/
/* when we unmap subwindows the associated window system will generate
   expose events. This we do not want as redisplay already copes with
   the repainting necessary. Worse, we can get in an endless cycle of
   redisplay if we are not careful. Thus we keep a per-frame list of
   expose events that are going to come and ignore them as
   required. */

#ifndef NEW_GC
struct expose_ignore_blocktype
{
  Blocktype_declare (struct expose_ignore);
} *the_expose_ignore_blocktype;
#endif /* not NEW_GC */

int
check_for_ignored_expose (struct frame* f, int x, int y, int width, int height)
{
  struct expose_ignore *ei, *prev;
  /* the ignore list is FIFO so we should generally get a match with
     the first element in the list */
  for (ei = f->subwindow_exposures, prev = 0; ei; ei = ei->next)
    {
      /* Checking for exact matches just isn't good enough as we
	 might get exposures for partially obscured subwindows, thus
	 we have to check for overlaps. Being conservative, we will
	 check for exposures wholly contained by the subwindow - this
	 might give us what we want.*/
      if (ei->x <= x && ei->y <= y
	  && ei->x + ei->width >= x + width
	  && ei->y + ei->height >= y + height)
	{
#ifdef DEBUG_WIDGETS
	  stderr_out ("ignored %d+%d, %dx%d for exposure %d+%d, %dx%d\n",
		      x, y, width, height, ei->x, ei->y, ei->width, ei->height);
#endif
	  if (!prev)
	    f->subwindow_exposures = ei->next;
	  else
	    prev->next = ei->next;

	  if (ei == f->subwindow_exposures_tail)
	    f->subwindow_exposures_tail = prev;

#ifndef NEW_GC
	  Blocktype_free (the_expose_ignore_blocktype, ei);
#endif /* not NEW_GC */
	  return 1;
	}
      prev = ei;
    }
  return 0;
}

static void
register_ignored_expose (struct frame* f, int x, int y, int width, int height)
{
  if (!hold_ignored_expose_registration)
    {
      struct expose_ignore *ei;

#ifdef NEW_GC
      ei = XEXPOSE_IGNORE (ALLOC_NORMAL_LISP_OBJECT (expose_ignore));
#else /* not NEW_GC */
      ei = Blocktype_alloc (the_expose_ignore_blocktype);
#endif /* not NEW_GC */

      ei->next = NULL;
      ei->x = x;
      ei->y = y;
      ei->width = width;
      ei->height = height;

      /* we have to add the exposure to the end of the list, since we
	 want to check the oldest events first. for speed we keep a record
	 of the end so that we can add right to it. */
      if (f->subwindow_exposures_tail)
	{
	  f->subwindow_exposures_tail->next = ei;
	}
      if (!f->subwindow_exposures)
	{
	  f->subwindow_exposures = ei;
	}
      f->subwindow_exposures_tail = ei;
    }
}

/****************************************************************************
 find_matching_subwindow

 See if there is a subwindow that completely encloses the requested
 area.
 ****************************************************************************/
int
find_matching_subwindow (struct frame* f, int x, int y, int width, int height)
{
  Lisp_Object rest;

  LIST_LOOP (rest, XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f)))
    {
      Lisp_Image_Instance *ii = XIMAGE_INSTANCE (XCAR (rest));

      if (IMAGE_INSTANCE_SUBWINDOW_DISPLAYEDP (ii)
	  &&
	  IMAGE_INSTANCE_DISPLAY_X (ii) <= x
	  &&
	  IMAGE_INSTANCE_DISPLAY_Y (ii) <= y
	  &&
	  IMAGE_INSTANCE_DISPLAY_X (ii)
	  + IMAGE_INSTANCE_DISPLAY_WIDTH (ii) >= x + width
	  &&
	  IMAGE_INSTANCE_DISPLAY_Y (ii)
	  + IMAGE_INSTANCE_DISPLAY_HEIGHT (ii) >= y + height)
	{
	  return 1;
	}
    }
  return 0;
}


/*****************************************************************************
 *                              subwindow functions                          *
 *****************************************************************************/

/* Update the displayed characteristics of a subwindow. This function
   should generally only get called if the subwindow is actually
   dirty. */
void
redisplay_subwindow (Lisp_Object subwindow)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (subwindow);
  int count = specpdl_depth ();

  /* The update method is allowed to call eval.  Since it is quite
     common for this function to get called from somewhere in
     redisplay we need to make sure that quits are ignored.  Otherwise
     Fsignal will abort. */
  specbind (Qinhibit_quit, Qt);

  ERROR_CHECK_IMAGE_INSTANCE (subwindow);

  if (WIDGET_IMAGE_INSTANCEP (subwindow))
    {
      if (image_instance_changed (subwindow))
	redisplay_widget (subwindow);
      /* Reset the changed flags. */
      IMAGE_INSTANCE_WIDGET_FACE_CHANGED (ii) = 0;
      IMAGE_INSTANCE_WIDGET_ITEMS_CHANGED (ii) = 0;
      IMAGE_INSTANCE_WIDGET_ACTION_OCCURRED (ii) = 0;
      IMAGE_INSTANCE_TEXT_CHANGED (ii) = 0;
    }
  else if (IMAGE_INSTANCE_TYPE (ii) == IMAGE_SUBWINDOW
	   &&
	   !NILP (IMAGE_INSTANCE_FRAME (ii)))
    {
      MAYBE_DEVMETH (DOMAIN_XDEVICE (ii->domain),
		     redisplay_subwindow, (ii));
    }

  IMAGE_INSTANCE_SIZE_CHANGED (ii) = 0;
  /* This function is typically called by redisplay just before
     outputting the information to the screen. Thus we record a hash
     of the output to determine whether on-screen is the same as
     recorded structure. This approach has limitations in there is a
     good chance that hash values will be different for the same
     visual appearance. However, we would rather that then the other
     way round - it simply means that we will get more displays than
     we might need. We can get better hashing by making the depth
     negative - currently it will recurse down 7 levels.*/
  IMAGE_INSTANCE_DISPLAY_HASH (ii) = internal_hash (subwindow,
						    IMAGE_INSTANCE_HASH_DEPTH,
                                                    0);

  unbind_to (count);
}

/* Determine whether an image_instance has changed structurally and
   hence needs redisplaying in some way.

   #### This should just look at the instantiator differences when we
   get rid of the stored items altogether. In fact we should probably
   store the new instantiator as well as the old - as we do with
   gui_items currently - and then pick-up the new on the next
   redisplay. This would obviate the need for any of this trickery
   with hashcodes. */
int
image_instance_changed (Lisp_Object subwindow)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (subwindow);

  if (internal_hash (subwindow, IMAGE_INSTANCE_HASH_DEPTH, 0) !=
      IMAGE_INSTANCE_DISPLAY_HASH (ii))
    return 1;
  /* #### I think there is probably a bug here. This gets called for
     layouts - and yet the pending items are always nil for
     layouts. We are saved by layout optimization, but I'm undecided
     as to what the correct fix is. */
  else if (WIDGET_IMAGE_INSTANCEP (subwindow)
	   && (!internal_equal_trapping_problems
	       (Qglyph, "bad subwindow instantiator",
		/* in this case we really don't want to be
		   interrupted by QUIT because we care about
		   the return value; and we know that any loops
		   will ultimately cause errors to be issued.
		   We specify a retval of 1 in that case so that
		   the glyph code doesn't try to keep reoutputting
		   a bad subwindow. */
		  INHIBIT_QUIT, 0, 1, IMAGE_INSTANCE_WIDGET_ITEMS (ii),
		  IMAGE_INSTANCE_WIDGET_PENDING_ITEMS (ii), 0)
	       || !NILP (IMAGE_INSTANCE_LAYOUT_CHILDREN (ii))
	       || IMAGE_INSTANCE_WIDGET_ACTION_OCCURRED (ii)))
    return 1;
  else
    return 0;
}

/* Update all the subwindows on a frame. */
void
update_widget_instances (Lisp_Object frame)
{
  struct frame* f;
  Lisp_Object rest;

  /* Its possible for the preceding callback to have deleted the
     frame, so cope with this. */
  if (!FRAMEP (frame) || !FRAME_LIVE_P (XFRAME (frame)))
    return;

  CHECK_FRAME (frame);
  f = XFRAME (frame);

  /* If we get called we know something has changed. */
  LIST_LOOP (rest, XWEAK_LIST_LIST (FRAME_SUBWINDOW_CACHE (f)))
    {
      Lisp_Object widget = XCAR (rest);

      if (XIMAGE_INSTANCE_SUBWINDOW_DISPLAYEDP (widget)
	  &&
	  image_instance_changed (widget))
	{
	  set_image_instance_dirty_p (widget, 1);
	  MARK_FRAME_GLYPHS_CHANGED (f);
	}
    }
}

/* remove a subwindow from its frame */
void
unmap_subwindow (Lisp_Object subwindow)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (subwindow);
  struct frame* f;

  ERROR_CHECK_IMAGE_INSTANCE (subwindow);

  if (!(image_instance_type_to_mask (IMAGE_INSTANCE_TYPE (ii))
	& (IMAGE_WIDGET_MASK | IMAGE_SUBWINDOW_MASK))
      || !IMAGE_INSTANCE_SUBWINDOW_DISPLAYEDP (ii))
    return;

#ifdef DEBUG_WIDGETS
  stderr_out ("unmapping subwindow %p\n", IMAGE_INSTANCE_SUBWINDOW_ID (ii));
#endif
  f = XFRAME (IMAGE_INSTANCE_FRAME (ii));

  /* make sure we don't get expose events */
  register_ignored_expose (f, IMAGE_INSTANCE_DISPLAY_X (ii),
			   IMAGE_INSTANCE_DISPLAY_Y (ii),
			   IMAGE_INSTANCE_DISPLAY_WIDTH (ii),
			   IMAGE_INSTANCE_DISPLAY_HEIGHT (ii));
  IMAGE_INSTANCE_SUBWINDOW_DISPLAYEDP (ii) = 0;

  MAYBE_DEVMETH (XDEVICE (IMAGE_INSTANCE_DEVICE (ii)),
		 unmap_subwindow, (ii));
}

/* show a subwindow in its frame */
void
map_subwindow (Lisp_Object subwindow, int x, int y,
	       struct display_glyph_area *dga)
{
  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (subwindow);

  ERROR_CHECK_IMAGE_INSTANCE (subwindow);

  if (!(image_instance_type_to_mask (IMAGE_INSTANCE_TYPE (ii))
	& (IMAGE_WIDGET_MASK | IMAGE_SUBWINDOW_MASK)))
    return;

#ifdef DEBUG_WIDGETS
  stderr_out ("mapping subwindow %p, %dx%d@%d+%d\n",
	      IMAGE_INSTANCE_SUBWINDOW_ID (ii),
	      dga->width, dga->height, x, y);
#endif
  /* Error check by side effect */
  (void) XFRAME (IMAGE_INSTANCE_FRAME (ii));
  IMAGE_INSTANCE_DISPLAY_X (ii) = x;
  IMAGE_INSTANCE_DISPLAY_Y (ii) = y;
  IMAGE_INSTANCE_DISPLAY_WIDTH (ii) = dga->width;
  IMAGE_INSTANCE_DISPLAY_HEIGHT (ii) = dga->height;

  MAYBE_DEVMETH (DOMAIN_XDEVICE (ii->domain),
		 map_subwindow, (ii, x, y, dga));
  IMAGE_INSTANCE_SUBWINDOW_DISPLAYEDP (ii) = 1;
}

static int
subwindow_possible_dest_types (void)
{
  return IMAGE_SUBWINDOW_MASK;
}

int
subwindow_governing_domain (void)
{
  return GOVERNING_DOMAIN_WINDOW;
}

/* Partially instantiate a subwindow. */
void
subwindow_instantiate (Lisp_Object image_instance, Lisp_Object instantiator,
		       Lisp_Object UNUSED (pointer_fg),
		       Lisp_Object UNUSED (pointer_bg),
		       int dest_mask, Lisp_Object domain)
{
  Lisp_Image_Instance *ii = XIMAGE_INSTANCE (image_instance);
  Lisp_Object device = image_instance_device (image_instance);
  Lisp_Object frame = DOMAIN_FRAME (domain);
  Lisp_Object width = find_keyword_in_vector (instantiator, Q_pixel_width);
  Lisp_Object height = find_keyword_in_vector (instantiator, Q_pixel_height);

  if (NILP (frame))
    invalid_state ("No selected frame", device);

  if (!(dest_mask & IMAGE_SUBWINDOW_MASK))
    incompatible_image_types (instantiator, dest_mask, IMAGE_SUBWINDOW_MASK);

  ii->data = 0;
  IMAGE_INSTANCE_SUBWINDOW_ID (ii) = 0;
  IMAGE_INSTANCE_SUBWINDOW_DISPLAYEDP (ii) = 0;

  if (INTP (width))
    {
      int w = 1;
      if (XINT (width) > 1)
	w = XINT (width);
      IMAGE_INSTANCE_WIDTH (ii) = w;
      IMAGE_INSTANCE_SUBWINDOW_H_RESIZEP (ii) = 0;
    }

  if (INTP (height))
    {
      int h = 1;
      if (XINT (height) > 1)
	h = XINT (height);
      IMAGE_INSTANCE_HEIGHT (ii) = h;
      IMAGE_INSTANCE_SUBWINDOW_V_RESIZEP (ii) = 0;
    }
}

/* This is just a backup in case no-one has assigned a suitable geometry.
   #### It should really query the enclose window for geometry. */
static void
subwindow_query_geometry (Lisp_Object UNUSED (image_instance),
			  int* width, int* height,
			  enum image_instance_geometry UNUSED (disp),
			  Lisp_Object UNUSED (domain))
{
  if (width)	*width = 20;
  if (height)	*height = 20;
}

DEFUN ("subwindowp", Fsubwindowp, 1, 1, 0, /*
Return non-nil if OBJECT is a subwindow.
*/
       (object))
{
  CHECK_IMAGE_INSTANCE (object);
  return (XIMAGE_INSTANCE_TYPE (object) == IMAGE_SUBWINDOW) ? Qt : Qnil;
}

DEFUN ("image-instance-subwindow-id", Fimage_instance_subwindow_id, 1, 1, 0, /*
Return the window id of SUBWINDOW as a number.
*/
       (subwindow))
{
  CHECK_SUBWINDOW_IMAGE_INSTANCE (subwindow);
  return make_int ((EMACS_INT) XIMAGE_INSTANCE_SUBWINDOW_ID (subwindow));
}

DEFUN ("resize-subwindow", Fresize_subwindow, 1, 3, 0, /*
Resize SUBWINDOW to WIDTH x HEIGHT.
If a value is nil that parameter is not changed.
*/
       (subwindow, width, height))
{
  int neww, newh;
  Lisp_Image_Instance* ii;

  CHECK_SUBWINDOW_IMAGE_INSTANCE (subwindow);
  ii = XIMAGE_INSTANCE (subwindow);

  if (NILP (width))
    neww = IMAGE_INSTANCE_WIDTH (ii);
  else
    neww = XINT (width);

  if (NILP (height))
    newh = IMAGE_INSTANCE_HEIGHT (ii);
  else
    newh = XINT (height);

  /* The actual resizing gets done asynchronously by
     update_subwindow. */
  IMAGE_INSTANCE_HEIGHT (ii) = newh;
  IMAGE_INSTANCE_WIDTH (ii) = neww;
  IMAGE_INSTANCE_SIZE_CHANGED (ii) = 1;

  return subwindow;
}

DEFUN ("force-subwindow-map", Fforce_subwindow_map, 1, 1, 0, /*
Generate a Map event for SUBWINDOW.
*/
       (subwindow))
{
  CHECK_SUBWINDOW_IMAGE_INSTANCE (subwindow);
#if 0
  map_subwindow (subwindow, 0, 0);
#endif
  return subwindow;
}


/*****************************************************************************
 *                              display tables                               *
 *****************************************************************************/

/* Get the display tables for use currently on window W with face
   FACE.  #### This will have to be redone.  */

void
get_display_tables (struct window *w, face_index findex,
		    Lisp_Object *face_table, Lisp_Object *window_table)
{
  Lisp_Object tem;
  tem = WINDOW_FACE_CACHEL_DISPLAY_TABLE (w, findex);
  if (UNBOUNDP (tem))
    tem = Qnil;
  if (!LISTP (tem))
    tem = noseeum_cons (tem, Qnil);
  *face_table = tem;
  tem = w->display_table;
  if (UNBOUNDP (tem))
    tem = Qnil;
  if (!LISTP (tem))
    tem = noseeum_cons (tem, Qnil);
  *window_table = tem;
}

Lisp_Object
display_table_entry (Ichar ch, Lisp_Object face_table,
		     Lisp_Object window_table)
{
  Lisp_Object tail;

  /* Loop over FACE_TABLE, and then over WINDOW_TABLE. */
  for (tail = face_table; 1; tail = XCDR (tail))
    {
      Lisp_Object table;
      if (NILP (tail))
	{
	  if (!NILP (window_table))
	    {
	      tail = window_table;
	      window_table = Qnil;
	    }
	  else
	    return Qnil;
	}
      table = XCAR (tail);

      if (VECTORP (table))
	{
	  if (ch < XVECTOR_LENGTH (table) && !NILP (XVECTOR_DATA (table)[ch]))
	    return XVECTOR_DATA (table)[ch];
	  else
	    continue;
	}
      else if (CHAR_TABLEP (table)
	       && XCHAR_TABLE_TYPE (table) == CHAR_TABLE_TYPE_CHAR)
	{
	  return get_char_table (ch, table);
	}
      else if (CHAR_TABLEP (table)
	       && XCHAR_TABLE_TYPE (table) == CHAR_TABLE_TYPE_GENERIC)
	{
	  Lisp_Object gotit = get_char_table (ch, table);
	  if (!NILP (gotit))
	    return gotit;
	  else
	    continue;
	}
      else if (RANGE_TABLEP (table))
	{
	  Lisp_Object gotit = Fget_range_table (make_char (ch), table, Qnil);
	  if (!NILP (gotit))
	    return gotit;
	  else
	    continue;
	}
      else
	ABORT ();
    }
}

/****************************************************************************
 *                        timeouts for animated glyphs                      *
 ****************************************************************************/
static Lisp_Object Qglyph_animated_timeout_handler;

DEFUN ("glyph-animated-timeout-handler", Fglyph_animated_timeout_handler, 1, 1, 0, /*
Callback function for updating animated images.
Don't use this.
*/
       (arg))
{
  CHECK_WEAK_LIST (arg);

  if (!NILP (XWEAK_LIST_LIST (arg)) && !NILP (XCAR (XWEAK_LIST_LIST (arg))))
    {
      Lisp_Object value = XCAR (XWEAK_LIST_LIST (arg));

      if (IMAGE_INSTANCEP (value))
	{
	  Lisp_Image_Instance* ii = XIMAGE_INSTANCE (value);

	  if (COLOR_PIXMAP_IMAGE_INSTANCEP (value)
	      &&
	      IMAGE_INSTANCE_PIXMAP_MAXSLICE (ii) > 1
	      &&
	      !disable_animated_pixmaps)
	    {
	      /* Increment the index of the image slice we are currently
		 viewing. */
	      IMAGE_INSTANCE_PIXMAP_SLICE (ii) =
		(IMAGE_INSTANCE_PIXMAP_SLICE (ii) + 1)
		% IMAGE_INSTANCE_PIXMAP_MAXSLICE (ii);
	      /* We might need to kick redisplay at this point - but we
		 also might not. */
	      MARK_DEVICE_FRAMES_GLYPHS_CHANGED
		(XDEVICE (image_instance_device (value)));
	      /* Cascade dirtiness so that we can have an animated glyph in a layout
		 for instance. */
	      set_image_instance_dirty_p (value, 1);
	    }
	}
    }
  return Qnil;
}

Lisp_Object
add_glyph_animated_timeout (EMACS_INT tickms, Lisp_Object image)
{
  Lisp_Object ret = Qnil;

  if (tickms > 0 && IMAGE_INSTANCEP (image))
    {
      double ms = ((double)tickms) / 1000.0;
      struct gcpro gcpro1;
      Lisp_Object holder = make_weak_list (WEAK_LIST_SIMPLE);

      GCPRO1 (holder);
      XWEAK_LIST_LIST (holder) = Fcons (image, Qnil);

      ret = Fadd_timeout (make_float (ms),
			  Qglyph_animated_timeout_handler,
			  holder, make_float (ms));

      UNGCPRO;
    }
  return ret;
}

void
disable_glyph_animated_timeout (int i)
{
  Fdisable_timeout (make_int (i));
}


/*****************************************************************************
 *                              initialization                               *
 *****************************************************************************/

void
glyph_objects_create (void)
{
  OBJECT_HAS_METHOD (glyph, getprop);
  OBJECT_HAS_METHOD (glyph, putprop);
  OBJECT_HAS_METHOD (glyph, remprop);
  OBJECT_HAS_METHOD (glyph, plist);
}

void
syms_of_glyphs (void)
{
  INIT_LISP_OBJECT (glyph);
  INIT_LISP_OBJECT (image_instance);

  /* image instantiators */

  DEFSUBR (Fimage_instantiator_format_list);
  DEFSUBR (Fvalid_image_instantiator_format_p);
  DEFSUBR (Fset_console_type_image_conversion_list);
  DEFSUBR (Fconsole_type_image_conversion_list);

  DEFKEYWORD (Q_file);
  DEFKEYWORD (Q_face);
  DEFKEYWORD (Q_pixel_height);
  DEFKEYWORD (Q_pixel_width);

#ifdef HAVE_XPM
  DEFKEYWORD (Q_color_symbols);
#endif
#ifdef HAVE_WINDOW_SYSTEM
  DEFKEYWORD (Q_mask_file);
  DEFKEYWORD (Q_mask_data);
  DEFKEYWORD (Q_hotspot_x);
  DEFKEYWORD (Q_hotspot_y);
  DEFKEYWORD (Q_foreground);
  DEFKEYWORD (Q_background);
#endif
  /* image specifiers */

  DEFSUBR (Fimage_specifier_p);
  /* Qimage in general.c */

  /* image instances */

  DEFSYMBOL_MULTIWORD_PREDICATE (Qimage_instancep);

  DEFSYMBOL (Qnothing_image_instance_p);
  DEFSYMBOL (Qtext_image_instance_p);
  DEFSYMBOL (Qmono_pixmap_image_instance_p);
  DEFSYMBOL (Qcolor_pixmap_image_instance_p);
  DEFSYMBOL (Qpointer_image_instance_p);
  DEFSYMBOL (Qwidget_image_instance_p);
  DEFSYMBOL (Qsubwindow_image_instance_p);

  DEFSUBR (Fmake_image_instance);
  DEFSUBR (Fimage_instance_p);
  DEFSUBR (Fimage_instance_type);
  DEFSUBR (Fvalid_image_instance_type_p);
  DEFSUBR (Fimage_instance_type_list);
  DEFSUBR (Fimage_instance_name);
  DEFSUBR (Fimage_instance_domain);
  DEFSUBR (Fimage_instance_instantiator);
  DEFSUBR (Fimage_instance_string);
  DEFSUBR (Fimage_instance_file_name);
  DEFSUBR (Fimage_instance_mask_file_name);
  DEFSUBR (Fimage_instance_depth);
  DEFSUBR (Fimage_instance_height);
  DEFSUBR (Fimage_instance_width);
  DEFSUBR (Fimage_instance_hotspot_x);
  DEFSUBR (Fimage_instance_hotspot_y);
  DEFSUBR (Fimage_instance_foreground);
  DEFSUBR (Fimage_instance_background);
  DEFSUBR (Fimage_instance_property);
  DEFSUBR (Fcolorize_image_instance);
  /* subwindows */
  DEFSUBR (Fsubwindowp);
  DEFSUBR (Fimage_instance_subwindow_id);
  DEFSUBR (Fresize_subwindow);
  DEFSUBR (Fforce_subwindow_map);

  /* Qnothing defined as part of the "nothing" image-instantiator
     type. */
  /* Qtext defined in general.c */
  DEFSYMBOL (Qmono_pixmap);
  DEFSYMBOL (Qcolor_pixmap);
  /* Qpointer defined in general.c */

  /* glyphs */

  DEFSYMBOL (Qglyphp);
  DEFSYMBOL (Qcontrib_p);
  DEFSYMBOL (Qbaseline);

  DEFSYMBOL (Qbuffer_glyph_p);
  DEFSYMBOL (Qpointer_glyph_p);
  DEFSYMBOL (Qicon_glyph_p);

  DEFSYMBOL (Qconst_glyph_variable);

  DEFSUBR (Fglyph_type);
  DEFSUBR (Fvalid_glyph_type_p);
  DEFSUBR (Fglyph_type_list);
  DEFSUBR (Fglyphp);
  DEFSUBR (Fmake_glyph_internal);
  DEFSUBR (Fglyph_width);
  DEFSUBR (Fglyph_ascent);
  DEFSUBR (Fglyph_descent);
  DEFSUBR (Fglyph_height);
  DEFSUBR (Fset_instantiator_property);

  /* Qbuffer defined in general.c. */
  /* Qpointer defined above */

  /* Unfortunately, timeout handlers must be lisp functions.  This is
     for animated glyphs. */
  DEFSYMBOL (Qglyph_animated_timeout_handler);
  DEFSUBR (Fglyph_animated_timeout_handler);

  /* Errors */
  DEFERROR_STANDARD (Qimage_conversion_error, Qconversion_error);
}

void
specifier_type_create_image (void)
{
  /* image specifiers */

  INITIALIZE_SPECIFIER_TYPE_WITH_DATA (image, "image", "imagep");

  SPECIFIER_HAS_METHOD (image, create);
  SPECIFIER_HAS_METHOD (image, mark);
  SPECIFIER_HAS_METHOD (image, instantiate);
  SPECIFIER_HAS_METHOD (image, validate);
  SPECIFIER_HAS_METHOD (image, after_change);
  SPECIFIER_HAS_METHOD (image, going_to_add);
  SPECIFIER_HAS_METHOD (image, copy_instantiator);
}

void
reinit_specifier_type_create_image (void)
{
  REINITIALIZE_SPECIFIER_TYPE (image);
}


static const struct memory_description iike_description_1[] = {
  { XD_LISP_OBJECT, offsetof (ii_keyword_entry, keyword) },
  { XD_END }
};

static const struct sized_memory_description iike_description = {
  sizeof (ii_keyword_entry),
  iike_description_1
};

static const struct memory_description iiked_description_1[] = {
  XD_DYNARR_DESC (ii_keyword_entry_dynarr, &iike_description),
  { XD_END }
};

static const struct sized_memory_description iiked_description = {
  sizeof (ii_keyword_entry_dynarr),
  iiked_description_1
};

static const struct memory_description iife_description_1[] = {
  { XD_LISP_OBJECT, offsetof (image_instantiator_format_entry, symbol) },
  { XD_LISP_OBJECT, offsetof (image_instantiator_format_entry, device) },
  { XD_BLOCK_PTR,  offsetof (image_instantiator_format_entry, meths), 1,
    { &iim_description } },
  { XD_END }
};

static const struct sized_memory_description iife_description = {
  sizeof (image_instantiator_format_entry),
  iife_description_1
};

static const struct memory_description iifed_description_1[] = {
  XD_DYNARR_DESC (image_instantiator_format_entry_dynarr, &iife_description),
  { XD_END }
};

static const struct sized_memory_description iifed_description = {
  sizeof (image_instantiator_format_entry_dynarr),
  iifed_description_1
};

static const struct memory_description iim_description_1[] = {
  { XD_LISP_OBJECT, offsetof (struct image_instantiator_methods, symbol) },
  { XD_LISP_OBJECT, offsetof (struct image_instantiator_methods, device) },
  { XD_BLOCK_PTR,  offsetof (struct image_instantiator_methods, keywords), 1,
    { &iiked_description } },
  { XD_BLOCK_PTR,  offsetof (struct image_instantiator_methods, consoles), 1,
    { &cted_description } },
  { XD_END }
};

const struct sized_memory_description iim_description = {
  sizeof (struct image_instantiator_methods),
  iim_description_1
};

void
image_instantiator_format_create (void)
{
  /* image instantiators */

  the_image_instantiator_format_entry_dynarr =
    Dynarr_new (image_instantiator_format_entry);

  Vimage_instantiator_format_list = Qnil;
  staticpro (&Vimage_instantiator_format_list);

  dump_add_root_block_ptr (&the_image_instantiator_format_entry_dynarr, &iifed_description);

  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (nothing, "nothing");

  IIFORMAT_HAS_METHOD (nothing, possible_dest_types);
  IIFORMAT_HAS_METHOD (nothing, instantiate);

  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (inherit, "inherit");

  IIFORMAT_HAS_METHOD (inherit, validate);
  IIFORMAT_HAS_METHOD (inherit, normalize);
  IIFORMAT_HAS_METHOD (inherit, possible_dest_types);
  IIFORMAT_HAS_METHOD (inherit, instantiate);

  IIFORMAT_VALID_KEYWORD (inherit, Q_face, check_valid_face);

  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (string, "string");

  IIFORMAT_HAS_METHOD (string, validate);
  IIFORMAT_HAS_SHARED_METHOD (string, governing_domain, subwindow);
  IIFORMAT_HAS_METHOD (string, possible_dest_types);
  IIFORMAT_HAS_METHOD (string, instantiate);

  IIFORMAT_VALID_KEYWORD (string, Q_data, check_valid_string);
  /* Do this so we can set strings. */
  /* #### Andy, what is this?  This is a bogus format and should not be
     visible to the user. */
  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (text, "text");
  IIFORMAT_HAS_METHOD (text, update);
  IIFORMAT_HAS_METHOD (text, query_geometry);

  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (formatted_string, "formatted-string");

  IIFORMAT_HAS_METHOD (formatted_string, validate);
  IIFORMAT_HAS_METHOD (formatted_string, possible_dest_types);
  IIFORMAT_HAS_METHOD (formatted_string, instantiate);
  IIFORMAT_VALID_KEYWORD (formatted_string, Q_data, check_valid_string);

  /* Do this so pointers have geometry. */
  /* #### Andy, what is this?  This is a bogus format and should not be
     visible to the user. */
  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (pointer, "pointer");
  IIFORMAT_HAS_SHARED_METHOD (pointer, query_geometry, subwindow);

  /* subwindows */
  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (subwindow, "subwindow");
  IIFORMAT_HAS_METHOD (subwindow, possible_dest_types);
  IIFORMAT_HAS_METHOD (subwindow, governing_domain);
  IIFORMAT_HAS_METHOD (subwindow, instantiate);
  IIFORMAT_HAS_METHOD (subwindow, query_geometry);
  IIFORMAT_VALID_KEYWORD (subwindow, Q_pixel_width, check_valid_int);
  IIFORMAT_VALID_KEYWORD (subwindow, Q_pixel_height, check_valid_int);

#ifdef HAVE_WINDOW_SYSTEM
  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (xbm, "xbm");

  IIFORMAT_HAS_METHOD (xbm, validate);
  IIFORMAT_HAS_METHOD (xbm, normalize);
  IIFORMAT_HAS_METHOD (xbm, possible_dest_types);

  IIFORMAT_VALID_KEYWORD (xbm, Q_data, check_valid_xbm_inline);
  IIFORMAT_VALID_KEYWORD (xbm, Q_file, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xbm, Q_mask_data, check_valid_xbm_inline);
  IIFORMAT_VALID_KEYWORD (xbm, Q_mask_file, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xbm, Q_hotspot_x, check_valid_int);
  IIFORMAT_VALID_KEYWORD (xbm, Q_hotspot_y, check_valid_int);
  IIFORMAT_VALID_KEYWORD (xbm, Q_foreground, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xbm, Q_background, check_valid_string);
#endif /* HAVE_WINDOW_SYSTEM */

#ifdef HAVE_XFACE
  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (xface, "xface");

  IIFORMAT_HAS_METHOD (xface, validate);
  IIFORMAT_HAS_METHOD (xface, normalize);
  IIFORMAT_HAS_METHOD (xface, possible_dest_types);

  IIFORMAT_VALID_KEYWORD (xface, Q_data, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xface, Q_file, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xface, Q_mask_data, check_valid_xbm_inline);
  IIFORMAT_VALID_KEYWORD (xface, Q_mask_file, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xface, Q_hotspot_x, check_valid_int);
  IIFORMAT_VALID_KEYWORD (xface, Q_hotspot_y, check_valid_int);
  IIFORMAT_VALID_KEYWORD (xface, Q_foreground, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xface, Q_background, check_valid_string);
#endif

#ifdef HAVE_XPM
  INITIALIZE_IMAGE_INSTANTIATOR_FORMAT (xpm, "xpm");

  IIFORMAT_HAS_METHOD (xpm, validate);
  IIFORMAT_HAS_METHOD (xpm, normalize);
  IIFORMAT_HAS_METHOD (xpm, possible_dest_types);

  IIFORMAT_VALID_KEYWORD (xpm, Q_data, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xpm, Q_file, check_valid_string);
  IIFORMAT_VALID_KEYWORD (xpm, Q_color_symbols, check_valid_xpm_color_symbols);
#endif /* HAVE_XPM */
}

void
reinit_vars_of_glyphs (void)
{
#ifndef NEW_GC
  the_expose_ignore_blocktype =
    Blocktype_new (struct expose_ignore_blocktype);
#endif /* not NEW_GC */

  hold_ignored_expose_registration = 0;
}


void
vars_of_glyphs (void)
{
  Vthe_nothing_vector = vector1 (Qnothing);
  staticpro (&Vthe_nothing_vector);

  /* image instances */

  Vimage_instance_type_list = Fcons (Qnothing,
				     list6 (Qtext, Qmono_pixmap, Qcolor_pixmap,
					    Qpointer, Qsubwindow, Qwidget));
  staticpro (&Vimage_instance_type_list);

  /* The Qunbound name means this test is not available from Lisp. */
  Vimage_instance_hash_table_test
    = define_hash_table_test (Qunbound, instantiator_eq_equal,
                              instantiator_eq_hash, Qunbound, Qunbound);
  staticpro (&Vimage_instance_hash_table_test);

  /* glyphs */

  Vglyph_type_list = list3 (Qbuffer, Qpointer, Qicon);
  staticpro (&Vglyph_type_list);

#ifdef HAVE_WINDOW_SYSTEM
  Fprovide (Qxbm);
#endif
#ifdef HAVE_XPM
  Fprovide (Qxpm);

  DEFVAR_LISP ("xpm-color-symbols", &Vxpm_color_symbols /*
Definitions of logical color-names used when reading XPM files.
Elements of this list should be of the form (COLOR-NAME FORM-TO-EVALUATE).
The COLOR-NAME should be a string, which is the name of the color to define;
the FORM should evaluate to a `color' specifier object, or a string to be
passed to `make-color-instance'.  If a loaded XPM file references a symbolic
color called COLOR-NAME, it will display as the computed color instead.

The default value of this variable defines the logical color names
\"foreground\" and \"background\" to be the colors of the `default' face.
*/ );
  Vxpm_color_symbols = Qnil; /* initialized in x-faces.el */
#endif /* HAVE_XPM */
#ifdef HAVE_XFACE
  Fprovide (Qxface);
#endif

  DEFVAR_BOOL ("disable-animated-pixmaps", &disable_animated_pixmaps /*
Whether animated pixmaps should be animated.
Default is t.
*/);
  disable_animated_pixmaps = 0;
}

void
specifier_vars_of_glyphs (void)
{
  /* #### Can we GC here? The set_specifier_* calls definitely need */
  /* protection. */
  /* display tables */

  DEFVAR_SPECIFIER ("current-display-table", &Vcurrent_display_table /*
*The display table currently in use.
This is a specifier; use `set-specifier' to change it.

Display tables are used to control how characters are displayed.  Each
time that redisplay processes a character, it is looked up in all the
display tables that apply (obtained by calling `specifier-instance' on
`current-display-table' and any overriding display tables specified in
currently active faces).  The first entry found that matches the
character determines how the character is displayed.  If there is no
matching entry, the default display method is used. (Non-control
characters are displayed as themselves and control characters are
displayed according to the buffer-local variable `ctl-arrow'.  Control
characters are further affected by `control-arrow-glyph' and
`octal-escape-glyph'.)

Each instantiator in this specifier and the display-table specifiers
in faces is a display table or a list of such tables.  If a list, each
table will be searched in turn for an entry matching a particular
character.  Each display table is one of

-- a vector, specifying values for characters starting at 0
-- a char table, either of type `char' or `generic'
-- a range table

Each entry in a display table should be one of

-- nil (this entry is ignored and the search continues)
-- a character (use this character; if it happens to be the same as
   the original character, default processing happens, otherwise
   redisplay attempts to display this character directly;
   #### At some point recursive display-table lookup will be
   implemented.)
-- a string (display each character in the string directly;
   #### At some point recursive display-table lookup will be
   implemented.)
-- a glyph (display the glyph;
   #### At some point recursive display-table lookup will be
   implemented when a string glyph is being processed.)
-- a cons of the form (format "STRING") where STRING is a printf-like
   spec used to process the character. #### Unfortunately no
   formatting directives other than %% are implemented.
-- a vector (each element of the vector is processed recursively;
   in such a case, nil elements in the vector are simply ignored)

#### At some point in the near future, display tables are likely to
be expanded to include other features, such as referencing characters
in particular fonts and allowing the character search to continue
all the way up the chain of specifier instantiators.  These features
are necessary to properly display Unicode characters.
*/ );
  Vcurrent_display_table = Fmake_specifier (Qdisplay_table);
  set_specifier_fallback (Vcurrent_display_table,
			  list1 (Fcons (Qnil, Qnil)));
  set_specifier_caching (Vcurrent_display_table,
			 offsetof (struct window, display_table),
			 some_window_value_changed,
			 0, 0, 0);
}

void
complex_vars_of_glyphs (void)
{
  /* Partially initialized in glyphs-x.c, glyphs.el */
  DEFVAR_LISP ("truncation-glyph", &Vtruncation_glyph /*
What to display at the end of truncated lines.
*/ );
  Vtruncation_glyph = allocate_glyph (GLYPH_BUFFER, redisplay_glyph_changed);

  /* Partially initialized in glyphs-x.c, glyphs.el */
  DEFVAR_LISP ("continuation-glyph", &Vcontinuation_glyph /*
What to display at the end of wrapped lines.
*/ );
  Vcontinuation_glyph = allocate_glyph (GLYPH_BUFFER, redisplay_glyph_changed);

  /* The octal-escape glyph, control-arrow-glyph and
     invisible-text-glyph are completely initialized in glyphs.el */

  DEFVAR_LISP ("octal-escape-glyph", &Voctal_escape_glyph /*
What to prefix character codes displayed in octal with.
*/);
  Voctal_escape_glyph = allocate_glyph (GLYPH_BUFFER, redisplay_glyph_changed);

  DEFVAR_LISP ("control-arrow-glyph", &Vcontrol_arrow_glyph /*
What to use as an arrow for control characters.
*/);
  Vcontrol_arrow_glyph = allocate_glyph (GLYPH_BUFFER,
					 redisplay_glyph_changed);

  DEFVAR_LISP ("invisible-text-glyph", &Vinvisible_text_glyph /*
What to use to indicate the presence of invisible text.
This is the glyph that is displayed when an ellipsis is called for
\(see `selective-display-ellipses' and `buffer-invisibility-spec').
Normally this is three dots ("...").
*/);
  Vinvisible_text_glyph = allocate_glyph (GLYPH_BUFFER,
					  redisplay_glyph_changed);

  /* Partially initialized in glyphs.el */
  DEFVAR_LISP ("hscroll-glyph", &Vhscroll_glyph /*
What to display at the beginning of horizontally scrolled lines.
*/);
  Vhscroll_glyph = allocate_glyph (GLYPH_BUFFER, redisplay_glyph_changed);

  /* Partially initialized in glyphs-x.c, glyphs.el */
  DEFVAR_LISP ("xemacs-logo", &Vxemacs_logo /*
The glyph used to display the XEmacs logo at startup.
*/ );
  Vxemacs_logo = allocate_glyph (GLYPH_BUFFER, 0);
}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.