/
DocumentWindowController.mm
2873 lines (2436 loc) · 103 KB
/
DocumentWindowController.mm
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "DocumentWindowController.h"
#import "ProjectLayoutView.h"
#import "SelectGrammarViewController.h"
#import "OakRunCommandWindowController.h"
#import <document/OakDocument.h>
#import <document/OakDocumentController.h>
#import <OakAppKit/NSAlert Additions.h>
#import <OakAppKit/NSMenuItem Additions.h>
#import <OakAppKit/OakAppKit.h>
#import <OakAppKit/OakFileIconImage.h>
#import <OakAppKit/OakFileManager.h>
#import <OakAppKit/OakPasteboard.h>
#import <OakAppKit/OakSavePanel.h>
#import <MenuBuilder/MenuBuilder.h>
#import <OakTabBarView/OakTabBarView.h>
#import <OakFoundation/NSString Additions.h>
#import <Preferences/Keys.h>
#import <OakTextView/OakDocumentView.h>
#import <OakFileBrowser/OakFileBrowser.h>
#import <OakCommand/OakCommand.h>
#import <HTMLOutputWindow/HTMLOutputWindow.h>
#import <OakFilterList/FileChooser.h>
#import <OakSystem/application.h>
#import <Find/Find.h>
#import <BundlesManager/BundlesManager.h>
#import <BundleEditor/BundleEditor.h>
#import <network/network.h>
#import <file/path_info.h>
#import <io/entries.h>
#import <scm/scm.h>
#import <text/parse.h>
#import <text/tokenize.h>
#import <text/utf8.h>
#import <regexp/glob.h>
#import <settings/settings.h>
#import <ns/ns.h>
#import <kvdb/kvdb.h>
#import <crash/info.h>
#import <license/LicenseManager.h>
static NSString* const kUserDefaultsAlwaysFindInDocument = @"alwaysFindInDocument";
static NSString* const kUserDefaultsDisableFolderStateRestore = @"disableFolderStateRestore";
static NSString* const kUserDefaultsHideStatusBarKey = @"hideStatusBar";
static NSString* const kUserDefaultsDisableBundleSuggestionsKey = @"disableBundleSuggestions";
static NSString* const kUserDefaultsGrammarsToNeverSuggestKey = @"grammarsToNeverSuggest";
static void show_command_error (std::string const& message, oak::uuid_t const& uuid, NSWindow* window = nil, std::string commandName = NULL_STR)
{
bundles::item_ptr bundleItem = bundles::lookup(uuid);
if(commandName == NULL_STR)
commandName = bundleItem ? bundleItem->name() : "(unknown)";
NSAlert* alert = [[NSAlert alloc] init];
[alert setAlertStyle:NSAlertStyleCritical];
[alert setMessageText:[NSString stringWithCxxString:text::format("Failure running “%.*s”.", (int)commandName.size(), commandName.data())]];
[alert setInformativeText:[NSString stringWithCxxString:message] ?: @"No output"];
[alert addButtonWithTitle:@"OK"];
if(bundleItem)
[alert addButtonWithTitle:@"Edit Command"];
[alert beginSheetModalForWindow:window completionHandler:^(NSInteger button){
if(button == NSAlertSecondButtonReturn)
[[BundleEditor sharedInstance] revealBundleItem:bundleItem];
}];
}
@interface QuickLookNSURLWrapper : NSObject <QLPreviewItem>
@property (nonatomic) NSURL* url;
@end
@implementation QuickLookNSURLWrapper
- (id)initWithURL:(NSURL*)aURL
{
if((self = [super init]))
self.url = aURL;
return self;
}
- (NSURL*)previewItemURL
{
return self.url;
}
@end
@interface DocumentWindowController () <NSWindowDelegate, NSTouchBarDelegate, OakTabBarViewDelegate, OakTabBarViewDataSource, OakTextViewDelegate, OakFileBrowserDelegate, QLPreviewPanelDelegate, QLPreviewPanelDataSource>
{
OBJC_WATCH_LEAKS(DocumentWindowController);
NSMutableSet<NSUUID*>* _stickyDocumentIdentifiers;
scm::info_ptr _projectSCMInfo;
std::map<std::string, std::string> _projectSCMVariables;
std::vector<std::string> _projectScopeAttributes; // kSettingsScopeAttributesKey
std::vector<std::string> _externalScopeAttributes; // attr.scm.git, attr.project.ninja
scm::info_ptr _documentSCMInfo;
std::map<std::string, std::string> _documentSCMVariables;
std::vector<std::string> _documentScopeAttributes; // attr.os-version, attr.untitled / attr.rev-path + kSettingsScopeAttributesKey
}
@property (nonatomic) ProjectLayoutView* layoutView;
@property (nonatomic) OakTabBarView* tabBarView;
@property (nonatomic) OakDocumentView* documentView;
@property (nonatomic) OakTextView* textView;
@property (nonatomic) OakFileBrowser* fileBrowser;
@property (nonatomic) BOOL disableFileBrowserWindowResize;
@property (nonatomic) BOOL autoRevealFile;
@property (nonatomic) NSRect oldWindowFrame;
@property (nonatomic) NSRect newWindowFrame;
@property (nonatomic) HTMLOutputWindowController* htmlOutputWindowController;
@property (nonatomic) OakHTMLOutputView* htmlOutputView;
@property (nonatomic) BOOL htmlOutputInWindow;
@property (nonatomic) NSSegmentedControl* previousNextTouchBarControl;
@property (nonatomic) NSString* projectPath;
@property (nonatomic) NSString* documentPath;
@property (nonatomic) NSArray* urlArrayForQuickLook;
@property (nonatomic) NSArray<Bundle*>* bundlesAlreadySuggested;
@property (nonatomic, readwrite) OakDocument* selectedDocument;
@property (nonatomic) NSArrayController* arrayController;
+ (void)scheduleSessionBackup:(id)sender;
- (void)makeTextViewFirstResponder:(id)sender;
- (void)updateFileBrowserStatus:(id)sender;
- (void)fileBrowser:(OakFileBrowser*)aFileBrowser openURLs:(NSArray*)someURLs;
- (void)fileBrowser:(OakFileBrowser*)aFileBrowser closeURL:(NSURL*)anURL;
- (void)takeNewTabIndexFrom:(id)sender; // used by newDocumentInTab:
- (void)takeTabsToTearOffFrom:(id)sender; // used by moveDocumentToNewWindow:
@end
namespace
{
// ==========================================
// = tracking document controller instances =
// ==========================================
static NSMutableDictionary<NSUUID*, DocumentWindowController*>* AllControllers ()
{
static NSMutableDictionary* res = [NSMutableDictionary new];
return res;
}
static NSArray<DocumentWindowController*>* SortedControllers ()
{
NSMutableArray* res = [NSMutableArray array];
for(NSNumber* flag in @[ @NO, @YES ])
{
for(NSWindow* window in [NSApp orderedWindows])
{
if([window isMiniaturized] == [flag boolValue] && [window.delegate respondsToSelector:@selector(identifier)])
{
DocumentWindowController* delegate = (DocumentWindowController*)window.delegate;
if(id controller = AllControllers()[delegate.identifier])
[res addObject:controller];
}
}
}
return res;
}
// ======================
// = document_t helpers =
// ======================
static bool is_disposable (OakDocument* doc)
{
return doc && !doc.isDocumentEdited && !doc.isOnDisk && !doc.path && doc.isLoaded && doc.isBufferEmpty;
}
}
static NSArray* const kObservedKeyPaths = @[ @"arrayController.arrangedObjects.path", @"arrayController.arrangedObjects.displayName", @"arrayController.arrangedObjects.documentEdited", @"selectedDocument.path", @"selectedDocument.displayName", @"selectedDocument.icon", @"selectedDocument.onDisk" , @"selectedDocument.documentEdited" ];
@implementation DocumentWindowController
+ (KVDB*)sharedProjectStateDB
{
NSString* appSupport = [[NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"TextMate"];
return [KVDB sharedDBUsingFile:@"RecentProjects.db" inDirectory:appSupport];
}
- (id)init
{
if((self = [super init]))
{
self.identifier = [NSUUID UUID];
self.tabBarView = [[OakTabBarView alloc] initWithFrame:NSZeroRect];
self.tabBarView.dataSource = self;
self.tabBarView.delegate = self;
self.documentView = [[OakDocumentView alloc] init];
self.textView = self.documentView.textView;
self.textView.delegate = self;
self.layoutView = [[ProjectLayoutView alloc] initWithFrame:NSZeroRect];
self.layoutView.tabBarView = self.tabBarView;
self.layoutView.documentView = self.documentView;
NSUInteger windowStyle = (NSWindowStyleMaskTitled|NSWindowStyleMaskClosable|NSWindowStyleMaskResizable|NSWindowStyleMaskMiniaturizable|NSWindowStyleMaskTexturedBackground);
self.window = [[NSWindow alloc] initWithContentRect:[NSWindow contentRectForFrameRect:[self frameRectForNewWindow] styleMask:windowStyle] styleMask:windowStyle backing:NSBackingStoreBuffered defer:NO];
self.window.collectionBehavior = NSWindowCollectionBehaviorFullScreenPrimary;
self.window.delegate = self;
self.window.releasedWhenClosed = NO;
[self.window setContentBorderThickness:0 forEdge:NSMaxYEdge]; // top border
[self.window setContentBorderThickness:0 forEdge:NSMinYEdge]; // bottom border
[self.window setAutorecalculatesContentBorderThickness:NO forEdge:NSMaxYEdge];
[self.window setAutorecalculatesContentBorderThickness:NO forEdge:NSMinYEdge];
[LicenseManager.sharedInstance decorateWindow:self.window];
OakAddAutoLayoutViewsToSuperview(@[ self.layoutView ], self.window.contentView);
OakSetupKeyViewLoop(@[ self.layoutView ], NO);
self.window.initialFirstResponder = self.textView;
[self.window.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|" options:0 metrics:nil views:@{ @"view" : self.layoutView }]];
[self.window.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:@{ @"view" : self.layoutView }]];
_arrayController = [[NSArrayController alloc] init];
[_arrayController bind:NSContentBinding toObject:self withKeyPath:@"documents" options:nil];
for(NSString* keyPath in kObservedKeyPaths)
[self addObserver:self forKeyPath:keyPath options:NSKeyValueObservingOptionInitial context:nullptr];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDefaultsDidChange:) name:NSUserDefaultsDidChangeNotification object:[NSUserDefaults standardUserDefaults]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActiveNotification:) name:NSApplicationDidBecomeActiveNotification object:NSApp];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidResignActiveNotification:) name:NSApplicationDidResignActiveNotification object:NSApp];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fileManagerWillDeleteItemAtPath:) name:OakFileManagerWillDeleteItemAtPath object:nil];
[self userDefaultsDidChange:nil];
}
return self;
}
- (void)dealloc
{
for(NSString* keyPath in kObservedKeyPaths)
[self removeObserver:self forKeyPath:keyPath];
[[NSNotificationCenter defaultCenter] removeObserver:self];
self.window.delegate = nil;
self.tabBarView.dataSource = nil;
self.tabBarView.delegate = nil;
self.textView.delegate = nil;
// When option-clicking to close all windows then
// messages are sent to our window after windowWillClose:
__autoreleasing __attribute__ ((unused)) NSWindow* delayRelease = self.window;
}
// ======================================
// = Find suitable frame for new window =
// ======================================
- (NSRect)windowFrame
{
NSRect res = [self.window frame];
if(self.fileBrowserVisible && !self.disableFileBrowserWindowResize)
res.size.width -= self.fileBrowserWidth;
return res;
}
- (NSRect)cascadedWindowFrame
{
NSRect r = [self windowFrame];
return { { NSMinX(r) + 21, NSMinY(r) - 23 }, r.size };
}
- (NSRect)frameRectForNewWindow
{
std::map<CGFloat, NSWindow*> ourWindows;
for(NSWindow* win in [NSApp windows])
{
if([win isVisible] && [win isOnActiveSpace] && ![win isZoomed] && (([win styleMask] & NSWindowStyleMaskFullScreen)) != NSWindowStyleMaskFullScreen && [[win delegate] isKindOfClass:[self class]])
ourWindows.emplace(NSMaxY([win frame]), win);
}
if(!ourWindows.empty())
{
NSRect r = [(DocumentWindowController*)ourWindows.begin()->second.delegate cascadedWindowFrame];
NSRect scrRect = [[NSScreen mainScreen] visibleFrame];
if(NSContainsRect(scrRect, r))
return r;
r.origin.x = 61;
r.origin.y = NSMaxY(scrRect) - NSHeight(r);
BOOL alreadyHasWrappedWindow = NO;
for(auto pair : ourWindows)
{
if(NSEqualPoints([pair.second frame].origin, r.origin))
alreadyHasWrappedWindow = YES;
}
if(alreadyHasWrappedWindow)
{
NSWindow* mainWindow = [NSApp mainWindow];
if([[mainWindow delegate] isKindOfClass:[self class]])
r = [(DocumentWindowController*)mainWindow.delegate cascadedWindowFrame];
}
return r;
}
if(NSString* rectStr = [[NSUserDefaults standardUserDefaults] stringForKey:@"DocumentControllerWindowFrame"])
return NSRectFromString(rectStr);
NSRect r = [[NSScreen mainScreen] visibleFrame];
return r = NSIntegralRect(NSInsetRect(r, NSWidth(r) / 3, NSHeight(r) / 5));
}
// =========================
- (void)windowWillClose:(NSNotification*)aNotification
{
if((([self.window styleMask] & NSWindowStyleMaskFullScreen) != NSWindowStyleMaskFullScreen) && !self.window.isZoomed)
[[NSUserDefaults standardUserDefaults] setObject:NSStringFromRect([self windowFrame]) forKey:@"DocumentControllerWindowFrame"];
[_arrayController unbind:NSContentBinding];
self.documents = nil;
self.selectedDocument = nil;
self.fileBrowserVisible = NO; // Make window frame small as we no longer respond to savableWindowFrame
self.identifier = nil; // This removes us from AllControllers and causes a release
}
- (void)showWindow:(id)sender
{
if(_documents.count == 0)
{
OakDocument* defaultDocument = [OakDocumentController.sharedInstance untitledDocument];
self.documents = @[ defaultDocument ];
[self openAndSelectDocument:defaultDocument];
}
[self.window makeKeyAndOrderFront:sender];
}
- (void)makeTextViewFirstResponder:(id)sender { [self.window makeFirstResponder:self.textView]; }
- (void)close { [self.window close]; }
- (IBAction)moveFocus:(id)sender
{
if([self.window firstResponder] == self.textView)
{
self.fileBrowserVisible = YES;
NSOutlineView* outlineView = self.fileBrowser.outlineView;
[self.window makeFirstResponder:outlineView];
if([outlineView numberOfSelectedRows] == 0)
{
for(NSUInteger row = 0; row < [outlineView numberOfRows]; ++row)
{
if([[outlineView delegate] respondsToSelector:@selector(outlineView:isGroupItem:)] && [[outlineView delegate] outlineView:outlineView isGroupItem:[outlineView itemAtRow:row]])
continue;
[outlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
break;
}
}
}
else
{
[self makeTextViewFirstResponder:sender];
}
}
// ==========================
// = Notification Callbacks =
// ==========================
- (void)userDefaultsDidChange:(NSNotification*)aNotification
{
self.htmlOutputInWindow = [[[NSUserDefaults standardUserDefaults] stringForKey:kUserDefaultsHTMLOutputPlacementKey] isEqualToString:@"window"];
self.disableFileBrowserWindowResize = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableFileBrowserWindowResizeKey];
self.autoRevealFile = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsAutoRevealFileKey];
self.documentView.hideStatusBar = [[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsHideStatusBarKey];
if(self.layoutView.fileBrowserOnRight != [[[NSUserDefaults standardUserDefaults] stringForKey:kUserDefaultsFileBrowserPlacementKey] isEqualToString:@"right"])
{
self.oldWindowFrame = self.newWindowFrame = NSZeroRect;
self.layoutView.fileBrowserOnRight = !self.layoutView.fileBrowserOnRight;
}
}
- (void)applicationDidBecomeActiveNotification:(NSNotification*)aNotification
{
if(_documents.count)
[self.textView performSelector:@selector(applicationDidBecomeActiveNotification:) withObject:aNotification];
}
- (void)applicationDidResignActiveNotification:(NSNotification*)aNotification
{
static BOOL IsSaving = NO;
if(std::exchange(IsSaving, YES))
return;
NSMutableArray* documentsToSave = [NSMutableArray array];
for(OakDocument* doc in _documents)
{
if(doc.isDocumentEdited && doc.path)
{
settings_t const settings = settings_for_path(to_s(doc.virtualPath ?: doc.path), to_s(doc.fileType), path::parent(to_s(doc.path)));
if(settings.get(kSettingsSaveOnBlurKey, false))
{
if([doc isEqual:self.selectedDocument])
[_textView updateDocumentMetadata];
[documentsToSave addObject:doc];
}
}
}
[self saveDocumentsUsingEnumerator:[documentsToSave objectEnumerator] completionHandler:^(OakDocumentIOResult result){
if(_documents.count)
[self.textView performSelector:@selector(applicationDidResignActiveNotification:) withObject:aNotification];
IsSaving = NO;
}];
}
// =================
// = Close Methods =
// =================
+ (NSAlert*)saveAlertForDocuments:(NSArray<OakDocument*>*)someDocuments
{
NSAlert* alert = [[NSAlert alloc] init];
[alert setAlertStyle:NSAlertStyleWarning];
if(someDocuments.count == 1)
{
OakDocument* document = someDocuments.firstObject;
[alert setMessageText:[NSString stringWithFormat:@"Do you want to save the changes you made in the document “%@”?", document.displayName]];
[alert setInformativeText:@"Your changes will be lost if you don’t save them."];
[alert addButtons:@"Save", @"Cancel", @"Don’t Save", nil];
}
else
{
NSString* body = @"";
for(OakDocument* document in someDocuments)
body = [body stringByAppendingFormat:@"• “%@”\n", document.displayName];
[alert setMessageText:@"Do you want to save documents with changes?"];
[alert setInformativeText:body];
[alert addButtons:@"Save All", @"Cancel", @"Don’t Save", nil];
}
return alert;
}
- (void)showCloseWarningUIForDocuments:(NSArray<OakDocument*>*)someDocuments completionHandler:(void(^)(BOOL canClose))callback
{
if(someDocuments.count == 0)
return callback(YES);
if(someDocuments.count == 1)
{
OakDocument* doc = someDocuments.firstObject;
if(![doc isEqual:self.selectedDocument])
{
self.selectedTabIndex = [self.documents indexOfObject:doc];
[self openAndSelectDocument:doc];
}
}
NSAlert* alert = [DocumentWindowController saveAlertForDocuments:someDocuments];
[alert beginSheetModalForWindow:self.window completionHandler:^(NSInteger returnCode){
switch(returnCode)
{
case NSAlertFirstButtonReturn: /* "Save" */
{
[self saveDocumentsUsingEnumerator:[someDocuments objectEnumerator] completionHandler:^(OakDocumentIOResult result){
callback(result == OakDocumentIOResultSuccess);
}];
}
break;
case NSAlertSecondButtonReturn: /* "Cancel" */
{
callback(NO);
}
break;
case NSAlertThirdButtonReturn: /* "Don't Save" */
{
callback(YES);
}
break;
}
}];
}
- (void)closeTabsAtIndexes:(NSIndexSet*)anIndexSet askToSaveChanges:(BOOL)askToSaveFlag createDocumentIfEmpty:(BOOL)createIfEmptyFlag
{
NSArray<OakDocument*>* documentsToClose = [_documents objectsAtIndexes:anIndexSet];
if(documentsToClose.count == 0)
return;
if(askToSaveFlag)
{
NSArray<OakDocument*>* documentsToSave = [documentsToClose filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isDocumentEdited == YES"]];
if(documentsToSave.count)
{
[self showCloseWarningUIForDocuments:documentsToSave completionHandler:^(BOOL canClose){
if(canClose)
{
[self closeTabsAtIndexes:anIndexSet askToSaveChanges:NO createDocumentIfEmpty:createIfEmptyFlag];
}
else
{
NSIndexSet* newIndexes = [_documents indexesOfObjectsAtIndexes:anIndexSet options:0 passingTest:^BOOL(OakDocument* doc, NSUInteger idx, BOOL* stop){
return doc.isDocumentEdited == NO;
}];
[self closeTabsAtIndexes:newIndexes askToSaveChanges:YES createDocumentIfEmpty:createIfEmptyFlag];
}
}];
return;
}
}
NSSet<NSUUID*>* uuids = [NSSet setWithArray:[documentsToClose valueForKey:@"identifier"]];
NSUUID* selectedUUID = _documents[_selectedTabIndex].identifier;
NSMutableArray<OakDocument*>* newDocuments = [NSMutableArray array];
NSUInteger newSelectedTabIndex = _selectedTabIndex;
for(OakDocument* document in _documents)
{
if(![uuids containsObject:document.identifier])
[newDocuments addObject:document];
if([selectedUUID isEqual:document.identifier])
newSelectedTabIndex = MAX(newDocuments.count, 1) - 1;
}
if(createIfEmptyFlag && newDocuments.count == 0)
[newDocuments addObject:[OakDocumentController.sharedInstance untitledDocument]];
self.documents = newDocuments;
self.selectedTabIndex = newSelectedTabIndex;
if(newDocuments.count && ![newDocuments[newSelectedTabIndex].identifier isEqual:selectedUUID])
[self openAndSelectDocument:newDocuments[newSelectedTabIndex]];
}
- (IBAction)performCloseTab:(id)sender
{
NSUInteger index = [sender isKindOfClass:[OakTabBarView class]] ? [sender tag] : _selectedTabIndex;
if(index == NSNotFound || _documents.count == 0 || _documents.count == 1 && (is_disposable(self.selectedDocument) || !self.fileBrowserVisible))
return [self performCloseWindow:sender];
[self closeTabsAtIndexes:[NSIndexSet indexSetWithIndex:index] askToSaveChanges:YES createDocumentIfEmpty:YES];
}
- (IBAction)performCloseSplit:(id)sender
{
ASSERT(sender == self.layoutView.htmlOutputView);
self.htmlOutputVisible = NO;
}
- (IBAction)performCloseWindow:(id)sender
{
[self.window performClose:self];
}
- (IBAction)performCloseAllTabs:(id)sender
{
NSIndexSet* allTabs = [_documents indexesOfObjectsPassingTest:^BOOL(OakDocument* doc, NSUInteger idx, BOOL* stop){
return [self isDocumentSticky:doc] == NO && (doc.isDocumentEdited == NO || doc.path);
}];
[self closeTabsAtIndexes:allTabs askToSaveChanges:YES createDocumentIfEmpty:YES];
}
- (IBAction)performCloseOtherTabsXYZ:(id)sender
{
NSMutableIndexSet* otherTabs = [[_documents indexesOfObjectsPassingTest:^BOOL(OakDocument* doc, NSUInteger idx, BOOL* stop){
return [self isDocumentSticky:doc] == NO && (doc.isDocumentEdited == NO || doc.path);
}] mutableCopy];
NSUInteger tabIndex = [sender isKindOfClass:[OakTabBarView class]] ? [sender tag] : _selectedTabIndex;
[otherTabs removeIndex:tabIndex];
[self closeTabsAtIndexes:otherTabs askToSaveChanges:YES createDocumentIfEmpty:YES];
}
- (IBAction)performCloseTabsToTheRight:(id)sender
{
NSUInteger from = _selectedTabIndex + 1, to = _documents.count;
if(from < to)
[self closeTabsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(from, to - from)] askToSaveChanges:YES createDocumentIfEmpty:YES];
}
- (void)saveProjectState
{
if(self.treatAsProjectWindow)
[[DocumentWindowController sharedProjectStateDB] setValue:[self sessionInfoIncludingUntitledDocuments:NO] forKey:self.projectPath];
}
- (BOOL)windowShouldClose:(id)sender
{
if(!self.htmlOutputInWindow && _htmlOutputView.isRunningCommand)
{
[_htmlOutputView stopLoadingWithUserInteraction:YES completionHandler:^(BOOL didStop){
if(didStop)
[sender performSelector:@selector(performClose:) withObject:self afterDelay:0];
}];
return NO;
}
NSArray<OakDocument*>* documentsToSave = [_documents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"isDocumentEdited == YES"]];
if(!documentsToSave.count)
{
[self saveProjectState];
return YES;
}
[self showCloseWarningUIForDocuments:documentsToSave completionHandler:^(BOOL canClose){
if(canClose)
{
[self saveProjectState];
[self.window close];
}
}];
return NO;
}
- (void)fileManagerWillDeleteItemAtPath:(NSNotification*)aNotification
{
NSDictionary* userInfo = [aNotification userInfo];
NSString* path = userInfo[OakFileManagerPathKey];
NSIndexSet* indexSet = [_documents indexesOfObjectsPassingTest:^BOOL(OakDocument* doc, NSUInteger idx, BOOL* stop){
return doc.isDocumentEdited == NO && path::is_child(to_s(doc.path), to_s(path));
}];
id oldFirstResponder = self.window.firstResponder;
[self closeTabsAtIndexes:indexSet askToSaveChanges:NO createDocumentIfEmpty:YES];
if(oldFirstResponder && oldFirstResponder != self.window.firstResponder)
[self.window makeFirstResponder:oldFirstResponder];
}
- (void)fileBrowserDidDuplicateAtURLs:(NSNotification*)aNotification
{
NSDictionary* userInfo = [aNotification userInfo];
NSDictionary* urls = userInfo[OakFileBrowserURLMapKey];
for(NSURL* url in urls)
{
if([url.path isEqualToString:self.selectedDocument.path])
[self openItems:@[ @{ @"path" : [urls[url] path] } ] closingOtherTabs:NO];
}
}
+ (void)saveSessionAndDetachBackups
{
BOOL restoresSession = ![[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableSessionRestoreKey];
[DocumentWindowController saveSessionIncludingUntitledDocuments:restoresSession];
for(DocumentWindowController* controller in [SortedControllers() reverseObjectEnumerator])
{
[controller saveProjectState];
// Ensure we do not remove backup files, as they are used to restore untitled documents
if(restoresSession)
{
for(OakDocument* document in controller.documents)
{
NSString* backupPath = document.backupPath;
document.backupPath = nil;
if(backupPath && document.path)
unlink([backupPath fileSystemRepresentation]);
}
}
}
}
- (NSArray<OakDocument*>*)documentsNeedingSaving
{
BOOL restoresSession = ![[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableSessionRestoreKey];
NSMutableArray<OakDocument*>* res = [NSMutableArray array];
for(OakDocument* doc in _documents)
{
if(doc.isDocumentEdited && (doc.path || !restoresSession))
[res addObject:doc];
}
return res.count ? res : nil;
}
+ (void)saveControllersUsingEnumerator:(NSEnumerator*)anEnumerator completionHandler:(void(^)(OakDocumentIOResult result))callback
{
if(DocumentWindowController* controller = [anEnumerator nextObject])
{
[controller saveDocumentsUsingEnumerator:[controller.documentsNeedingSaving objectEnumerator] completionHandler:^(OakDocumentIOResult result){
if(result == OakDocumentIOResultSuccess)
[self saveControllersUsingEnumerator:anEnumerator completionHandler:callback];
else if(callback)
callback(result);
}];
}
else if(callback)
{
callback(OakDocumentIOResultSuccess);
}
}
+ (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication*)sender
{
NSMutableArray<DocumentWindowController*>* controllers = [NSMutableArray array];
NSMutableArray<OakDocument*>* documents = [NSMutableArray array];
for(DocumentWindowController* controller in SortedControllers())
{
if(NSArray* newDocs = controller.documentsNeedingSaving)
{
[controllers addObject:controller];
[documents addObjectsFromArray:newDocs];
}
}
if(controllers.count == 0)
{
[self saveSessionAndDetachBackups];
return NSTerminateNow;
}
else if(controllers.count == 1)
{
DocumentWindowController* controller = controllers.firstObject;
[controller showCloseWarningUIForDocuments:controller.documentsNeedingSaving completionHandler:^(BOOL canClose){
if(canClose)
[self saveSessionAndDetachBackups];
[NSApp replyToApplicationShouldTerminate:canClose];
}];
}
else
{
switch([[DocumentWindowController saveAlertForDocuments:documents] runModal])
{
case NSAlertFirstButtonReturn: /* "Save" */
{
[self saveControllersUsingEnumerator:[controllers objectEnumerator] completionHandler:^(OakDocumentIOResult result){
if(result == OakDocumentIOResultSuccess)
[self saveSessionAndDetachBackups];
[NSApp replyToApplicationShouldTerminate:result == OakDocumentIOResultSuccess];
}];
}
break;
case NSAlertSecondButtonReturn: /* "Cancel" */
return NSTerminateCancel;
case NSAlertThirdButtonReturn: /* "Don't Save" */
return NSTerminateNow;
}
}
return NSTerminateLater;
}
// =====================
// = Document Tracking =
// =====================
- (void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)anObject change:(NSDictionary*)change context:(void*)context
{
OakDocument* document = self.selectedDocument;
if([keyPath isEqualToString:@"selectedDocument.path"] || [keyPath isEqualToString:@"selectedDocument.displayName"])
{
self.documentPath = document.virtualPath ?: document.path;
if(!self.projectPath)
self.projectPath = [document.path stringByDeletingLastPathComponent];
}
if([keyPath isEqualToString:@"selectedDocument.path"] || [keyPath isEqualToString:@"selectedDocument.displayName"])
[self updateWindowTitle];
if([keyPath isEqualToString:@"selectedDocument.documentEdited"])
self.window.documentEdited = document.isDocumentEdited;
if([keyPath isEqualToString:@"selectedDocument.onDisk"] || [keyPath isEqualToString:@"selectedDocument.path"])
self.window.representedFilename = document.isOnDisk ? document.path : @"";
if([keyPath isEqualToString:@"selectedDocument.onDisk"] || [keyPath isEqualToString:@"selectedDocument.icon"])
[self.window standardWindowButton:NSWindowDocumentIconButton].image = document.isOnDisk ? document.icon : nil;
if([keyPath hasSuffix:@"arrangedObjects.path"] || [keyPath hasSuffix:@"arrangedObjects.displayName"] || [keyPath hasSuffix:@"arrangedObjects.documentEdited"])
{
[self updateFileBrowserStatus:self];
[self.tabBarView reloadData];
[[self class] scheduleSessionBackup:self];
}
}
- (BOOL)isDocumentSticky:(OakDocument*)aDocument
{
return [_stickyDocumentIdentifiers containsObject:aDocument.identifier];
}
- (void)setDocument:(OakDocument*)aDocument sticky:(BOOL)stickyFlag
{
if(stickyFlag)
_stickyDocumentIdentifiers = _stickyDocumentIdentifiers ?: [NSMutableSet set];
if(stickyFlag)
[_stickyDocumentIdentifiers addObject:aDocument.identifier];
else [_stickyDocumentIdentifiers removeObject:aDocument.identifier];
}
// ====================
// = Create Documents =
// ====================
- (IBAction)newDocumentInTab:(id)sender
{
[self takeNewTabIndexFrom:[NSIndexSet indexSetWithIndex:_selectedTabIndex + 1]];
}
- (IBAction)newDocumentInDirectory:(id)sender
{
if(!self.fileBrowserVisible)
return;
if(NSString* folder = [self.fileBrowser directoryForNewItems])
{
std::string path = "untitled";
std::string fileType = settings_for_path(NULL_STR, "attr.untitled", to_s(folder)).get(kSettingsFileTypeKey, "text.plain");
for(auto item : bundles::query(bundles::kFieldGrammarScope, fileType))
{
std::string const& ext = item->value_for_field(bundles::kFieldGrammarExtension);
if(ext != NULL_STR)
path = "untitled." + ext;
}
NSURL* url = [NSURL fileURLWithPath:[NSString stringWithCxxString:path::unique(path::join([folder fileSystemRepresentation], path))]];
if([[OakFileManager sharedInstance] createFileAtURL:url view:self.fileBrowser.view])
{
OakDocument* doc = [OakDocumentController.sharedInstance documentWithPath:url.path];
doc.fileType = to_ns(fileType);
[self insertDocuments:@[ doc ] atIndex:_selectedTabIndex + 1 selecting:doc andClosing:self.disposableDocument ? @[ self.disposableDocument ] : nil];
// Using openAndSelectDocument: will move focus to OakTextView
[doc loadModalForWindow:nil completionHandler:^(OakDocumentIOResult result, NSString* errorMessage, oak::uuid_t const& filterUUID){
self.selectedDocument = doc;
[doc close];
}];
[self.fileBrowser editURL:url];
}
}
}
- (IBAction)moveDocumentToNewWindow:(id)sender
{
if(_documents.count > 1)
[self takeTabsToTearOffFrom:[NSIndexSet indexSetWithIndex:_selectedTabIndex]];
}
- (IBAction)mergeAllWindows:(id)sender
{
NSMutableArray<OakDocument*>* documents = [_documents mutableCopy];
for(DocumentWindowController* delegate in SortedControllers())
{
if(delegate != self && !delegate.window.isMiniaturized)
[documents addObjectsFromArray:delegate.documents];
}
self.documents = documents;
for(DocumentWindowController* delegate in SortedControllers())
{
if(delegate != self && !delegate.window.isMiniaturized)
[delegate.window close];
}
}
- (NSUUID*)disposableDocument
{
if(_selectedTabIndex < _documents.count && is_disposable(_documents[_selectedTabIndex]))
return _documents[_selectedTabIndex].identifier;
return nil;
}
- (void)insertDocuments:(NSArray<OakDocument*>*)documents atIndex:(NSInteger)index selecting:(OakDocument*)selectDocument andClosing:(NSArray<NSUUID*>*)closeDocuments
{
NSSet<NSUUID*>* newUUIDs = [NSSet setWithArray:[documents valueForKey:@"identifier"]];
NSMutableSet<NSUUID*>* oldUUIDs = [NSMutableSet setWithArray:[self.documents valueForKey:@"identifier"]];
[oldUUIDs minusSet:[NSSet setWithArray:closeDocuments]];
BOOL shouldReorder = ![[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableTabReorderingKey];
NSMutableArray<OakDocument*>* newDocuments = [NSMutableArray array];
for(NSUInteger i = 0; i <= _documents.count; ++i)
{
if(i == MIN(index, _documents.count))
{
NSMutableSet<NSUUID*>* didInsert = [NSMutableSet set];
for(NSUInteger j = 0; j < documents.count; ++j)
{
if(![didInsert containsObject:documents[j].identifier] && (shouldReorder || ![oldUUIDs containsObject:documents[j].identifier]))
{
[newDocuments addObject:documents[j]];
[didInsert addObject:documents[j].identifier];
}
}
}
if(i == _documents.count)
break;
else if(shouldReorder && [newUUIDs containsObject:_documents[i].identifier])
continue;
else if([closeDocuments containsObject:_documents[i].identifier])
continue;
[newDocuments addObject:_documents[i]];
}
self.documents = newDocuments;
self.selectedTabIndex = [_documents indexOfObject:selectDocument];
}
- (void)openItems:(NSArray*)items closingOtherTabs:(BOOL)closeOtherTabsFlag
{
NSMutableArray<OakDocument*>* documents = [NSMutableArray array];
for(NSDictionary* item in items)
{
OakDocument* doc;
if(!item[@"path"] && item[@"identifier"])
doc = [OakDocumentController.sharedInstance findDocumentWithIdentifier:[[NSUUID alloc] initWithUUIDString:item[@"identifier"]]];
if(!doc && item[@"path"])
doc = [OakDocumentController.sharedInstance documentWithPath:item[@"path"]];
if(doc)
{
doc.recentTrackingDisabled = YES;
if(item[@"selectionString"])
doc.selection = item[@"selectionString"];
[documents addObject:doc];
}
}
if(!documents.count)
return;
NSMutableArray<NSUUID*>* tabsToClose = [NSMutableArray array];
if(closeOtherTabsFlag)
{
for(OakDocument* doc in self.documents)
{
if(!doc.isDocumentEdited && ![self isDocumentSticky:doc])
[tabsToClose addObject:doc.identifier];
}
}
else if(NSUUID* uuid = self.disposableDocument)
{
[tabsToClose addObject:uuid];
}
[self insertDocuments:documents atIndex:_selectedTabIndex + 1 selecting:documents.lastObject andClosing:tabsToClose];
[self openAndSelectDocument:documents.lastObject];
if(self.tabBarView && ![[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableTabAutoCloseKey])
{
NSInteger excessTabs = _documents.count - std::max<NSUInteger>(self.tabBarView.countOfVisibleTabs, 8);
if(excessTabs > 0)
{
std::multimap<NSInteger, NSUInteger> ranked;
for(NSUInteger i = 0; i < _documents.count; ++i)
ranked.emplace([OakDocumentController.sharedInstance lruRankForDocument:_documents[i]], i);
NSSet<NSUUID*>* newUUIDs = [NSSet setWithArray:[documents valueForKey:@"identifier"]];
NSMutableIndexSet* indexSet = [NSMutableIndexSet indexSet];
for(auto const& pair : ranked)
{
OakDocument* doc = _documents[pair.second];
if(!doc.isDocumentEdited && ![self isDocumentSticky:doc] && doc.isOnDisk && ![newUUIDs containsObject:doc.identifier])
[indexSet addIndex:pair.second];
if([indexSet count] == excessTabs)
break;
}
[self closeTabsAtIndexes:indexSet askToSaveChanges:NO createDocumentIfEmpty:NO];
}
}
}
// ================
// = Document I/O =
// ================
- (void)didOpenDocuemntInTextView:(OakTextView*)textView
{
for(auto const& item : bundles::query(bundles::kFieldSemanticClass, "callback.document.did-open", [textView scopeContext], bundles::kItemTypeMost, oak::uuid_t(), false))
[textView performBundleItem:item];
}
- (void)openAndSelectDocument:(OakDocument*)document
{
[document loadModalForWindow:self.window completionHandler:^(OakDocumentIOResult result, NSString* errorMessage, oak::uuid_t const& filterUUID){
if(result == OakDocumentIOResultSuccess)
{
BOOL showBundleSuggestions = ![[NSUserDefaults standardUserDefaults] boolForKey:kUserDefaultsDisableBundleSuggestionsKey];
if(!document.fileType && showBundleSuggestions)
{
NSArray<BundleGrammar*>* grammars = document.proposedGrammars;
if(NSArray* excludedGrammars = [[NSUserDefaults standardUserDefaults] stringArrayForKey:kUserDefaultsGrammarsToNeverSuggestKey])
grammars = [grammars filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (identifier.UUIDString IN %@)", excludedGrammars]];
if(_bundlesAlreadySuggested)