-
Notifications
You must be signed in to change notification settings - Fork 4
/
IconFamily.m
1576 lines (1343 loc) · 56.6 KB
/
IconFamily.m
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
// IconFamily.m
// IconFamily class implementation
// by Troy Stephens, Thomas Schnitzer, David Remahl, Nathan Day, Ben Haller, Sven Janssen, Peter Hosey, Conor Dearden, Elliot Glaysher, and Dave MacLachlan
// version 0.9.3
//
// Project Home Page:
// http://iconfamily.sourceforge.net/
//
// Problems, shortcomings, and uncertainties that I'm aware of are flagged with "NOTE:". Please address bug reports, bug fixes, suggestions, etc. to the project Forums and bug tracker at https://sourceforge.net/projects/iconfamily/
/*
Copyright (c) 2001-2006 Troy N. Stephens
Portions Copyright (c) 2007 Google Inc.
Use and distribution of this source code is governed by the MIT License, whose terms are as follows.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#import "IconFamily.h"
#import "NSString+CarbonFSRefCreation.h"
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_4
// This is defined in 10.5 and beyond in IconStorage.h
enum {
kIconServices512PixelDataARGB = 'ic09' /* non-premultiplied 512x512 ARGB bitmap*/
};
#endif
#if MAC_OS_X_VERSION_MAX_ALLOWED <= MAC_OS_X_VERSION_10_3
// This is defined in 10.4 and beyond in IconStorage.h
enum {
kIconServices256PixelDataARGB = 'ic08' /* non-premultiplied 256x256 ARGB bitmap*/
};
#endif
@interface IconFamily (Internals)
+ (NSImage*) resampleImage:(NSImage*)image toIconWidth:(int)width usingImageInterpolation:(NSImageInterpolation)imageInterpolation;
+ (Handle) get32BitDataFromBitmapImageRep:(NSBitmapImageRep*)bitmapImageRep requiredPixelSize:(int)requiredPixelSize;
+ (Handle) get8BitDataFromBitmapImageRep:(NSBitmapImageRep*)bitmapImageRep requiredPixelSize:(int)requiredPixelSize;
+ (Handle) get8BitMaskFromBitmapImageRep:(NSBitmapImageRep*)bitmapImageRep requiredPixelSize:(int)requiredPixelSize;
+ (Handle) get1BitMaskFromBitmapImageRep:(NSBitmapImageRep*)bitmapImageRep requiredPixelSize:(int)requiredPixelSize;
- (BOOL) addResourceType:(OSType)type asResID:(int)resID;
@end
@implementation IconFamily
+ (IconFamily*) iconFamily
{
return [[[IconFamily alloc] init] autorelease];
}
+ (IconFamily*) iconFamilyWithContentsOfFile:(NSString*)path
{
return [[[IconFamily alloc] initWithContentsOfFile:path] autorelease];
}
+ (IconFamily*) iconFamilyWithIconOfFile:(NSString*)path
{
return [[[IconFamily alloc] initWithIconOfFile:path] autorelease];
}
+ (IconFamily*) iconFamilyWithIconFamilyHandle:(IconFamilyHandle)hNewIconFamily
{
return [[[IconFamily alloc] initWithIconFamilyHandle:hNewIconFamily] autorelease];
}
+ (IconFamily*) iconFamilyWithSystemIcon:(int)fourByteCode
{
return [[[IconFamily alloc] initWithSystemIcon:fourByteCode] autorelease];
}
+ (IconFamily*) iconFamilyWithThumbnailsOfImage:(NSImage*)image
{
return [[[IconFamily alloc] initWithThumbnailsOfImage:image] autorelease];
}
+ (IconFamily*) iconFamilyWithThumbnailsOfImage:(NSImage*)image usingImageInterpolation:(NSImageInterpolation)imageInterpolation
{
return [[[IconFamily alloc] initWithThumbnailsOfImage:image usingImageInterpolation:imageInterpolation] autorelease];
}
// This is IconFamily's designated initializer. It creates a new IconFamily that initially has no elements.
//
// The proper way to do this is to simply allocate a zero-sized handle (not to be confused with an empty handle) and assign it to hIconFamily. This technique works on Mac OS X 10.2 as well as on 10.0.x and 10.1.x. Our previous technique of allocating an IconFamily struct with a resourceSize of 0 no longer works as of Mac OS X 10.2.
- init
{
self = [super init];
if (self) {
hIconFamily = (IconFamilyHandle) NewHandle( 0 );
if (hIconFamily == NULL) {
[self autorelease];
return nil;
}
}
return self;
}
- initWithContentsOfFile:(NSString*)path
{
FSRef ref;
OSStatus result;
self = [self init];
if (self) {
if (hIconFamily) {
DisposeHandle( (Handle)hIconFamily );
hIconFamily = NULL;
}
if (![path getFSRef:&ref createFileIfNecessary:NO]) {
[self autorelease];
return nil;
}
result = ReadIconFromFSRef( &ref, &hIconFamily );
if (result != noErr) {
[self autorelease];
return nil;
}
}
return self;
}
- initWithIconFamilyHandle:(IconFamilyHandle)hNewIconFamily
{
self = [self init];
if (self) {
if (hIconFamily) {
DisposeHandle( (Handle)hIconFamily );
hIconFamily = NULL;
}
hIconFamily = hNewIconFamily;
}
return self;
}
- initWithIconOfFile:(NSString*)path
{
IconRef iconRef;
OSStatus result;
SInt16 label;
FSRef ref;
self = [self init];
if (self)
{
if (hIconFamily)
{
DisposeHandle( (Handle)hIconFamily );
hIconFamily = NULL;
}
if( ![path getFSRef:&ref createFileIfNecessary:NO] )
{
[self autorelease];
return nil;
}
result = GetIconRefFromFileInfo(
&ref,
/*inFileNameLength*/ 0,
/*inFileName*/ NULL,
kFSCatInfoNone,
/*inCatalogInfo*/ NULL,
kIconServicesNormalUsageFlag,
&iconRef,
&label );
if (result != noErr)
{
[self autorelease];
return nil;
}
result = IconRefToIconFamily(
iconRef,
kSelectorAllAvailableData,
&hIconFamily );
ReleaseIconRef( iconRef );
if (result != noErr || !hIconFamily)
{
[self autorelease];
return nil;
}
}
return self;
}
- initWithSystemIcon:(int)fourByteCode
{
IconRef iconRef;
OSErr result;
self = [self init];
if (self)
{
if (hIconFamily)
{
DisposeHandle( (Handle)hIconFamily );
hIconFamily = NULL;
}
result = GetIconRef(kOnSystemDisk, kSystemIconsCreator, fourByteCode, &iconRef);
if (result != noErr)
{
[self autorelease];
return nil;
}
result = IconRefToIconFamily(
iconRef,
kSelectorAllAvailableData,
&hIconFamily );
if (result != noErr || !hIconFamily)
{
[self autorelease];
return nil;
}
ReleaseIconRef( iconRef );
}
return self;
}
- initWithThumbnailsOfImage:(NSImage*)image
{
// The default is to use a high degree of antialiasing, producing a smooth image.
return [self initWithThumbnailsOfImage:image usingImageInterpolation:NSImageInterpolationHigh];
}
- initWithThumbnailsOfImage:(NSImage*)image usingImageInterpolation:(NSImageInterpolation)imageInterpolation
{
NSImage* iconImage512x512;
NSImage* iconImage256x256;
NSImage* iconImage128x128;
NSImage* iconImage32x32;
NSImage* iconImage16x16;
NSImage* bitmappedIconImage512x512;
NSBitmapImageRep* iconBitmap512x512;
NSBitmapImageRep* iconBitmap256x256;
NSBitmapImageRep* iconBitmap128x128;
NSBitmapImageRep* iconBitmap32x32;
NSBitmapImageRep* iconBitmap16x16;
// Start with a new, empty IconFamily.
self = [self init];
if (self == nil)
return nil;
// Resample the given image to create a 512x512 pixel, 32-bit RGBA
// version, and use that as our "thumbnail" (512x512) icon and mask.
//
// Our +resampleImage:toIconWidth:... method, in its present form,
// returns an NSImage that contains an NSCacheImageRep, rather than
// an NSBitmapImageRep. We convert to an NSBitmapImageRep, so that
// our methods can scan the image data, using initWithFocusedViewRect:.
iconImage512x512 = [IconFamily resampleImage:image toIconWidth:512 usingImageInterpolation:imageInterpolation];
if (!iconImage512x512) {
[self autorelease];
return nil;
}
[iconImage512x512 lockFocus];
iconBitmap512x512 = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, 512, 512)];
[iconImage512x512 unlockFocus];
if (!iconBitmap512x512) {
[self release];
return nil;
}
// Create an NSImage with the iconBitmap512x512 NSBitmapImageRep, that we
// can resample to create the smaller icon family elements. (This is
// most likely more efficient than resampling from the original image again,
// particularly if it is large. It produces a slightly different result, but
// the difference is minor and should not be objectionable...)
bitmappedIconImage512x512 = [[NSImage alloc] initWithSize:NSMakeSize(512, 512)];
[bitmappedIconImage512x512 addRepresentation:iconBitmap512x512];
if (!bitmappedIconImage512x512) {
[self autorelease];
return nil;
}
[self setIconFamilyElement:kIconServices512PixelDataARGB fromBitmapImageRep:iconBitmap512x512];
[iconBitmap512x512 release];
iconImage256x256 = [IconFamily resampleImage:bitmappedIconImage512x512 toIconWidth:256 usingImageInterpolation:imageInterpolation];
if (iconImage256x256) {
[iconImage256x256 lockFocus];
iconBitmap256x256 = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, 256, 256)];
[iconImage256x256 unlockFocus];
if (iconBitmap256x256) {
[self setIconFamilyElement:kIconServices256PixelDataARGB fromBitmapImageRep:iconBitmap256x256];
[iconBitmap256x256 release];
}
}
iconImage128x128 = [IconFamily resampleImage:bitmappedIconImage512x512 toIconWidth:128 usingImageInterpolation:imageInterpolation];
if (iconImage128x128) {
[iconImage128x128 lockFocus];
iconBitmap128x128 = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, 128, 128)];
[iconImage128x128 unlockFocus];
if (iconBitmap128x128) {
[self setIconFamilyElement:kThumbnail32BitData fromBitmapImageRep:iconBitmap128x128];
[self setIconFamilyElement:kThumbnail8BitMask fromBitmapImageRep:iconBitmap128x128];
[iconBitmap128x128 release];
}
}
// Resample the 512x512 image to create a 32x32 pixel, 32-bit RGBA version,
// and use that as our "large" (32x32) icon and 8-bit mask.
iconImage32x32 = [IconFamily resampleImage:bitmappedIconImage512x512 toIconWidth:32 usingImageInterpolation:imageInterpolation];
if (iconImage32x32) {
[iconImage32x32 lockFocus];
iconBitmap32x32 = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, 32, 32)];
[iconImage32x32 unlockFocus];
if (iconBitmap32x32) {
[self setIconFamilyElement:kLarge32BitData fromBitmapImageRep:iconBitmap32x32];
[self setIconFamilyElement:kLarge8BitData fromBitmapImageRep:iconBitmap32x32];
[self setIconFamilyElement:kLarge8BitMask fromBitmapImageRep:iconBitmap32x32];
[self setIconFamilyElement:kLarge1BitMask fromBitmapImageRep:iconBitmap32x32];
[iconBitmap32x32 release];
}
}
// Resample the 512x512 image to create a 16x16 pixel, 32-bit RGBA version,
// and use that as our "small" (16x16) icon and 8-bit mask.
iconImage16x16 = [IconFamily resampleImage:bitmappedIconImage512x512 toIconWidth:16 usingImageInterpolation:imageInterpolation];
if (iconImage16x16) {
[iconImage16x16 lockFocus];
iconBitmap16x16 = [[NSBitmapImageRep alloc] initWithFocusedViewRect:NSMakeRect(0, 0, 16, 16)];
[iconImage16x16 unlockFocus];
if (iconBitmap16x16) {
[self setIconFamilyElement:kSmall32BitData fromBitmapImageRep:iconBitmap16x16];
[self setIconFamilyElement:kSmall8BitData fromBitmapImageRep:iconBitmap16x16];
[self setIconFamilyElement:kSmall8BitMask fromBitmapImageRep:iconBitmap16x16];
[self setIconFamilyElement:kSmall1BitMask fromBitmapImageRep:iconBitmap16x16];
[iconBitmap16x16 release];
}
}
// Release the icon.
[bitmappedIconImage512x512 release];
// Return the new icon family!
return self;
}
- (void) dealloc
{
DisposeHandle( (Handle)hIconFamily );
[super dealloc];
}
- (NSBitmapImageRep*) bitmapImageRepWithAlphaForIconFamilyElement:(OSType)elementType;
{
NSBitmapImageRep* bitmapImageRep;
int pixelsWide;
Handle hRawBitmapData;
Handle hRawMaskData;
OSType maskElementType;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
NSBitmapFormat bitmapFormat = NSAlphaFirstBitmapFormat;
#endif
OSErr result;
unsigned long* pRawBitmapData;
unsigned long* pRawBitmapDataEnd;
unsigned char* pRawMaskData;
unsigned char* pBitmapImageRepBitmapData;
// Make sure elementType is a valid type that we know how to handle, and
// figure out the dimensions and bit depth of the bitmap for that type.
switch (elementType) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
// 'ic09' 512x512 32-bit RGB image
case kIconServices512PixelDataARGB:
maskElementType = 0;
pixelsWide = 512;
break;
#endif
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
// 'ic08' 256x256 32-bit ARGB image
case kIconServices256PixelDataARGB:
maskElementType = 0;
pixelsWide = 256;
break;
#endif
// 'it32' 128x128 32-bit RGB image
case kThumbnail32BitData:
maskElementType = kThumbnail8BitMask;
pixelsWide = 128;
break;
// 'ih32' 48x48 32-bit RGB image
case kHuge32BitData:
maskElementType = kHuge8BitMask;
pixelsWide = 48;
break;
// 'il32' 32x32 32-bit RGB image
case kLarge32BitData:
maskElementType = kLarge8BitMask;
pixelsWide = 32;
break;
// 'is32' 16x16 32-bit RGB image
case kSmall32BitData:
maskElementType = kSmall8BitMask;
pixelsWide = 16;
break;
default:
return nil;
}
// Get the raw, uncompressed bitmap data for the requested element.
hRawBitmapData = NewHandle( pixelsWide * pixelsWide * 4 );
result = GetIconFamilyData( hIconFamily, elementType, hRawBitmapData );
if (result != noErr) {
DisposeHandle( hRawBitmapData );
return nil;
}
if (maskElementType) {
// Get the corresponding raw, uncompressed 8-bit mask data.
hRawMaskData = NewHandle( pixelsWide * pixelsWide );
result = GetIconFamilyData( hIconFamily, maskElementType, hRawMaskData );
if (result != noErr) {
DisposeHandle( hRawMaskData );
hRawMaskData = NULL;
}
}
// The retrieved raw bitmap data is stored in memory as 32 bit per pixel, 8 bit per sample xRGB data. (The sample order provided by IconServices is the same, regardless of whether we're running on a big-endian (PPC) or little-endian (Intel) architecture.)
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
// With proper attention to byte order, we can fold the mask data into the color data in-place, producing ARGB data suitable for handing off to NSBitmapImageRep.
#else
// With proper attention to byte order, we can fold the mask data into the color data in-place, producing RGBA data suitable for handing off to NSBitmapImageRep.
#endif
// HLock( hRawBitmapData ); // Handle-based memory isn't compacted anymore, so calling HLock()/HUnlock() is unnecessary.
pRawBitmapData = (unsigned long*) *hRawBitmapData;
pRawBitmapDataEnd = pRawBitmapData + pixelsWide * pixelsWide;
if (hRawMaskData) {
// HLock( hRawMaskData ); // Handle-based memory isn't compacted anymore, so calling HLock()/HUnlock() is unnecessary.
pRawMaskData = (unsigned char*) *hRawMaskData;
while (pRawBitmapData < pRawBitmapDataEnd) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
// Convert the xRGB pixel data to ARGB.
// PowerPC Intel
// ------- -----
// Bytes in memory are x R G B x R G B
// *pRawBitmapData loads as 32-bit word into register xRGB BGRx
// NSSwapHostLongToBig() swaps this to xRGB xRGB
// Loading *pRawMaskData and shifting left 24 bits yields A000 A000
// Bitwise ORing these two words together yields ARGB ARGB
// NSSwapBigLongToHost() swaps this to ARGB BGRA
// Bytes in memory after they're stored as a 32-bit word A R G B A R G B
*pRawBitmapData = NSSwapBigLongToHost((*pRawMaskData++ << 24) | NSSwapHostLongToBig(*pRawBitmapData));
#else
// Convert the xRGB pixel data to RGBA.
// PowerPC Intel
// ------- -----
// Bytes in memory are x R G B x R G B
// *pRawBitmapData loads as 32-bit word into register xRGB BGRx
// NSSwapHostLongToBig() swaps this to xRGB xRGB
// Shifting left 8 bits yields ('0' denotes all zero bits) RGB0 RGB0
// Bitwise ORing with *pRawMaskData byte yields RGBA RGBA
// NSSwapBigLongToHost() swaps this to RGBA ABGR
// Bytes in memory after they're stored as a 32-bit word R G B A R G B A
*pRawBitmapData = NSSwapBigLongToHost((NSSwapHostLongToBig(*pRawBitmapData) << 8) | *pRawMaskData++);
#endif
++pRawBitmapData;
}
// HUnlock( hRawMaskData ); // Handle-based memory isn't compacted anymore, so calling HLock()/HUnlock() is unnecessary.
} else {
if(maskElementType) {
// We SHOULD have a mask, but apparently not. Fake it with alpha=1.
while (pRawBitmapData < pRawBitmapDataEnd) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
// Set alpha byte to 0xff.
// PowerPC Intel
// ------- -----
// Bytes in memory are x R G B x R G B
// Writing a single 0xff byte ('1') at pRawBitmapData yields 1 R G B 1 R G B
*(unsigned char *)pRawBitmapData = 0xff;
#else
// Set alpha byte to 0xff.
// PowerPC Intel
// ------- -----
// Bytes in memory are R G B x R G B x
// Writing a single 0xff byte, 3 bytes past pRawBitmapData yields R G B 1 R G B 1
*((unsigned char *)pRawBitmapData + 3) = 0xff;
#endif
++pRawBitmapData;
}
}
}
// Create a new NSBitmapImageRep with the given bitmap data. Note that
// when creating the NSBitmapImageRep we pass in NULL for the "planes"
// parameter. This causes the new NSBitmapImageRep to allocate its own
// buffer for the bitmap data (which it will own and release when the
// NSBitmapImageRep is released), rather than referencing the bitmap
// data we pass in (which will soon disappear when we call
// DisposeHandle() below!). (See the NSBitmapImageRep documentation for
// the -initWithBitmapDataPlanes:... method, where this is explained.)
//
// Once we have the new NSBitmapImageRep, we get a pointer to its
// bitmapData and copy our bitmap data in.
bitmapImageRep = [[[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:pixelsWide
pixelsHigh:pixelsWide
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSDeviceRGBColorSpace // NOTE: is this right?
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_4
bitmapFormat:bitmapFormat
#endif
bytesPerRow:0
bitsPerPixel:0] autorelease];
pBitmapImageRepBitmapData = [bitmapImageRep bitmapData];
if (pBitmapImageRepBitmapData) {
memcpy( pBitmapImageRepBitmapData, *hRawBitmapData,
pixelsWide * pixelsWide * 4 );
}
// HUnlock( hRawBitmapData ); // Handle-based memory isn't compacted anymore, so calling HLock()/HUnlock() is unnecessary.
// Free the retrieved raw data.
DisposeHandle( hRawBitmapData );
if (hRawMaskData)
DisposeHandle( hRawMaskData );
// Return nil if the NSBitmapImageRep didn't give us a buffer to copy into.
if (pBitmapImageRepBitmapData == NULL)
return nil;
// Return the new NSBitmapImageRep.
return bitmapImageRep;
}
- (NSImage*) imageWithAllReps
{
NSImage* image = NULL;
image = [[[NSImage alloc] initWithData:[NSData dataWithBytes:*hIconFamily length:GetHandleSize((Handle)hIconFamily)]] autorelease];
return image;
}
- (BOOL) setIconFamilyElement:(OSType)elementType fromBitmapImageRep:(NSBitmapImageRep*)bitmapImageRep
{
Handle hRawData = NULL;
OSErr result;
switch (elementType) {
// 'ic08' 512x512 32-bit ARGB image
case kIconServices512PixelDataARGB:
hRawData = [IconFamily get32BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:512];
break;
// 'ic08' 256x256 32-bit ARGB image
case kIconServices256PixelDataARGB:
hRawData = [IconFamily get32BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:256];
break;
// 'it32' 128x128 32-bit RGB image
case kThumbnail32BitData:
hRawData = [IconFamily get32BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:128];
break;
// 't8mk' 128x128 8-bit alpha mask
case kThumbnail8BitMask:
hRawData = [IconFamily get8BitMaskFromBitmapImageRep:bitmapImageRep requiredPixelSize:128];
break;
// 'il32' 32x32 32-bit RGB image
case kLarge32BitData:
hRawData = [IconFamily get32BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:32];
break;
// 'l8mk' 32x32 8-bit alpha mask
case kLarge8BitMask:
hRawData = [IconFamily get8BitMaskFromBitmapImageRep:bitmapImageRep requiredPixelSize:32];
break;
// 'ICN#' 32x32 1-bit alpha mask
case kLarge1BitMask:
hRawData = [IconFamily get1BitMaskFromBitmapImageRep:bitmapImageRep requiredPixelSize:32];
break;
// 'icl8' 32x32 8-bit indexed image data
case kLarge8BitData:
hRawData = [IconFamily get8BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:32];
break;
// 'is32' 16x16 32-bit RGB image
case kSmall32BitData:
hRawData = [IconFamily get32BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:16];
break;
// 's8mk' 16x16 8-bit alpha mask
case kSmall8BitMask:
hRawData = [IconFamily get8BitMaskFromBitmapImageRep:bitmapImageRep requiredPixelSize:16];
break;
// 'ics#' 16x16 1-bit alpha mask
case kSmall1BitMask:
hRawData = [IconFamily get1BitMaskFromBitmapImageRep:bitmapImageRep requiredPixelSize:16];
break;
// 'ics8' 16x16 8-bit indexed image data
case kSmall8BitData:
hRawData = [IconFamily get8BitDataFromBitmapImageRep:bitmapImageRep requiredPixelSize:16];
break;
default:
return NO;
}
// NSLog(@"setIconFamilyElement:%@ fromBitmapImageRep:%@ generated handle %p of size %d", NSFileTypeForHFSTypeCode(elementType), bitmapImageRep, hRawData, GetHandleSize(hRawData));
if (hRawData == NULL)
{
NSLog(@"Null data returned to setIconFamilyElement:fromBitmapImageRep:");
return NO;
}
result = SetIconFamilyData( hIconFamily, elementType, hRawData );
DisposeHandle( hRawData );
if (result != noErr)
{
NSLog(@"SetIconFamilyData() returned error %d", result);
return NO;
}
return YES;
}
- (BOOL) setAsCustomIconForFile:(NSString*)path
{
return( [self setAsCustomIconForFile:path withCompatibility:NO] );
}
- (BOOL) setAsCustomIconForFile:(NSString*)path withCompatibility:(BOOL)compat
{
FSRef targetFileFSRef;
FSRef parentDirectoryFSRef;
SInt16 file;
OSStatus result;
struct FSCatalogInfo catInfo;
struct FileInfo *finderInfo = (struct FileInfo *)&catInfo.finderInfo;
Handle hExistingCustomIcon;
Handle hIconFamilyCopy;
NSString *parentDirectory;
// Before we do anything, get the original modification time for the target file.
NSDate* modificationDate = [[[NSFileManager defaultManager] fileAttributesAtPath:path traverseLink:NO] objectForKey:NSFileModificationDate];
if ([path isAbsolutePath])
parentDirectory = [path stringByDeletingLastPathComponent];
else
parentDirectory = [[[NSFileManager defaultManager] currentDirectoryPath] stringByAppendingPathComponent:[path stringByDeletingLastPathComponent]];
// Get an FSRef for the target file's parent directory that we can use in
// the FSCreateResFile() and FNNotify() calls below.
if (![parentDirectory getFSRef:&parentDirectoryFSRef createFileIfNecessary:NO])
return NO;
// Get the name of the file, for FSCreateResFile.
struct HFSUniStr255 filename;
NSString *filenameString = [path lastPathComponent];
filename.length = [filenameString length];
[filenameString getCharacters:filename.unicode];
// Make sure the file has a resource fork that we can open. (Although
// this sounds like it would clobber an existing resource fork, the Carbon
// Resource Manager docs for this function say that's not the case. If
// the file already has a resource fork, we receive a result code of
// dupFNErr, which is not really an error per se, but just a notification
// to us that creating a new resource fork for the file was not necessary.)
FSCreateResFile(
&parentDirectoryFSRef,
filename.length,
filename.unicode,
kFSCatInfoNone,
/*catalogInfo/*/ NULL,
&targetFileFSRef,
/*newSpec*/ NULL);
result = ResError();
if (result == dupFNErr) {
// If the call to FSCreateResFile() returned dupFNErr, targetFileFSRef will not have been set, so create it from the path.
if (![path getFSRef:&targetFileFSRef createFileIfNecessary:NO])
return NO;
} else if (result != noErr) {
return NO;
}
// Open the file's resource fork.
file = FSOpenResFile( &targetFileFSRef, fsRdWrPerm );
if (file == -1)
return NO;
// Make a copy of the icon family data to pass to AddResource().
// (AddResource() takes ownership of the handle we pass in; after the
// CloseResFile() call its master pointer will be set to 0xffffffff.
// We want to keep the icon family data, so we make a copy.)
// HandToHand() returns the handle of the copy in hIconFamily.
hIconFamilyCopy = (Handle) hIconFamily;
result = HandToHand( &hIconFamilyCopy );
if (result != noErr) {
CloseResFile( file );
return NO;
}
// Remove the file's existing kCustomIconResource of type kIconFamilyType
// (if any).
hExistingCustomIcon = GetResource( kIconFamilyType, kCustomIconResource );
if( hExistingCustomIcon )
RemoveResource( hExistingCustomIcon );
// Now add our icon family as the file's new custom icon.
AddResource( (Handle)hIconFamilyCopy, kIconFamilyType,
kCustomIconResource, "\p");
if (ResError() != noErr) {
CloseResFile( file );
return NO;
}
if( compat )
{
[self addResourceType:kLarge8BitData asResID:kCustomIconResource];
[self addResourceType:kLarge1BitMask asResID:kCustomIconResource];
[self addResourceType:kSmall8BitData asResID:kCustomIconResource];
[self addResourceType:kSmall1BitMask asResID:kCustomIconResource];
}
// Close the file's resource fork, flushing the resource map and new icon
// data out to disk.
CloseResFile( file );
if (ResError() != noErr)
return NO;
// Prepare to get the Finder info.
// Now we need to set the file's Finder info so the Finder will know that
// it has a custom icon. Start by getting the file's current finder info:
result = FSGetCatalogInfo(
&targetFileFSRef,
kFSCatInfoFinderInfo,
&catInfo,
/*outName*/ NULL,
/*fsSpec*/ NULL,
/*parentRef*/ NULL);
if (result != noErr)
return NO;
// Set the kHasCustomIcon flag, and clear the kHasBeenInited flag.
//
// From Apple's "CustomIcon" code sample:
// "set bit 10 (has custom icon) and unset the inited flag
// kHasBeenInited is 0x0100 so the mask will be 0xFEFF:"
// finderInfo.fdFlags = 0xFEFF & (finderInfo.fdFlags | kHasCustomIcon ) ;
finderInfo->finderFlags = (finderInfo->finderFlags | kHasCustomIcon ) & ~kHasBeenInited;
// Now write the Finder info back.
result = FSSetCatalogInfo( &targetFileFSRef, kFSCatInfoFinderInfo, &catInfo );
if (result != noErr)
return NO;
// Now set the modification time back to when the file was actually last modified.
NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:modificationDate, NSFileModificationDate, nil];
[[NSFileManager defaultManager] changeFileAttributes:attributes atPath:path];
// Notify the system that the directory containing the file has changed, to
// give Finder the chance to find out about the file's new custom icon.
result = FNNotify( &parentDirectoryFSRef, kFNDirectoryModifiedMessage, kNilOptions );
if (result != noErr)
return NO;
return YES;
}
+ (BOOL) removeCustomIconFromFile:(NSString*)path
{
FSRef targetFileFSRef;
FSRef parentDirectoryFSRef;
SInt16 file;
OSStatus result;
struct FSCatalogInfo catInfo;
struct FileInfo *finderInfo = (struct FileInfo *)&catInfo.finderInfo;
Handle hExistingCustomIcon;
// Get an FSRef for the target file.
if (![path getFSRef:&targetFileFSRef createFileIfNecessary:NO])
return NO;
// Open the file's resource fork, if it has one.
file = FSOpenResFile( &targetFileFSRef, fsRdWrPerm );
if (file == -1)
return NO;
// Remove the file's existing kCustomIconResource of type kIconFamilyType
// (if any).
hExistingCustomIcon = GetResource( kIconFamilyType, kCustomIconResource );
if( hExistingCustomIcon )
RemoveResource( hExistingCustomIcon );
// Close the file's resource fork, flushing the resource map out to disk.
CloseResFile( file );
if (ResError() != noErr)
return NO;
// Now we need to set the file's Finder info so the Finder will know that
// it has no custom icon. Start by getting the file's current Finder info.
// Also get an FSRef for its parent directory, that we can use in the
// FNNotify() call below.
result = FSGetCatalogInfo(
&targetFileFSRef,
kFSCatInfoFinderInfo,
&catInfo,
/*outName*/ NULL,
/*fsSpec*/ NULL,
&parentDirectoryFSRef );
if (result != noErr)
return NO;
// Clear the kHasCustomIcon flag and the kHasBeenInited flag.
finderInfo->finderFlags = finderInfo->finderFlags & ~(kHasCustomIcon | kHasBeenInited);
// Now write the Finder info back.
result = FSSetCatalogInfo( &targetFileFSRef, kFSCatInfoFinderInfo, &catInfo );
if (result != noErr)
return NO;
// Notify the system that the directory containing the file has changed, to give Finder the chance to find out about the file's new custom icon.
result = FNNotify( &parentDirectoryFSRef, kFNDirectoryModifiedMessage, kNilOptions );
if (result != noErr)
return NO;
return YES;
}
- (BOOL) setAsCustomIconForDirectory:(NSString*)path
{
return [self setAsCustomIconForDirectory:path withCompatibility:NO];
}
- (BOOL) setAsCustomIconForDirectory:(NSString*)path withCompatibility:(BOOL)compat
{
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isDir;
BOOL exists;
NSString *iconrPath;
FSRef targetFolderFSRef, iconrFSRef;
SInt16 file;
OSErr result;
struct HFSUniStr255 filename;
struct FSCatalogInfo catInfo;
Handle hExistingCustomIcon;
Handle hIconFamilyCopy;
// Confirm that "path" exists and specifies a directory.
exists = [fm fileExistsAtPath:path isDirectory:&isDir];
if( !isDir || !exists )
return NO;
// Get an FSRef for the folder.
if( ![path getFSRef:&targetFolderFSRef createFileIfNecessary:NO] )
return NO;
// Remove and re-create any existing "Icon\r" file in the directory, and get an FSRef for it.
iconrPath = [path stringByAppendingPathComponent:@"Icon\r"];
if( [fm fileExistsAtPath:iconrPath] )
{
if( ![fm removeFileAtPath:iconrPath handler:nil] )
return NO;
}
if( ![iconrPath getFSRef:&iconrFSRef createFileIfNecessary:YES] )
return NO;
// Get type and creator information for the Icon file.
result = FSGetCatalogInfo(
&iconrFSRef,
kFSCatInfoFinderInfo,
&catInfo,
/*outName*/ NULL,
/*fsSpec*/ NULL,
/*parentRef*/ NULL );
if( result == fnfErr ) {
// The file doesn't exist. Prepare to create it.
struct FileInfo *finderInfo = (struct FileInfo *)catInfo.finderInfo;
// These are the file type and creator given to Icon files created by
// the Finder.
finderInfo->fileType = 'icon';
finderInfo->fileCreator = 'MACS';
// Icon files should be invisible.
finderInfo->finderFlags = kIsInvisible;
// Because the inited flag is not set in finderFlags above, the Finder
// will ignore the location, unless it's in the 'magic rectangle' of
// { -24,000, -24,000, -16,000, -16,000 } (technote TB42).
// So we need to make sure to set this to zero anyway, so that the
// Finder will position it automatically. If the user makes the Icon
// file visible for any reason, we don't want it to be positioned in an
// exotic corner of the window.
finderInfo->location.h = finderInfo->location.v = 0;
// Standard reserved-field practice.
finderInfo->reservedField = 0;
} else if( result != noErr )
return NO;
// Get the filename, to be applied to the Icon file.
filename.length = [@"Icon\r" length];
[@"Icon\r" getCharacters:filename.unicode];
// Make sure the file has a resource fork that we can open. (Although
// this sounds like it would clobber an existing resource fork, the Carbon
// Resource Manager docs for this function say that's not the case.)
FSCreateResFile(
&targetFolderFSRef,
filename.length,
filename.unicode,
kFSCatInfoFinderInfo,
&catInfo,
&iconrFSRef,
/*newSpec*/ NULL);
result = ResError();
if (!(result == noErr || result == dupFNErr))
return NO;
// Open the file's resource fork.
file = FSOpenResFile( &iconrFSRef, fsRdWrPerm );
if (file == -1)
return NO;
// Make a copy of the icon family data to pass to AddResource().
// (AddResource() takes ownership of the handle we pass in; after the
// CloseResFile() call its master pointer will be set to 0xffffffff.
// We want to keep the icon family data, so we make a copy.)
// HandToHand() returns the handle of the copy in hIconFamily.
hIconFamilyCopy = (Handle) hIconFamily;
result = HandToHand( &hIconFamilyCopy );
if (result != noErr) {
CloseResFile( file );
return NO;
}
// Remove the file's existing kCustomIconResource of type kIconFamilyType
// (if any).
hExistingCustomIcon = GetResource( kIconFamilyType, kCustomIconResource );
if( hExistingCustomIcon )
RemoveResource( hExistingCustomIcon );
// Now add our icon family as the file's new custom icon.
AddResource( (Handle)hIconFamilyCopy, kIconFamilyType,
kCustomIconResource, "\p");
if (ResError() != noErr) {
CloseResFile( file );
return NO;
}
if( compat )
{
[self addResourceType:kLarge8BitData asResID:kCustomIconResource];
[self addResourceType:kLarge1BitMask asResID:kCustomIconResource];
[self addResourceType:kSmall8BitData asResID:kCustomIconResource];
[self addResourceType:kSmall1BitMask asResID:kCustomIconResource];
}
// Close the file's resource fork, flushing the resource map and new icon
// data out to disk.
CloseResFile( file );
if (ResError() != noErr)
return NO;