-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathGTResourceFork.m
2099 lines (1723 loc) · 57.1 KB
/
GTResourceFork.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
/*
Copyright (c) 2006 Jonathan Grynspan.
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 <SproutedUtilities/GTResourceFork.h>
#if defined(__cplusplus)
#include <stdlib>
#include <string>
using namespace std;
extern "C" {
#else
#include <stdlib.h>
#include <string.h>
#endif
#pragma mark Threading and Memory
#if defined(MF_APPLICATION)
/* mFurc wraps malloc, etc. in inlined functions for debugging purposes */
#include <FurcKit/GTMemory.h>
/* mFurc uses a different implementation for the GTMutexRef type/functions */
#include <FurcKit/GTThreading.h>
#else /* defined(MF_APPLICATION) */
/* you can substitute your own memory management functions if you want (e.g.
NewPtrClear/DisposePtr, or NSZoneCalloc/NSZoneFree), but you must ensure
the allocated memory is zeroed before the macro/function returns. */
#define GTAllocate(SIZE) calloc(1, SIZE)
#define GTFree(PTR) free(PTR)
/* you can use some other implementation here too */
typedef NSRecursiveLock *GTMutexRef;
#define GTMutexCreate(RECURSIVE) ((RECURSIVE) ? [[NSRecursiveLock alloc] init] : [[NSLock alloc] init])
#define GTMutexDestroy(MUTEX) [(MUTEX) release]
#define GTMutexLock(MUTEX) ({ id __mutex = (MUTEX); [__mutex lock]; (__mutex != nil); })
#define GTMutexTryLock(MUTEX) [(MUTEX) tryLock]
#define GTMutexUnlock(MUTEX) ({ id __mutex = (MUTEX); [__mutex unlock]; (__mutex != nil); })
#endif /* defined(MF_APPLICATION) */
#pragma mark -
#pragma mark Global Variables
/* the global mutex for the Resource Manager */
static GTMutexRef resourcesMutex = (GTMutexRef)0;
/* This is a CFMutableDictionary instead of an NSMutableDictionary because we don't
want to mess with the retain counts for values--if we do, we could end up unable to
deallocate a resource fork because the table will always reference it. */
/* The reason we have this dictionary at all is so that two GTResourceFork objects aren't
created that have the same reference number. If they were, and one is deallocated,
it will close the reference number, leaving the other with an invalid reference
number. Better to maintain only one GTResourceFork object per reference number. */
static CFMutableDictionaryRef activeResourceForks = NULL;
#pragma mark -
#pragma mark Resource Sections
/* Used when beginning and ending a "resource section", which locks access to the
Resource Manager so one can send multiple GTResourceFork messages or call
multiple Resource Manager functions. */
struct OpaqueGTResourceSectionStateStruct {
ResFileRefNum lastRefNum;
id unretainedOwner;
};
#pragma mark -
#pragma mark String Encodings
const NSStringEncoding GTResourceForkStringEncoding = NSMacOSRomanStringEncoding;
const CFStringEncoding kGTResourceForkCFStringEncoding = kCFStringEncodingMacRoman;
#pragma mark -
#pragma mark Private GTResourceFork Category Interfaces
@interface GTResourceFork (Styles)
- (NSAttributedString *)attributedStringFromString: (NSString *)str andStyleHandle: (Handle)hand;
- (NSColor *)colorForStyleEntry: (ScrpSTElement *)entry;
- (NSFont *)fontForStyleEntry: (ScrpSTElement *)entry;
- (NSFontTraitMask)traitMaskForStyleEntry: (ScrpSTElement *)entry;
@end
@interface GTResourceFork (Cursors)
- (NSCursor *)cursorFromcrsrResource: (Handle)cursHand;
- (NSCursor *)cursorFromCURSResource: (Handle)cursHand;
- (NSImageRep *)imageRepWithBits16Data: (const Bits16)data andMask: (const Bits16)mask;
//- (NSImageRep *)imageRepWithColorCursor: (CCrsrPtr)cursor;
@end
#pragma mark -
#pragma mark GTResourceFork Implementation
@implementation GTResourceFork
+ (void)initialize {
CFDictionaryValueCallBacks valueCallbacks;
resourcesMutex = GTMutexCreate(YES);
/* don't want to mess with the retain count of the values */
valueCallbacks.version = 0;
valueCallbacks.retain = NULL;
valueCallbacks.release = NULL;
valueCallbacks.copyDescription = NULL;
valueCallbacks.equal = NULL;
activeResourceForks = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &valueCallbacks);
}
+ (GTResourceFork *)systemResourceFork {
static GTResourceFork *sysFork = nil;
GTResourceSectionStateRef state;
/* only create one resource fork object for the system resource fork */
if (NULL != (state = [self beginGlobalResourceSection])) {
if (!sysFork)
sysFork = [[GTResourceFork alloc] initWithResourceManagerReferenceNumber: kSystemResFile error: NULL];
[self endGlobalResourceSection: state];
}
return [[sysFork retain] autorelease];
}
- (id)init {
return [self initWithData: nil];
}
- (id)initWithData: (NSData *)data {
CFUUIDRef uuid;
CFStringRef uuidString;
NSString *tempPath;
/* get the temporary path */
tempPath = nil;
uuid = CFUUIDCreate(NULL);
if (uuid) {
uuidString = CFUUIDCreateString(NULL, uuid);
if (uuidString) {
tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @"GTResourceFork-%@", uuidString]];
CFRelease(uuidString);
}
CFRelease(uuid);
}
/* write the resource-fork-as-data to the temporary file */
if (tempPath && data) {
[data writeToFile: tempPath atomically: YES];
}
/* proceed as normal */
self = [self initWithContentsOfFile: tempPath dataFork: YES];
if (self)
self->isTemporary = YES;
return self;
}
- (id)initWithContentsOfFile: (NSString *)filename {
return [self initWithContentsOfFile: filename dataFork: NO error: NULL];
}
- (id)initWithContentsOfFile: (NSString *)filename dataFork: (BOOL)df {
return [self initWithContentsOfFile: filename dataFork: df error: NULL];
}
- (id)initWithContentsOfFile: (NSString *)filename dataFork: (BOOL)df error: (NSError **)outError {
/* +fileURLWithPath: throws on nil */
if (filename)
return [self initWithContentsOfURL: [NSURL fileURLWithPath: filename] dataFork: df error: outError];
else
return [self initWithContentsOfURL: nil dataFork: df error: outError];
}
- (id)initWithContentsOfURL: (NSURL *)url {
return [self initWithContentsOfURL: url dataFork: NO error: NULL];
}
- (id)initWithContentsOfURL: (NSURL *)url dataFork: (BOOL)df {
return [self initWithContentsOfURL: url dataFork: df error: NULL];
}
- (id)initWithContentsOfURL: (NSURL *)url dataFork: (BOOL)df error: (NSError **)outError {
FSRef ref;
/* make sure the URL can be used with the resource manager and that the file exists, even if empty */
if (url) {
if ([url isFileURL] && ![[NSFileManager defaultManager] fileExistsAtPath: [url path]]) {
if (![[NSData data] writeToFile: [url path] atomically: YES])
url = nil;
}
}
/* URL -> FSRef, create object */
if (url && CFURLGetFSRef((CFURLRef)url, &ref)) {
return [self initWithContentsOfFSRef: &ref dataFork: df error: outError];
}
return [self initWithContentsOfFSRef: NULL namedFork: NULL error: outError];
}
- (id)initWithContentsOfFSRef: (const FSRef *)ref {
return [self initWithContentsOfFSRef: ref dataFork: NO error: NULL];
}
- (id)initWithContentsOfFSRef: (const FSRef *)ref dataFork: (BOOL)df {
return [self initWithContentsOfFSRef: ref dataFork: df error: NULL];
}
- (id)initWithContentsOfFSRef: (const FSRef *)ref dataFork: (BOOL)df error: (NSError **)outError {
HFSUniStr255 forkName;
OSErr error;
if (ref) {
/* get the name for the resource fork */
if (df)
error = FSGetDataForkName(&forkName);
else
error = FSGetResourceForkName(&forkName);
/* proceed as normal */
if (error == noErr) {
return [self initWithContentsOfFSRef: ref namedFork: &forkName error: outError];
}
}
/* some error above */
return [self initWithContentsOfFSRef: NULL namedFork: NULL error: outError];
}
- (id)initWithContentsOfFSRef: (const FSRef *)ref namedFork: (ConstHFSUniStr255Param)frk {
return [self initWithContentsOfFSRef: ref namedFork: frk error: NULL];
}
- (id)initWithContentsOfFSRef: (const FSRef *)ref namedFork: (ConstHFSUniStr255Param)forkName error: (NSError **)outError {
GTResourceSectionStateRef state;
OSErr error;
ResFileRefNum refNumber;
self = [super init];
if (self) {
/* if left unchanged, will cause self to be released/nilled on
call to -initWithResourceManagerReferenceNumber:error: */
refNumber = -1;
if (!ref || !forkName) {
error = paramErr;
} else {
/* no error by default, natch */
error = noErr;
if (NULL != (state = [[self class] beginGlobalResourceSection])) {
/* create the fork */
if (error == noErr) {
error = FSCreateResourceFork(ref, forkName->length, forkName->unicode, 0);
if (error == errFSForkExists)
error = noErr;
}
/* open the fork */
if (error == noErr) {
error = FSOpenResourceFile(ref, forkName->length, forkName->unicode, fsRdWrPerm, &refNumber);
if (error != noErr)
refNumber = -1;
}
/* exit resource section */
[[self class] endGlobalResourceSection: state];
} else {
/* failed to enter resource section */
error = notLockedErr;
}
}
/* catch errors */
self = [self initWithResourceManagerReferenceNumber: refNumber error: outError];
if (error != noErr) {
if (outError) {
*outError = [NSError errorWithDomain: NSOSStatusErrorDomain code: (int)error userInfo: nil];
}
}
}
return self;
}
- (id)initWithResourceManagerReferenceNumber: (ResFileRefNum)refNumber {
return [self initWithResourceManagerReferenceNumber: refNumber error: NULL];
}
- (id)initWithResourceManagerReferenceNumber: (ResFileRefNum)refNumber error: (NSError **)outError {
GTResourceFork *otherFork;
GTResourceSectionStateRef state;
CFNumberRef key;
OSErr error;
self = [super init];
if (self) {
self->refNum = -1;
error = noErr;
if (refNumber >= 0) {
if (NULL != (state = [[self class] beginGlobalResourceSection])) {
/* check if the refNumber is in use */
key = CFNumberCreate(NULL, kCFNumberShortType, &refNumber);
if (key)
otherFork = (GTResourceFork *)CFDictionaryGetValue(activeResourceForks, key);
else
otherFork = nil;
if (otherFork) {
/* is already open, so kill self and replace with otherFork */
[self release];
self = [otherFork retain];
} else {
/* isn't already open, so creating a new fork object */
/* check if the refNumber is open by calling GetResFileAttrs and then checking ResError */
GetResFileAttrs(refNumber);
error = ResError();
if (error == noErr) {
/* success, set fields */
self->refNum = refNumber;
self->isTemporary = NO;
/* add to dictionary so it'll be used again */
if (key)
CFDictionarySetValue(activeResourceForks, key, self);
}
}
/* done with the key object */
if (key)
CFRelease(key);
/* exit section */
[[self class] endGlobalResourceSection: state];
} else {
/* couldn't enter section, so fail */
error = notLockedErr;
}
} else {
/* refNumber is less than 0, so is invalid */
error = paramErr;
}
if (error != noErr) {
/* error occurred, free self */
[self release];
self = nil;
if (outError)
*outError = [NSError errorWithDomain: NSOSStatusErrorDomain code: (int)error userInfo: nil];
}
}
return self;
}
- (id)retain {
id result;
GTResourceSectionStateRef state;
/* the lock here is so that the call in -release to -retainCount is not interrupted
by this call to -retain; if it fails, still retain */
state = [[self class] beginGlobalResourceSection];
result = [super retain];
[[self class] endGlobalResourceSection: state];
return result;
}
- (void)release {
GTResourceSectionStateRef state;
CFNumberRef key;
/* have to do this in -release rather than in -dealloc because of the following possibility:
Thread 0: Thread 1:
[aFork release];
newFork = [[GTResourceFork alloc] initWithResourceManagerReferenceNumber: aFork's number];
[aFork dealloc];
*/
state = [[self class] beginGlobalResourceSection];
if ([self retainCount] == 1) {
/* last release -- remove self from the table, so that
future resource forks on the same refNum will create
their own objects */
key = CFNumberCreate(NULL, kCFNumberShortType, &(self->refNum));
if (key) {
CFDictionaryRemoveValue(activeResourceForks, key);
CFRelease(key);
}
}
[[self class] endGlobalResourceSection: state];
[super release];
}
- (void)dealloc {
NSURL *url;
GTResourceSectionStateRef state;
if (self->isTemporary) {
/* delete file on disk */
url = [self URL];
if (url && [url isFileURL])
[[NSFileManager defaultManager] removeFileAtPath: [url path] handler: nil];
}
if (NULL != (state = [[self class] beginGlobalResourceSection])) {
/* have to lock it because we're calling Resource Manager functions */
if (self->refNum > 0) {
/* let Resource Manager know we're done */
CloseResFile(self->refNum);
}
[[self class] endGlobalResourceSection: state];
}
[super dealloc];
}
- (BOOL)isEqual: (id)anObject {
if ([anObject isKindOfClass: [GTResourceFork class]]) {
return [self isEqualToResourceFork: anObject];
}
return NO;
}
- (BOOL)isEqualToResourceFork: (GTResourceFork *)resourceFork {
return [self resourceManagerReferenceNumber] == [resourceFork resourceManagerReferenceNumber];
}
- (unsigned int)hash {
return (unsigned int)[self resourceManagerReferenceNumber];
}
- (id)copyWithZone: (NSZone *)zone {
return [self retain];
}
- (void)copyResourcesToResourceFork: (GTResourceFork *)otherFork {
NSEnumerator *e;
NSString *type;
GTResourceSectionStateRef state;
if (!otherFork || otherFork == self)
return;
if (NULL != (state = [self beginResourceSection])) {
e = [[self usedTypes] objectEnumerator];
while ((type = [e nextObject]) != nil) {
[self copyResourcesOfType: GTResTypeFromString(type) toResourceFork: otherFork];
}
[self endResourceSection: state];
}
}
- (void)copyResourcesOfType: (ResType)type toResourceFork: (GTResourceFork *)otherFork {
GTResourceSectionStateRef state;
if (!otherFork || otherFork == self)
return;
if (NULL != (state = [self beginResourceSection])) {
[self copyResources: [self usedResourcesOfType: type] ofType: type toResourceFork: otherFork];
[self endResourceSection: state];
}
}
- (void)copyResources: (NSArray *)resIDs ofType: (ResType)type toResourceFork: (GTResourceFork *)otherFork {
NSEnumerator *e;
NSNumber *resIDNumber;
GTResourceSectionStateRef state;
NSData *resData;
ResID resID;
if (!otherFork || otherFork == self)
return;
else if (!resIDs || [resIDs count] < 1)
return;
/* global resource section so we can deal with multiple forks at a time */
if (NULL != (state = [[self class] beginGlobalResourceSection])) {
e = [resIDs objectEnumerator];
while ((resIDNumber = [e nextObject]) != nil) {
/* get the resource ID number */
resID = (ResID)[resIDNumber shortValue];
/* get the resource data */
resData = [self dataForResource: resID ofType: type];
/* set it on the other fork */
[otherFork setData: resData forResource: resID withName: [self nameOfResource: resID ofType: type] ofType: type];
}
[[self class] endGlobalResourceSection: state];
}
}
- (NSURL *)URL {
NSURL *result;
FSRef fsRef;
result = nil;
if (FSGetForkCBInfo([self resourceManagerReferenceNumber], 0, NULL, NULL, NULL, &fsRef, NULL) == noErr) {
result = (NSURL *)CFURLCreateFromFSRef(NULL, &fsRef);
result = [result autorelease];
}
return result;
}
- (NSData *)dataRepresentation {
NSData *result;
NSMutableData *mutResult;
GTResourceSectionStateRef state;
char buffer[512];
SInt64 offset;
ByteCount got;
OSErr error;
ResFileRefNum myRefNum;
/* iterates through the resource fork as a byte stream, reading it in
512 bytes at a time, outputting to mutResult, and returning an
immutable copy thereof */
mutResult = nil;
if (NULL != (state = [self beginResourceSection])) {
/* make sure changes are synchronized */
[self write];
/* capacity of 16KB by default */
mutResult = [[NSMutableData alloc] initWithCapacity: 16384];
offset = S64SetU(0);
got = 0;
myRefNum = [self resourceManagerReferenceNumber];
do {
/* read a chunk of data from the fork */
error = FSReadFork(myRefNum, fsFromStart, offset, (ByteCount)sizeof(buffer), buffer, &got);
if (error != noErr && error != eofErr)
break;
/* write that chunk to the result object */
[mutResult appendBytes: buffer length: (unsigned int)got];
/* update the offset */
offset = S64Add(offset, S64SetU(got));
} while (got > 0);
[self endResourceSection: state];
}
result = [[mutResult copy] autorelease];
[mutResult release];
return result;
}
- (NSString *)description {
return [NSString stringWithFormat: @"%@ { ResFileRefNum: %i }", [super description], [self resourceManagerReferenceNumber]];
}
- (BOOL)writeToFile: (NSString *)filename dataFork: (BOOL)df {
if (filename)
return [self writeToURL: [NSURL fileURLWithPath: filename] dataFork: df];
else
return NO;
}
- (BOOL)writeToURL: (NSURL *)aURL dataFork: (BOOL)df {
GTResourceFork *tempFork;
BOOL result;
if ([aURL isEqual: [self URL]]) {
/* don't need to create a temp object */
result = [self write];
} else {
/* fail by default */
result = NO;
/* create a temp object attached to the passed URL, then write *that* object */
tempFork = [[GTResourceFork alloc] initWithContentsOfURL: aURL dataFork: df];
if (tempFork) {
/* write self to temp */
result = [self writeToResourceFork: tempFork];
/* sync */
[tempFork write];
/* free mem */
[tempFork release];
}
}
return result;
}
- (BOOL)writeToResourceFork: (GTResourceFork *)fork {
NSAutoreleasePool *pool;
NSData *data;
GTResourceSectionStateRef state;
ByteCount written;
ResFileRefNum forkRefNum;
BOOL success;
pool = [[NSAutoreleasePool alloc] init];
fork = [[fork retain] autorelease];
success = NO;
if (fork) {
data = [self dataRepresentation];
if (NULL != (state = [fork beginResourceSection])) {
forkRefNum = [fork resourceManagerReferenceNumber];
written = 0;
/* first, set the fork size to the size of the outgoing data; this will prevent extraneous
data trailing at the end of the file */
success = (noErr == FSSetForkSize(forkRefNum, fsFromStart, S64SetU([data length])));
if (success) {
/* now, write the data to the fork */
success = (noErr == FSWriteFork(forkRefNum, fsFromStart, S64SetU(0), (ByteCount)[data length], [data bytes], &written));
if (success) {
/* write that fork to disk */
success = [fork write];
}
}
[fork endResourceSection: state];
}
}
[pool release];
return success;
}
- (BOOL)write {
GTResourceSectionStateRef state;
BOOL result;
result = NO;
if (NULL != (state = [self beginResourceSection])) {
/* the Resource Manager function for this */
UpdateResFile([self resourceManagerReferenceNumber]);
/* if there was a problem writing, ResError() is set */
result = (ResError() == noErr);
[self endResourceSection: state];
}
return result;
}
- (void)flushChanges {
NSLog(@"calling deprecated method -[GTResourceFork flushChanges]; use -write instead");
(void)[self write];
}
- (ResFileRefNum)resourceManagerReferenceNumber {
/* If in a multithreaded environment, be sure to call -beginResourceSection
first and -endResourceSection: after! This class doesn't always obey this
rule, but when it breaks it it's for good reason (e.g. deallocating self.) */
return self->refNum;
}
- (NSData *)dataForResource: (ResID)resID ofType: (ResType)type {
Handle hand;
hand = [self handleForResource: resID ofType: type];
if (hand && *hand) {
return [NSData dataWithBytes: *hand length: GTUnsignedIntFromSize(GetHandleSize(hand))];
} else {
return nil;
}
}
- (NSData *)dataForNamedResource: (NSString *)name ofType: (ResType)type {
Handle hand;
hand = [self handleForNamedResource: name ofType: type];
if (hand && *hand) {
return [NSData dataWithBytes: *hand length: GTUnsignedIntFromSize(GetHandleSize(hand))];
} else {
return nil;
}
}
- (void)setData: (NSData *)data forResource: (ResID)resID ofType: (ResType)type {
[self setData: data forResource: resID withName: nil ofType: type];
}
- (void)setData: (NSData *)data forNamedResource: (NSString *)name ofType: (ResType)type {
GTResourceSectionStateRef state;
ResID resID;
if (NULL != (state = [self beginResourceSection])) {
if ([self getUniqueID: &resID forType: type]) {
[self setData: data forResource: resID withName: name ofType: type];
}
[self endResourceSection: state];
}
}
- (void)setData: (NSData *)data forResource: (ResID)resID withName: (NSString *)name ofType: (ResType)type {
ConstStringPtr pascStr;
GTResourceSectionStateRef state;
Handle hand;
if (NULL != (state = [self beginResourceSection])) {
[self removeDataForNamedResource: name ofType: type];
if (!name)
name = @"";
pascStr = GTStringGetPascalString(name);
if (data && pascStr) {
hand = NULL;
if (noErr == PtrToHand([data bytes], &hand, GTSizeFromUnsignedInt([data length]))) {
/* got ID, yay */
AddResource(hand, type, resID, pascStr);
if (noErr == ResError()) {
/* success adding resource */
ChangedResource(hand);
} else {
/* failure */
DisposeHandle(hand);
}
}
}
[self endResourceSection: state];
}
}
- (void)removeDataForResource: (ResID)resID ofType: (ResType)type {
GTResourceSectionStateRef state;
Handle hand;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForResource: resID ofType: type];
if (hand) {
RemoveResource(hand);
/* the handle is orphaned by RemoveResource() */
DisposeHandle(hand);
}
[self endResourceSection: state];
}
}
- (void)removeDataForNamedResource: (NSString *)name ofType: (ResType)type {
GTResourceSectionStateRef state;
Handle hand;
if (!name)
return;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForNamedResource: name ofType: type];
if (hand) {
RemoveResource(hand);
/* the handle is orphaned by RemoveResource() */
DisposeHandle(hand);
}
[self endResourceSection: state];
}
}
- (void)removeAllResourcesOfType: (ResType)type {
GTResourceSectionStateRef state;
Handle hand;
unsigned int resCount;
if (NULL != (state = [self beginResourceSection])) {
resCount = [self countOfResourcesOfType: type];
unsigned int i = 0; for (; i < resCount; i++) {
hand = Get1IndResource(type, i + 1);
if (hand) {
RemoveResource(hand);
/* the handle is orphaned by RemoveResource() */
DisposeHandle(hand);
}
}
[self endResourceSection: state];
}
}
- (BOOL)hasResource: (ResID)resID ofType: (ResType)type {
/* no Resource Manager function to specifically check for the existence of a resource, so must load it */
return [self handleForResource: resID ofType: type] ? YES : NO;
}
- (BOOL)hasNamedResource: (NSString *)name ofType: (ResType)type {
/* no Resource Manager function to specifically check for the existence of a resource, so must load it */
return [self handleForNamedResource: name ofType: type] ? YES : NO;
}
- (unsigned int)sizeOfResource: (ResID)resID ofType: (ResType)type {
GTResourceSectionStateRef state;
Handle hand;
unsigned int result;
result = 0;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForResource: resID ofType: type];
if (hand && *hand)
result = GTUnsignedIntFromSize(GetHandleSize(hand));
[self endResourceSection: state];
}
return result;
}
- (unsigned int)sizeOfNamedResource: (NSString *)name ofType: (ResType)type {
GTResourceSectionStateRef state;
Handle hand;
unsigned int result;
result = 0;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForNamedResource: name ofType: type];
if (hand && *hand)
result = GTUnsignedIntFromSize(GetHandleSize(hand));
[self endResourceSection: state];
}
return result;
}
- (BOOL)getID: (ResID *)outID ofNamedResource: (NSString *)name ofType: (ResType)type {
Handle hand;
GTResourceSectionStateRef state;
ResID theID;
BOOL gotIt;
theID = 0;
gotIt = NO;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForNamedResource: name ofType: type];
if (hand) {
if ([[self class] getInfoForHandle: hand type: NULL name: NULL ID: &theID]) {
gotIt = YES;
}
}
[self endResourceSection: state];
}
if (gotIt) {
if (outID)
*outID = theID;
}
return gotIt;
}
- (NSString *)nameOfResource: (ResID)resID ofType: (ResType)type {
NSString *result;
Handle hand;
GTResourceSectionStateRef state;
result = nil;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForResource: resID ofType: type];
if (hand) {
if (![[self class] getInfoForHandle: hand type: NULL name: &result ID: NULL]) {
result = nil;
}
}
[self endResourceSection: state];
}
return result;
}
- (void)setID: (ResID)resID ofNamedResource: (NSString *)name ofType: (ResType)type {
Handle hand;
GTResourceSectionStateRef state;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForNamedResource: name ofType: type];
if (hand) {
/* Passing an empty Pascal string as the name does not change
it, so there's no need to call GTStringGetPascalString() here. */
SetResInfo(hand, resID, "\p");
}
[self endResourceSection: state];
}
}
- (void)setName: (NSString *)name ofResource: (ResID)resID ofType: (ResType)type {
NSData *data;
Handle hand;
GTResourceSectionStateRef state;
if (NULL != (state = [self beginResourceSection])) {
hand = [self handleForResource: resID ofType: type];
if (hand) {
if (!name || [name length] < 1) {
/* SetResInfo() won't change the name if the passed string is
empty, so have to go about it a different way. Delete the existing
resource, then add a new one with the same ID and no name. */
data = [NSData dataWithBytes: *hand length: GTUnsignedIntFromSize(GetHandleSize(hand))];
[self removeDataForResource: resID ofType: type];
[self setData: data forResource: resID ofType: type];
} else {
/* Can do it the normal way. */
SetResInfo(hand, resID, GTStringGetPascalString(name));
}
}
[self endResourceSection: state];
}
}
@end
@implementation GTResourceFork (ThreadSafety)
+ (GTResourceSectionStateRef)beginGlobalResourceSection {
struct OpaqueGTResourceSectionStateStruct *result;
/* Creates a pointer to a state structure, locks the resource mutex, fills the
state with the currently-selected resource file refnum, returns pointer to state. */
result = GTAllocate(sizeof(struct OpaqueGTResourceSectionStateStruct));
if (result) {
if (GTMutexLock(resourcesMutex)) {
result->lastRefNum = CurResFile();
result->unretainedOwner = self;
} else {
/* couldn't obtain lock, must release memory to avoid leak */
GTFree(result);
result = NULL;
}
}
return result;
}
+ (void)endGlobalResourceSection: (GTResourceSectionStateRef)state {
/* Restores the currently-used resource file to its old refnum, unlocks the
resource mutex, and frees the allocated memory. */
if (state) {
UseResFile(state->lastRefNum);
GTMutexUnlock(resourcesMutex);
GTFree(state);
}
}
- (GTResourceSectionStateRef)beginResourceSection {
struct OpaqueGTResourceSectionStateStruct *result;
result = [[self class] beginGlobalResourceSection];
if (result) {
result->unretainedOwner = self;
UseResFile([self resourceManagerReferenceNumber]);
}
return result;
}
- (void)endResourceSection: (GTResourceSectionStateRef)state {
/* don't rely on this behaviour being identical in the future */
[[self class] endGlobalResourceSection: state];
}
+ (id)ownerOfResourceSectionState: (GTResourceSectionStateRef)state {
if (state) {
return [[state->unretainedOwner retain] autorelease];
}
return nil;
}
@end
@implementation GTResourceFork (Handles)
+ (GTResourceFork *)resourceForkOwningHandle: (Handle)aResource {
return [self resourceForkOwningHandle: aResource createIfNotFound: YES];
}
+ (GTResourceFork *)resourceForkOwningHandle: (Handle)aResource createIfNotFound: (BOOL)create {
GTResourceSectionStateRef state;
GTResourceFork *result;
CFNumberRef key;
ResFileRefNum refNum;
result = nil;
if (NULL != (state = [self beginGlobalResourceSection])) {
refNum = HomeResFile(aResource);
if (ResError() == noErr) {
/* fork exists! */
if (refNum == 0) {
/* system resource fork */