File: NSImage.m

package info (click to toggle)
gnustep-gui 0.25.0-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 13,088 kB
  • ctags: 3,417
  • sloc: objc: 153,800; ansic: 18,239; cpp: 579; yacc: 462; makefile: 143; sh: 5
file content (2490 lines) | stat: -rw-r--r-- 66,301 bytes parent folder | download
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
/** <title>NSImage</title>

   <abstract>Load, manipulate and display images</abstract>

   Copyright (C) 1996-2016 Free Software Foundation, Inc.
   
   Author: Adam Fedor <fedor@colorado.edu>
   Date: Feb 1996
   
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
   Boston, MA 02110-1301, USA.
*/

#include "config.h"
#include <string.h>
#include <math.h>

#import <Foundation/NSArray.h>
#import <Foundation/NSBundle.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSException.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSKeyedArchiver.h>
#import <Foundation/NSLock.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>

#import "AppKit/NSImage.h"

#import "AppKit/AppKitExceptions.h"
#import "AppKit/NSAffineTransform.h"
#import "AppKit/NSBitmapImageRep.h"
#import "AppKit/NSCachedImageRep.h"
#import "AppKit/NSColor.h"
#import "AppKit/NSPasteboard.h"
#import "AppKit/NSPrintOperation.h"
#import "AppKit/NSScreen.h"
#import "AppKit/NSView.h"
#import "AppKit/NSWindow.h"
#import "AppKit/DPSOperators.h"
#import "GNUstepGUI/GSDisplayServer.h"
#import "GSThemePrivate.h"

BOOL NSImageForceCaching = NO; /* use on missmatch */

static NSDictionary		*nsmapping = nil;

@interface NSView (Private)
- (void) _lockFocusInContext: (NSGraphicsContext *)ctxt inRect: (NSRect)rect;
@end

@implementation NSBundle (NSImageAdditions)

static NSArray*
imageTypes()
{
  NSArray   *types;

  /* If the extension is one of the image types,
   * remove it from the name and place it in the
   * type argument.
   */
  types = [[[GSTheme theme] imageClass] imageUnfilteredFileTypes];
  if (nil == types)
    {
      types = [NSImage imageUnfilteredFileTypes]; 
    }
  return types;
}

static void
fixupImageNameAndType(NSString **name, NSString **type)
{
  NSString      *ext = [*name pathExtension];

  if ([ext length] > 0)
    {
      /* If the extension is one of the image types,
       * remove it from the name and place it in the
       * type argument.
       */
      if ([imageTypes() indexOfObject: ext] != NSNotFound)
        {
          *type = ext;
          *name = [*name stringByDeletingPathExtension];
        }
    }
}

- (NSString *) _pathForImageNamed: (NSString *)aName 
                           ofType: (NSString *)ext 
                     subdirectory: (NSString *)aDir
                         inBundle: (NSBundle *)aBundle
{
  NSEnumerator  *e;
  id            o;

  if (ext != nil)
    {
      return [aBundle pathForResource: aName ofType: ext inDirectory: aDir];
    }

  e = [imageTypes() objectEnumerator];
  while ((o = [e nextObject]) != nil)
    {
      NSString  *path;

      path = [aBundle pathForResource: aName ofType: o inDirectory: aDir];
      if ([path length] > 0)
        {
          return path;
        }
    }
  return nil;
}

- (NSString *) _pathForLibraryImageNamed: (NSString *)aName 
                                  ofType: (NSString *)ext 
                             inDirectory: (NSString *)aDir
{
  NSEnumerator *e;
  id            o;

  if (ext != nil)
    {
      return [NSBundle pathForLibraryResource: aName
                                       ofType: ext
                                  inDirectory: aDir];
    }

  e = [imageTypes() objectEnumerator];
  while ((o = [e nextObject]) != nil)
    {
      NSString *path;

      path = [NSBundle pathForLibraryResource: aName
                                       ofType: o
                                  inDirectory: aDir];
      if ([path length] > 0)
        {
          return path;
        }
    }

  return nil;
}

- (NSString *) _pathForSystemImageNamed: (NSString *)realName 
                                 ofType: (NSString *)ext
{
  NSString      *path;

  path = [self _pathForLibraryImageNamed: realName 
                                  ofType: ext 
                             inDirectory: @"Images"];  

  /* If not found then search in system using the reverse NSImage nsmapping */
  if (nil == path)
    {
      NSEnumerator      *e;
      NSString          *aliasName;

      e = [[nsmapping allKeysForObject: realName] objectEnumerator];
      while ((aliasName = [e nextObject]) != nil)
        {
          path = [self _pathForLibraryImageNamed: aliasName 
                                          ofType: ext 
                                     inDirectory: @"Images"];

          if (path != nil)
            {
              break;
            }
        }
    }

  return path;
}

/*
 * nsmapping.strings maps alternative image naming schemes to the GSTheme 
 * standard image naming scheme. For example, NSSwitch (from OpenStep) and 
 * common_SwitchOff (from GNUstep) are mapped to GSSwitch. In nameDict that 
 * tracks image instances, the keys are image names from GSTheme such as 
 * GSSwitch or additional icon names such NSApplicationIcon or 
 * NSToolbarShowColors. In the long run, it would be cleaner to move built-in 
 * theme images into a GNUstep.theme bundle.
 *
 * If you pass NSSwitch to +imageNamed:, nsmapping is used to get GSSwitch as 
 * the real name, then _pathForImageNamed: will look up the image first in the 
 * theme and fall back on the Library images. For the library images, we do a 
 * reverse lookup in nsmapping (using allKeysForObject:) to get the image file 
 * name (e.g. from GSSwitch to common_SwitchOff). This reverse lookup is 
 * similar to the one supported for getting image file names from the 
 * bundle, this reverse lookup could be handled by GSTheme rather than being 
 * 
 * The type received in argument is meaningfull for searching image files 
 * using the proposed image name, but useless otherwise. 
 */
- (NSString *) _pathForThemeImageNamed: (NSString *)name 
                                ofType: (NSString *)ext 
{
  GSTheme       *theme;
  NSDictionary  *themeMapping;
  NSString      *mappedName;
  NSString      *path = nil;

  theme = [GSTheme theme];
  themeMapping = [[theme infoDictionary] objectForKey: @"GSThemeImages"];
  mappedName = [themeMapping objectForKey: name];

  /* First search among the theme images using the GSTheme mapping */
  if (mappedName != nil)
    {
      NSString *extension = nil;
      NSString *proposedName = mappedName;

      fixupImageNameAndType(&proposedName, &extension);

      /* If the image file name from the theme mapping uses an extension,
       * this extension is used to look up the path. If the image file
       * cannot be found, _pathForImageNamed:ofType:subdirectory:inBundle:
       * searches an image file for the file extensions from -imageFileTypes.
       */
      path = [self _pathForImageNamed: proposedName
                               ofType: extension 
                         subdirectory: @"ThemeImages"
                             inBundle: [theme bundle]];
    }

  /* If not found, search among the theme images using the reverse NSImage 
   * mapping (for GNUstep and OpenStep image names such as common_SwitchOff 
   * or NSSwitch)
   */
  if (nil == path)
    {
      NSEnumerator      *e;
      NSString          *aliasName;

      e = [[nsmapping allKeysForObject: name] objectEnumerator];
      while (nil == path && (aliasName = [e nextObject]) != nil)
        {
          NSAssert([[aliasName pathExtension] length] == 0,
            @"nsmapping.strings "
            "must include no extensions in image file names");

          path = [self _pathForImageNamed: aliasName 
                                   ofType: nil
                             subdirectory: @"ThemeImages"
                                 inBundle: [theme bundle]];
        }
    }

  /* If not found, search among the theme images using the image name directly
   */
  if (path == nil)
    {
      path = [self _pathForImageNamed: name 
                               ofType: ext 
                         subdirectory: @"ThemeImages" 
                             inBundle: [theme bundle]];
    }

  return path;   
}

- (NSString*) pathForImageResource: (NSString*)name
{
  NSString      *ext = nil;
  NSString      *path = nil;
  NSString      *ident;

  fixupImageNameAndType(&name, &ext);
  if (nil != (ident = [self bundleIdentifier]))
    {
      NSString  *subdir;

      subdir = [@"ThemeImages" stringByAppendingPathComponent: ident];
      path = [self _pathForImageNamed: name
                               ofType: ext
                         subdirectory: subdir
                             inBundle: [[GSTheme theme] bundle]];
    }
  if (nil == path)
    {
      path = [self _pathForImageNamed: name
                               ofType: ext
                         subdirectory: nil
                             inBundle: self];
      if (nil == path)
        {
          path = [self _pathForThemeImageNamed: name ofType: ext];
          if (nil == path)
            {
              path = [self _pathForSystemImageNamed: name ofType: ext];
            }
        }
    }
  return path;
}

@end

@interface GSRepData : NSObject
{
@public
  NSImageRep *rep;
  NSImageRep *original;
  NSColor *bg;
}
@end

@implementation GSRepData
- (id) copyWithZone: (NSZone*)z
{
  GSRepData *c = (GSRepData*)NSCopyObject(self, 0, z);

  if (c->rep)
    c->rep = [c->rep copyWithZone: z];
  if (c->bg)
    c->bg = [c->bg copyWithZone: z];
  return c;
}

- (void) dealloc
{
  TEST_RELEASE(rep);
  TEST_RELEASE(bg);
  [super dealloc];
}
@end

/* Class variables and functions for class methods */
static NSRecursiveLock		*imageLock = nil;
static NSMutableDictionary	*nameDict = nil;
static NSColor			*clearColor = nil;
static Class cachedClass = 0;
static Class bitmapClass = 0;
// Cache for the supported file types
static NSArray *imageUnfilteredFileTypes = nil;
static NSArray *imageFileTypes = nil;
static NSArray *imageUnfilteredPasteboardTypes = nil;
static NSArray *imagePasteboardTypes = nil;

static NSArray *iterate_reps_for_types(NSArray *imageReps, SEL method);

/* Find the GSRepData object holding a representation */
static GSRepData*
repd_for_rep(NSArray *_reps, NSImageRep *rep)
{
  NSEnumerator *enumerator = [_reps objectEnumerator];
  IMP nextImp = [enumerator methodForSelector: @selector(nextObject)];
  GSRepData *repd;

  while ((repd = (*nextImp)(enumerator, @selector(nextObject))) != nil)
    {
      if (repd->rep == rep)
        {
          return repd;
        }
    }
  [NSException raise: NSInternalInconsistencyException
              format: @"Cannot find stored representation"];
  /* NOT REACHED */
  return nil;
}

@interface NSImage (Private)
+ (void) _clearFileTypeCaches: (NSNotification*)notif;
+ (void) _reloadCachedImages;
- (BOOL) _useFromFile: (NSString *)fileName;
- (BOOL) _loadFromData: (NSData *)data;
- (BOOL) _loadFromFile: (NSString *)fileName;
- (BOOL) _resetAndUseFromFile: (NSString *)fileName;
- (GSRepData*) _cacheForRep: (NSImageRep*)rep;
- (NSCachedImageRep*) _doImageCache: (NSImageRep *)rep;
@end

@implementation NSImage

+ (void) initialize
{
  if (imageLock == nil)
    {
      NSString *path;

      imageLock = [NSRecursiveLock new];
      [imageLock lock];

      // Initial version
      [self setVersion: 1];

      // initialize the class variables
      nameDict = [[NSMutableDictionary alloc] initWithCapacity: 10];
      path = [NSBundle pathForLibraryResource: @"nsmapping"
				       ofType: @"strings"
				  inDirectory: @"Images"];
      if (path)
        nsmapping = RETAIN([[NSString stringWithContentsOfFile: path]
                               propertyListFromStringsFileFormat]);
      clearColor = RETAIN([NSColor clearColor]);
      cachedClass = [NSCachedImageRep class];
      bitmapClass = [NSBitmapImageRep class];
      [[NSNotificationCenter defaultCenter]
	addObserver: self
	   selector: @selector(_clearFileTypeCaches:)
	       name: NSImageRepRegistryChangedNotification
	     object: [NSImageRep class]];
      [imageLock unlock];
    }
}

+ (id) imageNamed: (NSString *)aName
{
  NSImage   *image;
  NSString  *realName;

  [imageLock lock];

  realName = [nsmapping objectForKey: aName];
  if (realName == nil)
    {
      realName = aName;
    }
  image = (NSImage*)[nameDict objectForKey: realName];

  if (image == nil && realName != nil)
    {
      NSString  *path = [[NSBundle mainBundle] pathForImageResource: realName];

      if ([path length] != 0) 
        {
	  image = [[[[GSTheme theme] imageClass] alloc]
	    initByReferencingFile: path];
          if (image != nil)
            {
              [image setName: realName];
              image->_flags.archiveByName = YES;
              AUTORELEASE(image);
            }
        }
    }

  IF_NO_GC([[image retain] autorelease]);
  [imageLock unlock];
  return image;
}

+ (NSImage *) _standardImageWithName: (NSString *)name
{
  NSImage *image = nil;

  image = [NSImage imageNamed: name];
  if (image == nil)
    image = [NSImage imageNamed: [@"common_" stringByAppendingString: name]];
  return image;
}

- (id) init
{
  return [self initWithSize: NSMakeSize(0, 0)];
}

- (id) initWithSize: (NSSize)aSize
{
  if (!(self = [super init]))
    return nil;

  //_flags.archiveByName = NO;
  //_flags.scalable = NO;
  //_flags.dataRetained = NO;
  //_flags.flipDraw = NO;
  if (aSize.width && aSize.height) 
    {
      _size = aSize;
      _flags.sizeWasExplicitlySet = YES;
    }
  //_flags.usesEPSOnResolutionMismatch = NO;
  _flags.colorMatchPreferred = YES;
  _flags.multipleResolutionMatching = YES;
  //_flags.cacheSeparately = NO;
  //_flags.unboundedCacheDepth = NO;
  //_flags.syncLoad = NO;
  _reps = [[NSMutableArray alloc] initWithCapacity: 2];
  ASSIGN(_color, clearColor);
  _cacheMode = NSImageCacheDefault;

  return self;
}

- (id) initByReferencingFile: (NSString *)fileName
{
  if (!(self = [self init]))
    return nil;

  if (![self _useFromFile: fileName])
    {
      RELEASE(self);
      return nil;
    }
  _flags.archiveByName = YES;

  return self;
}

- (id) initWithContentsOfFile: (NSString *)fileName
{
  if (!(self = [self init]))
    return nil;

  _flags.dataRetained = YES;
  if (![self _loadFromFile: fileName])
    {
      RELEASE(self);
      return nil;
    }

  return self;
}

- (id) initWithData: (NSData *)data
{
  if (!(self = [self init]))
    return nil;

  _flags.dataRetained = YES;
  if (![self _loadFromData: data])
    {
      RELEASE(self);
      return nil;
    }

  return self;
}

- (id) initWithBitmapHandle: (void *)bitmap
{
  NSImageRep *rep;
  
  if (!(self = [self init]))
    return nil;

  rep = [[NSBitmapImageRep alloc] initWithBitmapHandle: bitmap];
  if (rep == nil)
    {
      RELEASE(self);
      return nil;
    }

  [self addRepresentation: rep];
  RELEASE(rep);
  return self;
}

- (id)initWithIconHandle:(void *)icon
{
  // Only needed on MS Windows
  NSImageRep *rep;
  
  if (!(self = [self init]))
    return nil;

  rep = [[NSBitmapImageRep alloc] initWithIconHandle: icon];
  if (rep == nil)
    {
      RELEASE(self);
      return nil;
    }

  [self addRepresentation: rep];
  RELEASE(rep);
  return self;
}

- (id) initWithContentsOfURL: (NSURL *)anURL
{
  NSArray *array;

  if (!(self = [self init]))
    return nil;

  array = [NSImageRep imageRepsWithContentsOfURL: anURL];
  if (!array)
    {
      RELEASE(self);
      return nil;
    }

  _flags.dataRetained = YES;
  [self addRepresentations: array];
  return self;
}

- (id) initWithPasteboard: (NSPasteboard *)pasteboard
{
  NSArray *reps;
  if (!(self = [self init]))
    return nil;
  
  reps = [NSImageRep imageRepsWithPasteboard: pasteboard];
  if (reps != nil)
    [self addRepresentations: reps]; 
  else
    {
      NSArray *array = [pasteboard propertyListForType: NSFilenamesPboardType];
      NSString* file; 
      
      if ((array == nil) || ([array count] == 0)
        || (file = [array objectAtIndex: 0]) == nil
        || ![self _loadFromFile: file])
        {
          RELEASE(self);
          return nil;
        } 
    }
  _flags.dataRetained = YES;
  
  return self;
}

- (void) dealloc
{
  if (_name == nil)
    {
      RELEASE(_reps);
      TEST_RELEASE(_fileName);
      RELEASE(_color);
      [super dealloc];
    }
  else
    {
      [self retain];
      NSLog(@"Warning ... attempt to deallocate image with name: %@", _name);
    }
}

- (id) copyWithZone: (NSZone *)zone
{
  NSImage *copy;
  NSArray *reps = [self representations];
  NSEnumerator *enumerator = [reps objectEnumerator];
  NSImageRep *rep;

  copy = (NSImage*)NSCopyObject (self, 0, zone);

  copy->_name = nil;
  RETAIN(_fileName);
  RETAIN(_color);
  copy->_lockedView = nil;
  // FIXME: maybe we should retain if _flags.dataRetained = NO
  copy->_reps = [[NSMutableArray alloc] initWithCapacity: [_reps count]];

  //  Only copy non-cached reps.
  while ((rep = [enumerator nextObject]) != nil)
    {
      if (![rep isKindOfClass: cachedClass])
        {
          [copy addRepresentation: rep];
        }
    }
  
  return copy;
}

- (BOOL) isEqual: (id)anObject
{
  if (self == anObject)
    return YES;
  if (![anObject isKindOfClass: [NSImage class]])
    return NO;

  // FIXME
  return NO;
}

- (NSString*) description
{
  return [NSString stringWithFormat: @"<%@ %p Name=%@ Size=%@ Reps=%@>",
                   [self class],
                   self,
                   [self name],
                   NSStringFromSize([self size]),
                   [self representations]];
}

/* This methd sets the name of an image, updating the global name dictionary
 * to point to the image (or removing an image from the dictionary if the
 * new name is nil).
 */
- (BOOL) setName: (NSString *)aName
{
  [imageLock lock];

  /* The name is already set... nothing to do.
   */
  if (aName == _name || [aName isEqual: _name] == YES)
    {
      [imageLock unlock];
      return YES;
    }

  /* If the new name is already in use by another image,
   * we must do nothing.
   */
  if (aName != nil && [nameDict objectForKey: aName] != nil)
    {
      [imageLock unlock];
      return NO;
    }

  /* If this image had another name, we remove it.
   */
  if (_name != nil)
    {
      /* We retain self in case removing from the dictionary releases us */
      IF_NO_GC([[self retain] autorelease]);
      [nameDict removeObjectForKey: _name]; 
      DESTROY(_name);
    }
  
  /* If the new name is null, there is nothing more to do.
   */
  if (aName == nil)
    {
      [imageLock unlock];
      return NO;
    }

  ASSIGN(_name, aName);

  [nameDict setObject: self forKey: _name];
  
  [imageLock unlock];
  return YES;
}

- (NSString *) name
{
  NSString	*name;

  [imageLock lock];
  name = [[_name retain] autorelease];
  [imageLock unlock];
  return name;
}

- (void) setSize: (NSSize)aSize
{
  _size = aSize;
  _flags.sizeWasExplicitlySet = YES;
}

- (NSSize) size
{
  if (_size.width == 0) 
    {
      NSImageRep *rep = [self bestRepresentationForDevice: nil];

      if (rep)
        _size = [rep size];
      else
        _size = NSZeroSize;
    }
  return _size;
}

- (BOOL) isFlipped
{
  return _flags.flipDraw;
}

- (void) setFlipped: (BOOL)flag
{
  _flags.flipDraw = flag;
}

// Choosing Which Image Representation to Use 
- (void) setUsesEPSOnResolutionMismatch: (BOOL)flag
{
  _flags.useEPSOnResolutionMismatch = flag;
}

- (BOOL) usesEPSOnResolutionMismatch
{
  return _flags.useEPSOnResolutionMismatch;
}

- (void) setPrefersColorMatch: (BOOL)flag
{
  _flags.colorMatchPreferred = flag;
}

- (BOOL) prefersColorMatch
{
  return _flags.colorMatchPreferred;
}

- (void) setMatchesOnMultipleResolution: (BOOL)flag
{
  _flags.multipleResolutionMatching = flag;
}

- (BOOL) matchesOnMultipleResolution
{
  return _flags.multipleResolutionMatching;
}

// Determining How the Image is Stored 
- (void) setCachedSeparately: (BOOL)flag
{
  _flags.cacheSeparately = flag;
}

- (BOOL) isCachedSeparately
{
  return _flags.cacheSeparately;
}

- (void) setDataRetained: (BOOL)flag
{
  _flags.dataRetained = flag;
}

- (BOOL) isDataRetained
{
  return _flags.dataRetained;
}

- (void) setCacheDepthMatchesImageDepth: (BOOL)flag
{
  _flags.unboundedCacheDepth = flag;
}

- (BOOL) cacheDepthMatchesImageDepth
{
  return _flags.unboundedCacheDepth;
}

- (void) setCacheMode: (NSImageCacheMode)mode
{
  _cacheMode = mode;
}

- (NSImageCacheMode) cacheMode
{
  return _cacheMode;
}


// Determining How the Image is Drawn 
- (BOOL) isValid
{
  BOOL valid = NO;
  NSUInteger i, count;

  if (_flags.syncLoad)
    {
      /* Make sure any images that were added with _useFromFile: are loaded
         in and added to the representation list. */
      if (![self _loadFromFile: _fileName])
        return NO;
      _flags.syncLoad = NO;
    }

  /* Go through all our representations and determine if at least one
     is a valid cache */
  // FIXME: Not sure if this is correct
  count = [_reps count];
  for (i = 0; i < count; i++) 
    {
      GSRepData *repd = (GSRepData*)[_reps objectAtIndex: i];

      if (repd->bg != nil || [repd->rep isKindOfClass: cachedClass] == NO)
        {
          valid = YES;
          break;
        }
    }

  return valid;
}

- (void) recache
{
  NSUInteger i;

  i = [_reps count];
  while (i--) 
    {
      GSRepData *repd;

      repd = (GSRepData*)[_reps objectAtIndex: i];
      if (repd->original != nil)
        {
          [_reps removeObjectAtIndex: i];
        }
    }
}

- (void) setScalesWhenResized: (BOOL)flag
{
  // FIXME: This currently breaks NSImage.
  // See the test case in GSTest/Image-test that uses this method.

  // _flags.scalable = flag;
}

- (BOOL) scalesWhenResized
{
  return _flags.scalable;
}

- (void) setBackgroundColor: (NSColor *)aColor
{
  if (aColor == nil)
    {
      aColor = clearColor;
    }
  ASSIGN(_color, aColor);
}

- (NSColor *) backgroundColor
{
  return _color;
}

// Using the Image 
- (void) compositeToPoint: (NSPoint)aPoint 
                operation: (NSCompositingOperation)op
{
  [self compositeToPoint: aPoint
		fromRect: NSZeroRect
	       operation: op
		fraction: 1.0];
}

- (void) compositeToPoint: (NSPoint)aPoint
                 fromRect: (NSRect)aRect
                operation: (NSCompositingOperation)op
{
  [self compositeToPoint: aPoint 
		fromRect: aRect
	       operation: op
		fraction: 1.0];
}

- (void) compositeToPoint: (NSPoint)aPoint
                operation: (NSCompositingOperation)op
                 fraction: (CGFloat)delta
{
  [self compositeToPoint: aPoint 
		fromRect: NSZeroRect
	       operation: op 
		fraction: delta];
}

- (void) compositeToPoint: (NSPoint)aPoint
                 fromRect: (NSRect)srcRect
                operation: (NSCompositingOperation)op
                 fraction: (CGFloat)delta
{
  NSGraphicsContext *ctxt = GSCurrentContext();

  // Calculate the user space scale factor of the current window
  NSView *focusView = [NSView focusView];
  CGFloat scaleFactor = 1.0;
  if (focusView != nil)
    {
      scaleFactor = [[focusView window] userSpaceScaleFactor];
    }

  // Set the CTM to the identity matrix with the current translation
  // and the user space scale factor
  {
    NSAffineTransform *backup = [[ctxt GSCurrentCTM] retain];
    NSAffineTransform *newTransform = [NSAffineTransform transform];
    NSPoint translation = [backup transformPoint: aPoint];
    [newTransform translateXBy: translation.x
			   yBy: translation.y];
    [newTransform scaleBy: scaleFactor];
    
    [ctxt GSSetCTM: newTransform];
    
    [self drawAtPoint: NSMakePoint(0, 0)
	     fromRect: srcRect
	    operation: op
	     fraction: delta];
    
    [ctxt GSSetCTM: backup];

    [backup release];
  }
}

- (void) dissolveToPoint: (NSPoint)aPoint fraction: (CGFloat)aFloat
{
  [self dissolveToPoint: aPoint 
	       fromRect: NSZeroRect
	       fraction: aFloat];
}

- (void) dissolveToPoint: (NSPoint)aPoint
                fromRect: (NSRect)aRect 
                fraction: (CGFloat)aFloat
{
  [self compositeToPoint: aPoint
		fromRect: aRect
	       operation: NSCompositeSourceOver
		fraction: aFloat];
}

- (BOOL) drawRepresentation: (NSImageRep *)imageRep inRect: (NSRect)aRect
{
  BOOL r;
  NSGraphicsContext *ctxt = GSCurrentContext();

  DPSgsave(ctxt);

  if (_color != nil)
    {
      NSRect fillrect = aRect;

      [_color set];
      NSRectFill(fillrect);

      if ([GSCurrentContext() isDrawingToScreen] == NO)
        {
          /* Reset alpha for image drawing. */
          [[NSColor colorWithCalibratedWhite: 1.0 alpha: 1.0] set];
        }
    }

  if (!_flags.scalable)
    r = [imageRep drawAtPoint: aRect.origin];
  else
    r = [imageRep drawInRect: aRect];

  DPSgrestore(ctxt);

  return r;
}

- (void) drawAtPoint: (NSPoint)point
            fromRect: (NSRect)srcRect
           operation: (NSCompositingOperation)op
            fraction: (CGFloat)delta
{
  [self drawInRect: NSMakeRect(point.x, point.y, srcRect.size.width, srcRect.size.height)
	  fromRect: srcRect
	 operation: op
	  fraction: delta
    respectFlipped: NO
	     hints: nil];
}

- (void) drawInRect: (NSRect)rect
{
  [self drawInRect: rect
          fromRect: NSZeroRect
         operation: NSCompositeSourceOver
          fraction: 1.0];
}

- (void) drawInRect: (NSRect)dstRect
           fromRect: (NSRect)srcRect
          operation: (NSCompositingOperation)op
           fraction: (CGFloat)delta
{
  [self drawInRect: dstRect
	  fromRect: srcRect
	 operation: op
	  fraction: delta
    respectFlipped: NO
	     hints: nil];
}

/**
 * Base drawing method in NSImage; all other draw methods call this one
 */
- (void) drawInRect: (NSRect)dstRect // Negative width/height => Nothing draws.
	   fromRect: (NSRect)srcRect
	  operation: (NSCompositingOperation)op
	   fraction: (CGFloat)delta
     respectFlipped: (BOOL)respectFlipped
	      hints: (NSDictionary*)hints
{
  NSImageRep *rep;
  NSGraphicsContext *ctxt;
  NSSize imgSize, repSize;
  NSRect repSrcRect;

  ctxt = GSCurrentContext();
  imgSize = [self size];

  // Handle abbreviated parameters

  if (NSEqualRects(srcRect, NSZeroRect))
    {
      srcRect.size = imgSize;
    }
  if (NSEqualSizes(dstRect.size, NSZeroSize)) // For -drawAtPoint:fromRect:operation:fraction:
    {
      dstRect.size = imgSize;
    }

 if (imgSize.width <= 0 || imgSize.height <= 0)
    return;

  // Select a rep

  rep = [self bestRepresentationForRect: dstRect
				context: ctxt
				  hints: hints];
  if (rep == nil)
    return;

  // Try to cache / get a cached version of the best rep
  
  /** 
   * We only use caching on backends that can efficiently draw a rect from the cache
   * onto the current graphics context respecting the CTM, which is currently cairo.
   */
  if (_cacheMode != NSImageCacheNever &&
      [ctxt supportsDrawGState])
    {
      NSCachedImageRep *cache = [self _doImageCache: rep];
      if (cache != nil)
	{
	  rep = cache;
	}
    }
  
  repSize = [rep size];
  
  // Convert srcRect from image coordinate space to rep coordinate space      
  {
    const CGFloat imgToRepWidthScaleFactor = repSize.width / imgSize.width;
    const CGFloat imgToRepHeightScaleFactor = repSize.height / imgSize.height;
    
    repSrcRect = NSMakeRect(srcRect.origin.x * imgToRepWidthScaleFactor,
			    srcRect.origin.y * imgToRepHeightScaleFactor,
			    srcRect.size.width * imgToRepWidthScaleFactor,
			    srcRect.size.height * imgToRepHeightScaleFactor);
  }
  
  // FIXME: Draw background?
  
  [rep drawInRect: dstRect
	 fromRect: repSrcRect
	operation: op
	 fraction: delta
       respectFlipped: respectFlipped
	    hints: hints];
}

- (void) addRepresentation: (NSImageRep *)imageRep
{
  GSRepData *repd;

  if (imageRep != nil)
    {
      repd = [GSRepData new];
      repd->rep = RETAIN(imageRep);
      [_reps addObject: repd]; 
      RELEASE(repd);
    }
}

- (void) addRepresentations: (NSArray *)imageRepArray
{
  NSUInteger i, count;
  GSRepData *repd;

  count = [imageRepArray count];
  for (i = 0; i < count; i++)
    {
      repd = [GSRepData new];
      repd->rep = RETAIN([imageRepArray objectAtIndex: i]);
      [_reps addObject: repd]; 
      RELEASE(repd);
    }
}

- (void) removeRepresentation: (NSImageRep *)imageRep
{
  NSUInteger i;
  GSRepData *repd;

  i = [_reps count];
  while (i-- > 0)
    {
      repd = (GSRepData*)[_reps objectAtIndex: i];
      if (repd->rep == imageRep)
        {
          [_reps removeObjectAtIndex: i];
        }
      else if (repd->original == imageRep)
        {
          // Remove cached representations for this representation
          // instead of turning them into real ones
          //repd->original = nil;
          [_reps removeObjectAtIndex: i];
        }
    }
}

- (void) lockFocus
{
  [self lockFocusOnRepresentation: nil];
}

- (void) lockFocusOnRepresentation: (NSImageRep *)imageRep
{
  if (_cacheMode != NSImageCacheNever)
    {
      NSWindow *window;
      GSRepData *repd;

      if (NSEqualSizes(NSZeroSize, [self size]))
        [NSException raise: NSImageCacheException
		    format: @"Cannot lock focus on image with size (0, 0)"];
      
      if (imageRep == nil)
        imageRep = [self bestRepresentationForDevice: nil];

      repd = [self _cacheForRep: imageRep];
      if (repd == nil)
	return;

      imageRep = repd->rep;

      window = [(NSCachedImageRep *)imageRep window];
      _lockedView = [window contentView];
      if (_lockedView == nil)
        {
          [NSException raise: NSImageCacheException
                      format: @"Cannot lock focus on nil rep"];
        }

      // FIXME: This is needed to get image caching working while printing. A better solution
      // needs to remove the viewIsPrinting variable from NSView.
      [_lockedView _lockFocusInContext: [window graphicsContext] inRect: [_lockedView bounds]];
      if (repd->bg == nil) 
        {
          NSRect fillrect = NSMakeRect(0, 0, _size.width, _size.height);

          // Clear the background of the cached image, as it is not valid
          if ([_color alphaComponent] < 1.0)
            {
              /* With a Quartz-like alpha model, alpha can't be cleared
                 with a rectfill, so we need to clear the alpha channel
                 explictly. (A compositerect with NSCompositeCopy would
                 be more efficient, but it doesn't seem like it's 
                 implemented correctly in all backends yet (as of 
                 2002-08-23). Also, this will work with both the Quartz-
                 and DPS-model.) */
              NSRectFillUsingOperation(fillrect, NSCompositeClear);
            }

          repd->bg = [_color copy];
      
          if ([repd->bg alphaComponent] == 1.0)
            {
              [imageRep setOpaque: YES];
            }
          else
            {
              [imageRep setOpaque: [repd->original isOpaque]];
            }

          // Fill with background colour and draw repesentation
          [self drawRepresentation: repd->original
                            inRect: fillrect];
        }
    }
}

- (void) unlockFocus
{
  if (_lockedView != nil)
    {
      [_lockedView unlockFocus];
      _lockedView = nil;
    }
}

/* Determine the number of color components in the device and
   filter out reps with a different number of color components.
   
   If the device lacks a color space name, all reps are treated
   as matching.

   If a rep lacks a color space name, it is assumed to match the
   device.

   WARNING: Be careful not to inadvertently mix greyscale and color
   representations in a TIFF. The greyscale representations
   will never be selected as a best rep unless you are drawing on
   a greyscale surface, or all reps in the TIFF are greyscale. 
*/
- (NSMutableArray *) _bestRep: (NSArray *)reps 
               withColorMatch: (NSDictionary*)deviceDescription
{
  NSMutableArray *breps = [NSMutableArray array];
  NSString *deviceColorSpace = [deviceDescription objectForKey: NSDeviceColorSpaceName];

  if (deviceColorSpace != nil)
    {
      NSUInteger deviceColors = NSNumberOfColorComponents(deviceColorSpace);
      NSEnumerator *enumerator = [reps objectEnumerator];  
      NSImageRep *rep;
      while ((rep = [enumerator nextObject]) != nil)
	{
	  if ([rep colorSpaceName] == nil || 
	      NSNumberOfColorComponents([rep colorSpaceName]) == deviceColors)
	    {
	      [breps addObject: rep];
	    }
	}
    }

  /* If there are no matches, pass all the reps */
  if ([breps count] == 0)
    {
      [breps setArray: reps]; 
    }

  return breps;
}

/**
 * Returns YES if x in an integer multiple of y
 */
static BOOL GSIsMultiple(CGFloat x, CGFloat y)
{
  // FIXME: Test when CGFloat is float and make sure this test isn't
  // too strict due to floating point rounding errors.
  return (x/y) == floor(x/y);
}

/**
 * Returns YES if there exist integers p and q such that
 * (baseSize.width * p == size.width) && (baseSize.height * q == size.height)
 */
static BOOL GSSizeIsIntegerMultipleOfSize(NSSize size, NSSize baseSize)
{
  return NSEqualSizes(size, baseSize) ||
    (GSIsMultiple(size.width, baseSize.width) &&
     GSIsMultiple(size.height, baseSize.height));
}

/**
 * Returns {0, 0} if the image rep doesn't have a size set,
 * or the pixelsWide or pixelsHigh are NSImageRepMatchesDevice
 */
static NSSize GSResolutionOfImageRep(NSImageRep *rep)
{
  const int pixelsWide = [rep pixelsWide];
  const int pixelsHigh = [rep pixelsHigh];
  const NSSize repSize = [rep size];

  if (repSize.width == 0 || repSize.height == 0)
    {
      return NSMakeSize(0, 0);
    }
  else if (pixelsWide == NSImageRepMatchesDevice ||
	   pixelsHigh == NSImageRepMatchesDevice)
    {
      return NSMakeSize(0, 0);
    }
  else
    {
      return NSMakeSize(72.0 * (CGFloat)pixelsWide / repSize.width,
			72.0 * (CGFloat)pixelsHigh / repSize.height);
    }
}

/* Find reps that match the resolution (DPI) of the device (including integer
   multiples of the device resplition if [self multipleResolutionMatching]
   is YES).
   
   If there are no DPI matches, use any available vector reps if
   [self usesEPSOnResolutionMismatch] is YES. Otherwise, use the bitmap reps
   that have the highest DPI.
*/
- (NSMutableArray *) _bestRep: (NSArray *)reps 
          withResolutionMatch: (NSDictionary*)deviceDescription
{
  NSMutableArray *breps = [NSMutableArray array];

  NSValue *resolution = [deviceDescription objectForKey: NSDeviceResolution];

  // 1. Look for exact resolution matches, or integer multiples if permitted.

  if (nil != resolution)
    {
      const NSSize dres = [resolution sizeValue];
      
      if (![self matchesOnMultipleResolution])
	{
	  NSImageRep *rep;
	  NSEnumerator *enumerator = [reps objectEnumerator];   
	  
	  while ((rep = [enumerator nextObject]) != nil)
	    {
	      if (NSEqualSizes(GSResolutionOfImageRep(rep), dres))
		{
		  [breps addObject: rep];
		}
	    }
	}
      else // [self matchesOnMultipleResolution]
	{
	  NSMutableArray *integerMultiples = [NSMutableArray array];
	  NSSize closestRes = NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX);
	  NSImageRep *rep;
	  NSEnumerator *enumerator;
	  
	  // Iterate through the reps, keeping track of which ones
	  // have a resolution which is an integer multiple of the device
	  // res, and keep track of the cloest resolution

	  enumerator = [reps objectEnumerator];
	  while ((rep = [enumerator nextObject]) != nil)
	    {
	      const NSSize repRes = GSResolutionOfImageRep(rep);
	      if (GSSizeIsIntegerMultipleOfSize(repRes, dres))
		{
		  const NSSize repResDifference
                    = NSMakeSize(fabs(repRes.width - dres.width),
                      fabs(repRes.height - dres.height));
		  const NSSize closestResolutionDifference
                    = NSMakeSize(fabs(closestRes.width - dres.width),
                      fabs(closestRes.height - dres.height));
		  if (repResDifference.width
                    < closestResolutionDifference.width
                    && repResDifference.height
                    < closestResolutionDifference.height)
		    {
		      closestRes = repRes;
		    }
		  [integerMultiples addObject: rep];
		}
	    }

	  enumerator = [integerMultiples objectEnumerator];
	  while ((rep = [enumerator nextObject]) != nil)
	    {
	      const NSSize repRes = GSResolutionOfImageRep(rep);
	      if (NSEqualSizes(repRes, closestRes))
		{
		  [breps addObject: rep];
		}
	    }
	}
    }

  // 2. If no exact matches found, use vector reps, if they are preferred
  
  if ([breps count] == 0 && [self usesEPSOnResolutionMismatch])
    {
      NSImageRep *rep;
      NSEnumerator *enumerator = [reps objectEnumerator];    
      while ((rep = [enumerator nextObject]) != nil)
	{
	  if ([rep pixelsWide] == NSImageRepMatchesDevice && 
	      [rep pixelsHigh] == NSImageRepMatchesDevice)
	  {
	    [breps addObject: rep];
	  }
	}
    }

  // 3. If there are still no matches, use all of the bitmaps with the highest
  // resolution (DPI)
  
  if ([breps count] == 0)
    {
      NSSize maxRes = NSMakeSize(0,0);
      NSImageRep *rep;
      NSEnumerator *enumerator;

      // Determine maxRes

      enumerator = [reps objectEnumerator];
      while ((rep = [enumerator nextObject]) != nil)
	{
	  const NSSize res = GSResolutionOfImageRep(rep);
	  if (res.width > maxRes.width &&
	      res.height > maxRes.height)
	    {
	      maxRes = res;
	    }
	}

      // Use all reps with maxRes
      enumerator = [reps objectEnumerator];
      while ((rep = [enumerator nextObject]) != nil)
	{
	  const NSSize res = GSResolutionOfImageRep(rep);
	  if (NSEqualSizes(res, maxRes))
	    {
	      [breps addObject: rep];
	    }
	}      
    }

  // 4. If there are still none, use all available reps.
  // Note that this handles using vector reps in the case where there are 
  // no bitmap reps, but [self usesEPSOnResolutionMismatch] is NO.

  if ([breps count] == 0)
    {
      [breps setArray: reps];
    }

  return breps;
}

/* Find the reps that match the bitsPerSample of the device,
   or if none match exactly, return all that have the highest bitsPerSample.

   If the device lacks a bps, all reps are treated as matching.

   If a rep has NSImageRepMatchesDevice as its bps, it is treated as matching.
*/
- (NSMutableArray *) _bestRep: (NSArray *)reps 
                 withBpsMatch: (NSDictionary*)deviceDescription
{
  NSMutableArray *breps = [NSMutableArray array];
  NSNumber *bpsValue = [deviceDescription objectForKey: NSDeviceBitsPerSample];

  if (bpsValue != nil)
    {
      NSInteger deviceBps = [bpsValue integerValue];
      NSInteger maxBps = -1;
      BOOL haveDeviceBps = NO;
      NSImageRep *rep;
      NSEnumerator *enumerator;

      // Determine maxBps

      enumerator = [reps objectEnumerator];
      while ((rep = [enumerator nextObject]) != nil)
	{
	  if ([rep bitsPerSample] > maxBps)
	    {
	      maxBps = [rep bitsPerSample];
	    }
	  if ([rep bitsPerSample] == deviceBps)
	    {
	      haveDeviceBps = YES;
	    }
	}

      // Use all reps with deviceBps if haveDeviceBps is YES,
      // otherwise use all reps with maxBps
      enumerator = [reps objectEnumerator];
      while ((rep = [enumerator nextObject]) != nil)
	{
	  if ([rep bitsPerSample] == NSImageRepMatchesDevice ||
	      (!haveDeviceBps && [rep bitsPerSample] == maxBps) ||
	      (haveDeviceBps && [rep bitsPerSample] == deviceBps))
	    {
	      [breps addObject: rep];
	    }
	}
    }

  /* If there are no matches, pass all the reps */
  if ([breps count] == 0)
    {
      [breps setArray: reps]; 
    }

  return breps;
}

- (NSMutableArray *) _representationsWithCachedImages: (BOOL)flag
{
  NSUInteger count;

  if (_flags.syncLoad)
    {
      /* Make sure any images that were added with _useFromFile: are loaded
         in and added to the representation list. */
      [self _loadFromFile: _fileName];
      _flags.syncLoad = NO;
    }

  count = [_reps count];
  if (count == 0)
    {
      return [NSMutableArray array];
    }
  else
    {
      id repList[count];
      NSUInteger i, j;

      [_reps getObjects: repList];
      j = 0;
      for (i = 0; i < count; i++) 
        {
          if (flag || ((GSRepData*)repList[i])->original == nil)
            {
              repList[j] = ((GSRepData*)repList[i])->rep;
              j++;
            }
        }
      return [NSMutableArray arrayWithObjects: repList count: j];
    }
}

- (NSArray *) _bestRepresentationsForDevice: (NSDictionary*)deviceDescription
{
  NSMutableArray *reps = [self _representationsWithCachedImages: NO];
  
  if (deviceDescription == nil)
    {
      if ([GSCurrentContext() isDrawingToScreen] == YES)
        {
          // Take the device description from the current context.
          deviceDescription = [[[GSCurrentContext() attributes] objectForKey: 
                NSGraphicsContextDestinationAttributeName] 
                                  deviceDescription];
        }
      else if ([NSPrintOperation currentOperation])
        {
          /* FIXME: We could try to use the current printer, 
             but there are many cases where might
             not be printing (EPS, PDF, etc) to a specific device */
        }
    }

  if (_flags.colorMatchPreferred == YES)
    {
      reps = [self _bestRep: reps withColorMatch: deviceDescription];
      reps = [self _bestRep: reps withResolutionMatch: deviceDescription];
    }
  else
    {
      reps = [self _bestRep: reps withResolutionMatch: deviceDescription];
      reps = [self _bestRep: reps withColorMatch: deviceDescription];
    }
  reps = [self _bestRep: reps withBpsMatch: deviceDescription];

  return reps;
}

- (NSImageRep *) bestRepresentationForDevice: (NSDictionary*)deviceDescription
{
  NSArray *reps = [self _bestRepresentationsForDevice: deviceDescription];

  /* If we have more than one match check for a representation whose size
   * matches the image size exactly. Otherwise, arbitrarily choose the first
   * representation. */
  if ([reps count] > 1)
    {
      NSImageRep *rep;
      NSEnumerator *enumerator = [reps objectEnumerator];

      while ((rep = [enumerator nextObject]) != nil)
	{
	  if (NSEqualSizes(_size, [rep size]) == YES)
	    {
	      return rep;
	    }
	}
    }
  
  
  if ([reps count] > 0)
    {
      return [reps objectAtIndex: 0];
    }
  else
    {
      return nil;
    }
}

- (NSImageRep *) bestRepresentationForRect: (NSRect)rect
				   context: (NSGraphicsContext *)context
				     hints: (NSDictionary *)deviceDescription
{
  NSArray *reps = [self _bestRepresentationsForDevice: deviceDescription];
  const NSSize desiredSize = rect.size;
  NSImageRep *bestRep = nil;

  // Pick the smallest rep that is greater than or equal to the
  // desired size.

  {
    NSSize bestSize = NSMakeSize(CGFLOAT_MAX, CGFLOAT_MAX);
    NSImageRep *rep;
    NSEnumerator *enumerator = [reps objectEnumerator];   
    while ((rep = [enumerator nextObject]) != nil)
      {
	const NSSize repSize = [rep size];
	if ((repSize.width >= desiredSize.width)
          && (repSize.height >= desiredSize.height)
          && (repSize.width < bestSize.width)
          && (repSize.height < bestSize.height))
	  {
	    bestSize = repSize;
	    bestRep = rep;
	  }
      }
  }
  
  if (bestRep == nil)
    {
      bestRep = [reps lastObject];
    }
  
  return bestRep;
}

- (NSArray *) representations
{
  return [self _representationsWithCachedImages: YES];
}

- (void) setDelegate: anObject
{
  _delegate = anObject;
}

- (id) delegate
{
  return _delegate;
}

// Producing TIFF Data for the Image 
- (NSData *) TIFFRepresentation
{
  NSArray       *reps;
  NSData        *data;

  /* As a result of using bitmap representations,
   * new drawing wont show on the tiff data.
   */
  reps = [self _representationsWithCachedImages: NO];
  data = [bitmapClass TIFFRepresentationOfImageRepsInArray: reps];

  if (!data)
    {
      NSBitmapImageRep *rep;
      NSSize size = [self size];
      
      // If there isn't a bitmap representation to output, create one and store it.
      [self lockFocus];
      rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect: 
                       NSMakeRect(0.0, 0.0, size.width, size.height)];
      [self unlockFocus];
      if (nil != rep)
        {
          [self addRepresentation: rep];
          data = [rep TIFFRepresentation];
          RELEASE(rep);
        }
    }

  return data;
}

- (NSData *) TIFFRepresentationUsingCompression: (NSTIFFCompression)comp
                                         factor: (float)aFloat
{
  NSArray       *reps;
  NSData        *data;

  /* As a result of using bitmap representations,
   * new drawing wont show on the tiff data.
   */
  reps = [self _representationsWithCachedImages: NO];
  data = [bitmapClass TIFFRepresentationOfImageRepsInArray: reps
                                          usingCompression: comp
                                                    factor: aFloat];

  if (!data)
    {
      NSBitmapImageRep *rep;
      NSSize size = [self size];
      
      /* If there isn't a bitmap representation to output,
       * create one and store it.
       */
      [self lockFocus];
      rep = [[NSBitmapImageRep alloc] initWithFocusedViewRect: 
        NSMakeRect(0.0, 0.0, size.width, size.height)];
      [self unlockFocus];
      if (nil != rep)
        {
          [self addRepresentation: rep];
          data = [rep TIFFRepresentationUsingCompression: comp factor: aFloat];
          RELEASE(rep);
        }
    }

  return data;
}

// NSCoding
- (void) encodeWithCoder: (NSCoder*)coder
{
  BOOL        flag;

  if ([coder allowsKeyedCoding])
    {
      int flags = 0;

      if (_flags.archiveByName == NO)
        {
          NSMutableArray *container = [NSMutableArray array];
          NSMutableArray *reps = [NSMutableArray array];
          NSEnumerator *en = [_reps objectEnumerator];
          GSRepData *rd = nil;

          if ([_reps count] > 0)
            {
              [reps addObject: [NSNumber numberWithInt: 0]];
              while ((rd = [en nextObject]) != nil)
                {
                  [reps addObject: rd->rep];
                }

              // add the reps to the container...
              [container addObject: reps];
              [coder encodeObject: container forKey: @"NSReps"];
            }
        }
      else
        {
          [coder encodeObject: _name forKey: @"NSName"];
        }

      // encode the rest...
      if (_color != nil)
        {
          [coder encodeObject: _color forKey: @"NSColor"];
        }
      flags |= [self scalesWhenResized] ? 0x8000000 : 0;
      flags |= _flags.sizeWasExplicitlySet ? 0x2000000 : 0;
      flags |= [self usesEPSOnResolutionMismatch] ? 0x0200000 : 0;
      flags |= [self prefersColorMatch] ? 0x0100000 : 0;
      flags |= [self matchesOnMultipleResolution] ? 0x0080000 : 0;
      flags |= [self isFlipped] ? 0x0008000 : 0;
      flags |= [self cacheMode] << 11;
      [coder encodeInt: flags forKey: @"NSImageFlags"];
      if (_flags.sizeWasExplicitlySet)
        {
          [coder encodeSize: _size forKey: @"NSSize"];
        }
    }
  else
    {
      flag = _flags.archiveByName;
      [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
      if (flag == YES)
        {
          /*
           * System image - just encode the name.
           */
          [coder encodeValueOfObjCType: @encode(id) at: &_name];
        }
      else
        {
          NSMutableArray *a;
          NSEnumerator *e;
          NSImageRep *r;
          
          /*
           * Normal image - encode the ivars
           */
          [coder encodeValueOfObjCType: @encode(NSSize) at: &_size];
          [coder encodeValueOfObjCType: @encode(id) at: &_color];
          flag = _flags.scalable;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.dataRetained;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.flipDraw;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.sizeWasExplicitlySet;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.useEPSOnResolutionMismatch;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.colorMatchPreferred;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.multipleResolutionMatching;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.cacheSeparately;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          flag = _flags.unboundedCacheDepth;
          [coder encodeValueOfObjCType: @encode(BOOL) at: &flag];
          
          // FIXME: The documentation says to archive only the file name,
          // if not data retained!
          /*
           * Now encode an array of all the image reps (excluding cache)
           */
          a = [NSMutableArray arrayWithCapacity: 2];
          e = [[self representations] objectEnumerator];
          while ((r = [e nextObject]) != nil)
            {
              if ([r isKindOfClass: cachedClass] == NO)
                {
                  [a addObject: r];
                }
            }
          [coder encodeValueOfObjCType: @encode(id) at: &a];
        }
    }
}

- (id) initWithCoder: (NSCoder*)coder
{
  BOOL flag;

  _reps = [[NSMutableArray alloc] initWithCapacity: 2];
  if ([coder allowsKeyedCoding])
    {
      if ([coder containsValueForKey: @"NSName"])
        {
          RELEASE(self);
          return RETAIN([NSImage imageNamed:
            [coder decodeObjectForKey: @"NSName"]]);
        }
      if ([coder containsValueForKey: @"NSColor"])
        {
          [self setBackgroundColor: [coder decodeObjectForKey: @"NSColor"]];
        }
      if ([coder containsValueForKey: @"NSImageFlags"])
        {
          int flags = [coder decodeIntForKey: @"NSImageFlags"];

          [self setScalesWhenResized: ((flags & 0x8000000) != 0)];
          // _flags.sizeWasExplicitlySet = ((flags & 0x2000000) != 0);
          [self setUsesEPSOnResolutionMismatch: ((flags & 0x0200000) != 0)];
          [self setPrefersColorMatch: ((flags & 0x0100000) != 0)];
          [self setMatchesOnMultipleResolution: ((flags & 0x0080000) != 0)];
          [self setFlipped: ((flags & 0x0008000) != 0)];
          // ALIASED ((flags & 0x0004000) != 0)
          [self setCacheMode: ((flags & 0x0001800) >> 11)];
        }
      if ([coder containsValueForKey: @"NSReps"])
        {
          NSArray *reps;
          NSUInteger i;

          /* FIXME: NSReps is in a strange format. It is a mutable array
           * with one element which is an array with a first element 0
           * and than the image rep.  
           */
          reps = [coder decodeObjectForKey: @"NSReps"];
          reps = [reps objectAtIndex: 0];
          for (i = 1; i < [reps count]; i++)
            {
              id rep = [reps objectAtIndex: i];
              if ([rep isKindOfClass: [NSImageRep class]])
                { 
                  [self addRepresentation: rep];
                }
              else
                {
                  if ([rep isKindOfClass: [NSURL class]])
                    {
                      NSURL *tmp = (NSURL*)rep;
                      rep = [NSImageRep imageRepWithContentsOfURL: rep];
                      
                      /* If we are unable to resolved the URL,
                       * try to get it from the resources folder.
                       */
                      if (rep == nil)
                        {
                          NSString *fileName;
                          NSString *path;

                          fileName = [[tmp absoluteString] lastPathComponent];
                          path = [[NSBundle mainBundle]
                            pathForImageResource: fileName];
                          rep = [NSImageRep imageRepWithContentsOfFile: path];
                        }
                      
                      // If the representation was found, add it...
                      if (rep != nil)
                        {
                          [self addRepresentation: rep];
                        }
                    }
                }
            }
        }
      if ([coder containsValueForKey: @"NSSize"])
        {
          [self setSize: [coder decodeSizeForKey: @"NSSize"]];
        }
    }
  else
    {
      [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
      if (flag == YES)
        {
          NSString *theName = [coder decodeObject];

          RELEASE(self);
          self = RETAIN([NSImage imageNamed: theName]);
        }
      else
        {
          NSArray *a;

          [coder decodeValueOfObjCType: @encode(NSSize) at: &_size];
          [coder decodeValueOfObjCType: @encode(id) at: &_color];
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.scalable = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.dataRetained = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.flipDraw = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.sizeWasExplicitlySet = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.useEPSOnResolutionMismatch = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.colorMatchPreferred = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.multipleResolutionMatching = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.cacheSeparately = flag;
          [coder decodeValueOfObjCType: @encode(BOOL) at: &flag];
          _flags.unboundedCacheDepth = flag;
          
          /*
           * get the image reps and add them.
           */
          a = [coder decodeObject];
          [self addRepresentations: a];
        }
    }
  return self;
}

+ (BOOL) canInitWithPasteboard: (NSPasteboard *)pasteboard
{
  int i, count;
  NSArray* array = [NSImageRep registeredImageRepClasses];

  count = [array count];
  for (i = 0; i < count; i++)
    if ([[array objectAtIndex: i] canInitWithPasteboard: pasteboard])
      return YES;
  
  return NO;
}

+ (NSArray *) imageUnfilteredFileTypes
{
  if (nil == imageUnfilteredFileTypes)
    {
      ASSIGN(imageUnfilteredFileTypes, 
             iterate_reps_for_types([NSImageRep registeredImageRepClasses],
                                    @selector(imageUnfilteredFileTypes)));
    }
  return imageUnfilteredFileTypes;
}

+ (NSArray *) imageFileTypes
{
  if (nil == imageFileTypes)
    {
      ASSIGN(imageFileTypes,
             iterate_reps_for_types([NSImageRep registeredImageRepClasses],
                                    @selector(imageFileTypes)));
    }
  return imageFileTypes;
}

+ (NSArray *) imageUnfilteredPasteboardTypes
{
  if (nil == imageUnfilteredPasteboardTypes)
    {
      ASSIGN(imageUnfilteredPasteboardTypes,
             iterate_reps_for_types([NSImageRep registeredImageRepClasses],
                                    @selector(imageUnfilteredPasteboardTypes)));
    }
  return imageUnfilteredPasteboardTypes;
}

+ (NSArray *) imagePasteboardTypes
{
  if (nil == imagePasteboardTypes)
    {
      ASSIGN(imagePasteboardTypes,
             iterate_reps_for_types([NSImageRep registeredImageRepClasses],
                                    @selector(imagePasteboardTypes)));
    }
  return imagePasteboardTypes;
}

@end

/* For every image rep, call the specified method to obtain an
   array of objects.  Add these together, with duplicates
   weeded out.  Used by imageUnfilteredPasteboardTypes,
   imageUnfilteredFileTypes, etc. */
static NSArray *
iterate_reps_for_types(NSArray* imageReps, SEL method)
{
  NSImageRep *rep;
  NSEnumerator *e;
  NSMutableArray *types;

  types = [NSMutableArray arrayWithCapacity: 2];

  // Iterate through all the image reps
  e = [imageReps objectEnumerator];
  rep = [e nextObject];
  while (rep)
    {
      id e1;
      id obj;
      NSArray* pb_list;

      // Have the image rep perform the operation
      pb_list = [rep performSelector: method];

      // Iterate through the returned array
      // and add elements to types list, duplicates weeded.
      e1 = [pb_list objectEnumerator];
      obj = [e1 nextObject];
      while (obj)
        {
          if ([types indexOfObject: obj] == NSNotFound)
            [types addObject: obj];
          obj = [e1 nextObject];
        }

      rep = [e nextObject];
    }
    
  return (NSArray *)types;
}

@implementation NSImage (Private)
    
+ (void) _clearFileTypeCaches: (NSNotification*)notif
{
  DESTROY(imageUnfilteredFileTypes);
  DESTROY(imageFileTypes);
  DESTROY(imageUnfilteredPasteboardTypes);
  DESTROY(imagePasteboardTypes);
}

/**
 * For all NSImage instances cached in nameDict, recompute the
 * path using +_pathForImageNamed: and if it has changed,
 * reload the image contents using the new path.
 */
+ (void) _reloadCachedImages
{
  NSString *name;
  NSEnumerator *e = [nameDict keyEnumerator];

  [imageLock lock];
  while ((name = [e nextObject]) != nil)
    {
      NSImage *image = [nameDict objectForKey: name];
      NSString *path = [[NSBundle mainBundle] pathForImageResource: name];

      //NSLog(@"Loaded image %@ from %@", name, path);

      if (path != nil && ![path isEqual: image->_fileName])
	{
	  /* Reset the existing image to use the contents of
	   * the specified file.
	   */
	  [image _resetAndUseFromFile: path];
	}   
    }
  [imageLock unlock];
}


+ (NSString *) _resourceNameForImageNamed: (NSString *)aName 
                                     type: (NSString **)aType
{
  NSString *name = aName;
  NSString *ext = [aName pathExtension];

  if (ext != nil && [ext length] == 0)
    {
      ext = nil;
    }

  /* Check if extension is one of the image types */
  if (ext != nil && [[self imageFileTypes] indexOfObject: ext] != NSNotFound)
    {
      /* Extension is one of the image types, so remove from the name */
      name = [aName stringByDeletingPathExtension];
    }
  else
    {
      /* Otherwise extension is not an image type, so leave it alone */
      ext = nil;
    }

  *aType = ext;
  return name;
}

- (BOOL) _loadFromData: (NSData *)data
{
  BOOL ok;
  Class rep;

  ok = NO;
  rep = [NSImageRep imageRepClassForData: data];
  if (rep && [rep respondsToSelector: @selector(imageRepsWithData:)])
    {
      NSArray* array;

      array = [rep imageRepsWithData: data];
      if (array && ([array count] > 0))
        ok = YES;
      [self addRepresentations: array];
    }
  else if (rep)
    {
      NSImageRep* image;

      image = [rep imageRepWithData: data];
      if (image)
        ok = YES;
      [self addRepresentation: image];
    }
  return ok;
}

- (BOOL) _loadFromFile: (NSString *)fileName
{
  NSArray *array;

  array = [NSImageRep imageRepsWithContentsOfFile: fileName];
  if (array)
    [self addRepresentations: array];

  return (array && ([array count] > 0)) ? YES : NO;
}

- (BOOL) _useFromFile: (NSString *)fileName
{
  NSArray *array;
  NSString *ext;
  NSFileManager *manager = [NSFileManager defaultManager];

  if ([manager fileExistsAtPath: fileName] == NO)
    {
      return NO;
    }

  ext = [[fileName pathExtension] lowercaseString];
  if (!ext)
    return NO;
  array = [object_getClass(self) imageFileTypes];
  if ([array indexOfObject: ext] == NSNotFound)
    return NO;

  ASSIGN(_fileName, fileName);
  _flags.syncLoad = YES;
  return YES;
}

- (BOOL) _resetAndUseFromFile: (NSString *)fileName
{
  [_reps removeAllObjects];
  
  if (!_flags.sizeWasExplicitlySet)
    {
      _size = NSZeroSize;
    }
  return [self _useFromFile: fileName];
}

// Cache the bestRepresentation.  If the bestRepresentation is not itself
// a cache and no cache exists, create one and draw the representation in it
// If a cache exists, but is not valid, redraw the cache from the original
// image (if there is one).
- (NSCachedImageRep *) _doImageCache: (NSImageRep *)rep
{
  GSRepData *repd;
  NSCachedImageRep *cache;

  repd = [self _cacheForRep: rep];
  if (repd == nil)
    return nil;

  cache = (NSCachedImageRep*)(repd->rep);
  if ([cache isKindOfClass: cachedClass] == NO)
    return nil;
  
  NSDebugLLog(@"NSImage", @"Cached image rep is %p", cache);
  /*
   * if the cache is not valid, it's background color will not exist
   * and we must draw the background then render from the original
   * image rep into the cache.
   */
  if (repd->bg == nil) 
    {
      [self lockFocusOnRepresentation: cache];
      [self unlockFocus];
      
      NSDebugLLog(@"NSImage", @"Rendered rep %p on background %@",
                  cache, repd->bg);
    }
  
  return cache;
}

- (GSRepData*) _cacheForRep: (NSImageRep*)rep
{
  if ([rep isKindOfClass: cachedClass] == YES)
    {
      return repd_for_rep(_reps, rep);
    }
  else
    {
      /*
       * If this is not a cached image rep - try to find the cache rep
       * for this image rep. If none is found create a cache to be used to
       * render the image rep into, and switch to the cached rep.
       */
      NSUInteger count = [_reps count];

      if (count > 0)
        {
          GSRepData *invalidCache = nil;
          GSRepData *partialCache = nil;
          GSRepData *reps[count];
          NSUInteger partialCount = 0;
          NSUInteger i;
          BOOL opaque = [rep isOpaque];
          
          [_reps getObjects: reps];
          
          /*
           * Search the cached image reps for any whose original is our
           * 'best' image rep.  See if we can notice any invalidated
           * cache as we go - if we don't find a valid cache, we want to
           * re-use an invalidated one rather than creating a new one.
           * NB. If the image rep is opaque, then any cached rep is valid
           * irrespective of the background color it was drawn with.
           */
          for (i = 0; i < count; i++)
            {
              GSRepData *repd = reps[i];

              if (repd->original == rep && repd->rep != nil)
                {
                  if (repd->bg == nil)
                    {
                      NSDebugLLog(@"NSImage", @"Invalid %@ ... %@ %@", 
                                  repd->bg, _color, repd->rep);
                      invalidCache = repd;
                    }
                  else if (opaque == YES || [repd->bg isEqual: _color] == YES)
                    {
                      NSDebugLLog(@"NSImage", @"Exact %@ ... %@ %@", 
                                  repd->bg, _color, repd->rep);
                      return repd;
                    }
                  else
                    {
                      NSDebugLLog(@"NSImage", @"Partial %@ ... %@ %@", 
                                  repd->bg, _color, repd->rep);
                      partialCache = repd;
                      partialCount++;
                    }
                }
            }

          if (invalidCache != nil)
            {
              /*
               * If there is an unused cache - use it rather than
               * re-using this one, since we might get a request
               * to draw with this color again.
               */
              return invalidCache;
            }
          else if (partialCache != nil && partialCount > 2)
            {
              /*
               * Only re-use partially correct caches if there are already
               * a few partial matches - otherwise we fall default to
               * creating a new cache.
               */
              if (NSImageForceCaching == NO && opaque == NO)
                {
                  DESTROY(partialCache->bg);
                }
              return partialCache;
            }
        }

      // We end here, when no representation are there or no match is found.
        {     
          NSImageRep *cacheRep = nil;
          GSRepData *repd;
	  NSSize imageSize = [self size];
          NSSize repSize;
	  NSInteger pixelsWide, pixelsHigh;

	  if (rep != nil)
	    {
	      repSize = [rep size];

	      if (repSize.width <= 0 || repSize.height <= 0)
		repSize = imageSize;

	      pixelsWide = [rep pixelsWide];
	      pixelsHigh = [rep pixelsHigh];
	      
	      if (pixelsWide == NSImageRepMatchesDevice ||
		  pixelsHigh == NSImageRepMatchesDevice)
		{
		  /* FIXME: Since the cached rep must be a bitmap,
		   * we must rasterize vector reps at a particular DPI.
		   * Here we hardcode 72, but we should choose the DPI
		   * more intelligently.
		   */
		  pixelsWide = repSize.width; 
		  pixelsHigh = repSize.height;
		}
	    }
	  else // e.g. when there are no representations at all
	    {
	      repSize = imageSize;
	      /* FIXME: assumes 72 DPI. Also truncates,
               * not sure if that is a problem.
               */
	      pixelsWide = imageSize.width;
	      pixelsHigh = imageSize.height;
	    }
	  
          if (repSize.width <= 0 || repSize.height <= 0 ||
	      pixelsWide <= 0 || pixelsHigh <= 0)
            return nil;

          // Create a new cached image rep without any contents.
          cacheRep = [[cachedClass alloc] 
                         initWithSize: repSize
			   pixelsWide: pixelsWide
			   pixelsHigh: pixelsHigh
				depth: [[NSScreen mainScreen] depth]
			     separate: _flags.cacheSeparately
				alpha: [rep hasAlpha]];
          if (cacheRep == nil)
            {
              return nil;
            }

          repd = [GSRepData new];
          repd->rep = cacheRep;
          repd->original = rep; // may be nil!
          [_reps addObject: repd]; 
          RELEASE(repd); /* Retained in _reps array. */

          return repd;
        }
    }
}

@end