jessegrosjean / bdocuments

This URL has Read+Write access

bdocuments / BDocument.m
100644 456 lines (364 sloc) 18.568 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//
// BDocument.m
// BDocuments
//
// Created by Jesse Grosjean on 10/16/07.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//
 
#import "BDocument.h"
#import "BDocuments.h"
#import "BDocumentWindowController.h"
#import "SyncedDocumentsControllerDelegate.h"
#import "DiffMatchPatch.h"
#import "BDocumentDifferencesWindowController.h"
#import "UKKQueue.h"
 
 
@implementation BDocument
 
+ (void)initialize {
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
nil]];
}
 
#pragma mark Document Defaults Repository
 
static NSMutableArray *documentUserDefautlsArchive = nil;
 
 
- (void)updateChangeCount:(NSDocumentChangeType)changeType {
[super updateChangeCount:changeType];
}
 
 
+ (NSString *)documentUserDefaultsArchivePath {
return [[[NSFileManager defaultManager] processesApplicationSupportFolder] stringByAppendingPathComponent:@"DocumentsUserDefaults.archive"];
}
 
+ (NSMutableArray *)documentUserDefautlsArchive {
if (!documentUserDefautlsArchive) {
documentUserDefautlsArchive = [NSUnarchiver unarchiveObjectWithFile:[self documentUserDefaultsArchivePath]];
if (!documentUserDefautlsArchive) {
documentUserDefautlsArchive = [[NSMutableArray alloc] init];
}
}
return documentUserDefautlsArchive;
}
 
+ (NSDictionary *)loadDocumentUserDefaultsForDocumentURL:(NSURL *)documentURL {
NSDictionary *documentUserDefaults = [[[self documentUserDefautlsArchive] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"BDocumentsDocumentURL = %@", [documentURL path]]] lastObject];
if (!documentUserDefaults) {
documentUserDefaults = [NSDictionary dictionary];
}
return documentUserDefaults;
}
 
+ (BOOL)storeDocumentUserDefaults:(NSDictionary *)documentUserDefaults forDocumentURL:(NSURL *)documentURL {
if (!documentURL) return NO;
if (!documentUserDefaults) return NO;
 
NSDictionary *oldDocumentUserDefaults = [[[self documentUserDefautlsArchive] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"BDocumentsDocumentURL = %@", [documentURL path]]] lastObject];
if (oldDocumentUserDefaults) {
[documentUserDefautlsArchive removeObject:oldDocumentUserDefaults];
}
 
NSMutableDictionary *newDocumentUserDefaults = [documentUserDefaults mutableCopy];
[newDocumentUserDefaults setObject:[documentURL path] forKey:@"BDocumentsDocumentURL"];
[documentUserDefautlsArchive addObject:newDocumentUserDefaults];
 
return YES;
}
 
+ (BOOL)synchronizeDocumentUserDefaultsRepository {
[[NSNotificationCenter defaultCenter] postNotificationName:BDocumentUserDefaultsWillSynchronizeNotification object:self];
 
NSInteger count = [[self documentUserDefautlsArchive] count];
NSInteger max = 100;
 
if (count > max) {
[documentUserDefautlsArchive removeObjectsInRange:NSMakeRange(0, count - max)]; // keep newer user infos at end of array
}
 
if (![NSArchiver archiveRootObject:documentUserDefautlsArchive toFile:[self documentUserDefaultsArchivePath]]) {
BLogWarning(@"failed to save documentUserDefautlsArchive");
return NO;
}
 
[[NSNotificationCenter defaultCenter] postNotificationName:BDocumentUserDefaultsDidSynchronizeNotification object:self];
 
return YES;
}
 
#pragma mark awakeFromNib-like methods
 
- (void)makeWindowControllers {
// First make sure to load plugins containing all window controller factories so that NSClassFromString(className) will work bellow for saved window controllers.
for (BPlugin *each in [[[BExtensionRegistry sharedInstance] configurationElementsFor:@"com.blocks.BDocuments.documentDefaultWindowControllersFactory"] valueForKey:@"plugin"]) {
NSError *error = nil;
if (![each loadAndReturnError:&error]) {
[NSApp presentError:error];
}
}
 
NSDictionary *documentWindowControllersState = [self documentUserDefaultForKey:BDocumentsWindowControllersDefaultsKey];
 
for (NSString *eachKey in [documentWindowControllersState keyEnumerator]) {
NSDictionary *windowControllerState = [documentWindowControllersState objectForKey:eachKey];
NSString *className = [windowControllerState objectForKey:@"class"];
if (className) {
Class class = NSClassFromString(className);
NSWindowController *windowController = [[class alloc] initWithWindowControllerUserDefaultsKey:eachKey];
if (windowController) {
[self addWindowController:windowController];
}
}
}
 
if ([[self windowControllers] count] == 0) {
for (BConfigurationElement *each in [[BExtensionRegistry sharedInstance] configurationElementsFor:@"com.blocks.BDocuments.documentDefaultWindowControllersFactory"]) {
id <BDocumentWindowControllerFactory> windowControllerFactory = [each createExecutableExtensionFromAttribute:@"factory" conformingToClass:nil conformingToProtocol:@protocol(BDocumentWindowControllerFactory) respondingToSelectors:nil];
NSWindowController *windowController = [windowControllerFactory createDocumentWindowControllerForDocument:self];
if (windowController) {
[self addWindowController:windowController];
}
}
}
}
 
- (void)removeWindowController:(BDocumentWindowController *)windowController {
NSMutableDictionary *documentWindowControllersState = [self documentUserDefaultForKey:BDocumentsWindowControllersDefaultsKey];
if ([documentWindowControllersState count] > 1) {
[documentWindowControllersState removeObjectForKey:[windowController windowControllerUserDefaultsKey]];
}
[super removeWindowController:windowController];
}
 
#pragma mark Printing
 
- (NSPrintOperation *)printOperationWithSettings:(NSDictionary *)printSettings error:(NSError **)outError {
    if ([[self windowControllers] count] == 0) [self makeWindowControllers];
 
id windowController = [[self windowControllers] lastObject];
 
if ([windowController respondsToSelector:@selector(printOperationWithSettings:error:)]) {
return [windowController printOperationWithSettings:printSettings error:outError];
}
 
return nil;
}
 
#pragma mark Document User Defaults
 
- (NSDictionary *)defaultDocumentUserDefaults {
return [NSDictionary dictionary];
}
 
- (NSDictionary *)documentUserDefaults {
if (!documentUserDefaults) {
documentUserDefaults = [[self defaultDocumentUserDefaults] mutableCopy];
}
return documentUserDefaults;
}
 
- (id)documentUserDefaultForKey:(NSString *)key {
return [[self documentUserDefaults] objectForKey:key];
}
 
- (void)setDocumentUserDefault:(id)documentUserDefault forKey:(NSString *)key {
if (documentUserDefault) {
if ([documentUserDefault conformsToProtocol:@protocol(NSCoding)]) {
[(id)[self documentUserDefaults] setObject:documentUserDefault forKey:key];
} else {
BLogWarning([NSString stringWithFormat:@"%@ cannot be set as document user default because it does not conform to coding protocol", documentUserDefault], nil);
}
} else {
[documentUserDefaults removeObjectForKey:key];
}
}
 
- (void)addDocumentUserDefaultsFromDictionary:(NSDictionary *)newDocumentUserDefaults {
for (NSString *eachKey in [newDocumentUserDefaults keyEnumerator]) {
[self setDocumentUserDefault:[newDocumentUserDefaults objectForKey:eachKey] forKey:eachKey];
}
}
 
- (void)close {
[BDocument storeDocumentUserDefaults:[self documentUserDefaults] forDocumentURL:[self fileURL]];
NSURL *fileURL = [self fileURL];
if (fileURL) {
UKKQueue *sharedFileWatcher = [UKKQueue sharedFileWatcher];
[sharedFileWatcher removePathFromQueue:[[fileURL path] stringByDeletingLastPathComponent]];
[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:sharedFileWatcher];
}
 
[super close];
}
 
#pragma mark ODB Editor Suite support
 
@synthesize fromExternal;
@synthesize externalSender;
@synthesize externalToken;
 
- (NSString *)displayName {
if (fromExternal && externalDisplayName != nil) {
return externalDisplayName;
} else if (fromSyncedDocument) {
return [SyncedDocumentsControllerDelegate displayNameForSyncedDocument:[self fileURL]];
}
return [super displayName];
}
 
#pragma mark Reading and Writing
 
- (IBAction)showUnsavedChanges:(id)sender {
NSWindowController *windowController = [[self windowControllers] lastObject];
NSWindow *window = [windowController window];
NSURL *fileURL = [self fileURL];
NSString *messageText = nil;
NSString *informativeText = @"";
 
if (fileURL) {
NSString *unsavedText = [self textContents];
NSString *savedText = [self savedTextContents:nil];
 
if ([savedText isEqualToString:unsavedText]) {
messageText = BLocalizedString(@"Your document has no unsaved changes.", nil);
informativeText = BLocalizedString(@"The content of your open document is exactly the same as the content that is saved on disk.", nil);
} else {
BDocumentDifferencesWindowController *differencesWindowController = [[BDocumentDifferencesWindowController alloc] initWithText1:savedText text2:unsavedText];
[differencesWindowController setMessageText:BLocalizedString(@"These are your unsaved changes.", nil)];
[NSApp beginSheet:[differencesWindowController window] modalForWindow:window modalDelegate:self didEndSelector:@selector(showUnsavedChangesSheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
return;
}
} else {
messageText = BLocalizedString(@"Your document has not been saved.", nil);
informativeText = BLocalizedString(@"You must first save your document before you can compare it to the content that is saved on disk.", nil);
}
 
NSAlert *alert = [NSAlert alertWithMessageText:messageText defaultButton:BLocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:informativeText];
[alert beginSheetModalForWindow:window modalDelegate:nil didEndSelector:nil contextInfo:nil];
}
 
- (void)showUnsavedChangesSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
[sheet orderOut:self];
}
 
- (NSString *)textContentsFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
NSMutableString *string = [[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (string) {
NSString *windowsLineEnding = [[NSString alloc] initWithFormat:@"%C%C", 0x000D, 0x000A];
NSString *macLineEnding = [[NSString alloc] initWithFormat:@"%C", 0x000D];
[string replaceOccurrencesOfString:windowsLineEnding withString:@"\n" options:NSLiteralSearch range:NSMakeRange(0, [string length])];
[string replaceOccurrencesOfString:macLineEnding withString:@"\n" options:NSLiteralSearch range:NSMakeRange(0, [string length])];
return string;
} else {
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
BLocalizedString(@"The file is not in the right format.", nil), NSLocalizedDescriptionKey,
BLocalizedString(@"The file might be corrupted, truncated, or in a different format than you expect.", nil), NSLocalizedRecoverySuggestionErrorKey,
BLocalizedString(@"The file is not in the right format.", nil), NSLocalizedFailureReasonErrorKey,
nil];
 
*outError = [[NSError alloc] initWithDomain:@"com.hogbaysoftware.taskpaper.TPDocument" code:1 userInfo:userInfo]; // Why does none of this error info get displayed?
 
return nil;
}
}
 
- (NSString *)savedTextContents:(NSError **)error {
return [self textContentsFromData:[NSData dataWithContentsOfURL:[self fileURL]] ofType:[self fileType] error:error];
}
 
- (NSString *)textContents {
return nil;
}
 
- (void)setTextContents:(NSString *)newString {
}
 
- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
NSString *string = [self textContentsFromData:data ofType:typeName error:outError];
 
if (string) {
[[self undoManager] disableUndoRegistration];
[self setTextContents:string];
[[self undoManager] enableUndoRegistration];
[self addDocumentUserDefaultsFromDictionary:[BDocument loadDocumentUserDefaultsForDocumentURL:[self fileURL]]];
lastKnownTextContentsOnDisk = string;
return YES;
} else {
return NO;
}
}
 
void BDocumentSubscriptionProc(FNMessage message, OptionBits flags, void *refcon, FNSubscriptionRef subscription) {
    BDocument *document = (BDocument *) refcon;
    
    if( message == kFNDirectoryModifiedMessage ) // No others exist as of 10.4
[document checkForModificationOfFileOnDisk];
    else
        NSLog(@"BDocumentSubscriptionProc: Unknown message %d", message);
}
 
- (void)setFileURL:(NSURL *)absoluteURL {
UKKQueue *sharedFileWatcher = [UKKQueue sharedFileWatcher];
NSURL *oldFileURL = [self fileURL];
if (oldFileURL) {
[sharedFileWatcher removePathFromQueue:[[oldFileURL path] stringByDeletingLastPathComponent]];
[[NSNotificationCenter defaultCenter] removeObserver:self name:nil object:sharedFileWatcher];
}
 
if (absoluteURL) {
[sharedFileWatcher addPathToQueue:[[absoluteURL path] stringByDeletingLastPathComponent]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didChangeFileSomewhere:) name:nil object:sharedFileWatcher];
}
 
[super setFileURL:absoluteURL];
fromSyncedDocument = [SyncedDocumentsControllerDelegate isSyncedDocumentURL:[self fileURL]];
}
 
- (NSInteger)fileHFSTypeCode {
[NSException raise:@"Subclass must overide" format:@""];
return 0;
}
 
- (NSInteger)fileHFSCreatorCode {
[NSException raise:@"Subclass must overide" format:@""];
return 0;
}
 
- (NSDictionary *)fileAttributesToWriteToFile:(NSString *)fullDocumentPath ofType:(NSString *)docType saveOperation:(NSSaveOperationType)saveOperationType {
NSMutableDictionary *attributes = [[super fileAttributesToWriteToFile:fullDocumentPath ofType:docType saveOperation:saveOperationType] mutableCopy];
[attributes setObject:[NSNumber numberWithUnsignedInteger:[self fileHFSTypeCode]] forKey:NSFileHFSTypeCode];
[attributes setObject:[NSNumber numberWithUnsignedInteger:[self fileHFSCreatorCode]] forKey:NSFileHFSCreatorCode];
return attributes;
}
 
@synthesize fromSyncedDocument;
 
/*- (void)saveDocumentWithDelegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo {
if ([self checkForModificationOfFileOnDisk]) {
NSInvocation *callback = [NSInvocation invocationWithMethodSignature:[delegate methodSignatureForSelector:didSaveSelector]];
[callback setSelector:didSaveSelector];
[callback setArgument:&self atIndex:2];
[callback setArgument:NO atIndex:3];
[callback setArgument:contextInfo atIndex:4];
[callback invokeWithTarget:delegate];
return;
}
[super saveDocumentWithDelegate:delegate didSaveSelector:didSaveSelector contextInfo:contextInfo];
}*/
 
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation originalContentsURL:(NSURL *)absoluteOriginalContentsURL error:(NSError **)outError {
NSString *textContents = [self textContents];
 
if ([textContents writeToURL:absoluteURL atomically:YES encoding:NSUTF8StringEncoding error:outError]) {
if (saveOperation == NSSaveOperation || saveOperation == NSSaveAsOperation) {
[BDocument storeDocumentUserDefaults:[self documentUserDefaults] forDocumentURL:[self fileURL]];
lastKnownTextContentsOnDisk = textContents;
}
return YES;
}
 
return NO;
}
 
- (BOOL)BDocument_checkForModificationOfFileOnDisk {
NSDate *knownFileModificationDate = [self fileModificationDate];
BOOL result = NO;
 
if (knownFileModificationDate) {
NSFileManager *fileManager = [NSFileManager defaultManager];
 
if ([fileManager fileExistsAtPath:[[self fileURL] path]]) {
//if ([self respondsToSelector:@selector(_resetMoveAndRenameSensing)]) {
// [self performSelector:@selector(_resetMoveAndRenameSensing)];
//}
 
NSDate *actualFileModificationDate = [[fileManager fileAttributesAtPath:[[self fileURL] path] traverseLink:YES] fileModificationDate];
 
if ([knownFileModificationDate isLessThan:actualFileModificationDate]) {
NSError *error = nil;
NSString *savedTextContents = [self savedTextContents:&error];
if (savedTextContents) {
DiffMatchPatch *dmp = [[DiffMatchPatch alloc] init];
NSMutableArray *patches = [dmp patchMakeText1:lastKnownTextContentsOnDisk text2:savedTextContents];
if ([patches count] > 0) {
NSArray *patchResults = [dmp patchApply:patches text:[self textContents]];
NSString *patchedDocumentText = [patchResults objectAtIndex:0];
[self setTextContents:patchedDocumentText];
lastKnownTextContentsOnDisk = savedTextContents;
 
NSUInteger index = 0;
NSMutableArray *failedDiffs = [NSMutableArray array];
for (NSNumber *each in [patchResults objectAtIndex:1]) {
if ([each boolValue] == NO) {
[failedDiffs addObjectsFromArray:[[patches objectAtIndex:index] diffs]];
}
index++;
}
 
if ([failedDiffs count] > 0) {
NSWindow *window = [[[self windowControllers] lastObject] window];
BDocumentDifferencesWindowController *differencesWindowController = [[BDocumentDifferencesWindowController alloc] initWithDiffs:failedDiffs];
[differencesWindowController setMessageText:BLocalizedString(@"This document's file has been changed by another application. These changes could not be merged back into your open document.", nil)];
[NSApp beginSheet:[differencesWindowController window] modalForWindow:window modalDelegate:self didEndSelector:@selector(showMergeFailuresSheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
result = YES;
}
}
 
[self setFileModificationDate:actualFileModificationDate];
}
}
}
}
return result;
}
 
- (void)showMergeFailuresSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
[sheet orderOut:self];
}
 
 
@end
 
@implementation NSDocument (BDocumentAdditions)
 
- (BOOL)checkForModificationOfFileOnDisk {
if ([self respondsToSelector:@selector(BDocument_checkForModificationOfFileOnDisk)]) {
return [((id)self) BDocument_checkForModificationOfFileOnDisk];
}
return NO;
}
 
@end
 
 
@implementation NSDocument (BDocumentMethodReplacements)
 
+ (void)load {
    if (self == [NSDocument class]) {
[NSDocument replaceMethod:@selector(_handleDocumentFileChanges:) withMethod:@selector(BDocument_handleDocumentFileChanges:)];
    }
}
 
- (void)BDocument_handleDocumentFileChanges:(id)arg {
if (![[NSFileManager defaultManager] fileExistsAtPath:[[self fileURL] path]]) {
[self BDocument_handleDocumentFileChanges:arg]; // Only allow AppKit to track moved files if the original file path has been deleted.
}
}
 
@end
 
 
NSString *BDocumentUserDefaultsWillSynchronizeNotification = @"BDocumentUserDefaultsWillSynchronizeNotification";
NSString *BDocumentUserDefaultsDidSynchronizeNotification = @"BDocumentUserDefaultsDidSynchronizeNotification";