public
Description:
Homepage:
Clone URL: git://github.com/jessegrosjean/bdocuments.git
bdocuments / BDocumentController.m
100644 416 lines (334 sloc) 15.369 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
//
// BDocumentController.m
// BDocuments
//
// Created by Jesse Grosjean on 9/7/07.
// Copyright 2007 __MyCompanyName__. All rights reserved.
//
 
#import "BDocumentController.h"
#import "BUserInterfaceController.h"
#import <objc/runtime.h>
#import "Cloud.h"
#import "BDocumentCloudDelegate.h"
 
 
@implementation BDocumentController
 
#pragma mark Class Methods
 
+ (void)initialize {
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], BDocumentsReopenLastDocumentWorkspaceKey,
[NSNumber numberWithInteger:5], BDocumentsAutosavingDelayKey,
nil]];
}
 
+ (id)sharedInstance {
    static id sharedInstance = nil;
    if (sharedInstance == nil) {
        sharedInstance = [[self alloc] init];
BLogAssert(sharedInstance == [NSDocumentController sharedDocumentController], @"BDocumentController must be set as standard document controller.");
    }
    return sharedInstance;
}
 
#pragma mark Init
 
- (id)init {
if (self = [super init]) {
[self bind:@"autosavingDelay" toObject:[NSUserDefaultsController sharedUserDefaultsController] withKeyPath:@"values.BDocumentsAutosavingDelayKey" options:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowDidBecomeMainNotification:) name:NSWindowDidBecomeMainNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowWillCloseNotification:) name:NSWindowWillCloseNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActiveNotification:) name:NSApplicationDidBecomeActiveNotification object:[NSApplication sharedApplication]];
 
}
return self;
}
 
#pragma mark Dynamic Document types
 
- (NSArray *)documentTypeDeclarations {
if (!documentTypeDeclarations) {
documentTypeDeclarations = [[NSMutableArray alloc] init];
documentTypeDeclarationsToPlugins = [[NSMutableDictionary alloc] init];
 
for (BPlugin *each in [[BExtensionRegistry sharedInstance] plugins]) {
for (NSDictionary *eachBundleDocumentType in [[[each bundle] infoDictionary] objectForKey:@"CFBundleDocumentTypes"]) {
[documentTypeDeclarations addObject:eachBundleDocumentType];
[documentTypeDeclarationsToPlugins setObject:each forKey:eachBundleDocumentType];
}
}
}
 
return documentTypeDeclarations;
}
 
- (NSArray *)documentClassNames {
NSMutableArray *documentClassNames = [[super documentClassNames] mutableCopy];
 
for (NSDictionary *each in [self documentTypeDeclarations]) {
NSString *documentClassName = [each objectForKey:@"NSDocumentClass"];
 
if (documentClassName) {
if (![documentClassNames containsObject:each]) {
[documentClassNames addObject:documentClassName];
}
} else {
BLogWarning([NSString stringWithFormat:@"Failed to find NSDocumentClass key in documentType dictionary %@", each]);
}
}
 
return documentClassNames;
}
 
- (Class)documentClassForType:(NSString *)documentTypeName {
for (NSDictionary *each in [self documentTypeDeclarations]) {
NSString *eachDocumentTypeName = [each objectForKey:@"CFBundleTypeName"];
 
if (eachDocumentTypeName) {
if ([eachDocumentTypeName isEqualToString:documentTypeName]) {
BPlugin *plugin = [documentTypeDeclarationsToPlugins objectForKey:each];
Class pluginDocumentClass = [plugin classNamed:[each objectForKey:@"NSDocumentClass"]];
 
if (pluginDocumentClass) {
Class defaultDocumentClass = [super documentClassForType:documentTypeName];
 
if (!defaultDocumentClass) {
return pluginDocumentClass;
} else if (pluginDocumentClass != defaultDocumentClass) {
BLogInfo([NSString stringWithFormat:@"Main bundle plist and plugin declare difference document classes for the same document type %@, will use class declared in main bundle plist", documentTypeName]);
return defaultDocumentClass;
}
}
}
} else {
BLogWarning([NSString stringWithFormat:@"Failed to find CFBundleTypeName key in documentType dictionary %@", each]);
}
}
 
return [super documentClassForType:documentTypeName];
}
 
- (NSString *)defaultType {
NSString *documentTypeName = [super defaultType];
 
for (BConfigurationElement *each in [[BExtensionRegistry sharedInstance] configurationElementsFor:@"com.blocks.BDocuments.documentControllerDelegate"]) {
id <BDocumentControllerDelegate> documentControllerDelegate = [each createExecutableExtensionFromAttribute:@"class" conformingToClass:nil conformingToProtocol:@protocol(BDocumentControllerDelegate) respondingToSelectors:nil];
NSString *overrideDocumentTypeName = [documentControllerDelegate defaultType];
if (overrideDocumentTypeName) {
return overrideDocumentTypeName;
}
}
 
if (documentTypeName == nil || [documentTypeName isEqualToString:@"WildcardDocumentType"]) {
for (NSDictionary *each in [self documentTypeDeclarations]) {
NSString *eachDocumentTypeName = [each objectForKey:@"CFBundleTypeName"];
if (eachDocumentTypeName) {
return eachDocumentTypeName;
}
}
}
 
return documentTypeName;
}
 
 
- (NSString *)displayNameForType:(NSString *)documentTypeName {
NSString *displayNameForType = [super displayNameForType:documentTypeName];
 
if ([displayNameForType isEqualToString:documentTypeName]) {
for (NSDictionary *each in [self documentTypeDeclarations]) {
NSString *eachDocumentTypeName = [each objectForKey:@"CFBundleTypeName"];
if (eachDocumentTypeName) {
if ([eachDocumentTypeName isEqualToString:documentTypeName]) {
NSString *typeName = [each objectForKey:@"NSTypeName"];
if (typeName) {
return typeName;
}
}
}
}
}
 
return displayNameForType;
}
 
- (NSArray *)fileExtensionsFromType:(NSString *)documentTypeName {
NSMutableArray *fileExtensionsFromType = [[super fileExtensionsFromType:documentTypeName] mutableCopy];
 
for (NSDictionary *each in [self documentTypeDeclarations]) {
NSString *eachDocumentTypeName = [each objectForKey:@"CFBundleTypeName"];
 
if (eachDocumentTypeName) {
if ([eachDocumentTypeName isEqualToString:documentTypeName]) {
NSMutableArray *fileExtensions = [[each objectForKey:@"CFBundleTypeExtensions"] mutableCopy];
if (fileExtensions) {
[fileExtensions removeObjectsInArray:fileExtensionsFromType];
[fileExtensionsFromType addObjectsFromArray:fileExtensions];
}
}
}
}
 
return fileExtensionsFromType;
}
 
- (NSString *)typeFromFileExtension:(NSString *)fileExtensionOrHFSFileType {
NSString *documentTypeName = [super typeFromFileExtension:fileExtensionOrHFSFileType];
 
if (!documentTypeName || [documentTypeName isEqualToString:@"WildcardDocumentType"]) {
for (NSDictionary *each in [self documentTypeDeclarations]) {
NSString *eachDocumentTypeName = [each objectForKey:@"CFBundleTypeName"];
 
if (eachDocumentTypeName) {
NSArray *typeExtensions = [each objectForKey:@"CFBundleTypeExtensions"];
if ([typeExtensions containsObject:fileExtensionOrHFSFileType]) {
return eachDocumentTypeName;
}
}
}
}
 
return documentTypeName;
}
 
#pragma mark Notifications
 
- (void)windowDidBecomeMainNotification:(NSNotification *)notification {
NSWindow *window = [notification object];
NSWindowController *windowController = [window windowController];
NSDocument *document = [windowController document];
 
if (document) {
[NSApp setValue:document forKey:@"currentDocument"];
[NSApp setValue:windowController forKey:@"currentDocumentWindowController"];
[document checkForModificationOfFileOnDisk];
}
}
 
- (void)windowWillCloseNotification:(NSNotification *)notification {
NSWindow *window = [notification object];
 
if (window == [[NSApp currentDocumentWindowController] window]) {
[NSApp setValue:nil forKey:@"currentDocumentWindowController"];
[NSApp setValue:nil forKey:@"currentDocument"];
}
}
 
- (void)applicationDidBecomeActiveNotification:(NSNotification *)notification {
[[NSApp currentDocument] checkForModificationOfFileOnDisk];
}
 
#pragma mark Lifecycle Callback
 
- (void)applicationLaunching {
}
 
- (void)applicationDidFinishLaunching {
[[NSMenu menuForMenuExtensionPoint:@"com.blocks.BUserInterface.menus.main.file.openRecent"] setDelegate:self];
}
 
- (void)menuNeedsUpdate:(NSMenu *)menu {
for (NSMenuItem *each in [menu itemArray]) {
[menu removeItem:each];
}
 
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
 
for (NSURL *each in [self recentDocumentURLs]) {
NSString *path = [each path];
NSString *title = nil;
 
// if ([BCloudDocumentsService isCloudDocumentURL:each]) {
// title = [[BCloudDocumentsService displayNameForCloudDocument:each] stringByAppendingFormat:@"—%@", [[BCloudDocumentsService sharedInstance] serviceLabel]];
// } else {
title = [path lastPathComponent];
// }
NSMenuItem *eachMenuItem = [[NSMenuItem alloc] initWithTitle:title action:@selector(openRecentDocument:) keyEquivalent:@""];
[eachMenuItem setRepresentedObject:each];
NSImage *icon = [workspace iconForFile:path];
[icon setSize:NSMakeSize(16, 16)];
[eachMenuItem setImage:icon];
[menu addItem:eachMenuItem];
}
 
if ([menu numberOfItems] > 0) {
[menu addItem:[NSMenuItem separatorItem]];
}
 
[menu addItemWithTitle:BLocalizedString(@"Clear Menu", nil) action:@selector(clearRecentDocuments:) keyEquivalent:@""];
}
 
- (void)openRecentDocument:(NSMenuItem *)aMenuItem {
NSError *error = nil;
if (![self openDocumentWithContentsOfURL:[aMenuItem representedObject] display:YES error:&error]) {
if (error) {
[self presentError:error];
} else {
NSBeep();
}
}
}
 
- (void)applicationMayTerminateNotification {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
 
applicationMayBeTerminating = YES;
 
BOOL automaticallySaveDocumentsWhenQuiting = [defaults boolForKey:BAutomaticallySaveDocumentsWhenQuiting];
 
for (BDocument *each in [self documents]) {
if ([each fileURL]) {
if (automaticallySaveDocumentsWhenQuiting) [each saveDocument:nil];
[BDocument storeDocumentUserDefaults:[each documentUserDefaults] forDocumentURL:[each fileURL]];
}
}
 
if ([[self documents] count] > 0) {
[defaults setObject:[NSArray array] forKey:BDocumentsLastDocumentWorkspaceKey];
}
}
 
- (void)applicationCancledTerminateNotification {
if ([[self documents] count] > 0) {
[[NSUserDefaults standardUserDefaults] setObject:[NSArray array] forKey:BDocumentsLastDocumentWorkspaceKey];
}
applicationMayBeTerminating = NO;
}
 
- (void)applicationWillTerminate {
[BDocument synchronizeDocumentUserDefaultsRepository];
}
 
#pragma mark Sync
 
- (IBAction)sync:(id)sender {
[[Cloud sharedInstance] beginSync:sender];
}
 
#pragma mark Loading Document Workspace
 
- (void)removeRecentDocumentURL:(NSURL *)removedURL {
NSArray *recentDocumentURLs = [self recentDocumentURLs];
[self clearRecentDocuments:nil];
for (NSURL *each in recentDocumentURLs) {
if (![each isEqual:removedURL]) {
[self noteNewRecentDocumentURL:each];
}
}
}
 
- (void)addDocument:(NSDocument *)document {
[super addDocument:document];
[[NSNotificationCenter defaultCenter] postNotificationName:BDocumentControllerDocumentAddedNotification object:self userInfo:[NSDictionary dictionaryWithObject:document forKey:@"document"]];
}
 
- (void)removeDocument:(NSDocument *)document {
if (applicationMayBeTerminating || [[self documents] count] == 1) {
NSString *path = [[document fileURL] path];
if (path) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[[defaults valueForKey:BDocumentsLastDocumentWorkspaceKey] arrayByAddingObject:path] forKey:BDocumentsLastDocumentWorkspaceKey];
if ([[self documents] count] == 1) {
[defaults synchronize];
}
}
}
[super removeDocument:document];
[[NSNotificationCenter defaultCenter] postNotificationName:BDocumentControllerDocumentRemovedNotification object:self userInfo:[NSDictionary dictionaryWithObject:document forKey:@"document"]];
}
 
- (void)openLastDocumentWorkspace {
NSError *error = nil;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSFileManager *fileManager = [NSFileManager defaultManager];
 
if ([userDefaults boolForKey:BDocumentsReopenLastDocumentWorkspaceKey]) {
for (NSString *each in [userDefaults objectForKey:BDocumentsLastDocumentWorkspaceKey]) {
if ([fileManager fileExistsAtPath:each]) {
if (![self openDocumentWithContentsOfURL:[NSURL fileURLWithPath:each] display:YES error:&error]) {
[self presentError:error];
}
}
}
 
if ([[self documents] count] == 0) {
NSURL *lastDocumentURL = [[self recentDocumentURLs] lastObject];
if ([fileManager fileExistsAtPath:[lastDocumentURL path]]) {
if (![self openDocumentWithContentsOfURL:lastDocumentURL display:YES error:&error]) {
[self presentError:error];
}
}
}
}
 
[[NSUserDefaults standardUserDefaults] setObject:[NSArray array] forKey:BDocumentsLastDocumentWorkspaceKey];
}
 
- (BOOL)applicationShouldOpenUntitledFile:(NSApplication *)sender {
[self openLastDocumentWorkspace];
 
if ([[self documents] count] == 0) {
return YES;
}
 
return NO;
}
 
@end
 
@implementation NSApplication (BDocumentControllerMethodReplacements)
 
+ (void)load {
    if (self == [NSApplication class]) {
[self replaceMethod:@selector(_handleAEOpen:) withMethod:@selector(BDocumentController_handleAEOpen:)];
[self replaceMethod:@selector(_handleAEQuitWithActivating:documentSaving:) withMethod:@selector(BDocumentController_handleAEQuitWithActivating:documentSaving:)];
    }
}
 
- (void)BDocumentController_handleAEOpen:(NSAppleEventDescriptor *)event {
NSParameterAssert(_cmd == @selector(_handleAEOpen:));
[self BDocumentController_handleAEOpen:event];
 
// Normally applications are not asked to applicationShouldOpenUntitledFile when opened as a login item. But if there is a saved
// workspace we want to open that. So here were are checking for keyAELaunchedAsLogInItem and if found give the (our subclass)
// document controller the chance to open last workspace.
NSAppleEventDescriptor *currentEvent = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
if ([[[NSDocumentController sharedDocumentController] documents] count] == 0 && [[currentEvent paramDescriptorForKeyword:keyAEPropData] typeCodeValue] == keyAELaunchedAsLogInItem) {
[[NSDocumentController sharedDocumentController] openLastDocumentWorkspace];
}
}
 
- (short)BDocumentController_handleAEQuitWithActivating:(BOOL)fp8 documentSaving:(unsigned int)fp12 {
// Hack, goal is to call applicationMayTerminateNotification when application starts to quit. Normally this can be done by overriding
// [App terminate:], but that doesn't seem to get called when app is quit via applescript, so in that case we need to use this method.
NSParameterAssert(_cmd == @selector(_handleAEQuitWithActivating:documentSaving:));
[[BDocumentController sharedInstance] applicationMayTerminateNotification];
return [self BDocumentController_handleAEQuitWithActivating:fp8 documentSaving:fp12];
}
 
@end
 
NSString *BDocumentsAutosavingDelayKey = @"BDocumentsAutosavingDelayKey";
NSString *BDocumentsLastDocumentWorkspaceKey = @"BDocumentsLastDocumentWorkspaceKey";
NSString *BDocumentsReopenLastDocumentWorkspaceKey = @"BDocumentsReopenLastDocumentWorkspaceKey";
NSString *BAutomaticallySaveDocumentsWhenQuiting = @"BAutomaticallySaveDocumentsWhenQuiting";