-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing11.html
executable file
·1587 lines (1296 loc) · 53.5 KB
/
listing11.html
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>ThreadsExporter - /MyDocument.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/Cocoa/index.html">Cocoa</a> > <a href="../../samplecode/Cocoa/idxQuickTime-date.html">QuickTime</a> > <A HREF="javascript:location.replace('index.html');">ThreadsExporter</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">ThreadsExporter</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/MyDocument.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/AutoRunSettings.h</option>
<option value="listing2.html">/AutoRunSettings.m</option>
<option value="listing3.html">/DataRefUtilities.c</option>
<option value="listing4.html">/DataRefUtilities.h</option>
<option value="listing5.html">/ExporterObject.h</option>
<option value="listing6.html">/ExporterObject.m</option>
<option value="listing7.html">/FileObject.h</option>
<option value="listing8.html">/FileObject.m</option>
<option value="listing9.html">/main.m</option>
<option value="listing10.html">/MyDocument.h</option>
<option value="listing11.html">/MyDocument.m</option>
<option value="listing12.html">/ThreadData.h</option>
<option value="listing13.html">/ThreadsExporter_Prefix.h</option>
<option value="listing14.html">/URLUtilities.c</option>
<option value="listing15.html">/URLUtilities.h</option>
<option value="listing16.html">/WorkerThread.c</option>
<option value="listing17.html">/WorkerThread.h</option></select>
</p>
</form>
<p><strong><a href="ThreadsExporter.zip">Download Sample</a></strong> (“ThreadsExporter.zip”, 139.0K)<BR>
<strong><a href="ThreadsExporter.dmg">Download Sample</a></strong> (“ThreadsExporter.dmg”, 185.3K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">/*
File: MyDocument.m
Description: Document-specific code for thread-safety test application.
Author: QTEngineering, dts
Copyright: © Copyright 2003 Apple Computer, Inc. All rights reserved.
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apple's
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first): <1> dts 11/06/03 fixes for initial release
*/
//////////
//
// header files
//
//////////
#import "MyDocument.h"
#import "AutoRunSettings.h"
#import "ExporterObject.h"
#import "DataRefUtilities.h"
#import "WorkerThread.h"
#import <fcntl.h>
//////////
//
// non-Controller function declarations
//
//////////
static OSErr exportTheImage (ThreadData *threadData);
static pascal OSErr imageProgressProc (short message, Fixed percentDone, long refCon);
void workerActionRoutine (void *refcon, WorkerRequestRef request);
void workerCancelRoutine (void *refcon, WorkerRequestRef request);
void workerResponseMainThreadCallback (void *refcon, WorkerRequestRef request);
static void convert4CharsToPString (OSType ext, StringPtr str, Boolean downcase);
//////////
//
// static global variables
//
//////////
static ICMProgressUPP gImageProgressProcUPP = NULL; // UPP for our progress procedure
static UInt32 gNumIteration = 0;
static unsigned long gOSVersion = 0;
#pragma mark-
//////////
//
// MyDocument implementation
//
//////////
@implementation MyDocument
- (id)init
{
WorkerThreadRef outWorker = NULL;
[super init];
if (self) {
autoRunSettings = [[AutoRunSettings alloc] init];
_threadModelTag = USE_POSIX_THREAD; // use POSIX threads by default
_dhTag = USE_FILE_DH; // use file data handler by default
_onlySafeComponents = YES; // use only thread-safe components by default
// allocate progress proc UPP, if necessary
if (gImageProgressProcUPP == NULL)
gImageProgressProcUPP = NewICMProgressUPP(imageProgressProc);
// get the current version of the OS we're running on
Gestalt(gestaltSystemVersion, &gOSVersion);
if (gOSVersion < 0x00001030) {
// thread-safe components are available only in 10.3 (Panther) and beyond; for earlier systems,
// don't allow POSIX threads
_threadModelTag = USE_MAIN_THREAD;
}
// add a notification observer to monitor selections in the file table view
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tableViewSelectionDidChange:)
name:NSTableViewSelectionDidChangeNotification
object:fileTableView];
// create a worker thread handler
createWorkerThread(
workerActionRoutine,
workerCancelRoutine,
workerResponseMainThreadCallback,
(void *)self,
&outWorker);
_worker = outWorker;
}
// add available graphics exporters to _exporterArray
[self createExporterArray];
return self;
}
- (void)dealloc
{
// remove the worker thread handler
releaseWorkerThread(_worker);
// remove the notification that monitors selections in the file table view
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSTableViewSelectionDidChangeNotification
object:fileTableView];
// clean up the list of images
[self setFileArray:nil];
// clean up the list of export components
[self setExporterArray:nil];
if (_currThreadData != NULL) {
free(_currThreadData->expDirName);
free(_currThreadData);
_currThreadData = NULL;
}
[_outputDirName release];
[autoRunSettings release];
[super dealloc];
}
- (NSString *)windowNibName
{
return @"MyDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
// select the first item in the list, and reload the data
[exporterTableView selectRow:0 byExtendingSelection:NO];
[exporterTableView reloadData];
[super windowControllerDidLoadNib:aController];
}
- (void)showWindows
{
[super showWindows];
[self updateWindowTitle];
}
- (NSData *)dataRepresentationOfType:(NSString *)aType
{
return nil;
}
- (BOOL)loadDataRepresentation:(NSData *)data ofType:(NSString *)aType
{
return YES;
}
//////////
//
// grex finder
//
//////////
- (void)createExporterArray
{
// populate the array _exporterArray with graphics exporters meeting the current settings of this document
// (that is, either any graphics exporters or only the thread-safe ones)
NSMutableArray *exporterArray = [NSMutableArray array];
ComponentDescription desc, compDesc;
Component component = NULL;
GraphicsExportComponent exporter = NULL;
QTAtomContainer exporterList = NULL;
QTAtom atom = 0;
Ptr mimeType, exporterDesc = NULL;
Size mimeTypeSize, exporterDescSize;
OSType fileExtension;
Str31 fileExtensionStr;
UInt32 count = 0;
OSErr err = noErr;
desc.componentType = GraphicsExporterComponentType;
desc.componentSubType = 0;
desc.componentManufacturer = 0;
desc.componentFlags = 0;
desc.componentFlagsMask = graphicsExporterIsBaseExporter | cmpIsMissing;
// overide for demo/testing purposes only
// we don't want to have components returning errors on open here
CSSetComponentsThreadMode(kCSAcceptAllComponentsMode);
if (_onlySafeComponents) {
desc.componentFlags = cmpThreadSafe;
desc.componentFlagsMask |= cmpThreadSafe;
}
do {
component = FindNextComponent(component, &desc);
if (component != NULL) {
// get the component information
err = GetComponentInfo(component, &compDesc, NULL, NULL, NULL);
if (err == noErr) {
ExporterObject *exporterObject = [[ExporterObject alloc] init];
char *compName, *compMIME, *compExt = NULL;
err = OpenAComponent(component, &exporter);
if (err == noErr) {
err = GraphicsExportGetMIMETypeList(exporter, &exporterList);
if (err == noErr) {
QTLockContainer(exporterList);
atom = QTFindChildByIndex(exporterList, kParentAtomIsContainer, kGraphicsExportMIMEType, 1, &atom);
if (atom != 0) {
err = QTGetAtomDataPtr(exporterList, atom, &mimeTypeSize, &mimeType);
compMIME = calloc(1, mimeTypeSize + 1);
BlockMove(mimeType, compMIME, mimeTypeSize);
}
atom = QTFindChildByIndex(exporterList, kParentAtomIsContainer, kGraphicsExportDescription, 1, &atom);
if (atom != 0) {
err = QTGetAtomDataPtr(exporterList, atom, &exporterDescSize, &exporterDesc);
if (err == noErr) {
compName = calloc(1, exporterDescSize + 1);
BlockMove(exporterDesc, compName, exporterDescSize);
}
}
QTUnlockContainer(exporterList);
QTDisposeAtomContainer(exporterList);
}
// get the file type extension (for example, .jpg)
err = GraphicsExportGetDefaultFileNameExtension(exporter, &fileExtension);
if (err == noErr) {
convert4CharsToPString(fileExtension, fileExtensionStr, true);
compExt = calloc(1, fileExtensionStr[0] + 1);
BlockMove(&fileExtensionStr[1], compExt, fileExtensionStr[0]);
}
}
// configure the exporter object
[exporterObject setExporter:exporter];
[exporterObject setDescription:compName];
[exporterObject setExtension:compExt];
[exporterObject setMIMEType:compMIME];
[exporterObject setFileType:compDesc.componentSubType];
// add the exporter object to the array
[exporterArray insertObject:exporterObject atIndex:count];
count++;
[exporterObject release]; // exporter object was retained by the array, so release this instance
}
}
} while (component != NULL);
[self setExporterArray:exporterArray];
}
//////////
//
// window notifications
//
//////////
- (void)windowWillClose:(NSNotification*)notification
{
// note that NSTimer's scheduledTimerWithTimeInterval method increments the retain count of its target,
// so we cannot release a timer in our dealloc method (since that method will never get called if at least one timer is active...)
// stop the timer
[self setAutoRunTimer:nil];
}
//////////
//
// window delegates
//
//////////
- (BOOL)windowShouldClose:(id)sender
{
WorkerRequestRef wkrRequest = NULL;
// the window wants to close; make sure the threads are closed down
if (_currThreadData != NULL) {
if (_currThreadData->threadModelTag == USE_POSIX_THREAD) {
if (_currThreadData->busy) {
// cancel the current worker request
wkrRequest = _currThreadData->request;
if (wkrRequest != NULL) {
// it's not safe to close the document window right now; cancel any current request
// and mark the document as wanting to be closed when it's safe to do so
cancelWorkerRequest(wkrRequest);
_currThreadData->closeWhenSafe = YES;
return NO;
}
}
} else if (_currThreadData->threadModelTag == USE_MAIN_THREAD) {
// dispose of the thread data and any memory it accesses
[self setCurrThreadData:NULL];
}
}
return YES;
}
//////////
//
// auto-run routines
//
//////////
- (void)cycleImages:(NSTimer *)timer
{
if (_doneExporting) {
if (_randomAutoRun) {
// select a random row for each table
double randFileNum = (rand()/(double)RAND_MAX) * [fileTableView numberOfRows];
UInt32 currFileRow = [fileTableView selectedRow];
UInt32 nextFileRow = (UInt32)randFileNum;
double randGrexNum = (rand()/(double)RAND_MAX) * [exporterTableView numberOfRows];
UInt32 currGrexRow = [exporterTableView selectedRow];
UInt32 nextGrexRow = (UInt32)randGrexNum;
if (currFileRow == nextFileRow) {
nextFileRow++;
if (nextFileRow >= [fileTableView numberOfRows]) {
nextFileRow = 0;
}
}
if (currGrexRow == nextGrexRow) {
nextGrexRow++;
if (nextGrexRow >= [exporterTableView numberOfRows]) {
nextGrexRow = 0;
}
}
_doneExporting = false;
[fileTableView selectRow:nextFileRow byExtendingSelection:NO];
[exporterTableView selectRow:nextGrexRow byExtendingSelection:NO];
[self doExport:nil];
} else {
if ((gNumIteration < _autoRunIterations) || (_autoRunIterations == 0)) {
int currFileRow = [fileTableView selectedRow];
int currGrexRow = [exporterTableView selectedRow];
currFileRow++;
if (currFileRow == [fileTableView numberOfRows]) {
currFileRow = 0;
currGrexRow++;
if (currGrexRow == [exporterTableView numberOfRows]) {
currGrexRow = 0;
gNumIteration++;
}
}
_doneExporting = false;
[fileTableView selectRow:currFileRow byExtendingSelection:NO];
[exporterTableView selectRow:currGrexRow byExtendingSelection:NO];
// export the selected file
[self doExport:nil];
} else {
// stop the auto-run
[self setAutoRunTimer:nil];
[autorunBtn setTitle:@"Auto-Run"];
}
}
}
}
- (void)setExportDoneState:(BOOL)state
{
_doneExporting = state;
}
//////////
//
// button action handlers
//
//////////
- (IBAction)autoRun:(id)sender {
gNumIteration = 0; // reset iteration counter
if (_autorunTimer == nil) {
_doneExporting = true; // just starting out, so we're not waiting on anybody
// reset to the end, so that cycleImages: bumps both lists to the beginning
[fileTableView selectRow:0 byExtendingSelection:NO];
[exporterTableView selectRow:0 byExtendingSelection:NO];
[self setAutoRunTimer:[NSTimer
scheduledTimerWithTimeInterval:kAutoRunInterval
target:self
selector:@selector(cycleImages:)
userInfo:nil
repeats:YES]];
[autorunBtn setTitle:@"Stop"];
} else {
[self setAutoRunTimer:nil];
[autorunBtn setTitle:@"Auto-Run"];
}
}
- (IBAction)selectFolder:(id)sender
{
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
NSString *filename;
NSString *dirname;
NSEnumerator *enumerator = nil;
UInt32 count = 0;
UInt32 dirPathLength = 0;
int result;
// elicit a folder from the user
[oPanel setCanChooseDirectories:YES];
[oPanel setCanChooseFiles:NO];
[oPanel setAllowsMultipleSelection:NO];
result = [oPanel runModalForTypes:nil];
if (result != NSOKButton)
return;
// no current thread data yet...
_currThreadData = NULL;
// enable the export and auto-run buttons but disable the select-folder button
[exportBtn setEnabled:YES];
[autorunBtn setEnabled:YES];
[folderBtn setEnabled:NO];
// allocate and retain a file array
[self setFileArray:[NSMutableArray array]];
dirname = [[oPanel filenames] objectAtIndex:0];
dirPathLength = [dirname cStringLength];
// put filenames and full pathnames into the file array
enumerator = [[[NSFileManager defaultManager] directoryContentsAtPath: [[oPanel filenames] objectAtIndex:0]] objectEnumerator];
while (filename = [enumerator nextObject]) {
if ([filename length] > 0) {
// don't allow any "hidden" files
if ([filename characterAtIndex:0] == '.')
continue;
FileObject *fileObject = [[FileObject alloc] init];
char *cFileName, *cPathName;
cFileName = malloc([filename cStringLength] + 1);
cPathName = malloc([filename cStringLength] + dirPathLength + 2);
if ((cFileName != NULL) && (cPathName != NULL)) {
[filename getCString:cFileName];
[[[oPanel filenames] objectAtIndex:0] getCString:cPathName];
*(cPathName + dirPathLength) = '/';
[filename getCString:cPathName + dirPathLength + 1];
[fileObject setPathName: cPathName];
[fileObject setFileName: cFileName];
}
// don't put directories in the list
NSDictionary *fattrs = [[NSFileManager defaultManager] fileAttributesAtPath:[NSString stringWithCString:cPathName] traverseLink:YES];
if (fattrs) {
NSString *fileType = [fattrs objectForKey:NSFileType];
if (fileType == NSFileTypeRegular) {
[_fileArray insertObject:fileObject atIndex:count];
count++;
}
[fileObject release]; // was retained by the array, so release this instance
}
}
}
// create a directory to hold the exported files; make sure the directory does not already exist
// (so that we can have multiple simultaneous exports going on the same folder of images)
count = 0;
_outputDirName = [NSString stringWithFormat:@"%@/%@", dirname, @"Output"];
while (![[NSFileManager defaultManager] createDirectoryAtPath:_outputDirName attributes:nil]) {
_outputDirName = [NSString stringWithFormat:@"%@/%@%d", dirname, @"Output", ++count];
}
[_outputDirName retain];
// select the first item in the list, and reload the data
[fileTableView selectRow:0 byExtendingSelection:NO];
[fileTableView reloadData];
[[fileTableView window] makeFirstResponder:fileTableView];
[self updateWindowTitle];
}
//////////
//
// table notification handler and data source methods
//
//////////
- (void)tableViewSelectionDidChange:(NSNotification *)aNotification
{
// nothing needed here for this sample
}
// table data source methods
- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
if (tableView == fileTableView)
return [[self fileArray] count];
if (tableView == exporterTableView)
return [[self exporterArray] count];
return 0;
}
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(id)column row:(int)row
{
if (tableView == fileTableView) {
FileObject *fileObject;
fileObject = [[self fileArray] objectAtIndex:row];
return [NSString stringWithCString: [fileObject fileName]];
}
if (tableView == exporterTableView) {
ExporterObject *exporterObject;
exporterObject = [[self exporterArray] objectAtIndex:row];
return [NSString stringWithCString: [exporterObject description]];
}
return nil;
}
//////////
//
// auto-run settings
//
//////////
- (void)setIterations:(UInt32)iterations
{
_autoRunIterations = iterations;
}
- (void)setRandom:(UInt32)random
{
_randomAutoRun = random;
}
//////////
//
// menu validator and handlers
//
//////////
- (BOOL)validateMenuItem:(NSMenuItem *)item {
BOOL isValid = NO;
SEL action = [item action];
if ((action == @selector(usePOSIXThreads:)) ||
(action == @selector(useMainThread:))) {
[item setState: ([item tag] == _threadModelTag) ? NSOnState : NSOffState];
isValid = YES;
// disable POSIX threads on systems earlier than 10.3
if (gOSVersion < 0x00001030)
if (action == @selector(usePOSIXThreads:))
isValid = NO;
}
if ((action == @selector(useHandleDH:)) ||
(action == @selector(usePointerDH:)) ||
(action == @selector(useFileDH:)) ||
(action == @selector(useURLDH:))) {
[item setState: ([item tag] == _dhTag) ? NSOnState : NSOffState];
isValid = YES;
}
if (action == @selector(toggleSafeImporters:)) {
[item setState: _onlySafeComponents ? NSOnState : NSOffState];
if (_autorunTimer) {
// if we're doing auto-run, don't allow this setting to be toggled
isValid = NO;
} else {
isValid = YES;
}
}
if (action == @selector(doAutoRunSettingsBox:)) {
isValid = YES;
}
return isValid;
}
- (IBAction)useHandleDH:(id)sender
{
_dhTag = USE_HANDLE_DH;
[self updateWindowTitle];
}
- (IBAction)usePointerDH:(id)sender
{
_dhTag = USE_POINTER_DH;
[self updateWindowTitle];
}
- (IBAction)useFileDH:(id)sender
{
_dhTag = USE_FILE_DH;
[self updateWindowTitle];
}
- (IBAction)useURLDH:(id)sender
{
_dhTag = USE_URL_DH;
[self updateWindowTitle];
}
- (IBAction)usePOSIXThreads:(id)sender
{
_threadModelTag = USE_POSIX_THREAD;
[self updateWindowTitle];
}
- (IBAction)useMainThread:(id)sender
{
_threadModelTag = USE_MAIN_THREAD;
[self updateWindowTitle];
}
- (IBAction)toggleSafeImporters:(id)sender
{
_onlySafeComponents = !_onlySafeComponents;
[self updateWindowTitle];
[self createExporterArray];
[exporterTableView selectRow:0 byExtendingSelection:NO];
[exporterTableView reloadData];
}
- (IBAction)doAutoRunSettingsBox:(id)sender
{
// show the autorun settings box
[autoRunSettings showSettingsPanel];
}
- (IBAction)doExport:(id)sender
{
ThreadData *threadData = NULL;
WorkerRequestRef wkrRequest = NULL;
OSErr err = noErr;
// determine whether an image is currently being exported;
// if so, try to cancel the export if it's not on the main thread
if (_currThreadData != NULL) {
if (_currThreadData->threadModelTag == USE_POSIX_THREAD) {
if (_currThreadData->busy) {
// cancel the current worker request
wkrRequest = (WorkerRequestRef)_currThreadData->request;
if (wkrRequest != NULL) {
cancelWorkerRequest(wkrRequest);
}
}
}
}
// load the image currently selected in the list of files
// and export it using the currently selected export component
_fileObject = [_fileArray objectAtIndex:[fileTableView selectedRow]];
_exporterObject = [_exporterArray objectAtIndex:[exporterTableView selectedRow]];
if (_fileObject && _exporterObject) {
// start the progress indicator animation
[progressBar startAnimation:nil];
// each export operation gets its own thread data
threadData = calloc(1, sizeof(ThreadData));
if (threadData == NULL)
return;
// configure the thread data to the current settings
threadData->dhTag = _dhTag;
threadData->threadModelTag = _threadModelTag;
threadData->fileObject = _fileObject;
threadData->exporterObject = _exporterObject;
threadData->onlySafeComps = _onlySafeComponents;
threadData->expDirName = calloc(1, [_outputDirName cStringLength] + 1);
[_outputDirName getCString:threadData->expDirName];
_currThreadData = threadData;
switch (_threadModelTag) {
case USE_MAIN_THREAD:
// export the file on the main thread
// in theory, we could force threadData->onlySafeComps to be false here (since we're on the main thread),
// in which case we can dispense with the retry logic just below;
// for demo/testing purposes, I'm going to follow the user's explicit selection
[statusField setStringValue:@""];
_doneExporting = false;
exportTheImage(threadData);
if (threadData->retry) {
[statusField setStringValue:@"Main Thread - Will retry with any components!"];
threadData->onlySafeComps = false;
exportTheImage(threadData);
}
// dispose of the thread data and any memory it accesses
free(threadData->expDirName);
if (threadData == _currThreadData) _currThreadData = NULL;
free(threadData);
_doneExporting = true;
[progressBar stopAnimation:nil];
break;
case USE_POSIX_THREAD:
// export the file on a pthread: create, configure, and send a new worker request
err = createWorkerRequest(_worker, &wkrRequest);
if (err == noErr) {
setWorkerRequestThreadData(wkrRequest, threadData);
setWorkerRequestDoc(wkrRequest, (UInt32)self);
threadData->request = (void *)wkrRequest;
}
if (err == noErr) {
threadData->busy = true;
err = sendWorkerRequest(wkrRequest);
}
break;
}
}
}
- (void)updateWindowTitle
{
// set the window title to reflect the current thread/data handler/etc. settings
NSMutableString *titleString = [NSMutableString string];
switch (_threadModelTag) {
case USE_POSIX_THREAD:
[titleString appendFormat: @"PThreads * "];
break;
case USE_MAIN_THREAD:
[titleString appendFormat: @"Main Thread * "];
}
switch (_dhTag) {
case USE_HANDLE_DH:
[titleString appendFormat: @"Handle DH * "];
break;
case USE_POINTER_DH:
[titleString appendFormat: @"Pointer DH * "];
break;
case USE_FILE_DH:
[titleString appendFormat: @"File DH * "];
break;
case USE_URL_DH:
[titleString appendFormat: @"URL DH * "];
}
if (_onlySafeComponents)
[titleString appendFormat: @"Safe Components"];
else
[titleString appendFormat: @"Any Components"];
[[folderBtn window] setTitle:titleString];
}
//////////
//
// getters and setters
//
//////////
- (id)statusField;
{
return statusField;
}
- (id)progressBar;
{
return progressBar;
}
- (ThreadData *)currThreadData
{
return _currThreadData;
}
- (void)setCurrThreadData:(ThreadData *)threadData
{
_currThreadData = threadData;
}
- (NSString *)currOutputDir
{
return _outputDirName;
}
- (NSMutableArray *)fileArray
{
return _fileArray;
}
- (void)setFileArray:(NSMutableArray *)array
{
[_fileArray release];
[array retain];
_fileArray = array;
}
- (NSMutableArray *)exporterArray
{
return _exporterArray;
}
- (void)setExporterArray:(NSMutableArray *)array
{
[_exporterArray release];
[array retain];
_exporterArray = array;
}
- (void)setAutoRunTimer:(NSTimer *)theTimer
{