forked from cellularmitosis/ADC-reference-library-2009-july
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlisting4.html
More file actions
executable file
·967 lines (768 loc) · 30.8 KB
/
Copy pathlisting4.html
File metadata and controls
executable file
·967 lines (768 loc) · 30.8 KB
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
<!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>ImageApp - /ImageDoc.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/GraphicsImaging/index.html">Graphics & Imaging</a> > <a href="../../samplecode/GraphicsImaging/idxCocoa-date.html">Cocoa</a> > <A HREF="javascript:location.replace('index.html');">ImageApp</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">ImageApp</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>/ImageDoc.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">/ImageApp.h</option>
<option value="listing2.html">/ImageApp.m</option>
<option value="listing3.html">/ImageDoc.h</option>
<option value="listing4.html">/ImageDoc.m</option>
<option value="listing5.html">/ImageDocController.h</option>
<option value="listing6.html">/ImageDocController.m</option>
<option value="listing7.html">/ImageFilter.h</option>
<option value="listing8.html">/ImageFilter.m</option>
<option value="listing9.html">/ImageInfoPanel.h</option>
<option value="listing10.html">/ImageInfoPanel.m</option>
<option value="listing11.html">/ImageView.h</option>
<option value="listing12.html">/ImageView.m</option>
<option value="listing13.html">/PrintView.h</option>
<option value="listing14.html">/PrintView.m</option>
<option value="listing15.html">/Profile.h</option>
<option value="listing16.html">/Profile.m</option></select>
</p>
</form>
<p><strong><a href="ImageApp.zip">Download Sample</a></strong> (“ImageApp.zip”, 692.0K)<BR>
<strong><a href="ImageApp.dmg">Download Sample</a></strong> (“ImageApp.dmg”, 1.24M)</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: ImageDoc.m
Abstract: ImageDoc.m class implementation
Version: <1.0>
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.
Copyright © 2005-2008 Apple Inc. All Rights Reserved.
Change History (most recent first):
1/08 added CFRelease() call to profiles: method to fix leak
*/
#import "ImageDoc.h"
#import "PrintView.h"
#import "ImageInfoPanel.h"
/*
* Typically, an application that uses NSDocument can only
* support a static list of file formats enumrated in its Info.plist
* file.
*
* This subclass of NSDocument is provided so that this
* application can dynamically support all the file formats supported
* by ImageIO.
*/
static NSString* ImageIOLocalizedString (NSString* key)
{
static NSBundle* b = nil;
if (b==nil)
b = [NSBundle bundleWithIdentifier:@"com.apple.ImageIO.framework"];
// Returns a localized version of the string designated by 'key' in table 'CGImageSource'.
return [b localizedStringForKey:key value:key table: @"CGImageSource"];
}
@implementation ImageDoc
// Return the names of the types for which this class can be instantiated to play the
// Editor or Viewer role.
//
+ (NSArray*) readableTypes
{
return [(NSArray*)CGImageSourceCopyTypeIdentifiers() autorelease];
}
// Return the names of the types which this class can save. Typically this includes all types
// for which the application can play the Viewer role, plus types than can be merely exported by
// the application.
//
+ (NSArray*) writableTypes
{
return [(NSArray*)CGImageDestinationCopyTypeIdentifiers() autorelease];
}
// Return YES if instances of this class can be instantiated to play the Editor role.
//
+ (BOOL)isNativeType:(NSString *)type
{
return [[self writableTypes] containsObject:type];
}
- (void) dealloc
{
CGImageRelease(mImage);
if (mMetadata) CFRelease(mMetadata);
[mFilteredImage release];
[mExposureValue release];
[mSaturationValue release];
[mProfileValue release];
[mProfiles release];
[mSaveUTI release];
if (mSaveMetaAndOpts) CFRelease(mSaveMetaAndOpts);
[[self undoManager] removeAllActionsWithTarget: self];
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
- (NSString*) windowNibName
{
return @"ImageDoc";
}
#pragma mark -
- (NSArray*) profiles
{
if (mProfiles == nil)
{
NSArray* profArray = [Profile arrayOfAllProfiles];
CFIndex i, count = [profArray count];
NSMutableArray* profs = [NSMutableArray arrayWithCapacity:0];
for (i=0; i<count; i++)
{
// check profile space and class
Profile* prof = (Profile*)[profArray objectAtIndex:i];
OSType pSpace = [prof spaceType];
OSType pClass = [prof classType];
// look only for image profiles with RGB, CMYK and Gray color spaces,
// and only monitor and printer profiles
if ((pSpace==cmRGBData || pSpace==cmCMYKData || pSpace==cmGrayData) &&
(pClass==cmDisplayClass || pClass==cmOutputClass) && [prof description])
[profs addObject:prof];
}
[profArray release];
mProfiles = [profs retain];
}
return mProfiles;
}
// getter for image effects state (on or off)
- (BOOL) switchState
{
return [mSwitchValue boolValue];
}
- (NSNumber*) exposure
{
return mExposureValue;
}
- (NSNumber*) saturation
{
return mSaturationValue;
}
- (Profile*) profile
{
return mProfileValue;
}
// Keep track of image effects state
// val parameter is TRUE if effects are turned on for the image
// val parameter is FALSE if effects are turned off for the image
//
- (void) setSwitchState:(NSNumber*)val
{
if (val == mSwitchValue)
return;
if (mSwitchValue)
{
[[self undoManager] registerUndoWithTarget:self selector:@selector(setSwitchState:) object:mSwitchValue];
[[self undoManager] setActionName:[mSwitchValue intValue]?@"Disable Effects":@"Enable Effects"];
}
[mSwitchValue release];
mSwitchValue = [val retain];
[mImageView setNeedsDisplay:YES];
}
// Setter for image exposure value
//
- (void) setExposure:(NSNumber*)val
{
if (val == mExposureValue)
return;
if (mExposureValue)
{
[[self undoManager] registerUndoWithTarget:self selector:@selector(setExposure:) object:mExposureValue];
[[self undoManager] setActionName:@"Exposure"];
}
[mExposureValue release];
mExposureValue = [val retain];
[mFilteredImage setExposure:mExposureValue];
[mImageView setNeedsDisplay:YES];
}
// Setter for image saturation value
//
- (void) setSaturation:(NSNumber*)val
{
if (val == mSaturationValue)
return;
if (mSaturationValue)
{
[[self undoManager] registerUndoWithTarget:self selector:@selector(setSaturation:) object:mSaturationValue];
[[self undoManager] setActionName:@"Saturation"];
}
[mSaturationValue release];
mSaturationValue = [val retain];
[mFilteredImage setSaturation:mSaturationValue];
[mImageView setNeedsDisplay:YES];
}
// Setter for image profile
//
- (void) setProfile:(Profile*)val
{
if (val == mProfileValue)
return;
if (mProfileValue)
{
[[self undoManager] registerUndoWithTarget:self selector:@selector(setProfile:) object:mProfileValue];
[[self undoManager] setActionName:[[mProfilePopup selectedItem] title]];
}
[mProfileValue release];
mProfileValue = [val retain];
[mFilteredImage setProfile:mProfileValue];
[mImageView setNeedsDisplay:YES];
}
// Initialization for image exposure slider
//
- (void) setupExposure
{
CIFilter* filter = [CIFilter filterWithName: @"CIExposureAdjust"];
NSDictionary* input = [[filter attributes] objectForKey: @"inputEV"];
[mExposureSlider setMinValue: [[input objectForKey: @"CIAttributeSliderMin"] floatValue]/4.0];
[mExposureSlider setMaxValue: [[input objectForKey: @"CIAttributeSliderMax"] floatValue]/4.0];
[self setExposure:[input objectForKey: @"CIAttributeIdentity"]];
}
// Initialization for image saturation slider
//
- (void) setupSaturation
{
CIFilter* filter = [CIFilter filterWithName: @"CIColorControls"];
NSDictionary* input = [[filter attributes] objectForKey: @"inputSaturation"];
[mSaturationSlider setMinValue: [[input objectForKey: @"CIAttributeSliderMin"] floatValue]];
[mSaturationSlider setMaxValue: [[input objectForKey: @"CIAttributeSliderMax"] floatValue]];
[self setSaturation:[input objectForKey: @"CIAttributeIdentity"]];
}
- (void) setupAll
{
// Reset the sliders et. al.
[self setSwitchState:[NSNumber numberWithBool:FALSE]];
[self setupExposure];
[self setupSaturation];
[self setProfile:[Profile profileWithGenericRGB]];
// Un-dirty the file and remove any undo state
[self updateChangeCount:NSChangeCleared];
[[self undoManager] removeAllActions];
}
#pragma mark -
// Getter for image dpi width value
//
- (float) dpiWidth
{
NSNumber* val = [(NSDictionary*)mMetadata objectForKey:(id)kCGImagePropertyDPIWidth];
float f = [val floatValue];
return (f==0 ? 72 : f); // return default 72 if none specified
}
// Getter for image dpi height value
//
- (float) dpiHeight
{
NSNumber* val = [(NSDictionary*)mMetadata objectForKey:(id)kCGImagePropertyDPIHeight];
float f = [val floatValue];
return (f==0 ? 72 : f); // return default 72 if none specified
}
// Getter for display orientation of the image.
//
- (int) orientation
{
// If present, the value of the kCGImagePropertyOrientation key is a
// CFNumberRef with the same value as defined by the TIFF and Exif
// specifications. That is:
// 1 = row 0 top, col 0 lhs = normal
// 2 = row 0 top, col 0 rhs = flip horizontal
// 3 = row 0 bot, col 0 rhs = rotate 180
// 4 = row 0 bot, col 0 lhs = flip vertical
// 5 = row 0 lhs, col 0 top = rot -90, flip vert
// 6 = row 0 rhs, col 0 top = rot 90
// 7 = row 0 rhs, col 0 bot = rot 90, flip vert
// 8 = row 0 lhs, col 0 bot = rotate -90
NSNumber* val = [(NSDictionary*)mMetadata objectForKey:(id)kCGImagePropertyOrientation];
int orient = [val intValue];
if (orient<1 || orient>8)
orient = 1;
return orient;
}
// Getter for image transform
//
- (CGAffineTransform) imageTransform
{
float xdpi = [self dpiWidth];
float ydpi = [self dpiHeight];
int orient = [self orientation];
float x = (ydpi>xdpi) ? ydpi/xdpi : 1;
float y = (xdpi>ydpi) ? xdpi/ydpi : 1;
float w = x * CGImageGetWidth(mImage);
float h = y * CGImageGetHeight(mImage);
CGAffineTransform ctms[8] = {
{ x, 0, 0, y, 0, 0}, // 1 = row 0 top, col 0 lhs = normal
{-x, 0, 0, y, w, 0}, // 2 = row 0 top, col 0 rhs = flip horizontal
{-x, 0, 0,-y, w, h}, // 3 = row 0 bot, col 0 rhs = rotate 180
{ x, 0, 0,-y, 0, h}, // 4 = row 0 bot, col 0 lhs = flip vertical
{ 0,-x,-y, 0, h, w}, // 5 = row 0 lhs, col 0 top = rot -90, flip vert
{ 0,-x, y, 0, 0, w}, // 6 = row 0 rhs, col 0 top = rot 90
{ 0, x, y, 0, 0, 0}, // 7 = row 0 rhs, col 0 bot = rot 90, flip vert
{ 0, x,-y, 0, h, 0} // 8 = row 0 lhs, col 0 bot = rotate -90
};
return ctms[orient-1];
}
// Returns a new image representing the original image with the transform
// matrix ctm appended to it.
//
- (CIImage*) currentCIImageWithTransform:(CGAffineTransform)ctm
{
if ([self switchState])
return [mFilteredImage imageWithTransform:ctm];
else
return nil;
}
// getter for current CGImage
//
- (CGImageRef) currentCGImage
{
if ([self switchState])
return [mFilteredImage createCGImage];
else
return CGImageRetain(mImage);
}
// getter for image size
//
- (CGSize) imageSize
{
return CGSizeMake(CGImageGetWidth(mImage), CGImageGetHeight(mImage));
}
#pragma mark -
- (void) windowControllerDidLoadNib:(NSWindowController*) aController
{
[super windowControllerDidLoadNib:aController];
NSWindow* window = [self windowForSheet];
[window setDelegate:self];
[window setDisplaysWhenScreenProfileChanges:YES];
[self setupAll];
}
- (BOOL) readFromURL:(NSURL *)absURL ofType:(NSString *)typeName error:(NSError **)outError
{
BOOL status = NO;
// Release and clear any old image variables
[mFilteredImage release];
mFilteredImage = nil;
if (mMetadata) CFRelease(mMetadata);
mMetadata = nil;
CGImageRelease(mImage);
mImage = nil;
// Load (or reload) the image
CGImageSourceRef source = CGImageSourceCreateWithURL((CFURLRef)absURL, NULL);
if (source == nil)
goto bail;
// build options dictionary for image creation that specifies:
//
// kCGImageSourceShouldCache = kCFBooleanTrue
// Specifies that image should be cached in a decoded form.
//
// kCGImageSourceShouldAllowFloat = kCFBooleanTrue
// Specifies that image should be returned as a floating
// point CGImageRef if supported by the file format.
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanTrue, (id)kCGImageSourceShouldCache,
(id)kCFBooleanTrue, (id)kCGImageSourceShouldAllowFloat,
nil];
CGImageRef image = CGImageSourceCreateImageAtIndex(source, 0, (CFDictionaryRef)options);
// Assign user preferred default profiles if image is not tagged with a profile
mImage = CGImageCreateCopyWithDefaultSpace(image);
mMetadata = (CFMutableDictionaryRef)CGImageSourceCopyPropertiesAtIndex(source, 0, (CFDictionaryRef)options);
mFilteredImage = [(ImageFilter*)[ImageFilter alloc] initWithImage:mImage];
CFRelease(source);
CGImageRelease(image);
if (mImage != nil)
status = YES;
bail:
if (status==NO && outError)
*outError = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:nil];
return status;
}
#pragma mark -
/*
These methods NSDocument allow this document to present custom interface
when saving. The interface hace a custom format popup, quality slider,
and compression type popup.
*/
- (NSMutableDictionary*) saveMetaAndOpts
{
if (mSaveMetaAndOpts == nil)
{
if (mMetadata)
mSaveMetaAndOpts = CFDictionaryCreateMutableCopy(nil, 0, mMetadata);
else
mSaveMetaAndOpts = CFDictionaryCreateMutable(nil, 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
// save a dictionary of the image properties
CFDictionaryRef tiffProfs = CFDictionaryGetValue(mSaveMetaAndOpts, kCGImagePropertyTIFFDictionary);
CFShow(tiffProfs);
CFMutableDictionaryRef tiffProfsMut;
if (tiffProfs)
tiffProfsMut = CFDictionaryCreateMutableCopy(nil, 0, tiffProfs);
else
tiffProfsMut = CFDictionaryCreateMutable(nil, 0,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
CFDictionarySetValue(mSaveMetaAndOpts, kCGImagePropertyTIFFDictionary, tiffProfsMut);
CFRelease(tiffProfsMut);
CFDictionarySetValue(mSaveMetaAndOpts, kCGImageDestinationLossyCompressionQuality,
[NSNumber numberWithFloat:0.85]);
}
return (NSMutableDictionary*)mSaveMetaAndOpts;
}
// Binding methods for save panel's image fomat popup menu.
//
- (NSArray*) saveTypes
{
NSArray* wt = [ImageDoc writableTypes];
NSMutableArray* wtl = [NSMutableArray arrayWithCapacity:0];
NSEnumerator* enumerator = [wt objectEnumerator];
NSString* type;
while ((type = [enumerator nextObject]))
{
[wtl addObject:
[NSDictionary dictionaryWithObjectsAndKeys:
type,@"uti",
ImageIOLocalizedString(type),@"localized", nil]];
}
return wtl;
}
- (NSString*) saveType
{
if (mSaveUTI==nil)
{
if ([[ImageDoc writableTypes] containsObject:[self fileType]])
mSaveUTI = [[self fileType] retain];
else
mSaveUTI = @"public.tiff";
}
return mSaveUTI;
}
- (void) setSaveType:(NSString*)uti
{
[self willChangeValueForKey:@"saveTab"];
[mSaveUTI release];
mSaveUTI = [uti retain];
[self didChangeValueForKey:@"saveTab"];
// get the file extension so we can control file types shown
CFDictionaryRef utiDecl = UTTypeCopyDeclaration((CFStringRef)mSaveUTI);
CFDictionaryRef utiSpec = CFDictionaryGetValue(utiDecl, kUTTypeTagSpecificationKey);
CFTypeRef ext = CFDictionaryGetValue(utiSpec, kUTTagClassFilenameExtension);
NSSavePanel* savePanel = (NSSavePanel*)[mSavePanelView window];
if (CFGetTypeID(ext) == CFStringGetTypeID())
[savePanel setRequiredFileType:(NSString*)ext];
else
[savePanel setAllowedFileTypes:(NSArray*)ext];
CFRelease(utiDecl);
}
// Binding method for save panel's tabless tab view.
// This tabless tabview (below file type popup) contains
// panes with apporpiate UI for various file format.
// In this simple implementaion:
// pane index 2 contains the compression type popup for TIFF,
// pane index 1 contains the quality slider for JPG and JP2,
// pane index 0 is empty for all other formats.
//
- (int) saveTab
{
// return the appropriate tab view index based on chosen format
if ([mSaveUTI isEqual:@"public.tiff"])
return 2;
else if ([mSaveUTI isEqual:@"public.jpeg"] || [mSaveUTI isEqual:@"public.jpeg-2000"])
return 1;
else
return 0;
}
// Binding methods for save panel's image quality slider.
// The slider's value is bound to the kCGImageDestinationLossyCompressionQuality
// value of the metadata/options dictionary to use when saving.
//
// We set the kCGImageDestinationLossyCompressionQuality option to specify
// the compression quality to use when writing to a jpeg or jp2 image
// desination. 0.0=maximum compression, 1.0=lossless compression
//
- (NSNumber*) saveQuality
{
return [[self saveMetaAndOpts] objectForKey:(id)kCGImageDestinationLossyCompressionQuality];
}
- (void) setSaveQuality:(NSNumber*)q
{
[[self saveMetaAndOpts] setObject:q forKey:(id)kCGImageDestinationLossyCompressionQuality];
}
// Binding methods for save panel's image compression popup.
// The popup's tag value is bound to the kCGImagePropertyTIFFCompression
// value of the kCGImagePropertyTIFFDictionary of the
// metadata/options dictionary to use when saving.
//
// We set kCGImagePropertyTIFFDictionary > kCGImagePropertyTIFFCompression
// to specify the compression type to use when writing to a tiff image
// destination. 1=no compression, 5=LZW, 32773=PackBits.
//
// Note: values for the compression options as just described (5=LZW, and so on)
// are not currently defined in the Quartz (Core Graphics) interfaces, but
// these are the same as those defined in the Cocoa interfaces for
// _NSTIFFCompression as shown here (taken from NSBitmapImageRep.h):
//
// typedef enum _NSTIFFCompression {
// NSTIFFCompressionNone = 1,
// NSTIFFCompressionCCITTFAX3 = 3, /* 1 bps only */
// NSTIFFCompressionCCITTFAX4 = 4, /* 1 bps only */
// NSTIFFCompressionLZW = 5,
// NSTIFFCompressionJPEG = 6, /* No longer supported for input or output */
// NSTIFFCompressionNEXT = 32766, /* Input only */
// NSTIFFCompressionPackBits = 32773,
// NSTIFFCompressionOldJPEG = 32865 /* No longer supported for input or output */
// } NSTIFFCompression;
//
- (int) saveCompression
{
NSNumber* val = [[[self saveMetaAndOpts] objectForKey:(id)kCGImagePropertyTIFFDictionary]
objectForKey:(id)kCGImagePropertyTIFFCompression];
int comp = [val intValue];
return (comp==1 || comp==5 || comp==32773) ? comp : 1;
}
- (void) setSaveCompression:(int)c
{
[[[self saveMetaAndOpts] objectForKey:(id)kCGImagePropertyTIFFDictionary]
setObject:[NSNumber numberWithInt:c]
forKey:(id)kCGImagePropertyTIFFCompression];
}
// Insert our cusom save panel view
//
- (BOOL) prepareSavePanel:(NSSavePanel*)savePanel
{
[savePanel setAccessoryView: mSavePanelView];
// Set format popup to current UTI (or TIFF if current UTI is not writable)
[self setSaveType:[self saveType]];
return YES;
}
// We need to override this because our save panel has its own format popup
//
- (NSString*) fileTypeFromLastRunSavePanel
{
return mSaveUTI;
}
#pragma mark -
// This method is subclassed so that we can reload the image
// and update the user interface after writing the file.
//
- (BOOL) saveToURL:(NSURL *)absURL ofType:(NSString *)type forSaveOperation:(NSSaveOperationType)saveOp
error:(NSError **)outError
{
BOOL status = [super saveToURL:absURL ofType:type forSaveOperation:saveOp error:outError];
if (status==YES && (saveOp==NSSaveOperation || saveOp==NSSaveAsOperation))
{
NSURL* url = [self fileURL];
// reload the image (this could faile)
status = [self readFromURL:url ofType:type error:outError];
// re-initialize the UI
[self setupAll];
// Tell the info panel that the url changed
[ImageInfoPanel setURL:url];
}
return status;
}
// This actually writes the file using CGImageDesination API
//
- (BOOL) writeToURL:(NSURL *)absURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOp
originalContentsURL:(NSURL *)absOrigURL error:(NSError **)outError
{
BOOL status = NO;
CGImageRef image = [self currentCGImage];
if (image==nil)
goto bail;
// Create an image destination writing to `url'
CGImageDestinationRef dest = CGImageDestinationCreateWithURL((CFURLRef)absURL, (CFStringRef)typeName, 1, nil);
if (dest==nil)
goto bail;
// Set the image in the image destination to be `image' with
// optional properties specified in saved properties dict.
CGImageDestinationAddImage(dest, image, (CFDictionaryRef)[self saveMetaAndOpts]);
status = CGImageDestinationFinalize(dest);
CGImageRelease(image);
bail:
if (status==NO && outError)
*outError = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileWriteUnknownError userInfo:nil];
return status;
}
#pragma mark -
// Set the "shared" NSPrintInfo for image doc. The shared print info object is the one that is
// used automatically by -[NSPageLayout runModal] and +[NSPrintOperation printOperationWithView:].
//
- (void) setPrintInfo:(NSPrintInfo*)info
{
if (mPrintInfo == info)
return;
[mPrintInfo autorelease];
mPrintInfo = [info copyWithZone:[self zone]];
}
// Get the "shared" NSPrintInfo for image doc. The shared print info object is the one that is
// used automatically by -[NSPageLayout runModal] and +[NSPrintOperation printOperationWithView:].
//
- (NSPrintInfo*) printInfo
{
if (mPrintInfo == nil)
[self setPrintInfo: [NSPrintInfo sharedPrintInfo]];
return mPrintInfo;
}
// Create a print operation that can be run to print the document's current contents, and return
// it if successful. If not successful, return nil after setting *outError to an NSError that
// encapsulates the reason why the print operation could not be created.
//
- (NSPrintOperation*) printOperationWithSettings:(NSDictionary*) printSettings error: (NSError **) outError
{
NSPrintInfo* printInfo = [self printInfo];
NSSize paperSize = [printInfo paperSize];
NSRect printableRect = [printInfo imageablePageBounds];
// calculate page margins
float marginL = printableRect.origin.x;
float marginR = paperSize.width - (printableRect.origin.x + printableRect.size.width);
float marginB = printableRect.origin.y;
float marginT = paperSize.height - (printableRect.origin.y + printableRect.size.height);
// Make sure margins are symetric and positive
float marginLR = MAX(0,MAX(marginL,marginR));
float marginTB = MAX(0,MAX(marginT,marginB));
// Tell printInfo what the nice new margins are
[printInfo setLeftMargin: marginLR];
[printInfo setRightMargin: marginLR];
[printInfo setTopMargin: marginTB];
[printInfo setBottomMargin: marginTB];
NSRect printViewFrame = {};
printViewFrame.size.width = paperSize.width - marginLR*2;
printViewFrame.size.height = paperSize.height - marginTB*2;
PrintView* printView = [[PrintView alloc] initWithFrame:printViewFrame document:self];
NSPrintOperation* printOp = [NSPrintOperation printOperationWithView:printView printInfo:printInfo];
if (outError) // Clear error.
*outError = NULL;
[printView release];
return printOp;
}
@end
</pre>
<!--googleoff: index -->
</td>
</tr>
</table>
<!-- END WIDE COLUMN -->
<!-- END MAIN CONTENT -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td><div style="width: 100%; height: 1px; background-color: #919699; margin-top: 5px; margin-bottom: 15px"></div></td>
</tr>
<tr>
<td align="center"><br/>
<table border="0" cellpadding="0" cellspacing="0" class="graybox">
<tr>
<th>Did this document help you?</th>
</tr>
<tr>
<td>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=1&url=/samplecode/ImageApp/listing4.html%3Fid%3DDTS10003685-1.1&media=dvd" target=_new>Yes</a>: Tell us what works for you.</div>
<div style="margin-bottom: 8px"><a href="http://developer.apple.com/feedback/?v=2&url=/samplecode/ImageApp/listing4.html%3Fid%3DDTS10003685-1.1&media=dvd" target=_new>It’s good, but:</a> Report typos, inaccuracies, and so forth.</div>
<div><a href="http://developer.apple.com/feedback/?v=3&url=/samplecode/ImageApp/listing4.html%3Fid%3DDTS10003685-1.1&media=dvd" target=_new>It wasn’t helpful</a>: Tell us what would have helped.</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- START BOTTOM APPLE NAVIGATION -->
<!--#include virtual="/includes/footer"-->
<!-- END BOTTOM APPLE NAVIGATION -->
<!-- START CENTER CLOSE -->
</center>
<!-- END CENTER CLOSE -->
</body>
</html>