-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing4.html
executable file
·2309 lines (2030 loc) · 122 KB
/
listing4.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>Quartz Composer WWDC 2005 TextEdit - /TextEdit_01/Document.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/idxGraphicsImaging-date.html">Graphics & Imaging</a> > <A HREF="javascript:location.replace('index.html');">Quartz Composer WWDC 2005 TextEdit</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">Quartz Composer WWDC 2005 TextEdit</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>/TextEdit_01/Document.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">/TextEdit_01/Controller.h</option>
<option value="listing2.html">/TextEdit_01/Controller.m</option>
<option value="listing3.html">/TextEdit_01/Document.h</option>
<option value="listing4.html">/TextEdit_01/Document.m</option>
<option value="listing5.html">/TextEdit_01/DocumentReadWrite.m</option>
<option value="listing6.html">/TextEdit_01/Edit_main.m</option>
<option value="listing7.html">/TextEdit_01/EncodingManager.h</option>
<option value="listing8.html">/TextEdit_01/EncodingManager.m</option>
<option value="listing9.html">/TextEdit_01/MultiplePageView.h</option>
<option value="listing10.html">/TextEdit_01/MultiplePageView.m</option>
<option value="listing11.html">/TextEdit_01/Preferences.h</option>
<option value="listing12.html">/TextEdit_01/Preferences.m</option>
<option value="listing13.html">/TextEdit_01/ScalingScrollView.h</option>
<option value="listing14.html">/TextEdit_01/ScalingScrollView.m</option>
<option value="listing15.html">/TextEdit_01/TextEdit.scriptSuite</option>
<option value="listing16.html">/TextEdit_01/TextEdit.scriptTerminology</option>
<option value="listing17.html">/TextEdit_02/Controller.h</option>
<option value="listing18.html">/TextEdit_02/Controller.m</option>
<option value="listing19.html">/TextEdit_02/Document.h</option>
<option value="listing20.html">/TextEdit_02/Document.m</option>
<option value="listing21.html">/TextEdit_02/DocumentReadWrite.m</option>
<option value="listing22.html">/TextEdit_02/Edit_main.m</option>
<option value="listing23.html">/TextEdit_02/EncodingManager.h</option>
<option value="listing24.html">/TextEdit_02/EncodingManager.m</option>
<option value="listing25.html">/TextEdit_02/MultiplePageView.h</option>
<option value="listing26.html">/TextEdit_02/MultiplePageView.m</option>
<option value="listing27.html">/TextEdit_02/Preferences.h</option>
<option value="listing28.html">/TextEdit_02/Preferences.m</option>
<option value="listing29.html">/TextEdit_02/ScalingScrollView.h</option>
<option value="listing30.html">/TextEdit_02/ScalingScrollView.m</option>
<option value="listing31.html">/TextEdit_02/TextEdit.scriptSuite</option>
<option value="listing32.html">/TextEdit_02/TextEdit.scriptTerminology</option>
<option value="listing33.html">/TextEdit_03/Controller.h</option>
<option value="listing34.html">/TextEdit_03/Controller.m</option>
<option value="listing35.html">/TextEdit_03/Document.h</option>
<option value="listing36.html">/TextEdit_03/Document.m</option>
<option value="listing37.html">/TextEdit_03/DocumentReadWrite.m</option>
<option value="listing38.html">/TextEdit_03/Edit_main.m</option>
<option value="listing39.html">/TextEdit_03/EncodingManager.h</option>
<option value="listing40.html">/TextEdit_03/EncodingManager.m</option>
<option value="listing41.html">/TextEdit_03/MultiplePageView.h</option>
<option value="listing42.html">/TextEdit_03/MultiplePageView.m</option>
<option value="listing43.html">/TextEdit_03/Preferences.h</option>
<option value="listing44.html">/TextEdit_03/Preferences.m</option>
<option value="listing45.html">/TextEdit_03/ScalingScrollView.h</option>
<option value="listing46.html">/TextEdit_03/ScalingScrollView.m</option>
<option value="listing47.html">/TextEdit_03/TextEdit.scriptSuite</option>
<option value="listing48.html">/TextEdit_03/TextEdit.scriptTerminology</option></select>
</p>
</form>
<p><strong><a href="QuartzComposer_WWDC_TextEdit.zip">Download Sample</a></strong> (“QuartzComposer_WWDC_TextEdit.zip”, 1.62M)<BR>
<strong><a href="QuartzComposer_WWDC_TextEdit.dmg">Download Sample</a></strong> (“QuartzComposer_WWDC_TextEdit.dmg”, 2.06M)</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">/*
Document.m
Copyright (c) 1995-2005 by Apple Computer, Inc., all rights reserved.
Author: Ali Ozer
Document object for TextEdit.
Needs to be switched over to the NSDocument object.
*/
/*
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.
*/
#import <Cocoa/Cocoa.h>
#import <math.h>
#import <stdio.h> // for NULL
#import <objc/objc-runtime.h> // for objc_msgSend
#import "Document.h"
#import "MultiplePageView.h"
#import "Preferences.h"
#import "EncodingManager.h"
#import "ScalingScrollView.h"
// Functions implemented later in this file
static int nextAvailableUntitledDocNumber(void);
static Document *transientDocument = nil;
static NSRect transientDocumentWindowFrame;
// We have disabled use of per-document zones, but have a way to reenable them in case we need to do per-document memory analysis
static BOOL useZones = NO;
static NSZone *zoneForNewDocument(void) {
return useZones ? NSCreateZone(NSPageSize(), NSPageSize(), YES) : NSDefaultMallocZone();
}
/* A very simple container class which is used to collect the outlets from loading the encoding accessory. No implementation provided, because all of the references are weak and don't need retain/release. Would be nice to be able to switch to a mutable dictionary here at some point.
*/
@interface OpenSaveAccessoryOwner : NSObject {
@public
IBOutlet NSView *accessoryView;
IBOutlet EncodingPopUpButton *encodingPopUp;
IBOutlet NSButton *checkBox;
}
@end
@implementation OpenSaveAccessoryOwner
@end
@implementation Document
- (void)setupInitialTextViewSharedState {
NSTextView *textView = [self firstTextView];
[textView setUsesFontPanel:YES];
[textView setUsesFindPanel:YES];
[textView setDelegate:self];
[textView setAllowsUndo:YES];
[textView setAllowsDocumentBackgroundColorChange:YES];
[textView setContinuousSpellCheckingEnabled:[[Preferences objectForKey:CheckSpellingAsYouType] boolValue]];
[self setRichText:[[Preferences objectForKey:RichText] boolValue] dealWithAttachments:NO showRuler:NO];
if ([self isRichText]) [self showRulerDelayed:YES]; // Bring up the ruler delayed to speed up launch a bit
[self setHyphenationFactor:0.0];
}
- (id)init {
static NSPoint cascadePoint = {0.0, 0.0};
NSLayoutManager *layoutManager;
NSZone *zone = [self zone];
self = [super init];
textStorage = [[NSTextStorage allocWithZone:zone] init];
if (![NSBundle loadNibNamed:@"DocumentWindow" owner:self]) {
NSLog(@"Failed to load DocumentWindow.nib");
[self release];
return nil;
}
layoutManager = [[NSLayoutManager allocWithZone:zone] init];
[textStorage addLayoutManager:layoutManager];
[layoutManager setDelegate:self];
[layoutManager release];
[self setEncoding:UnknownStringEncoding];
// This gives us our first view
[self setHasMultiplePages:[[Preferences objectForKey:ShowPageBreaks] boolValue] force:YES];
// This ensures the first view gets set up correctly
[self setupInitialTextViewSharedState];
[[self window] setDelegate:self];
// Set the window size from defaults...
if ([self hasMultiplePages]) {
[self setViewSize:[[scrollView documentView] pageRectForPageNumber:0].size];
} else {
int windowHeight = [[Preferences objectForKey:WindowHeight] intValue];
int windowWidth = [[Preferences objectForKey:WindowWidth] intValue];
NSFont *font = [Preferences objectForKey:[self isRichText] ? RichTextFont : PlainTextFont];
NSSize size;
size.height = ceil([layoutManager defaultLineHeightForFont:font] * windowHeight);
size.width = [font widthOfString:@"x"]; /* will be 0 if can't be rendered */
if (size.width == 0.0) size.width = [font widthOfString:@" "]; /* try for space width */
if (size.width == 0.0) size.width = [font maximumAdvancement].width; /* or max width */
size.width = ceil(size.width * windowWidth);
[self setViewSize:size];
}
if (NSEqualPoints(cascadePoint, NSZeroPoint)) { /* First time through... */
NSRect frame = [[self window] frame];
cascadePoint = NSMakePoint(frame.origin.x, NSMaxY(frame));
}
cascadePoint = [[self window] cascadeTopLeftFromPoint:cascadePoint];
// Register for appropriate notifications from this window's undo manager to control the state of the close box
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(undoManagerChangeUndone:) name:NSUndoManagerDidUndoChangeNotification object:[self undoManager]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(undoManagerChangeDone:) name:NSUndoManagerDidRedoChangeNotification object:[self undoManager]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(undoManagerChangeDone:) name:NSUndoManagerWillCloseUndoGroupNotification object:[self undoManager]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(undoManagerCheckpoint:) name:NSUndoManagerCheckpointNotification object:[self undoManager]];
return self;
}
- (id)initWithPath:(NSString *)filename encoding:(unsigned)encoding ignoreRTF:(BOOL)ignoreRTF ignoreHTML:(BOOL)ignoreHTML uniqueZone:(BOOL)flag error:(NSError **)errorPtr {
if (!(self = [self init])) {
if (flag) NSRecycleZone([self zone]);
// Return a generic read error; this is a very unlikely error case
if (errorPtr) *errorPtr = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:filename, NSFilePathErrorKey, nil]];
return nil;
}
uniqueZone = flag; /* So if something goes wrong we can recycle the zone correctly in dealloc */
[self setDocumentName:filename];
if (filename) {
if (![self loadFromPath:filename encoding:encoding ignoreRTF:ignoreRTF ignoreHTML:ignoreHTML error:errorPtr]) {
// Cancel showing the ruler - this removes the instance from the runloop and allows it to be released sooner
[self showRulerDelayed:NO];
[self release];
return nil;
}
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:documentName]];
openedIgnoringRTF = ignoreRTF;
openedIgnoringHTML = ignoreHTML;
if ([self isRichText]) {
if ([self isReadOnly]) {
[self showRulerDelayed:NO]; // Cancel the ruler; no need to show a ruler for readonly docs
} else {
[self showRuler:nil]; // Show the ruler immediately (doing it delayed causes a glitch...)
}
}
}
[[self firstTextView] setSelectedRange:NSMakeRange(0, 0)];
[self setDocumentEdited:NO];
[[self undoManager] removeAllActions];
return self;
}
/* Calls the above routine with the default values for ignoreRTF and ignoreHTML
*/
- (id)initWithPath:(NSString *)filename encoding:(unsigned)encoding uniqueZone:(BOOL)flag error:(NSError **)errorPtr {
BOOL ignoreRTF = [[Preferences objectForKey:IgnoreRichText] boolValue];
BOOL ignoreHTML = [[Preferences objectForKey:IgnoreHTML] boolValue];
return [self initWithPath:filename encoding:encoding ignoreRTF:ignoreRTF ignoreHTML:ignoreHTML uniqueZone:flag error:errorPtr];
}
/* Opens a new, untitled document. The argument specifies whether the document is created automatically by the system (as opposed to by the user).
*/
+ (id)openUntitled:(BOOL)isOpenedAutomatically {
Document *document = [[self allocWithZone:zoneForNewDocument()] initWithPath:nil encoding:UnknownStringEncoding uniqueZone:useZones error:NULL];
if (document) {
transientDocument = nil; // Opening a new untitled does not close previous...
[document setDocumentName:nil];
[document showWindowBehindDocument:nil];
if (isOpenedAutomatically) {
transientDocument = document;
transientDocumentWindowFrame = [[document window] frame];
}
return document;
} else {
return nil;
}
}
+ (id)openDocumentWithPath:(NSString *)filename encoding:(unsigned)encoding ignoreRTF:(BOOL)ignoreRTF ignoreHTML:(BOOL)ignoreHTML behind:(Document *)otherDoc error:(NSError **)errorPtr {
Document *document = [self documentForPath:filename];
if (document && [document isEditedExternally:nil]) { // If the document is already open, but has been edited externally
if ([document isDocumentEdited]) { // and has also been edited in TextEdit, do the conservative thing and don't open
NSBeginAlertSheet(NSLocalizedString(@"Couldn\\U2019t reopen file", @"Title of alert indicating file couldn't be reloaded"),
NSLocalizedString(@"OK", @"OK"),
nil, nil, [document window], self, NULL, NULL, document,
NSLocalizedString(@"The file you are trying to open, \\U201c%@\\U201d, is already open, has unsaved changes, and has been changed by another application. Because opening the file would cause you to lose your changes, request to open the file has been ignored.", @"Message indicating document couldn't be opened because doing so would cause changes to be lost."),
displayName([document documentName]));
return document;
} else { // If the document in TextEdit doesn't have any edits, then simply do a revert
[document doRevert];
}
}
if (!document) {
document = [[self allocWithZone:zoneForNewDocument()] initWithPath:filename encoding:encoding ignoreRTF:ignoreRTF ignoreHTML:ignoreHTML uniqueZone:useZones error:errorPtr];
if (!document) return nil;
}
[document showWindowBehindDocument:otherDoc];
// Do foreground layout only for the front-most document; others can be laid out in the background
if (!otherDoc) [document doForegroundLayoutToCharacterIndex:[[Preferences objectForKey:ForegroundLayoutToIndex] intValue]];
return document;
}
+ (id)openDocumentWithPath:(NSString *)filename encoding:(unsigned)encoding behind:(Document *)otherDoc error:(NSError **)errorPtr {
BOOL ignoreRTF = [[Preferences objectForKey:IgnoreRichText] boolValue];
BOOL ignoreHTML = [[Preferences objectForKey:IgnoreHTML] boolValue];
return [self openDocumentWithPath:filename encoding:encoding ignoreRTF:ignoreRTF ignoreHTML:ignoreHTML behind:otherDoc error:errorPtr];
}
/* Clear the delegates of the text views and window, then release all resources and go away...
*/
- (void)dealloc {
// Remove this document from the notification center as the observer of any notifications...
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (rulerIsBeingDisplayed) [self showRulerDelayed:NO]; // This cancels outstanding request to show ruler...
[[self firstTextView] setDelegate:nil];
[[self layoutManager] setDelegate:nil];
[[self window] setDelegate:nil];
[richTextDocumentFormatAccessory release];
[documentName release];
[revertDocumentName release];
[fileModDate release];
[textStorage release];
[printInfo release];
[author release];
[comment release];
[subject release];
[title release];
[keywords release];
[copyright release];
[lastChangedDocumentProperty release];
if (uniqueZone) NSRecycleZone([self zone]);
if (transientDocument == self) transientDocument = nil;
[super dealloc];
}
- (NSDictionary *)defaultTextAttributes:(BOOL)forRichText {
static NSParagraphStyle *defaultRichParaStyle = nil;
NSMutableDictionary *textAttributes = [[[NSMutableDictionary alloc] initWithCapacity:2] autorelease];
if (isRichText) {
[textAttributes setObject:[Preferences objectForKey:RichTextFont] forKey:NSFontAttributeName];
if (defaultRichParaStyle == nil) { // We do this once...
int cnt;
NSString *measurementUnits = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleMeasurementUnits"];
float tabInterval = ([@"Centimeters" isEqual:measurementUnits]) ? (72.0 / 2.54) : (72.0 / 2.0); // Every cm or half inch
NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
[paraStyle setTabStops:[NSArray array]]; // This first clears all tab stops
for (cnt = 0; cnt < 12; cnt++) { // Add 12 tab stops, at desired intervals...
NSTextTab *tabStop = [[NSTextTab alloc] initWithType:NSLeftTabStopType location:tabInterval * (cnt + 1)];
[paraStyle addTabStop:tabStop];
[tabStop release];
}
defaultRichParaStyle = [paraStyle copy];
[paraStyle release];
}
[textAttributes setObject:defaultRichParaStyle forKey:NSParagraphStyleAttributeName];
} else {
NSFont *plainFont = [Preferences objectForKey:PlainTextFont];
unsigned tabWidth = [[Preferences objectForKey:TabWidth] intValue];
float charWidth;
if ([plainFont glyphIsEncoded:(NSGlyph)' ']) {
charWidth = [[plainFont screenFontWithRenderingMode:NSFontDefaultRenderingMode] advancementForGlyph:(NSGlyph)' '].width;
} else {
charWidth = [[plainFont screenFontWithRenderingMode:NSFontDefaultRenderingMode] maximumAdvancement].width;
}
// Now use a default paragraph style, but with the tab width adjusted
NSMutableParagraphStyle *mStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[mStyle setTabStops:[NSArray array]];
[mStyle setDefaultTabInterval:(charWidth * tabWidth)];
NSParagraphStyle *style = [mStyle copy];
[textAttributes setObject:style forKey:NSParagraphStyleAttributeName];
[mStyle release];
[style release];
// Also set the font
[textAttributes setObject:plainFont forKey:NSFontAttributeName];
}
return textAttributes;
}
- (NSTextView *)firstTextView {
return [[self layoutManager] firstTextView];
}
/* We take "viewSize" to mean the pure size of the text area, so margins or line fragment paddings don't count. The ruler ends up being included though.
*/
- (NSSize)viewSize {
NSSize size = [NSScrollView contentSizeForFrameSize:[scrollView frame].size hasHorizontalScroller:[scrollView hasHorizontalScroller] hasVerticalScroller:[scrollView hasVerticalScroller] borderType:[scrollView borderType]];
if (![self hasMultiplePages]) {
size.width -= (defaultTextPadding() * 2.0);
}
return size;
}
- (void)setViewSize:(NSSize)size {
NSWindow *window = [scrollView window];
NSRect origWindowFrame = [window frame];
NSSize scrollViewSize;
if (![self hasMultiplePages]) {
size.width += (defaultTextPadding() * 2.0);
}
scrollViewSize = [NSScrollView frameSizeForContentSize:size hasHorizontalScroller:[scrollView hasHorizontalScroller] hasVerticalScroller:[scrollView hasVerticalScroller] borderType:[scrollView borderType]];
[window setContentSize:scrollViewSize];
[window setFrameTopLeftPoint:NSMakePoint(origWindowFrame.origin.x, NSMaxY(origWindowFrame))];
}
/* Show the window for the document, but also replace the transient untitled document if there's one. If otherDoc is provided, bring up document behind this other document. Otherwise come to front, as key.
*/
- (void)showWindowBehindDocument:(Document *)otherDoc {
BOOL closeTransient = transientDocument && NSEqualRects(transientDocumentWindowFrame, [[transientDocument window] frame]);
if (closeTransient) {
[[self window] setFrameTopLeftPoint:NSMakePoint(transientDocumentWindowFrame.origin.x, NSMaxY(transientDocumentWindowFrame))];
}
int otherWindowNumber = otherDoc ? [[otherDoc window] windowNumber] : 0;
if (otherWindowNumber) {
[[self window] orderWindow:NSWindowBelow relativeTo:otherWindowNumber];
} else {
[[self window] makeKeyAndOrderFront:nil];
}
if (closeTransient) { // Should be ready to close, unedited
[transientDocument close:nil];
}
}
/* This method causes the text to be laid out in the foreground (approximately) up to the indicated character index.
*/
- (void)doForegroundLayoutToCharacterIndex:(unsigned)loc {
unsigned len;
if (loc > 0 && (len = [[self textStorage] length]) > 0) {
NSRange glyphRange;
if (loc >= len) loc = len - 1;
/* Find out which glyph index the desired character index corresponds to */
glyphRange = [[self layoutManager] glyphRangeForCharacterRange:NSMakeRange(loc, 1) actualCharacterRange:NULL];
if (glyphRange.location > 0) {
/* Now cause layout by asking a question which has to determine where the glyph is */
(void)[[self layoutManager] textContainerForGlyphAtIndex:glyphRange.location - 1 effectiveRange:NULL];
}
}
}
+ (NSString *)cleanedUpPath:(NSString *)filename {
NSString *resolvedSymlinks = [filename stringByResolvingSymlinksInPath];
if ([resolvedSymlinks length] > 0) {
NSString *standardized = [resolvedSymlinks stringByStandardizingPath];
return [standardized length] ? standardized : resolvedSymlinks;
}
return filename;
}
// newModDateIfKnown is optional (as a perf optimization); if not available, obtain it for the existing document name
//
- (BOOL)isEditedExternally:(NSDate *)newModDateIfKnown {
NSDate *curModDate = [self fileModDate];
if (!curModDate) return NO; // Not much we can do if we don't know anything about the file from before
if (!newModDateIfKnown && !(newModDateIfKnown = [[[NSFileManager defaultManager] fileAttributesAtPath:[self documentName] traverseLink:YES] fileModificationDate])) return NO;
return [curModDate isEqual:newModDateIfKnown] ? NO : YES;
}
- (void)setFileModDate:(NSDate *)date {
if (date != fileModDate) {
[fileModDate release];
fileModDate = [date copy];
}
}
- (NSDate *)fileModDate {
return [[fileModDate retain] autorelease];
}
- (void)setDocumentName:(NSString *)filename updateIcon:(BOOL)updateIcon {
if (filename) {
BOOL same = [filename isEqual:documentName];
[documentName autorelease];
[revertDocumentName autorelease]; // Name the document will use to revert to (having a separate ivar allows docs whose formats have changed to revert)
documentName = [[[self class] cleanedUpPath:filename] copyWithZone:[self zone]];
revertDocumentName = [documentName copyWithZone:[self zone]];
if (same && updateIcon) [[self window] setTitleWithRepresentedFilename:@""]; // Workaround NSWindow optimization
[[self window] setTitleWithRepresentedFilename:documentName];
if (uniqueZone) NSSetZoneName([self zone], documentName);
} else {
NSString *untitled = [self untitledDocumentName:UnknownStringEncoding];
[[self window] setTitle:untitled];
if (uniqueZone) NSSetZoneName([self zone], untitled);
documentName = nil;
}
}
- (void)setDocumentName:(NSString *)filename {
[self setDocumentName:filename updateIcon:NO];
}
- (NSString *)documentName {
return documentName;
}
// Note that because setDocumentEdited: is called from undo notifications, undoable actions do not need to concern themselves with calling this.
//
- (void)setDocumentEdited:(BOOL)flag {
if (flag != isDocumentEdited) {
isDocumentEdited = flag;
[[self window] setDocumentEdited:isDocumentEdited];
if (transientDocument == self) transientDocument = nil;
}
if (!isDocumentEdited) changeCount = 0;
}
- (BOOL)isDocumentEdited {
return isDocumentEdited;
}
- (void)setReadOnly:(BOOL)flag {
isReadOnly = flag;
[[self firstTextView] setEditable:!isReadOnly];
}
- (BOOL)isReadOnly {
return isReadOnly;
}
- (void)setBackgroundColor:(NSColor *)color {
[[self firstTextView] setBackgroundColor:color];
}
- (NSColor *)backgroundColor {
return [[self firstTextView] backgroundColor];
}
- (NSTextStorage *)textStorage {
return textStorage;
}
- (NSWindow *)window {
return [[self firstTextView] window];
}
- (BOOL)hasSheet {
return [[self window] attachedSheet] ? YES : NO;
}
- (NSUndoManager *)undoManager {
return [[self window] undoManager];
}
- (NSLayoutManager *)layoutManager {
return [[textStorage layoutManagers] objectAtIndex:0];
}
- (void)printInfoUpdated {
if ([self hasMultiplePages]) {
unsigned cnt, numberOfPages = [self numberOfPages];
MultiplePageView *pagesView = [scrollView documentView];
NSArray *textContainers = [[self layoutManager] textContainers];
[pagesView setPrintInfo:printInfo];
for (cnt = 0; cnt < numberOfPages; cnt++) {
NSRect textFrame = [pagesView documentRectForPageNumber:cnt];
NSTextContainer *textContainer = [textContainers objectAtIndex:cnt];
[textContainer setContainerSize:textFrame.size];
[[textContainer textView] setFrame:textFrame];
}
}
}
- (void)setPrintInfo:(NSPrintInfo *)anObject {
if (printInfo == anObject) return;
[printInfo autorelease];
printInfo = [anObject copyWithZone:[self zone]];
[self printInfoUpdated];
}
// Create and return the printInfo lazily
- (NSPrintInfo *)printInfo {
if (printInfo == nil) {
[self setPrintInfo:[NSPrintInfo sharedPrintInfo]];
[printInfo setHorizontalPagination:NSFitPagination];
[printInfo setHorizontallyCentered:NO];
[printInfo setVerticallyCentered:NO];
[printInfo setLeftMargin:72.0];
[printInfo setRightMargin:72.0];
[printInfo setTopMargin:72.0];
[printInfo setBottomMargin:72.0];
}
return printInfo;
}
- (NSSize)paperSize {
return [[self printInfo] paperSize];
}
- (void)setPaperSize:(NSSize)size {
[[self printInfo] setPaperSize:size];
[self printInfoUpdated];
}
/* Multiple page related code */
- (unsigned)numberOfPages {
return hasMultiplePages ? [[scrollView documentView] numberOfPages] : 1;
}
- (BOOL)hasMultiplePages {
return hasMultiplePages;
}
- (void)addPage {
NSZone *zone = [self zone];
unsigned numberOfPages = [self numberOfPages];
MultiplePageView *pagesView = [scrollView documentView];
NSSize textSize = [pagesView documentSizeInPage];
NSTextContainer *textContainer = [[NSTextContainer allocWithZone:zone] initWithContainerSize:textSize];
NSTextView *textView;
[pagesView setNumberOfPages:numberOfPages + 1];
textView = [[NSTextView allocWithZone:zone] initWithFrame:[pagesView documentRectForPageNumber:numberOfPages] textContainer:textContainer];
[textView setHorizontallyResizable:NO];
[textView setVerticallyResizable:NO];
[pagesView addSubview:textView];
[[self layoutManager] addTextContainer:textContainer];
[textView release];
[textContainer release];
}
- (void)removePage {
unsigned numberOfPages = [self numberOfPages];
NSArray *textContainers = [[self layoutManager] textContainers];
NSTextContainer *lastContainer = [textContainers objectAtIndex:[textContainers count] - 1];
MultiplePageView *pagesView = [scrollView documentView];
[pagesView setNumberOfPages:numberOfPages - 1];
[[lastContainer textView] removeFromSuperview];
[[lastContainer layoutManager] removeTextContainerAtIndex:[textContainers count] - 1];
}
/* This method sets whether the document has multiple pages or not. It can be called at anytime. force indicates whether to do the task even if the values are the same (usually needed for the first call).
*/
- (void)setHasMultiplePages:(BOOL)flag force:(BOOL)force {
NSZone *zone = [self zone];
if (!force && (hasMultiplePages == flag)) return;
hasMultiplePages = flag;
if (hasMultiplePages) {
NSTextView *textView = [self firstTextView];
MultiplePageView *pagesView = [[MultiplePageView allocWithZone:zone] init];
[scrollView setDocumentView:pagesView];
[pagesView setPrintInfo:[self printInfo]];
// Add the first new page before we remove the old container so we can avoid losing all the shared text view state.
[self addPage];
if (textView) {
[[self layoutManager] removeTextContainerAtIndex:0];
}
[scrollView setHasHorizontalScroller:YES];
// Make sure the selected text is shown
[[self firstTextView] scrollRangeToVisible:[[self firstTextView] selectedRange]];
NSRect visRect = [pagesView visibleRect];
NSRect pageRect = [pagesView pageRectForPageNumber:0];
if (visRect.size.width < pageRect.size.width) { // If we can't show the whole page, tweak a little further
NSRect docRect = [pagesView documentRectForPageNumber:0];
if (visRect.size.width >= docRect.size.width) { // Center document area in window
visRect.origin.x = docRect.origin.x - floor((visRect.size.width - docRect.size.width) / 2);
if (visRect.origin.x < pageRect.origin.x) visRect.origin.x = pageRect.origin.x;
} else { // If we can't show the document area, then show left edge of document area (w/out margins)
visRect.origin.x = docRect.origin.x;
}
[pagesView scrollRectToVisible:visRect];
}
} else {
NSSize size = [scrollView contentSize];
NSTextContainer *textContainer = [[NSTextContainer allocWithZone:zone] initWithContainerSize:NSMakeSize(size.width, FLT_MAX)];
NSTextView *textView = [[NSTextView allocWithZone:zone] initWithFrame:NSMakeRect(0.0, 0.0, size.width, size.height) textContainer:textContainer];
// Insert the single container as the first container in the layout manager before removing the existing pages in order to preserve the shared view state.
[[self layoutManager] insertTextContainer:textContainer atIndex:0];
if ([[scrollView documentView] isKindOfClass:[MultiplePageView class]]) {
NSArray *textContainers = [[self layoutManager] textContainers];
unsigned cnt = [textContainers count];
while (cnt-- > 1) {
[[self layoutManager] removeTextContainerAtIndex:cnt];
}
}
[textContainer setWidthTracksTextView:YES];
[textContainer setHeightTracksTextView:NO]; /* Not really necessary */
[textView setHorizontallyResizable:NO]; /* Not really necessary */
[textView setVerticallyResizable:YES];
[textView setAutoresizingMask:NSViewWidthSizable];
[textView setMinSize:size]; /* Not really necessary; will be adjusted by the autoresizing... */
[textView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)]; /* Will be adjusted by the autoresizing... */
/* The next line should cause the multiple page view and everything else to go away */
[scrollView setDocumentView:textView];
[scrollView setHasHorizontalScroller:NO];
[textView release];
[textContainer release];
// Show the selected region
[[self firstTextView] scrollRangeToVisible:[[self firstTextView] selectedRange]];
}
[[scrollView window] makeFirstResponder:[self firstTextView]];
[[scrollView window] setInitialFirstResponder:[self firstTextView]]; // So focus won't be stolen (2934918)
}
- (void)setHasMultiplePages:(BOOL)flag {
[self setHasMultiplePages:flag force:NO];
}
/* Used when converting to plain text
*/
- (void)removeAttachments {
NSTextStorage *attrString = [self textStorage];
NSTextView *view = [self firstTextView];
unsigned loc = 0;
unsigned end = [attrString length];
[attrString beginEditing];
while (loc < end) { /* Run through the string in terms of attachment runs */
NSRange attachmentRange; /* Attachment attribute run */
NSTextAttachment *attachment = [attrString attribute:NSAttachmentAttributeName atIndex:loc longestEffectiveRange:&attachmentRange inRange:NSMakeRange(loc, end-loc)];
if (attachment != nil) { /* If there is an attachment, make sure it is valid */
unichar ch = [[attrString string] characterAtIndex:loc];
if (ch == NSAttachmentCharacter) {
if ([view shouldChangeTextInRange:NSMakeRange(loc, 1) replacementString:@""]) {
[attrString replaceCharactersInRange:NSMakeRange(loc, 1) withString:@""];
[view didChangeText];
}
end = [attrString length]; /* New length */
} else {
loc++; /* Just skip over the current character... */
}
} else {
loc = NSMaxRange(attachmentRange);
}
}
[attrString endEditing];
}
/* Hyphenation related methods.
*/
- (void)setHyphenationFactor:(float)factor {
[[self layoutManager] setHyphenationFactor:factor];
}
- (float)hyphenationFactor {
return [[self layoutManager] hyphenationFactor];
}
/* Encoding...
*/
- (unsigned)encoding {
return documentEncoding;
}
- (void)setEncoding:(unsigned)encoding {
documentEncoding = encoding;
}
- (BOOL)converted {
return convertedDocument;
}
- (void)setConverted:(BOOL)flag {
convertedDocument = flag;
}
- (BOOL)lossy {
return lossyDocument;
}
- (void)setLossy:(BOOL)flag {
lossyDocument = flag;
}
/* Method to lazily display ruler. Call with YES to display, NO to cancel display; this method doesn't remove the ruler.
*/
- (void)showRulerDelayed:(BOOL)flag {
if (!flag && rulerIsBeingDisplayed) {
[[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(showRuler:) object:self];
} else if (flag && !rulerIsBeingDisplayed) {
[self performSelector:@selector(showRuler:) withObject:self afterDelay:0.0];
}
rulerIsBeingDisplayed = flag;
}
- (void)showRuler:(id)obj {
if (rulerIsBeingDisplayed && !obj) [self showRulerDelayed:NO]; // Cancel outstanding request, if not coming from the delayed request
if ([[Preferences objectForKey:ShowRuler] boolValue]) [[self firstTextView] setRulerVisible:YES];
}
/* Doesn't check to see if the prev value is the same --- Otherwise the first time doesn't work...
attachmentFlag allows for optimizing some cases where we know we have no attachments, so we don't need to scan looking for them.
*/
- (void)setRichText:(BOOL)flag dealWithAttachments:(BOOL)attachmentFlag showRuler:(BOOL)rulerFlag {
NSTextView *view = [self firstTextView];
NSDictionary *textAttributes;
NSParagraphStyle *paragraphStyle;
isRichText = flag;
[view setRichText:isRichText];
[view setUsesRuler:isRichText]; // If NO, this correctly gets rid of the ruler if it was up
if (!isRichText && rulerIsBeingDisplayed) [self showRulerDelayed:NO]; // Cancel delayed ruler request
if (isRichText && rulerFlag) [self showRuler:nil];
[view setImportsGraphics:isRichText];
textAttributes = [self defaultTextAttributes:isRichText];
paragraphStyle = [textAttributes objectForKey:NSParagraphStyleAttributeName];
// Note, since the textview content changes (removing attachments and changing attributes) create undo actions inside the textview, we do not execute them here if we're undoing or redoing
if (![[self undoManager] isUndoing] && ![[self undoManager] isRedoing]) {
if (!isRichText && attachmentFlag) [self removeAttachments];
NSRange range = NSMakeRange(0, [textStorage length]);
if ([view shouldChangeTextInRange:range replacementString:nil]) {
[textStorage setAttributes:textAttributes range: range];
[view didChangeText];
}
}
[view setTypingAttributes:textAttributes];
[view setDefaultParagraphStyle:paragraphStyle];
if (!isRichText) {
[self clearDocumentProperties];
} else {
[self setDocumentPropertiesToDefaults];
}
}
- (void)setRichText:(BOOL)flag {
[self setRichText:flag dealWithAttachments:YES showRuler:YES];
}
- (BOOL)isRichText {
return isRichText;
}
/* Document properties management */
/* Table mapping document property keys "company", etc, to text system document attribute keys (NSCompanyDocumentAttribute, etc)
*/
- (NSDictionary *)documentPropertyToAttributeNameMappings {
static NSDictionary *dict = nil;
if (!dict) dict = [[NSDictionary alloc] initWithObjectsAndKeys:
NSCompanyDocumentAttribute, @"company",
NSAuthorDocumentAttribute, @"author",
NSKeywordsDocumentAttribute, @"keywords",
NSCopyrightDocumentAttribute, @"copyright",
NSTitleDocumentAttribute, @"title",
NSSubjectDocumentAttribute, @"subject",
NSCommentDocumentAttribute, @"comment", nil];
return dict;
}
- (NSArray *)knownDocumentProperties {
return [[self documentPropertyToAttributeNameMappings] allKeys];
}
/* If there are document properties and they are not the same as the defaults established in preferences, return YES
*/
- (BOOL)hasDocumentProperties {
NSEnumerator *keyEnumerator = [[self knownDocumentProperties] objectEnumerator];
NSString *key;
while (key = [keyEnumerator nextObject]) {
id value = [self valueForKey:key];
if (value && ![value isEqual:[Preferences objectForKey:key]]) return YES;
}
return NO;
}
/* This actually clears all properties (rather than setting them to default values established in preferences)
*/
- (void)clearDocumentProperties {
NSEnumerator *keyEnumerator = [[self knownDocumentProperties] objectEnumerator];
NSString *key;
while (key = [keyEnumerator nextObject]) [self setValue:nil forKey:key];
}
/* This sets document properties to values established in defaults
*/
- (void)setDocumentPropertiesToDefaults {
NSEnumerator *keyEnumerator = [[self knownDocumentProperties] objectEnumerator];
NSString *key;
while (key = [keyEnumerator nextObject]) [self setValue:[Preferences objectForKey:key] forKey:key];
}
/* We implement a setValue:forDocumentProperty: to work around NSUndoManager bug where prepareWithInvocationTarget: fails to freeze-dry invocations with "known" methods such as setValue:forKey:.
*/
- (void)setValue:(id)value forDocumentProperty:(NSString *)property {
id oldValue = [self valueForKey:property];
if (value == oldValue || [value isEqual:oldValue]) return; // Workaround for bug 3752890 "Becoming non-editable causes textfield value to be committed instead of discarded"
// We want to do coalesced undo of changes to a single field. Although this would normally be done by undo grouping, another way to approach is to avoid registering unnecessary undo events altogether. We do that here, by checking the "checkpoint count" (which serves as generation count) before registering.
if ((lastDocumentPropertyChangeCheckpointCount != [self undoCheckpointCount]) || ![lastChangedDocumentProperty isEqual:property]) {
lastDocumentPropertyChangeCheckpointCount = [self undoCheckpointCount] + 1;
[lastChangedDocumentProperty release];
lastChangedDocumentProperty = [property copy];
[[[self undoManager] prepareWithInvocationTarget:self] setValue:oldValue forDocumentProperty:property];
[[self undoManager] setActionName:NSLocalizedString(property, "")]; // Potential strings for action names are listed below (for genstrings to pick up)
}
// Then we call the regular KVC mechanism to get the value to be properly set
[super setValue:value forKey:property];
}
- (void)setValue:(id)value forKey:(NSString *)key {
if ([[self knownDocumentProperties] containsObject:key]) {
[self setValue:value forDocumentProperty:key]; // We take a side-trip to this method to register for undo
} else {
[super setValue:value forKey:key]; // In case some other KVC call is sent to Document, we treat it normally
}
}