forked from omnigroup/LinkBack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Document.m
2055 lines (1763 loc) · 97 KB
/
Document.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Document.m
Copyright (c) 1995-2003 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"
#import "LinkBackTextView.h"
#import <LinkBack/LinkBack.h>
#import "LinkBackTextAttachment.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();
}
@implementation Document (LinkBackSupport)
- (NSArray*)selectedLinkBackTextAttachments
{
NSMutableArray* ret = [[NSMutableArray alloc] init] ;
// get the current selected range
NSTextStorage* ts = [self textStorage] ;
NSRange range = [[[self layoutManager] firstTextView] selectedRange] ;
NSRange erange ;
unsigned maxloc = NSMaxRange(range) ;
NSTextAttachment* attachment ;
// expand the selected range if it is 0 length to get the attachment following.
if ((0==range.length) && (range.location < [ts length])) range.length = 1 ;
// add any linkback text attachments to return list
while(range.length > 0) {
attachment = [ts attribute: NSAttachmentAttributeName atIndex: range.location effectiveRange: &erange] ;
if (attachment && [attachment isKindOfClass: [LinkBackTextAttachment class]]) {
[ret addObject: attachment] ;
}
// update range
range.location = NSMaxRange(erange) ;
range.length = (range.location < maxloc) ? maxloc - range.location : 0 ;
}
return [ret autorelease] ;
}
- (void)editLinkBackItems:(id)sender
{
NSLog(@"edit linkback items") ;
NSArray* attachments = [self selectedLinkBackTextAttachments] ;
int idx = [attachments count] ;
while(--idx >= 0) {
LinkBackTextAttachment* attachment = [attachments objectAtIndex: idx];
[self editLinkBackInTextAttachment: attachment] ;
}
}
- (BOOL)editLinkBackInTextAttachment:(id)attachment
{
BOOL ret = NO ;
id linkBackData ;
// get the live link data and start a live link if it is found.
if ([attachment isKindOfClass: [LinkBackTextAttachment class]] && (linkBackData=[attachment linkBackData])) {
// start the edit. If an object is returned, the edit succeeded.
NSString* srcName = [[self window] title] ;
NSString* itemKey = [attachment linkBackItemKey] ;
LinkBack* lnk = [LinkBack editLinkBackData: linkBackData sourceName: srcName delegate: self itemKey: itemKey] ;
if (lnk) {
[lnk setRepresentedObject: attachment] ;
[activeLinks addObject: lnk] ;
}
ret = YES ;
}
return ret ;
}
- (void)linkBackDidClose:(LinkBack*)aLink
{
NSLog(@"linkLinkDidClose: %@",aLink) ;
// remove from active links.
[activeLinks removeObject: aLink] ;
}
- (void)linkBackServerDidSendEdit:(LinkBack*)link
{
NSLog(@"linkBackServerDidSendEdit: %@",link) ;
id attachment = [link representedObject] ;
NSRange attachmentRange ; // the range to replace
attachmentRange.length = 0 ;
// find the current attachment's range.
NSTextStorage* ts = [self textStorage] ;
unsigned loc = 0 ;
unsigned lim = [ts length] ;
NSRange erange ;
while((0==attachmentRange.length) && (loc<lim)) {
id cattachment = [ts attribute: NSAttachmentAttributeName atIndex: loc effectiveRange: &erange] ;
loc = NSMaxRange(erange) ;
if (cattachment == attachment) attachmentRange = erange ;
}
if (0==attachmentRange.length) {
NSBeep() ;
return ;
}
NSTextView* tv = [self firstTextView] ;
NSPasteboard* pboard = [link pasteboard] ;
// let text view do the actual work since we do the work of collecting the live link data anyway.
[tv setSelectedRange: attachmentRange] ;
[tv readSelectionFromPasteboard: pboard] ;
// get the new attachment to make the new represented object.
attachment = [ts attribute: NSAttachmentAttributeName atIndex: attachmentRange.location effectiveRange: nil] ;
[attachment setLinkBackItemKey: [link itemKey]] ;
if (nil==attachment) {
NSBeep() ;
return ;
}
[link setRepresentedObject: attachment] ;
}
@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]];
[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([font boundingRectForFont].size.height) * 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 textStorageDidProcessEditing: to fix the tabstops in plain text documents. A small optimization is to register for this notification only for plain text documents. (Currently we check in the notification callback...)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textStorageDidProcessEditing:) name:NSTextStorageDidProcessEditingNotification object:[self textStorage]];
// 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]];
// LIVELINK EDITS
activeLinks = [[NSMutableArray alloc] init] ;
return self;
}
- (id)initWithPath:(NSString *)filename encoding:(unsigned)encoding ignoreRTF:(BOOL)ignoreRTF ignoreHTML:(BOOL)ignoreHTML uniqueZone:(BOOL)flag {
if (!(self = [self init])) {
if (flag) NSRecycleZone([self zone]);
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]) {
[self release];
return nil;
}
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:documentName]];
openedIgnoringRTF = ignoreRTF;
openedIgnoringHTML = ignoreHTML;
}
[[self firstTextView] setSelectedRange:NSMakeRange(0, 0)];
[self setDocumentEdited:NO];
return self;
}
/* Calls the above routine with the default values for ignoreRTF and ignoreHTML
*/
- (id)initWithPath:(NSString *)filename encoding:(unsigned)encoding uniqueZone:(BOOL)flag {
BOOL ignoreRTF = [[Preferences objectForKey:IgnoreRichText] boolValue];
BOOL ignoreHTML = [[Preferences objectForKey:IgnoreHTML] boolValue];
return [self initWithPath:filename encoding:encoding ignoreRTF:ignoreRTF ignoreHTML:ignoreHTML uniqueZone:flag];
}
/* 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];
if (document) {
transientDocument = nil; // Opening a new untitled does not close previous...
[document setDocumentName:nil];
[document showWindow];
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 {
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 opening, %@, is already open and has unsaved changes. The file on disk has also 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];
if (!document) return nil;
}
[document doForegroundLayoutToCharacterIndex:[[Preferences objectForKey:ForegroundLayoutToIndex] intValue]];
[document showWindow];
return document;
}
+ (id)openDocumentWithPath:(NSString *)filename encoding:(unsigned)encoding {
BOOL ignoreRTF = [[Preferences objectForKey:IgnoreRichText] boolValue];
BOOL ignoreHTML = [[Preferences objectForKey:IgnoreHTML] boolValue];
return [self openDocumentWithPath:filename encoding:encoding ignoreRTF:ignoreRTF ignoreHTML:ignoreHTML];
}
/* Clear the delegates of the text views and window, then release all resources and go away...
*/
- (void)dealloc {
// LIVELINK EDITS
// close any active links
NSEnumerator* e = [activeLinks objectEnumerator] ;
LinkBack* clink ;
while(clink = [e nextObject]) [clink closeLink] ;
[activeLinks release] ;
// Remove this document from the notification center as the observer of any notifications...
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[self firstTextView] setDelegate:nil];
[[self layoutManager] setDelegate:nil];
[[self window] setDelegate:nil];
[richTextDocumentFormatAccessory release];
[documentName release];
[revertDocumentName release];
[fileModDate release];
[textStorage release];
[printInfo 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 {
[textAttributes setObject:[Preferences objectForKey:PlainTextFont] forKey:NSFontAttributeName];
[textAttributes setObject:[NSParagraphStyle defaultParagraphStyle] forKey:NSParagraphStyleAttributeName];
}
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
*/
- (void)showWindow {
BOOL closeTransient = transientDocument && NSEqualRects(transientDocumentWindowFrame, [[transientDocument window] frame]);
if (closeTransient) {
[[self window] setFrameTopLeftPoint:NSMakePoint(transientDocumentWindowFrame.origin.x, NSMaxY(transientDocumentWindowFrame))];
}
[[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];
}
// Returns the untitled document name for this document.
// The withExtension flag determines whether the extension should be appended to the name in the rich case
// (For txt, if add it if user wanted it added, by having specified preference)
- (NSString *)untitledDocumentName:(BOOL)withExtension {
NSString *untitled;
if (untitledDocNumber == 0) untitledDocNumber = nextAvailableUntitledDocNumber();
if (untitledDocNumber > 1) {
// "LaunchTime" table contains the very few strings needed at launch time... A little performance optimization.
untitled = [NSString stringWithFormat:NSLocalizedStringFromTable(@"Untitled %d", @"LaunchTime", @"Name of new, untitled document with sequence number"), untitledDocNumber];
} else {
untitled = NSLocalizedStringFromTable(@"Untitled", @"LaunchTime", @"Name of new, untitled document");
}
// Don't add extension to untitled rtf documents
if ([self isRichText]) {
if (withExtension) untitled = [untitled stringByAppendingPathExtension:[textStorage containsAttachments] ? @"rtfd" : @"rtf"];
} else if ([[Preferences objectForKey:AddExtensionToNewPlainTextFiles] boolValue]) {
untitled = [untitled stringByAppendingPathExtension:@"txt"];
}
return untitled;
}
- (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:NO];
[[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 = [[LinkBackTextView 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 = [[LinkBackTextView 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];
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) {
[attrString replaceCharactersInRange:NSMakeRange(loc, 1) withString:@""];
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;
}
/* 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 {
NSTextView *view = [self firstTextView];
NSDictionary *textAttributes;
NSParagraphStyle *paragraphStyle;
isRichText = flag;
if (!isRichText && attachmentFlag) [self removeAttachments];
[view setRichText:isRichText];
[view setUsesRuler:isRichText]; /* If NO, this correctly gets rid of the ruler if it was up */
if (isRichText && [[Preferences objectForKey:ShowRuler] boolValue]) [view setRulerVisible:YES]; /* Show ruler if rich, and desired */
[view setImportsGraphics:isRichText];
textAttributes = [self defaultTextAttributes:isRichText];
paragraphStyle = [textAttributes objectForKey:NSParagraphStyleAttributeName];
if ([textStorage length]) {
[textStorage setAttributes:textAttributes range: NSMakeRange(0, [textStorage length])];
}
[view setTypingAttributes:textAttributes];
[view setDefaultParagraphStyle:paragraphStyle];
}
- (void)setRichText:(BOOL)flag {
[self setRichText:flag dealWithAttachments:YES];
}
- (BOOL)isRichText {
return isRichText;
}
/* Outlet methods */
- (void)setScrollView:(id)anObject {
scrollView = anObject;
[scrollView setHasVerticalScroller:YES];
[scrollView setHasHorizontalScroller:NO];
[[scrollView contentView] setAutoresizesSubviews:YES];
[[scrollView contentView] setBackgroundColor:[NSColor controlColor]];
if (NSInterfaceStyleForKey(NSInterfaceStyleDefault, scrollView) == NSWindows95InterfaceStyle) {
[scrollView setBorderType:NSBezelBorder];
}
}
/* User commands... */
- (void)printDocumentUsingPrintPanel:(BOOL)uiFlag {
NSPrintOperation *op = [NSPrintOperation printOperationWithView:[scrollView documentView] printInfo:[self printInfo]];
[op setShowPanels:uiFlag];
[op runOperationModalForWindow:[self window] delegate:nil didRunSelector:NULL contextInfo:NULL];
}
- (void)printDocument:(id)sender {
[self printDocumentUsingPrintPanel:YES];
}
/* Toggles read-only state of the document
*/
- (void)toggleReadOnly:(id)sender {
[[self undoManager] registerUndoWithTarget:self selector:@selector(toggleReadOnly:) object:nil];
[[self undoManager] setActionName:[self isReadOnly] ?
NSLocalizedString(@"Allow Editing", @"Menu item to make the current document editable (not read-only)") :
NSLocalizedString(@"Prevent Editing", @"Menu item to make the current document read-only")];
[self setReadOnly:![self isReadOnly]];
}
/* doToggleRich, called from toggleRich: or the endToggleRichSheet:... alert panel method, toggle the isRichText state
*/
- (void)doToggleRich {
[self setRichText:!isRichText];
[self setEncoding:UnknownStringEncoding];
[self setConverted:NO];
if ([textStorage length] > 0) [self setDocumentEdited:YES];
[self setDocumentName:nil];
}
/* toggleRich: puts up an alert before ultimately calling doToggleRich
*/
- (void)toggleRich:(id)sender {
int length = [textStorage length];
NSRange range;
NSDictionary *attrs;
// If we are rich and any ofthe text attrs have been changed from the default, then put up an alert first...
if (isRichText && (length > 0) && (attrs = [textStorage attributesAtIndex:0 effectiveRange:&range]) && ((attrs == nil) || (range.length < length) || ![[self defaultTextAttributes:YES] isEqual:attrs])) {
NSBeginAlertSheet(NSLocalizedString(@"Convert document to plain text?", @"Title of alert confirming Make Plain Text"),
NSLocalizedString(@"OK", @"OK"), NSLocalizedString(@"Cancel", @"Button choice allowing user to cancel."), nil, [self window],
self, NULL, @selector(didEndToggleRichSheet:returnCode:contextInfo:), NULL,
NSLocalizedString(@"Converting will lose fonts, colors, and other text styles in the document.", @"Subtitle of alert confirming Make Plain Text"));
} else {
[self doToggleRich];
}
}
- (void)didEndToggleRichSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSAlertDefaultReturn) [self doToggleRich];
}
- (void)togglePageBreaks:(id)sender {
[self setHasMultiplePages:![self hasMultiplePages]];
}
- (void)toggleHyphenation:(id)sender {
[self setHyphenationFactor:([self hyphenationFactor] > 0.0) ? 0.0 : 0.9]; /* Toggle between 0.0 and 0.9 */
if ([self isRichText]) [self setDocumentEdited:YES];
}
- (void)doPageLayout:(id)sender {
NSPrintInfo *tempPrintInfo = [[self printInfo] copy];
NSPageLayout *pageLayout = [NSPageLayout pageLayout];
[pageLayout beginSheetWithPrintInfo:tempPrintInfo modalForWindow:[self window] delegate:self didEndSelector:@selector(didEndPageLayout:returnCode:contextInfo:) contextInfo:(void *)tempPrintInfo];
}
- (void)didEndPageLayout:(NSPageLayout *)pageLayout returnCode:(int)result contextInfo:(void *)contextInfo {
NSPrintInfo *tempPrintInfo = (NSPrintInfo *)contextInfo;
if (result == NSOKButton) [self setPrintInfo:tempPrintInfo];
[tempPrintInfo release];
}
/* doRevert does the actual reverting...
*/
- (void)doRevert {
NSRange prevSelectedRange = [[self firstTextView] selectedRange];
if (![self loadFromPath:revertDocumentName encoding:documentEncoding ignoreRTF:openedIgnoringRTF ignoreHTML:openedIgnoringHTML]) {
NSString *title = [NSString stringWithFormat:NSLocalizedString(@"Couldn\\U2019t revert to saved version of %@.", @"Title of alert panel indicating file couldn't be reverted."), displayName(revertDocumentName)];
// No endSheet method required for the alert, as there's only one possible response and nothing to clean up
NSBeginAlertSheet(title,
NSLocalizedString(@"OK", @"OK"), nil, nil, [self window],
self, NULL, NULL, NULL,
NSLocalizedString(@"The file has been removed.", @"Subtitle of alert panel indicating file couldn't be reverted."));
} else {
// Restore selection, if still within bounds
if (NSMaxRange(prevSelectedRange) <= [textStorage length]) {
[[self firstTextView] setSelectedRange:prevSelectedRange];
} else {
[[self firstTextView] setSelectedRange:NSMakeRange(0, 0)];
}
[self setDocumentName:revertDocumentName];
[self setDocumentEdited:NO];
[[self undoManager] removeAllActions];
[[NSDocumentController sharedDocumentController] noteNewRecentDocumentURL:[NSURL fileURLWithPath:revertDocumentName]];
}
}
/* revert: puts up an alert or calls doRevert directly
*/
- (void)revert:(id)sender {
if (revertDocumentName != nil) {
if ([self isDocumentEdited]) {
NSString *title = [NSString stringWithFormat:NSLocalizedString(@"Revert to saved version of %@?", @"Title of alert panel warning user about effects of reverting."), displayName(revertDocumentName)];
NSBeginAlertSheet(title,
NSLocalizedString(@"OK", @"OK"), NSLocalizedString(@"Cancel", @"Button choice allowing user to cancel."), nil, [self window], self, NULL, @selector(didEndRevertSheet:returnCode:contextInfo:), NULL,
NSLocalizedString(@"Reverting will lose your current changes.", @"Subtitle of alert panel warning user about effects of reverting."));
} else {
[self doRevert];
}
}
}
- (void)didEndRevertSheet:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSAlertDefaultReturn) [self doRevert];
}
- (void)close:(id)sender {
[[self window] close];
}
/* This no longer has a menu item ("Save To...") by default. It basically allows saving the file elsewhere w/out changing where it is.
*/
- (void)saveTo:(id)sender {
[self saveDocument:YES rememberName:NO shouldClose:NO];
}