forked from macvim-dev/macvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMMVimController.m
2503 lines (2163 loc) · 87.1 KB
/
MMVimController.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
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
/* vi:set ts=8 sts=4 sw=4 ft=objc:
*
* VIM - Vi IMproved by Bram Moolenaar
* MacVim GUI port by Bjorn Winckler
*
* Do ":help uganda" in Vim to read copying and usage conditions.
* Do ":help credits" in Vim to see a list of people who contributed.
* See README.txt for an overview of the Vim source code.
*/
/*
* MMVimController
*
* Coordinates input/output to/from backend. A MMVimController sends input
* directly to a MMBackend, but communication from MMBackend to MMVimController
* goes via MMAppController so that it can coordinate all incoming distributed
* object messages.
*
* MMVimController does not deal with visual presentation. Essentially it
* should be able to run with no window present.
*
* Output from the backend is received in processInputQueue: (this message is
* called from MMAppController so it is not a DO call). Input is sent to the
* backend via sendMessage:data: or addVimInput:. The latter allows execution
* of arbitrary strings in the Vim process, much like the Vim script function
* remote_send() does. The messages that may be passed between frontend and
* backend are defined in an enum in MacVim.h.
*/
#import "MMAppController.h"
#import "MMFindReplaceController.h"
#import "MMTextView.h"
#import "MMVimController.h"
#import "MMVimView.h"
#import "MMWindowController.h"
#import "Miscellaneous.h"
#import "MMCoreTextView.h"
#import "MMWindow.h"
static NSString * const MMDefaultToolbarImageName = @"Attention";
static int MMAlertTextFieldHeight = 22;
static NSString * const MMToolbarMenuName = @"ToolBar";
static NSString * const MMTouchbarMenuName = @"TouchBar";
static NSString * const MMWinBarMenuName = @"WinBar";
static NSString * const MMPopUpMenuPrefix = @"PopUp";
static NSString * const MMUserPopUpMenuPrefix = @"]";
// NOTE: By default a message sent to the backend will be dropped if it cannot
// be delivered instantly; otherwise there is a possibility that MacVim will
// 'beachball' while waiting to deliver DO messages to an unresponsive Vim
// process. This means that you cannot rely on any message sent with
// sendMessage: to actually reach Vim.
static NSTimeInterval MMBackendProxyRequestTimeout = 0;
// Timeout used for setDialogReturn:.
static NSTimeInterval MMSetDialogReturnTimeout = 1.0;
static BOOL isUnsafeMessage(int msgid);
// HACK! AppKit private methods from NSToolTipManager. As an alternative to
// using private methods, it would be possible to set the user default
// NSInitialToolTipDelay (in ms) on app startup, but then it is impossible to
// change the balloon delay without closing/reopening a window.
@interface NSObject (NSToolTipManagerPrivateAPI)
+ (id)sharedToolTipManager;
- (void)setInitialToolTipDelay:(double)arg1;
@end
@interface MMAlert : NSAlert {
NSTextField *textField;
}
- (void)setTextFieldString:(NSString *)textFieldString;
- (NSTextField *)textField;
- (void)beginSheetModalForWindow:(NSWindow *)window
modalDelegate:(id)delegate;
@end
#if MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_12
@interface MMTouchBarInfo : NSObject;
@property (readonly) NSTouchBar *touchbar;
@property (readonly) NSMutableDictionary *itemDict;
@property (readonly) NSMutableArray *itemOrder;
@end
@interface MMTouchBarItemInfo : NSObject;
@property (readonly) NSTouchBarItem *touchbarItem;
@property (readwrite) BOOL enabled;
@property (readonly) NSString *label;
@property (readonly) MMTouchBarInfo *childTouchbar; // Set when this is a submenu
- (id)initWithItem:(NSTouchBarItem *)item label:(NSString *)label;
- (void)setTouchBarItem:(NSTouchBarItem *)item;
- (void)makeChildTouchBar;
@end
#endif
@interface MMVimController (Private)
- (void)doProcessInputQueue:(NSArray *)queue;
- (void)handleMessage:(int)msgid data:(NSData *)data;
- (void)savePanelDidEnd:(NSSavePanel *)panel code:(int)code
context:(void *)context;
- (void)alertDidEnd:(MMAlert *)alert code:(int)code context:(void *)context;
- (NSMenuItem *)menuItemForDescriptor:(NSArray *)desc;
- (NSMenu *)parentMenuForDescriptor:(NSArray *)desc;
- (NSMenu *)topLevelMenuForTitle:(NSString *)title;
- (void)addMenuWithDescriptor:(NSArray *)desc atIndex:(int)index;
- (void)addMenuItemWithDescriptor:(NSArray *)desc
atIndex:(int)index
tip:(NSString *)tip
icon:(NSString *)icon
keyEquivalent:(NSString *)keyEquivalent
modifierMask:(int)modifierMask
action:(NSString *)action
isAlternate:(BOOL)isAlternate;
- (void)removeMenuItemWithDescriptor:(NSArray *)desc;
- (void)enableMenuItemWithDescriptor:(NSArray *)desc state:(BOOL)on;
- (void)updateMenuItemTooltipWithDescriptor:(NSArray *)desc tip:(NSString *)tip;
- (NSImage*)findToolbarIcon:(NSString*)icon;
- (void)addToolbarItemToDictionaryWithLabel:(NSString *)title
toolTip:(NSString *)tip icon:(NSString *)icon;
- (void)addToolbarItemWithLabel:(NSString *)label
tip:(NSString *)tip icon:(NSString *)icon
atIndex:(int)idx;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12_2
- (void)addTouchbarItemWithLabel:(NSString *)label
icon:(NSString *)icon
tip:(NSString *)tip
atIndex:(int)idx
isSubMenu:(BOOL)submenu
desc:(NSArray *)desc
atTouchBar:(MMTouchBarInfo *)touchbarInfo;
- (void)updateTouchbarItemLabel:(NSString *)label
tip:(NSString *)tip
atTouchBarItem:(MMTouchBarItemInfo*)item;
- (BOOL)touchBarItemForDescriptor:(NSArray *)desc
touchBar:(MMTouchBarInfo **)touchBarPtr
touchBarItem:(MMTouchBarItemInfo **)touchBarItemPtr;
#endif
- (void)popupMenuWithDescriptor:(NSArray *)desc
atRow:(NSNumber *)row
column:(NSNumber *)col;
- (void)popupMenuWithAttributes:(NSDictionary *)attrs;
- (void)connectionDidDie:(NSNotification *)notification;
- (void)scheduleClose;
- (void)handleBrowseForFile:(NSDictionary *)attr;
- (void)handleShowDialog:(NSDictionary *)attr;
- (void)handleDeleteSign:(NSDictionary *)attr;
- (void)setToolTipDelay;
@end
@implementation MMVimController
- (id)initWithBackend:(id)backend pid:(int)processIdentifier
{
if (!(self = [super init]))
return nil;
// Use a random identifier. Currently, MMBackend connects using a public
// NSConnection, which has security implications. Using random identifiers
// make it much harder for third-party attacker to spoof.
int secSuccess = SecRandomCopyBytes(kSecRandomDefault, sizeof(identifier), &identifier);
if (secSuccess != errSecSuccess) {
// Don't know what concrete reasons secure random would fail, but just
// as a failsafe, use a less secure option.
identifier = ((unsigned long)arc4random()) << 32 | (unsigned long)arc4random();
}
windowController =
[[MMWindowController alloc] initWithVimController:self];
backendProxy = [backend retain];
popupMenuItems = [[NSMutableArray alloc] init];
toolbarItemDict = [[NSMutableDictionary alloc] init];
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12_2
if (AVAILABLE_MAC_OS_PATCH(10, 12, 2)) {
touchbarInfo = [[MMTouchBarInfo alloc] init];
}
#endif
pid = processIdentifier;
creationDate = [[NSDate alloc] init];
NSConnection *connection = [backendProxy connectionForProxy];
// TODO: Check that this will not set the timeout for the root proxy
// (in MMAppController).
[connection setRequestTimeout:MMBackendProxyRequestTimeout];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(connectionDidDie:)
name:NSConnectionDidDieNotification object:connection];
// Set up a main menu with only a "MacVim" menu (copied from a template
// which itself is set up in MainMenu.nib). The main menu is populated
// by Vim later on.
mainMenu = [[NSMenu alloc] initWithTitle:@"MainMenu"];
NSMenuItem *appMenuItem = [[MMAppController sharedInstance]
appMenuItemTemplate];
appMenuItem = [[appMenuItem copy] autorelease];
// Note: If the title of the application menu is anything but what
// CFBundleName says then the application menu will not be typeset in
// boldface for some reason. (It should already be set when we copy
// from the default main menu, but this is not the case for some
// reason.)
NSString *appName = [[NSBundle mainBundle]
objectForInfoDictionaryKey:@"CFBundleName"];
[appMenuItem setTitle:appName];
[mainMenu addItem:appMenuItem];
[self setToolTipDelay];
isInitialized = YES;
// After MMVimController's initialization is completed,
// set up the variable `v:os_appearance`.
[self appearanceChanged:getCurrentAppearance([windowController vimView].effectiveAppearance)];
return self;
}
- (void)dealloc
{
ASLogDebug(@"");
isInitialized = NO;
[serverName release]; serverName = nil;
[backendProxy release]; backendProxy = nil;
[toolbarItemDict release]; toolbarItemDict = nil;
[toolbar release]; toolbar = nil;
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12_2
[touchbarInfo release]; touchbarInfo = nil;
#endif
[popupMenuItems release]; popupMenuItems = nil;
[windowController release]; windowController = nil;
[vimState release]; vimState = nil;
[mainMenu release]; mainMenu = nil;
[creationDate release]; creationDate = nil;
[super dealloc];
}
/// This should only be called by MMAppController when it's doing an app quit.
/// We just wait for all Vim processes to terminate instad of individually
/// closing each MMVimController. We simply unset isInitialized to prevent it
/// from handling and sending messages to now invalid Vim connections.
- (void)uninitialize
{
isInitialized = NO;
}
- (unsigned long)vimControllerId
{
return identifier;
}
- (MMWindowController *)windowController
{
return windowController;
}
- (NSDictionary *)vimState
{
return vimState;
}
- (id)objectForVimStateKey:(NSString *)key
{
return [vimState objectForKey:key];
}
- (NSMenu *)mainMenu
{
return mainMenu;
}
- (BOOL)isPreloading
{
return isPreloading;
}
- (void)setIsPreloading:(BOOL)yn
{
isPreloading = yn;
}
- (BOOL)hasModifiedBuffer
{
return hasModifiedBuffer;
}
- (NSDate *)creationDate
{
return creationDate;
}
- (void)setServerName:(NSString *)name
{
if (name != serverName) {
[serverName release];
serverName = [name copy];
}
}
- (NSString *)serverName
{
return serverName;
}
- (int)pid
{
return pid;
}
- (void)dropFiles:(NSArray *)filenames forceOpen:(BOOL)force
{
filenames = normalizeFilenames(filenames);
ASLogInfo(@"filenames=%@ force=%d", filenames, force);
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
// Default to opening in tabs if layout is invalid or set to "windows".
NSInteger layout = [ud integerForKey:MMOpenLayoutKey];
if (layout < 0 || layout > MMLayoutTabs)
layout = MMLayoutTabs;
BOOL splitVert = [ud boolForKey:MMVerticalSplitKey];
if (splitVert && MMLayoutHorizontalSplit == layout)
layout = MMLayoutVerticalSplit;
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:(int)layout], @"layout",
filenames, @"filenames",
[NSNumber numberWithBool:force], @"forceOpen",
nil];
[self sendMessage:DropFilesMsgID data:[args dictionaryAsData]];
// Add dropped files to the "Recent Files" menu.
[[NSDocumentController sharedDocumentController]
noteNewRecentFilePaths:filenames];
}
// This is called when a file is dragged on top of a tab. We will open the file
// list similar to drag-and-dropped files.
- (void)file:(NSString *)filename draggedToTabAtIndex:(NSUInteger)tabIndex
{
filename = normalizeFilename(filename);
ASLogInfo(@"filename=%@ index=%ld", filename, tabIndex);
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
// This is similar to dropFiles:forceOpen: except we first switch to the
// selected tab, and just open the first file (this could be modified in the
// future to support multiple files). It also forces layout to be splits
// because we specified one tab to receive the file so doesn't make sense to
// open another tab.
int layout = MMLayoutHorizontalSplit;
if ([ud boolForKey:MMVerticalSplitKey])
layout = MMLayoutVerticalSplit;
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:layout], @"layout",
@[filename], @"filenames",
[NSNumber numberWithInt:(int)tabIndex + 1], @"tabpage",
nil];
[self sendMessage:OpenWithArgumentsMsgID data:[args dictionaryAsData]];
}
// This is called when a file is dragged on top of the tab bar but not a
// particular tab (e.g. the new tab button). We will open the file list similar
// to drag-and-dropped files.
- (void)filesDraggedToTabBar:(NSArray *)filenames
{
filenames = normalizeFilenames(filenames);
ASLogInfo(@"%@", filenames);
// This is similar to dropFiles:forceOpen: except we just force layout to be
// tabs (since the receipient is the tab bar, we assume that's the
// intention) instead of loading from user defaults.
int layout = MMLayoutTabs;
NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:layout], @"layout",
filenames, @"filenames",
nil];
[self sendMessage:OpenWithArgumentsMsgID data:[args dictionaryAsData]];
}
- (void)dropString:(NSString *)string
{
ASLogInfo(@"%@", string);
NSUInteger len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding] + 1;
if (len > 0 && len < INT_MAX) {
NSMutableData *data = [NSMutableData data];
int len_int = (int)len;
[data appendBytes:&len_int length:sizeof(int)];
[data appendBytes:[string UTF8String] length:len_int];
[self sendMessage:DropStringMsgID data:data];
}
}
- (void)appearanceChanged:(int)flag
{
[self sendMessage:NotifyAppearanceChangeMsgID
data:[NSData dataWithBytes: &flag
length:sizeof(flag)]];
}
- (void)passArguments:(NSDictionary *)args
{
if (!args) return;
ASLogDebug(@"args=%@", args);
[self sendMessage:OpenWithArgumentsMsgID data:[args dictionaryAsData]];
}
- (void)sendMessage:(int)msgid data:(NSData *)data
{
ASLogDebug(@"msg=%s (isInitialized=%d)",
MMVimMsgIDStrings[msgid], isInitialized);
if (!isInitialized) return;
@try {
[backendProxy processInput:msgid data:data];
}
@catch (NSException *ex) {
ASLogDebug(@"processInput:data: failed: pid=%d id=%lu msg=%s reason=%@",
pid, identifier, MMVimMsgIDStrings[msgid], ex);
}
}
- (BOOL)sendMessageNow:(int)msgid data:(NSData *)data
timeout:(NSTimeInterval)timeout
{
// Send a message with a timeout. USE WITH EXTREME CAUTION! Sending
// messages in rapid succession with a timeout may cause MacVim to beach
// ball forever. In almost all circumstances sendMessage:data: should be
// used instead.
ASLogDebug(@"msg=%s (isInitialized=%d)",
MMVimMsgIDStrings[msgid], isInitialized);
if (!isInitialized)
return NO;
if (timeout < 0) timeout = 0;
BOOL sendOk = YES;
NSConnection *conn = [backendProxy connectionForProxy];
NSTimeInterval oldTimeout = [conn requestTimeout];
[conn setRequestTimeout:timeout];
@try {
[backendProxy processInput:msgid data:data];
}
@catch (NSException *ex) {
sendOk = NO;
ASLogDebug(@"processInput:data: failed: pid=%d id=%lu msg=%s reason=%@",
pid, identifier, MMVimMsgIDStrings[msgid], ex);
}
@finally {
[conn setRequestTimeout:oldTimeout];
}
return sendOk;
}
- (void)addVimInput:(NSString *)string
{
ASLogDebug(@"%@", string);
// This is a very general method of adding input to the Vim process. It is
// basically the same as calling remote_send() on the process (see
// ':h remote_send').
if (string) {
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
[self sendMessage:AddInputMsgID data:data];
}
}
- (NSString *)evaluateVimExpression:(NSString *)expr
{
NSString *eval = nil;
@try {
eval = [backendProxy evaluateExpression:expr];
ASLogDebug(@"eval(%@)=%@", expr, eval);
}
@catch (NSException *ex) {
ASLogDebug(@"evaluateExpression: failed: pid=%d id=%lu reason=%@",
pid, identifier, ex);
}
return eval;
}
- (id)evaluateVimExpressionCocoa:(NSString *)expr
errorString:(NSString **)errstr
{
id eval = nil;
@try {
eval = [backendProxy evaluateExpressionCocoa:expr
errorString:errstr];
ASLogDebug(@"eval(%@)=%@", expr, eval);
} @catch (NSException *ex) {
ASLogDebug(@"evaluateExpressionCocoa: failed: pid=%d id=%lu reason=%@",
pid, identifier, ex);
*errstr = [ex reason];
}
return eval;
}
- (id)backendProxy
{
return backendProxy;
}
- (void)cleanup
{
if (!isInitialized) return;
// Remove any delayed calls made on this object.
[NSObject cancelPreviousPerformRequestsWithTarget:self];
isInitialized = NO;
[toolbar setDelegate:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self];
//[[backendProxy connectionForProxy] invalidate];
//[windowController close];
[windowController cleanup];
}
- (void)processInputQueue:(NSArray *)queue
{
if (!isInitialized) return;
// NOTE: This method must not raise any exceptions (see comment in the
// calling method).
@try {
[self doProcessInputQueue:queue];
[windowController processInputQueueDidFinish];
}
@catch (NSException *ex) {
ASLogDebug(@"Exception: pid=%d id=%lu reason=%@", pid, identifier, ex);
}
}
- (NSToolbarItem *)toolbar:(NSToolbar *)theToolbar
itemForItemIdentifier:(NSString *)itemId
willBeInsertedIntoToolbar:(BOOL)flag
{
NSToolbarItem *item = [toolbarItemDict objectForKey:itemId];
if (!item) {
ASLogWarn(@"No toolbar item with id '%@'", itemId);
}
return item;
}
- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)theToolbar
{
return nil;
}
- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)theToolbar
{
return nil;
}
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_12_2
- (NSTouchBar *)makeTouchBarOn:(MMTouchBarInfo *)touchbarInfo
{
NSMutableArray *filteredTouchbarItemOrder = [NSMutableArray array];
NSMutableSet *filteredItems = [NSMutableSet set];
for (NSString *label in touchbarInfo.itemOrder) {
MMTouchBarItemInfo *itemInfo = [touchbarInfo.itemDict objectForKey:label];
if ([itemInfo enabled]) {
[filteredTouchbarItemOrder addObject:[itemInfo label]];
if ([itemInfo touchbarItem]) {
if ([itemInfo childTouchbar]) {
NSTouchBar *childTouchbar = [self makeTouchBarOn:[itemInfo childTouchbar]];
NSPopoverTouchBarItem *popoverItem = (NSPopoverTouchBarItem *)[itemInfo touchbarItem];
[popoverItem setPopoverTouchBar:childTouchbar];
}
[filteredItems addObject:itemInfo.touchbarItem];
}
}
}
[filteredTouchbarItemOrder addObject:NSTouchBarItemIdentifierOtherItemsProxy];
touchbarInfo.touchbar.defaultItemIdentifiers = filteredTouchbarItemOrder;
touchbarInfo.touchbar.templateItems = filteredItems;
return touchbarInfo.touchbar;
}
- (NSTouchBar *)makeTouchBar
{
return [self makeTouchBarOn:touchbarInfo];
}
#endif
@end // MMVimController
@implementation MMVimController (Private)
- (void)doProcessInputQueue:(NSArray *)queue
{
NSMutableArray *delayQueue = nil;
unsigned i, count = (unsigned)[queue count];
if (count % 2) {
ASLogWarn(@"Uneven number of components (%u) in command queue. "
"Skipping...", count);
return;
}
for (i = 0; i < count; i += 2) {
NSData *value = [queue objectAtIndex:i];
NSData *data = [queue objectAtIndex:i+1];
int msgid = *((int*)[value bytes]);
BOOL inDefaultMode = [[[NSRunLoop currentRunLoop] currentMode]
isEqual:NSDefaultRunLoopMode];
if (!inDefaultMode && isUnsafeMessage(msgid)) {
// NOTE: Because we may be listening to DO messages in "event
// tracking mode" we have to take extra care when doing things
// like releasing view items (and other Cocoa objects).
// Messages that may be potentially "unsafe" are delayed until
// the run loop is back to default mode at which time they are
// safe to call again.
// A problem with this approach is that it is hard to
// classify which messages are unsafe. As a rule of thumb, if
// a message may release an object used by the Cocoa framework
// (e.g. views) then the message should be considered unsafe.
// Delaying messages may have undesired side-effects since it
// means that messages may not be processed in the order Vim
// sent them, so beware.
if (!delayQueue)
delayQueue = [NSMutableArray array];
ASLogDebug(@"Adding unsafe message '%s' to delay queue (mode=%@)",
MMVimMsgIDStrings[msgid],
[[NSRunLoop currentRunLoop] currentMode]);
[delayQueue addObject:value];
[delayQueue addObject:data];
} else {
[self handleMessage:msgid data:data];
}
}
if (delayQueue) {
ASLogDebug(@" Flushing delay queue (%ld items)",
[delayQueue count]/2);
[self performSelector:@selector(processInputQueue:)
withObject:delayQueue
afterDelay:0];
}
}
- (void)handleMessage:(int)msgid data:(NSData *)data
{
switch (msgid) {
case OpenWindowMsgID:
{
[windowController openWindow];
if (!isPreloading) {
[windowController presentWindow:nil];
}
}
break;
case BatchDrawMsgID:
{
[[[windowController vimView] textView] performBatchDrawWithData:data];
}
break;
case SelectTabMsgID:
{
#if 0 // NOTE: Tab selection is done inside updateTabsWithData:.
const void *bytes = [data bytes];
int idx = *((int*)bytes);
[windowController selectTabWithIndex:idx];
#endif
}
break;
case UpdateTabBarMsgID:
{
[windowController updateTabsWithData:data];
}
break;
case ShowTabBarMsgID:
{
[windowController showTabBar:YES];
[self sendMessage:BackingPropertiesChangedMsgID data:nil];
}
break;
case HideTabBarMsgID:
{
[windowController showTabBar:NO];
[self sendMessage:BackingPropertiesChangedMsgID data:nil];
}
break;
case SetTextDimensionsMsgID:
case LiveResizeMsgID:
case SetTextDimensionsNoResizeWindowMsgID:
case SetTextDimensionsReplyMsgID:
{
const void *bytes = [data bytes];
int rows = *((int*)bytes); bytes += sizeof(int);
int cols = *((int*)bytes);
// NOTE: When a resize message originated in the frontend, Vim
// acknowledges it with a reply message. When this happens the window
// should not move (the frontend would already have moved the window).
BOOL onScreen = SetTextDimensionsReplyMsgID!=msgid;
BOOL keepGUISize = SetTextDimensionsNoResizeWindowMsgID == msgid;
[windowController setTextDimensionsWithRows:rows
columns:cols
isLive:(LiveResizeMsgID==msgid)
keepGUISize:keepGUISize
keepOnScreen:onScreen];
}
break;
case ResizeViewMsgID:
{
[windowController resizeView];
}
break;
case SetWindowTitleMsgID:
{
const void *bytes = [data bytes];
int len = *((int*)bytes); bytes += sizeof(int);
NSString *string = [[NSString alloc] initWithBytes:(void*)bytes
length:len encoding:NSUTF8StringEncoding];
[windowController setTitle:string];
[string release];
}
break;
case SetDocumentFilenameMsgID:
{
const void *bytes = [data bytes];
int len = *((int*)bytes); bytes += sizeof(int);
if (len > 0) {
NSString *filename = [[NSString alloc] initWithBytes:(void*)bytes
length:len encoding:NSUTF8StringEncoding];
[windowController setDocumentFilename:filename];
[filename release];
} else {
[windowController setDocumentFilename:@""];
}
}
break;
case AddMenuMsgID:
{
NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
[self addMenuWithDescriptor:[attrs objectForKey:@"descriptor"]
atIndex:[[attrs objectForKey:@"index"] intValue]];
}
break;
case AddMenuItemMsgID:
{
NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
[self addMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
atIndex:[[attrs objectForKey:@"index"] intValue]
tip:[attrs objectForKey:@"tip"]
icon:[attrs objectForKey:@"icon"]
keyEquivalent:[attrs objectForKey:@"keyEquivalent"]
modifierMask:[[attrs objectForKey:@"modifierMask"] intValue]
action:[attrs objectForKey:@"action"]
isAlternate:[[attrs objectForKey:@"isAlternate"] boolValue]];
}
break;
case RemoveMenuItemMsgID:
{
NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
[self removeMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]];
}
break;
case EnableMenuItemMsgID:
{
NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
[self enableMenuItemWithDescriptor:[attrs objectForKey:@"descriptor"]
state:[[attrs objectForKey:@"enable"] boolValue]];
}
break;
case UpdateMenuItemTooltipMsgID:
{
NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
[self updateMenuItemTooltipWithDescriptor:[attrs objectForKey:@"descriptor"]
tip:[attrs objectForKey:@"tip"]];
}
break;
case ShowToolbarMsgID:
{
const void *bytes = [data bytes];
int enable = *((int*)bytes); bytes += sizeof(int);
int flags = *((int*)bytes);
int mode = NSToolbarDisplayModeDefault;
if (flags & ToolbarLabelFlag) {
mode = flags & ToolbarIconFlag ? NSToolbarDisplayModeIconAndLabel
: NSToolbarDisplayModeLabelOnly;
} else if (flags & ToolbarIconFlag) {
mode = NSToolbarDisplayModeIconOnly;
}
int size = flags & ToolbarSizeRegularFlag ? NSToolbarSizeModeRegular
: NSToolbarSizeModeSmall;
[windowController showToolbar:enable size:size mode:mode];
}
break;
case CreateScrollbarMsgID:
{
const void *bytes = [data bytes];
int32_t ident = *((int32_t*)bytes); bytes += sizeof(int32_t);
int type = *((int*)bytes);
[windowController createScrollbarWithIdentifier:ident type:type];
}
break;
case DestroyScrollbarMsgID:
{
const void *bytes = [data bytes];
int32_t ident = *((int32_t*)bytes);
[windowController destroyScrollbarWithIdentifier:ident];
}
break;
case ShowScrollbarMsgID:
{
const void *bytes = [data bytes];
int32_t ident = *((int32_t*)bytes); bytes += sizeof(int32_t);
int visible = *((int*)bytes);
[windowController showScrollbarWithIdentifier:ident state:visible];
}
break;
case SetScrollbarPositionMsgID:
{
const void *bytes = [data bytes];
int32_t ident = *((int32_t*)bytes); bytes += sizeof(int32_t);
int pos = *((int*)bytes); bytes += sizeof(int);
int len = *((int*)bytes);
[windowController setScrollbarPosition:pos length:len
identifier:ident];
}
break;
case SetScrollbarThumbMsgID:
{
const void *bytes = [data bytes];
int32_t ident = *((int32_t*)bytes); bytes += sizeof(int32_t);
float val = *((float*)bytes); bytes += sizeof(float);
float prop = *((float*)bytes);
[windowController setScrollbarThumbValue:val proportion:prop
identifier:ident];
}
break;
case SetFontMsgID:
{
const void *bytes = [data bytes];
float size = *((float*)bytes); bytes += sizeof(float);
int len = *((int*)bytes); bytes += sizeof(int);
NSString *name = [[NSString alloc]
initWithBytes:(void*)bytes length:len
encoding:NSUTF8StringEncoding];
NSFont *font = nil;
if ([name hasPrefix:MMSystemFontAlias]) {
#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_15
if (@available(macos 10.15, *)) {
NSFontWeight fontWeight = NSFontWeightRegular;
if (name.length > MMSystemFontAlias.length) {
const NSRange cmpRange = NSMakeRange(MMSystemFontAlias.length, name.length - MMSystemFontAlias.length);
if ([name compare:@"UltraLight" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightUltraLight;
else if ([name compare:@"Thin" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightThin;
else if ([name compare:@"Light" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightLight;
else if ([name compare:@"Regular" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightRegular;
else if ([name compare:@"Medium" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightMedium;
else if ([name compare:@"Semibold" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightSemibold;
else if ([name compare:@"Bold" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightBold;
else if ([name compare:@"Heavy" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightHeavy;
else if ([name compare:@"Black" options:NSCaseInsensitiveSearch range:cmpRange] == NSOrderedSame)
fontWeight = NSFontWeightBlack;
}
font = [NSFont monospacedSystemFontOfSize:size weight:fontWeight];
}
else
#endif
{
// Fallback to Menlo on older macOS versions that don't support the system monospace font API
font = [NSFont fontWithName:@"Menlo-Regular" size:size];
}
}
else {
font = [NSFont fontWithName:name size:size];
}
if (!font) {
// This should only happen if the system default font has changed
// name since MacVim was compiled in which case we fall back on
// using the user fixed width font.
ASLogInfo(@"Failed to load font '%@' / %f", name, size);
font = [NSFont userFixedPitchFontOfSize:size];
}
[windowController setFont:font];
[name release];
}
break;
case SetWideFontMsgID:
{
const void *bytes = [data bytes];
float size = *((float*)bytes); bytes += sizeof(float);
int len = *((int*)bytes); bytes += sizeof(int);
if (len > 0) {
NSString *name = [[NSString alloc]
initWithBytes:(void*)bytes length:len
encoding:NSUTF8StringEncoding];
NSFont *font = [NSFont fontWithName:name size:size];
[windowController setWideFont:font];
[name release];
} else {
[windowController setWideFont:nil];
}
}
break;
case SetDefaultColorsMsgID:
{
const void *bytes = [data bytes];
unsigned bg = *((unsigned*)bytes); bytes += sizeof(unsigned);
unsigned fg = *((unsigned*)bytes);
NSColor *back = [NSColor colorWithArgbInt:bg];
NSColor *fore = [NSColor colorWithRgbInt:fg];
[windowController setDefaultColorsBackground:back foreground:fore];
}
break;
case ExecuteActionMsgID:
{
const void *bytes = [data bytes];
int len = *((int*)bytes); bytes += sizeof(int);
NSString *actionName = [[NSString alloc]
initWithBytes:(void*)bytes length:len
encoding:NSUTF8StringEncoding];
SEL sel = NSSelectorFromString(actionName);
[NSApp sendAction:sel to:nil from:self];
[actionName release];
}
break;
case ShowPopupMenuMsgID:
{
NSDictionary *attrs = [NSDictionary dictionaryWithData:data];
// The popup menu enters a modal loop so delay this call so that we