-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing24.html
executable file
·636 lines (554 loc) · 36.5 KB
/
listing24.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
<!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>TextEditPlus - /TextEditPlus Step 1/DocumentReadWrite.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/AppleScript/index.html">AppleScript</a> > <a href="../../samplecode/AppleScript/idxTools-date.html">Tools</a> > <A HREF="javascript:location.replace('index.html');">TextEditPlus</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">TextEditPlus</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>/TextEditPlus Step 1/DocumentReadWrite.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">/ReadMe.txt</option>
<option value="listing2.html">/TextEditPlus Starter/AppleScriptKit.sdef</option>
<option value="listing3.html">/TextEditPlus Starter/Controller.h</option>
<option value="listing4.html">/TextEditPlus Starter/Controller.m</option>
<option value="listing5.html">/TextEditPlus Starter/Document.h</option>
<option value="listing6.html">/TextEditPlus Starter/Document.m</option>
<option value="listing7.html">/TextEditPlus Starter/DocumentReadWrite.m</option>
<option value="listing8.html">/TextEditPlus Starter/Edit_main.m</option>
<option value="listing9.html">/TextEditPlus Starter/EncodingManager.h</option>
<option value="listing10.html">/TextEditPlus Starter/EncodingManager.m</option>
<option value="listing11.html">/TextEditPlus Starter/MultiplePageView.h</option>
<option value="listing12.html">/TextEditPlus Starter/MultiplePageView.m</option>
<option value="listing13.html">/TextEditPlus Starter/Preferences.h</option>
<option value="listing14.html">/TextEditPlus Starter/Preferences.m</option>
<option value="listing15.html">/TextEditPlus Starter/ScalingScrollView.h</option>
<option value="listing16.html">/TextEditPlus Starter/ScalingScrollView.m</option>
<option value="listing17.html">/TextEditPlus Starter/TextEdit.scriptSuite</option>
<option value="listing18.html">/TextEditPlus Starter/TextEdit.scriptTerminology</option>
<option value="listing19.html">/TextEditPlus Step 1/AppleScriptKit.sdef</option>
<option value="listing20.html">/TextEditPlus Step 1/Controller.h</option>
<option value="listing21.html">/TextEditPlus Step 1/Controller.m</option>
<option value="listing22.html">/TextEditPlus Step 1/Document.h</option>
<option value="listing23.html">/TextEditPlus Step 1/Document.m</option>
<option value="listing24.html">/TextEditPlus Step 1/DocumentReadWrite.m</option>
<option value="listing25.html">/TextEditPlus Step 1/Edit_main.m</option>
<option value="listing26.html">/TextEditPlus Step 1/EncodingManager.h</option>
<option value="listing27.html">/TextEditPlus Step 1/EncodingManager.m</option>
<option value="listing28.html">/TextEditPlus Step 1/MultiplePageView.h</option>
<option value="listing29.html">/TextEditPlus Step 1/MultiplePageView.m</option>
<option value="listing30.html">/TextEditPlus Step 1/Preferences.h</option>
<option value="listing31.html">/TextEditPlus Step 1/Preferences.m</option>
<option value="listing32.html">/TextEditPlus Step 1/ScalingScrollView.h</option>
<option value="listing33.html">/TextEditPlus Step 1/ScalingScrollView.m</option>
<option value="listing34.html">/TextEditPlus Step 1/testAS.applescript</option>
<option value="listing35.html">/TextEditPlus Step 1/TextEdit.scriptSuite</option>
<option value="listing36.html">/TextEditPlus Step 1/TextEdit.scriptTerminology</option>
<option value="listing37.html">/TextEditPlus Step 2/AppleScriptKit.sdef</option>
<option value="listing38.html">/TextEditPlus Step 2/Controller.h</option>
<option value="listing39.html">/TextEditPlus Step 2/Controller.m</option>
<option value="listing40.html">/TextEditPlus Step 2/Document.h</option>
<option value="listing41.html">/TextEditPlus Step 2/Document.m</option>
<option value="listing42.html">/TextEditPlus Step 2/DocumentReadWrite.m</option>
<option value="listing43.html">/TextEditPlus Step 2/Edit_main.m</option>
<option value="listing44.html">/TextEditPlus Step 2/EncodingManager.h</option>
<option value="listing45.html">/TextEditPlus Step 2/EncodingManager.m</option>
<option value="listing46.html">/TextEditPlus Step 2/MultiplePageView.h</option>
<option value="listing47.html">/TextEditPlus Step 2/MultiplePageView.m</option>
<option value="listing48.html">/TextEditPlus Step 2/Preferences.h</option>
<option value="listing49.html">/TextEditPlus Step 2/Preferences.m</option>
<option value="listing50.html">/TextEditPlus Step 2/ScalingScrollView.h</option>
<option value="listing51.html">/TextEditPlus Step 2/ScalingScrollView.m</option>
<option value="listing52.html">/TextEditPlus Step 2/testAS.applescript</option>
<option value="listing53.html">/TextEditPlus Step 2/TextEdit.scriptSuite</option>
<option value="listing54.html">/TextEditPlus Step 2/TextEdit.scriptTerminology</option></select>
</p>
</form>
<p><strong><a href="TextEditPlus.zip">Download Sample</a></strong> (“TextEditPlus.zip”, 2.11M)<BR>
<strong><a href="TextEditPlus.dmg">Download Sample</a></strong> (“TextEditPlus.dmg”, 2.66M)</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">/*
DocumentReadWrite.m
Copyright (c) 1995-2005 by Apple Computer, Inc., all rights reserved.
Author: Ali Ozer
Code to read/write text documents.
Some of the complexity here comes from the fact that we want to
preserve the original encoding of the file in order to save the file
correctly later on. If the user opens a Unicode file, on save, it should
be saved as Unicode. If the user opens a file in WinLatin1 encoding,
and on save it has to be changed to Unicode, we should be able to tell
the user this. Without these constraints, opening plain or rich files as
attributed strings would actually be a lot easier (and most apps can just
go that route)...
In the save routine we also have additional complexity because of the use
of exchangedata(), which allows exchanging contents of files, which in turn
allows preserving external information associated with files, such as
aliases to the file, icon location, creation date, etc.
*/
/*
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 "Document.h"
#import "ScalingScrollView.h"
#import "Preferences.h"
#import <sys/stat.h>
#import <string.h> // For memcmp()...
#import <unistd.h> // For exchangedata()
#import <sys/param.h> // For MAXPATHLEN
/* Implementations further below
*/
static BOOL exchangeFileContents(NSString *path1, NSString *path2, NSDictionary *path2Attrs);
static NSString *tempFileName(NSString *origName);
/* Old Edit app used to write out 12 pt paddings; we compensate for that.
*/
#define oldEditPaddingCompensation 12.0
@implementation Document(ReadWrite)
/* Loads from the specified path, sets encoding and textStorage. Note that if the file looks like RTF or RTFD, this method will open the file in rich text mode, regardless of the setting of encoding.
*/
- (BOOL)loadFromPath:(NSString *)fileName encoding:(unsigned)encoding ignoreRTF:(BOOL)ignoreRTF ignoreHTML:(BOOL)ignoreHTML error:(NSError **)errorPtr {
NSMutableDictionary *options = [NSMutableDictionary dictionary];
NSDictionary *docAttrs;
NSTextStorage *text = [self textStorage];
NSLayoutManager *layoutManager = [self layoutManager];
NSURL *url = [NSURL fileURLWithPath:fileName];
NSString *docType;
id val, viewSizeVal, paperSizeVal;
NSDate *modDate;
// Set up the options dictionary with desired parameters
[options setObject:url forKey:NSBaseURLDocumentOption];
if (encoding < SmallestCustomStringEncoding) [options setObject:[NSNumber numberWithUnsignedInt:encoding] forKey:NSCharacterEncodingDocumentOption];
// Check extensions to see if we should load the document as plain. Note that this check isn't always conclusive,
// which is why we do another check below, after the document has been loaded (and correctly categorized).
if (ignoreRTF || ignoreHTML) {
NSString *extension = [[fileName pathExtension] lowercaseString];
if ((ignoreRTF && [extension isEqual:@"rtf"]) || (ignoreHTML && ([extension isEqual:@"htm"] || [extension isEqual:@"html"]))) {
[options setObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentOption]; // Force plain
}
}
[[text mutableString] setString:@""]; // Empty the document
[self setRichText:YES dealWithAttachments:NO showRuler:NO]; // Assume rich...
modDate = [[[NSFileManager defaultManager] fileAttributesAtPath:fileName traverseLink:YES] fileModificationDate];
while (TRUE) { // We actually run through this once or twice, no more
BOOL success;
[layoutManager retain]; // Temporarily remove layout manager so it doesn't do any work while loading
[text removeLayoutManager:layoutManager];
[text beginEditing]; // Bracket with begin/end editing for efficiency
success = [text readFromURL:url options:options documentAttributes:&docAttrs error:errorPtr]; // Read!
[text endEditing];
[text addLayoutManager:layoutManager]; // Hook layout manager back up
[layoutManager release];
if (!success) return NO;
docType = [docAttrs objectForKey:NSDocumentTypeDocumentAttribute]; // Check what we actually read
// If the document turns out to be rich after all (we can't always tell, reload it, this time as plain for sure).
if (![[options objectForKey:NSDocumentTypeDocumentOption] isEqualToString:NSPlainTextDocumentType] &&
((ignoreHTML && [docType isEqual:NSHTMLTextDocumentType]) || (ignoreRTF && [docType isEqual:NSRTFTextDocumentType]))) {
[[text mutableString] setString:@""]; // Empty the document, and reload
[options setObject:NSPlainTextDocumentType forKey:NSDocumentTypeDocumentOption];
} else {
break;
}
};
if ([docType isEqual:NSRTFDTextDocumentType]) encoding = RichTextWithGraphicsStringEncoding;
else if ([docType isEqual:NSWebArchiveTextDocumentType]) encoding = WebArchiveStringEncoding;
else if ([docType isEqual:NSRTFTextDocumentType]) encoding = RichTextStringEncoding;
else if ([docType isEqual:NSHTMLTextDocumentType]) encoding = HTMLStringEncoding;
else if ([docType isEqual:NSDocFormatTextDocumentType]) encoding = DocStringEncoding;
else if ([docType isEqual:NSWordMLTextDocumentType]) encoding = WordMLStringEncoding;
else if ([docType isEqual:NSMacSimpleTextDocumentType]) encoding = SimpleTextStringEncoding;
else if ([docType isEqual:NSPlainTextDocumentType]) {
val = [docAttrs objectForKey:NSCharacterEncodingDocumentAttribute];
encoding = val ? [val unsignedIntValue] : UnknownStringEncoding;
[self setRichText:NO dealWithAttachments:NO showRuler:NO];
} else {
encoding = UnknownStringEncoding;
}
[self setEncoding:encoding];
if (val = [docAttrs objectForKey:NSConvertedDocumentAttribute]) {
[self setConverted:([val intValue] > 0)]; // Indicates filtered
[self setLossy:([val intValue] < 0)]; // Indicates lossily loaded
}
if ((val = [docAttrs objectForKey:NSViewModeDocumentAttribute]) && ([val intValue] == 1)) {
[self setHasMultiplePages:YES]; // Page layout view
if ((val = [docAttrs objectForKey:NSViewZoomDocumentAttribute])) {
float zoom = [val floatValue];
[scrollView setScaleFactor:(zoom / 100.0) adjustPopup:YES];
}
} else {
[self setHasMultiplePages:NO]; // Normal view
}
if ((val = [docAttrs objectForKey:NSLeftMarginDocumentAttribute])) [[self printInfo] setLeftMargin:[val floatValue]];
if ((val = [docAttrs objectForKey:NSRightMarginDocumentAttribute])) [[self printInfo] setRightMargin:[val floatValue]];
if ((val = [docAttrs objectForKey:NSBottomMarginDocumentAttribute])) [[self printInfo] setBottomMargin:[val floatValue]];
if ((val = [docAttrs objectForKey:NSTopMarginDocumentAttribute])) [[self printInfo] setTopMargin:[val floatValue]];
[self printInfoUpdated];
// Pre MacOSX versions of TextEdit wrote out the view (window) size in PaperSize
// If we encounter a non-MacOSX RTF file, and it's written by TextEdit, use PaperSize as ViewSize
viewSizeVal = [docAttrs objectForKey:NSViewSizeDocumentAttribute];
paperSizeVal = [docAttrs objectForKey:NSPaperSizeDocumentAttribute];
if (paperSizeVal && NSEqualSizes([paperSizeVal sizeValue], NSZeroSize)) paperSizeVal = nil; // Protect against some old documents with 0 paper size
if (viewSizeVal) {
[self setViewSize:[viewSizeVal sizeValue]];
if (paperSizeVal) [self setPaperSize:[paperSizeVal sizeValue]];
} else { // No ViewSize...
if (paperSizeVal) { // See if PaperSize should be used as ViewSize; if so, we also have some tweaking to do on it
val = [docAttrs objectForKey:NSCocoaVersionDocumentAttribute];
if (val && ([val intValue] < 100)) { // Indicates old RTF file; value described in AppKit/NSAttributedString.h
NSSize size = [paperSizeVal sizeValue];
if (size.width > 0 && size.height > 0 && ![self hasMultiplePages]) {
size.width = size.width - oldEditPaddingCompensation;
[self setViewSize:size];
}
} else {
[self setPaperSize:[paperSizeVal sizeValue]];
}
}
}
[self setHyphenationFactor:(val = [docAttrs objectForKey:NSHyphenationFactorDocumentAttribute]) ? [val floatValue] : 0];
[self setBackgroundColor:(val = [docAttrs objectForKey:NSBackgroundColorDocumentAttribute]) ? val : [NSColor whiteColor]];
// Set the document properties, generically, going through key value coding
NSArray *properties = [self knownDocumentProperties];
int cnt = [properties count];
while (cnt--) {
id value = [docAttrs objectForKey:[[self documentPropertyToAttributeNameMappings] objectForKey:[properties objectAtIndex:cnt]]];
[self setValue:value forKey:[properties objectAtIndex:cnt]]; // OK to set nil to clear
}
[self setReadOnly:((val = [docAttrs objectForKey:NSReadOnlyDocumentAttribute]) && ([val intValue] > 0))];
[self setFileModDate:modDate];
return YES;
}
- (SaveStatus)saveToPath:(NSString *)fileName encoding:(unsigned)encoding updateFilenames:(BOOL)updateFileNamesFlag overwriteOK:(BOOL)overwrite hideExtension:(FileExtensionStatus)extensionStatus {
BOOL success = NO;
NSString *intermediateFileNameToSave;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *actualFileNameToSave = [fileName stringByResolvingSymlinksInPath]; /* Follow links to save */
NSDictionary *curAttributes = [fileManager fileAttributesAtPath:actualFileNameToSave traverseLink:YES];
NSMutableDictionary *newAttributes;
/* Check to see if file seems writable */
if (curAttributes) { /* File exists; if it is not writable and we were not asked to overwrite, then punt... */
if (!overwrite && ![fileManager isWritableFileAtPath:actualFileNameToSave]) return SaveStatusFileNotWritable;
if (!overwrite && [actualFileNameToSave isEqual:[self documentName]] && [self isEditedExternally:[curAttributes fileModificationDate]]) return SaveStatusFileEditedExternally;
} else { /* File doesn't exist; if the enclosing folder is not writable then punt */
if (![fileManager isWritableFileAtPath:[actualFileNameToSave stringByDeletingLastPathComponent]]) return SaveStatusDestinationNotWritable;
}
/* Determine name of intermediate file */
if (curAttributes) { // File exists, so use an intermediate file
// Make up a unique name in the destination folder by prepending a prefix to the desired file name
intermediateFileNameToSave = tempFileName(actualFileNameToSave);
} else { // No existing file, just write the final destination
intermediateFileNameToSave = actualFileNameToSave;
}
/* Now actually write the file */
if (encoding == RichTextWithGraphicsStringEncoding || encoding == WebArchiveStringEncoding || encoding == RichTextStringEncoding || encoding == HTMLStringEncoding || encoding == DocStringEncoding || encoding == WordMLStringEncoding) {
NSRange range = NSMakeRange(0, [[self textStorage] length]);
NSString *docType = nil;
id val; // Holding temporary values
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSValue valueWithSize:[self viewSize]], NSViewSizeDocumentAttribute,
[NSValue valueWithSize:[self paperSize]], NSPaperSizeDocumentAttribute,
[NSNumber numberWithInt:[self isReadOnly] ? 1 : 0], NSReadOnlyDocumentAttribute,
[NSNumber numberWithFloat:[self hyphenationFactor]], NSHyphenationFactorDocumentAttribute,
[NSNumber numberWithFloat:[[self printInfo] leftMargin]], NSLeftMarginDocumentAttribute,
[NSNumber numberWithFloat:[[self printInfo] rightMargin]], NSRightMarginDocumentAttribute,
[NSNumber numberWithFloat:[[self printInfo] bottomMargin]], NSBottomMarginDocumentAttribute,
[NSNumber numberWithFloat:[[self printInfo] topMargin]], NSTopMarginDocumentAttribute,
[NSNumber numberWithInt:[self hasMultiplePages] ? 1 : 0], NSViewModeDocumentAttribute,
nil];
if (encoding == RichTextWithGraphicsStringEncoding) docType = NSRTFDTextDocumentType;
else if (encoding == WebArchiveStringEncoding) docType = NSWebArchiveTextDocumentType;
else if (encoding == RichTextStringEncoding) docType = NSRTFTextDocumentType;
else if (encoding == HTMLStringEncoding) docType = NSHTMLTextDocumentType;
else if (encoding == DocStringEncoding) docType = NSDocFormatTextDocumentType;
else if (encoding == WordMLStringEncoding) docType = NSWordMLTextDocumentType;
if (docType) [dict setObject:docType forKey:NSDocumentTypeDocumentAttribute];
if ([self hasMultiplePages]) [dict setObject:[NSNumber numberWithFloat:[scrollView scaleFactor] * 100.0] forKey:NSViewZoomDocumentAttribute];
if (val = [self backgroundColor]) [dict setObject:val forKey:NSBackgroundColorDocumentAttribute];
// Set HTML-specific attributes
if (docType == NSHTMLTextDocumentType || docType == NSWebArchiveTextDocumentType) {
NSMutableArray *excludedElements = [NSMutableArray array];
if (![[Preferences objectForKey:UseXHTMLDocType] boolValue]) [excludedElements addObject:@"XML"];
if (![[Preferences objectForKey:UseTransitionalDocType] boolValue]) [excludedElements addObjectsFromArray:[NSArray arrayWithObjects:@"APPLET", @"BASEFONT", @"CENTER", @"DIR", @"FONT", @"ISINDEX", @"MENU", @"S", @"STRIKE", @"U", nil]];
if (![[Preferences objectForKey:UseEmbeddedCSS] boolValue]) {
[excludedElements addObject:@"STYLE"];
if (![[Preferences objectForKey:UseInlineCSS] boolValue]) [excludedElements addObject:@"SPAN"];
}
if (![[Preferences objectForKey:PreserveWhitespace] boolValue]) {
[excludedElements addObject:@"Apple-converted-space"];
[excludedElements addObject:@"Apple-converted-tab"];
[excludedElements addObject:@"Apple-interchange-newline"];
}
[dict setObject:excludedElements forKey:NSExcludedElementsDocumentAttribute];
[dict setObject:[Preferences objectForKey:HTMLEncoding] forKey:NSCharacterEncodingDocumentAttribute];
[dict setObject:[NSNumber numberWithInt:2] forKey:NSPrefixSpacesDocumentAttribute];
}
// Set the document properties, generically, going through key value coding
NSArray *properties = [self knownDocumentProperties];
int cnt = [properties count];
while (cnt--) {
NSString *property = [properties objectAtIndex:cnt];
id value = [self valueForKey:property];
if (value && ![value isEqual:@""] && ![value isEqual:[NSArray array]]) [dict setObject:value forKey:[[self documentPropertyToAttributeNameMappings] objectForKey:property]];
}
if (encoding == RichTextWithGraphicsStringEncoding) {
NSFileWrapper *wrapper = [[self textStorage] RTFDFileWrapperFromRange:range documentAttributes:dict];
success = wrapper ? [wrapper writeToFile:intermediateFileNameToSave atomically:YES updateFilenames:updateFileNamesFlag] : NO;
} else {
NSData *data = [[self textStorage] dataFromRange:range documentAttributes:dict error:NULL];
success = data ? [data writeToFile:intermediateFileNameToSave atomically:YES] : NO;
}
} else {
NSData *data = [[textStorage string] dataUsingEncoding:encoding];
if (!data) return SaveStatusEncodingNotApplicable;
success = [data writeToFile:intermediateFileNameToSave atomically:YES];
}
if (!success) return SaveStatusNotOK;
/* At this point we have written the data out. Now for the paperwork.
If there was no previous file, then we just need to set some attributes (see further below).
If there was an existing file, we need to:
Exchange the intermediate and actual file (so the original file's attributes are preserved)
If exchange succeeds:
If backup is desired, rename the intermediate to backup file name; otherwise delete it
If exchange fails:
If backup is desired, rename the original to backup file name
Rename the intermediate to actual file name
*/
if (curAttributes) { // This indicates there was an existing file...
BOOL backupDesired = ![[Preferences objectForKey:DeleteBackup] boolValue];
BOOL thereIsABackup;
// First create the backup file name: basename~.extension, or basename~, or .extension~
NSString *backupFileName = [actualFileNameToSave stringByDeletingPathExtension]; // Temporary state, holding name without extension
NSString *extension = [actualFileNameToSave pathExtension];
if (![backupFileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
backupFileName = [[backupFileName stringByAppendingString:@"~"] stringByAppendingPathExtension:extension];
} else {
backupFileName = [actualFileNameToSave stringByAppendingString:@"~"];
}
thereIsABackup = [fileManager fileExistsAtPath:backupFileName];
if (exchangeFileContents(intermediateFileNameToSave, actualFileNameToSave, curAttributes)) {
// Exchange worked; at this point the document is saved under actualFileNameToSave; previous contents are in intermediateFileNameToSave
if (backupDesired) {
if (thereIsABackup && exchangeFileContents(intermediateFileNameToSave, backupFileName, nil)) { // If there is an existing backup, attempt exchange
// If exchange worked, manually copy the attributes over and remove the 2nd generation backup (which is now in intermediateFileNameToSave)
(void)[fileManager changeFileAttributes:curAttributes atPath:backupFileName];
(void)[fileManager removeFileAtPath:intermediateFileNameToSave handler:nil];
} else {
if (thereIsABackup) (void)[fileManager removeFileAtPath:backupFileName handler:nil];
if ([fileManager movePath:intermediateFileNameToSave toPath:backupFileName handler:nil]) {
(void)[fileManager changeFileAttributes:curAttributes atPath:backupFileName];
} else { // For some reason, could not generate backup; delete intermediate
(void)[fileManager removeFileAtPath:intermediateFileNameToSave handler:nil];
}
}
} else { // No backup desired; delete the intermediate. But leave around any existing older backup
(void)[fileManager removeFileAtPath:intermediateFileNameToSave handler:nil];
}
} else { // Exchange did not work, do the file exchange by moving stuff around
if (thereIsABackup) (void)[fileManager removeFileAtPath:backupFileName handler:nil]; // Remove old backup
// Now move old file to backup; if this fails, we should give up as something is wrong and we don't want to lose the backup
success = [fileManager movePath:actualFileNameToSave toPath:backupFileName handler:nil];
if (success) {
// And move intermediate to actual file; but if that fails, restore the backup as actual
success = [fileManager movePath:intermediateFileNameToSave toPath:actualFileNameToSave handler:nil];
if (success) {
if (!backupDesired) (void)[fileManager removeFileAtPath:backupFileName handler:nil]; // Delete unwanted backup
} else if ([fileManager movePath:backupFileName toPath:actualFileNameToSave handler:nil]) { // Restore backup
(void)[fileManager removeFileAtPath:intermediateFileNameToSave handler:nil]; // Clean intermediate
}
}
}
if (!success) return SaveStatusNotOK;
}
/* Now we set attributes and such on the destination file, as needed. We could be a little more sophisticated here and only do some stuff based on whether the exchange operation worked or not.
*/
newAttributes = [NSMutableDictionary dictionary];
if (curAttributes) { // Existing file
BOOL saveFilesWritable = [[Preferences objectForKey:SaveFilesWritable] boolValue];
id permissions = [curAttributes objectForKey:NSFilePosixPermissions];
if (permissions) {
if (saveFilesWritable) permissions = [NSNumber numberWithUnsignedLong:([permissions unsignedLongValue] | 0200)];
[newAttributes setObject:permissions forKey:NSFilePosixPermissions];
}
// !!! This does not make the file immutable on file systems w/out exchange; probably should do that though
if (saveFilesWritable && [curAttributes fileIsImmutable]) [newAttributes setObject:[NSNumber numberWithBool:NO] forKey:NSFileImmutable];
// Preserve previous state of hidden extension bit
if (extensionStatus == FileExtensionPreviousState) {
id hiddenExtension = [curAttributes objectForKey:NSFileExtensionHidden];
if (hiddenExtension) extensionStatus = [hiddenExtension boolValue] ? FileExtensionHidden : FileExtensionShown ;
}
// Set hidden extension bit
[newAttributes setObject:[NSNumber numberWithBool:(extensionStatus != FileExtensionShown)] forKey:NSFileExtensionHidden];
// We need to clear previous type/creator out as it might not apply at all to the new document
if ([curAttributes fileHFSCreatorCode] != 0) [newAttributes setObject:[NSNumber numberWithUnsignedInt:0] forKey:NSFileHFSCreatorCode];
if ([curAttributes fileHFSTypeCode] != 0) [newAttributes setObject:[NSNumber numberWithUnsignedInt:0] forKey:NSFileHFSTypeCode];
} else { // New file
// Set hidden extension bit to YES if desired; otherwise don't do anything (as NO is the default)
if (extensionStatus != FileExtensionShown) [newAttributes setObject:[NSNumber numberWithBool:YES] forKey:NSFileExtensionHidden];
}
if ([newAttributes count] > 0) (void)[fileManager changeFileAttributes:newAttributes atPath:actualFileNameToSave];
// Refresh the file attrs (if for some reason not available, will become nil, which is fine, as it indicates "not known")
[self setFileModDate:[[fileManager fileAttributesAtPath:actualFileNameToSave traverseLink:YES] fileModificationDate]];
return SaveStatusOK;
}
@end
/* Exchange the contents of the two specified files. First file is assumed to be new (and writable); second file will be temporarily made writable to allow the exchange. The attributes are those of the second file; if nil, they will be computed on the fly.
*/
static BOOL exchangeFileContents(NSString *path1, NSString *path2, NSDictionary *path2Attrs) {
NSFileManager *fileManager = [NSFileManager defaultManager];
char cPath1[MAXPATHLEN+1];
char cPath2[MAXPATHLEN+1];
int err;
if (![path1 getFileSystemRepresentation:cPath1 maxLength:MAXPATHLEN] || ![path2 getFileSystemRepresentation:cPath2 maxLength:MAXPATHLEN]) return NO;
err = exchangedata(cPath1, cPath2, 0) ? errno : 0;
if (err == EACCES || err == EPERM) { // Seems to be a write-protected or locked file; try temporarily changing
NSDictionary *attrs = path2Attrs ? path2Attrs : [fileManager fileAttributesAtPath:path2 traverseLink:YES];
NSNumber *curPerms = [attrs objectForKey:NSFilePosixPermissions];
BOOL curImmutable = [attrs fileIsImmutable];
if (curPerms) [fileManager changeFileAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithUnsignedLong:[curPerms unsignedLongValue] | 0200], NSFilePosixPermissions, nil] atPath:path2];
if (curImmutable) [fileManager changeFileAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:NO], NSFileImmutable, nil] atPath:path2];
err = exchangedata(cPath1, cPath2, 0) ? errno : 0;
// Restore original values
if (curPerms) [fileManager changeFileAttributes:[NSDictionary dictionaryWithObjectsAndKeys:curPerms, NSFilePosixPermissions, nil] atPath:path2];
if (curImmutable) [fileManager changeFileAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSFileImmutable, nil] atPath:path2];
}
return err ? NO : YES;
}
/* Generate a reasonably short temporary unique file, given an original path. Use a "." prefix to hide the file in Finder.
*/
static NSString *tempFileName(NSString *origPath) {
static int sequenceNumber = 0;
NSString *name;
do {
sequenceNumber++;
name = [NSString stringWithFormat:@".%d-%d-%d.%@", [[NSProcessInfo processInfo] processIdentifier], (int)[NSDate timeIntervalSinceReferenceDate], sequenceNumber, [origPath pathExtension]];
name = [[origPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:name];
} while ([[NSFileManager defaultManager] fileExistsAtPath:name]);
return name;
}
</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/TextEditPlus/listing24.html%3Fid%3DDTS10004025-1.0&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/TextEditPlus/listing24.html%3Fid%3DDTS10004025-1.0&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/TextEditPlus/listing24.html%3Fid%3DDTS10004025-1.0&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>