-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathTTDocument.m
271 lines (230 loc) · 8.83 KB
/
TTDocument.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
//
// TTDocument.m
// Textus
//
// Created by Jjgod Jiang on 2/16/09.
//
#import "TTDocument.h"
#import "ExtendedAttributes.h"
#import "chardetect.h"
#import "TTTextView.h"
#define kLastReadLocationKey @"org.jjgod.textus.lastReadLocation"
#define BUFSIZE 4096
/* Use universal charset detector to automatically determine which encoding
* we should use to open the URL */
NSStringEncoding detectedEncodingForData(NSData* data) {
chardet_t chardetContext;
char charset[CHARDET_MAX_ENCODING_NAME];
int ret;
CFStringEncoding cfenc;
CFStringRef charsetStr;
chardet_create(&chardetContext);
chardet_reset(chardetContext);
chardet_handle_data(chardetContext, (const char*)[data bytes], [data length] > BUFSIZE ? BUFSIZE : (unsigned int)[data length]);
chardet_data_end(chardetContext);
ret = chardet_get_charset(chardetContext, charset, CHARDET_MAX_ENCODING_NAME);
chardet_destroy(chardetContext);
if (ret != CHARDET_RESULT_OK)
return NSUTF8StringEncoding;
charsetStr = CFStringCreateWithCString(NULL, charset, kCFStringEncodingUTF8);
cfenc = CFStringConvertIANACharSetNameToEncoding(charsetStr);
CFRelease(charsetStr);
return CFStringConvertEncodingToNSStringEncoding(cfenc);
}
@implementation TTDocument {
NSCharacterSet* _linePrefixCharset;
}
@synthesize fileContents, fileContentsInPlainText;
@synthesize lastReadLocation;
- (id)init {
self = [super init];
if (self) {
fileContents = nil;
lastReadLocation = 0;
_linePrefixCharset =
[NSCharacterSet characterSetWithCharactersInString:@" "];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSArray* keyPaths =
@[ @"backgroundColor", @"lineHeight", @"fontName", @"fontSize" ];
for (NSString* keyPath in keyPaths)
[defaults addObserver:self forKeyPath:keyPath options:0 context:nil];
}
return self;
}
- (void)close {
[self saveMetaData];
[super close];
}
- (void)dealloc {
NSArray* keyPaths =
@[ @"backgroundColor", @"lineHeight", @"fontName", @"fontSize" ];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
for (NSString* keyPath in keyPaths)
[defaults removeObserver:self forKeyPath:keyPath];
}
- (void)saveMetaData {
NSURL* fileURL = [self fileURL];
[fileURL setUnsignedInteger:lastReadLocation
forXattrKey:kLastReadLocationKey];
}
- (NSString*)windowNibName {
return @"TTDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController*)aController {
[super windowControllerDidLoadNib:aController];
[textView setDocument:self];
if (fileContents) {
[textView invalidateLayout];
[textView scrollToLocation:lastReadLocation];
}
}
- (NSData*)dataOfType:(NSString*)typeName error:(NSError**)outError {
if (outError != NULL) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain
code:unimpErr
userInfo:NULL];
}
return nil;
}
- (NSDictionary*)attributesForText {
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
CTFontRef font =
CTFontCreateWithName((CFStringRef)[defaults stringForKey:@"fontName"],
[defaults doubleForKey:@"fontSize"],
NULL);
NSDictionary* attributes =
@{(NSString*)kCTFontAttributeName : CFBridgingRelease(font)};
return attributes;
}
#define outputLine(output, line) [output appendFormat:@"%@\n", line]
#define outputParagraph(output, paragraph) \
do { \
[output appendFormat:@"%@\n\n", paragraph]; \
paragraph = nil; \
} while (0)
- (NSString*)firstLine:(NSString*)line {
line = [line stringByTrimmingCharactersInSet:_linePrefixCharset];
// Align first line with “「 optically
NSString* prefix = @" ";
if (line.length > 0) {
UniChar ch = [line characterAtIndex:0];
if (ch == 0x201C /* “ */ || ch == 0x300C /* 「 */)
prefix = @" ";
}
return [prefix stringByAppendingString:line];
}
- (void)outputTo:(NSMutableString*)output from:(NSString*)contents {
BOOL inParagraph = NO;
NSUInteger length = [contents length];
NSUInteger start = 0, end = 0;
NSRange range, lineRange;
NSString* line;
NSMutableString* paragraph = nil;
NSCharacterSet* newlineCharset = [NSCharacterSet newlineCharacterSet];
for (range = NSMakeRange(0, 0); end < length; range.location = end) {
[contents getLineStart:&start end:&end contentsEnd:NULL forRange:range];
lineRange = NSMakeRange(start, end - start);
line = [[contents substringWithRange:lineRange]
stringByTrimmingCharactersInSet:newlineCharset];
if (inParagraph) {
if ([line length] == 0) {
inParagraph = NO;
outputParagraph(output, paragraph);
} else if ([line hasPrefix:@"="] || [line hasPrefix:@"*"] ||
[line hasPrefix:@"*"]) {
inParagraph = NO;
outputParagraph(output, paragraph);
outputLine(output, line);
} else if ([line hasPrefix:@" "] || [line hasPrefix:@" "]) {
outputParagraph(output, paragraph);
paragraph =
[[NSMutableString alloc] initWithString:[self firstLine:line]];
} else
[paragraph appendString:line];
} else {
if ([line hasPrefix:@" "] || [line hasPrefix:@" "]) {
inParagraph = YES;
paragraph =
[[NSMutableString alloc] initWithString:[self firstLine:line]];
} else {
outputLine(output, line);
}
}
}
if (inParagraph && paragraph && [paragraph length]) {
outputParagraph(output, paragraph);
}
}
- (BOOL)readFromURL:(NSURL*)absoluteURL
ofType:(NSString*)typeName
error:(NSError**)outError {
NSString* contents;
NSData* data = [NSData dataWithContentsOfURL:absoluteURL];
contents = [[NSString alloc] initWithData:data
encoding:detectedEncodingForData(data)];
if (!contents)
return NO;
NSMutableString* wrappedText = [[NSMutableString alloc] init];
[self outputTo:wrappedText
from:[contents stringByReplacingOccurrencesOfString:@"\r"
withString:@""]];
[self setFileContentsInPlainText:wrappedText];
// Remove DOS line endings
fileContents = [[NSMutableAttributedString alloc]
initWithString:self.fileContentsInPlainText
attributes:[self attributesForText]];
// If "latinFontName" is set, use it as the primary font and leave the regular
// font as a fallback.
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSString* latinFontName = [defaults stringForKey:@"latinFontName"];
if (latinFontName) {
CGFloat fontSize = [defaults doubleForKey:@"fontSize"];
NSFont* latinFont = [NSFont fontWithName:latinFontName size:fontSize];
NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace |
NSLinguisticTaggerOmitPunctuation |
NSLinguisticTaggerJoinNames;
NSString* const scheme = NSLinguisticTagSchemeScript;
NSLinguisticTagger* tagger =
[[NSLinguisticTagger alloc] initWithTagSchemes:@[ scheme ]
options:options];
tagger.string = self.fileContentsInPlainText;
[tagger enumerateTagsInRange:NSMakeRange(
0, [self.fileContentsInPlainText length])
scheme:scheme
options:options
usingBlock:^(NSString* tag,
NSRange tokenRange,
NSRange sentenceRange,
BOOL* stop) {
if (![tag hasPrefix:@"Han"]) {
[self.fileContents
addAttribute:(NSString*)kCTFontAttributeName
value:latinFont
range:tokenRange];
}
}];
}
NSArray* keys = [absoluteURL allXattrKeys];
if ([keys containsObject:kLastReadLocationKey])
lastReadLocation =
[absoluteURL unsignedIntegerFromXattrKey:kLastReadLocationKey];
return YES;
}
- (void)observeValueForKeyPath:(NSString*)keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context {
if ([keyPath isEqual:@"lineHeight"] || [keyPath isEqual:@"fontName"] ||
[keyPath isEqual:@"fontSize"]) {
if (fileContents) {
[fileContents setAttributes:[self attributesForText]
range:NSMakeRange(0, fileContents.length)];
[textView invalidateLayout];
}
}
}
- (NSSize)window:(NSWindow*)window
willUseFullScreenContentSize:(NSSize)proposedSize {
return NSMakeSize(textView.frame.size.width, proposedSize.height);
}
@end