public
Description:
Homepage:
Clone URL: git://github.com/jessegrosjean/bdocuments.git
bdocuments / BDocument.m
100644 353 lines (284 sloc) 14.356 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
//
// 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 "BDocumentCloudDelegate.h"
//#import "BDocumentDifferencesWindowController.h"
//#import "BCloudDocumentsService.h"
 
 
@implementation BDocument
 
+ (void)initialize {
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
nil]];
}
 
#pragma mark Document Defaults Repository
 
static NSMutableArray *documentUserDefautlsArchive = nil;
 
+ (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]];
[super close];
}
 
#pragma mark ODB Editor Suite support
 
@synthesize fromExternal;
@synthesize externalSender;
@synthesize externalToken;
 
- (NSString *)displayName {
if (fromExternal && externalDisplayName != nil) {
return externalDisplayName;
} else if (fromCloud) {
return [BDocumentCloudDelegate displayNameForCloudDocument:[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 *informativeTextText = @"";
 
if (fileURL) {
NSString *unsavedText = [self documentDataAsText];
NSString *savedText = [NSString stringWithContentsOfFile:[fileURL path] encoding:NSUTF8StringEncoding error:nil];
 
if ([savedText isEqualToString:unsavedText]) {
messageText = BLocalizedString(@"There are no differences between your document and the version saved on disk", nil);
} else {
// BDocumentDifferencesWindowController *differencesWindowController = [[BDocumentDifferencesWindowController alloc] initWithText1:savedText text2:unsavedText];
// [NSApp beginSheet:[differencesWindowController window] modalForWindow:window modalDelegate:self didEndSelector:@selector(showUnsavedChangesSheetDidEnd:returnCode:contextInfo:) contextInfo:nil];
NSBeep();
return;
}
} else {
messageText = BLocalizedString(@"Your document has not been saved yet", nil);
}
 
NSAlert *alert = [NSAlert alertWithMessageText:messageText defaultButton:BLocalizedString(@"OK", nil) alternateButton:nil otherButton:nil informativeTextWithFormat:informativeTextText];
[alert beginSheetModalForWindow:window modalDelegate:nil didEndSelector:nil contextInfo:nil];
}
 
- (void)showUnsavedChangesSheetDidEnd:(NSWindow *)sheet returnCode:(int)returnCode contextInfo:(void *)contextInfo {
[sheet orderOut:self];
}
 
- (NSString *)documentDataAsText {
return nil;
}
 
- (void)setFileURL:(NSURL *)absoluteURL {
[super setFileURL:absoluteURL];
fromCloud = [BDocumentCloudDelegate isCloudDocumentURL:[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 fromCloud;
 
- (NSString *)cloudID {
return [[[[self fileURL] path] stringByDeletingLastPathComponent] lastPathComponent];
}
 
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError {
[BDocument storeDocumentUserDefaults:[self documentUserDefaults] forDocumentURL:[self fileURL]];
return [[self documentDataAsText] writeToURL:absoluteURL atomically:YES encoding:NSUTF8StringEncoding error:outError];
}
 
- (void)readModifiedFileFromDisk:(NSDate *)newModificationDate {
NSError *error = nil;
if (![self revertToContentsOfURL:[self fileURL] ofType:[self fileType] error:&error]) {
BLogError(@"failed revertToSavedFromURL:ofType:");
[self presentError:error];
} else {
[self setFileModificationDate:newModificationDate];
}
[[self undoManager] removeAllActions];
[self updateChangeCount:NSChangeCleared];
}
 
- (void)fileWasModifiedExternallyByAnotherApplication:(NSDate *)newModificationDate {
if ([self isDocumentEdited]) {
NSString *processName = [[NSProcessInfo processInfo] processName];
NSString *message = BLocalizedString(@"Warning", nil);
NSString *informativeText = BLocalizedString(@"The file for this document has been modified by another application. There are also unsaved changes in %@. Do you want to keep the %@ version or revert to the version on disk?", nil);
NSString *defaultButton = BLocalizedString(@"Keep %@ Version", nil);
NSString *alternateButton = BLocalizedString(@"Revert", nil);
NSAlert *alert = [NSAlert alertWithMessageText:message defaultButton:[NSString stringWithFormat:defaultButton, processName] alternateButton:alternateButton otherButton:nil informativeTextWithFormat:informativeText, processName, processName];
[alert beginSheetModalForWindow:[[NSApp currentDocumentWindowController] window] modalDelegate:self didEndSelector:@selector(fileWasModifiedExternallyAlertDidEnd:returnCode:contextInfo:) contextInfo:newModificationDate];
} else {
[self readModifiedFileFromDisk:newModificationDate];
}
 
for (NSWindowController *each in [self windowControllers]) {
[each synchronizeWindowTitleWithDocumentName];
}
}
 
- (void)checkForModificationOfFileOnDisk {
NSDate *knownFileModificationDate = [self fileModificationDate];
if (knownFileModificationDate) {
NSDate *actualFileModificationDate = [[[NSFileManager defaultManager] fileAttributesAtPath:[[self fileURL] path] traverseLink:YES] fileModificationDate];
if ([knownFileModificationDate isLessThan:actualFileModificationDate]) {
[self performSelector:@selector(fileWasModifiedExternallyByAnotherApplication:) withObject:actualFileModificationDate];
}
}
}
 
- (void)fileWasModifiedExternallyAlertDidEnd:(NSAlert *)alert returnCode:(int)returnCode contextInfo:(void *)contextInfo {
if (returnCode == NSAlertDefaultReturn) { // keep current version
[self setFileModificationDate:contextInfo];
} else { // revert
[self readModifiedFileFromDisk:contextInfo];
}
}
 
@end
 
@implementation NSDocument (BDocumentAdditions)
 
- (void)checkForModificationOfFileOnDisk {
if ([self respondsToSelector:@selector(fileWasModifiedExternallyByAnotherApplication:)]) {
NSDate *knownFileModificationDate = [self fileModificationDate];
if (knownFileModificationDate) {
NSDate *actualFileModificationDate = [[[NSFileManager defaultManager] fileAttributesAtPath:[[self fileURL] path] traverseLink:YES] fileModificationDate];
if ([knownFileModificationDate isLessThan:actualFileModificationDate]) {
[self performSelector:@selector(fileWasModifiedExternallyByAnotherApplication:) withObject:actualFileModificationDate];
}
}
}
}
 
@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";