forked from b4winckler/macvim
/
MMBackend.m
3012 lines (2499 loc) · 96.8 KB
/
MMBackend.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.
*/
/*
* MMBackend
*
* MMBackend communicates with the frontend (MacVim). It maintains a queue of
* output which is flushed to the frontend under controlled circumstances (so
* as to maintain a steady framerate). Input from the frontend is also handled
* here.
*
* The frontend communicates with the backend via the MMBackendProtocol. In
* particular, input is sent to the backend via processInput:data: and Vim
* state can be queried from the frontend with evaluateExpression:.
*
* It is very important to realize that all state is held by the backend, the
* frontend must either ask for state [MMBackend evaluateExpression:] or wait
* for the backend to update [MMAppController processInput:forIdentifier:].
*
* The client/server functionality of Vim is handled by the backend. It sets
* up a named NSConnection to which other Vim processes can connect.
*/
#import "MMBackend.h"
// NOTE: Colors in MMBackend are stored as unsigned ints on the form 0xaarrggbb
// whereas colors in Vim are int without the alpha component. Also note that
// 'transp' is assumed to be a value between 0 and 100.
#define MM_COLOR(col) ((unsigned)( ((col)&0xffffff) | 0xff000000 ))
#define MM_COLOR_WITH_TRANSP(col,transp) \
((unsigned)( ((col)&0xffffff) \
| ((((unsigned)((((100-(transp))*255)/100)+.5f))&0xff)<<24) ))
// Values for window layout (must match values in main.c).
#define WIN_HOR 1 // "-o" horizontally split windows
#define WIN_VER 2 // "-O" vertically split windows
#define WIN_TABS 3 // "-p" windows on tab pages
static unsigned MMServerMax = 1000;
// TODO: Move to separate file.
static int eventModifierFlagsToVimModMask(int modifierFlags);
static int eventModifierFlagsToVimMouseModMask(int modifierFlags);
static int eventButtonNumberToVimMouseButton(int buttonNumber);
// In gui_macvim.m
vimmenu_T *menu_for_descriptor(NSArray *desc);
static id evalExprCocoa(NSString * expr, NSString ** errstr);
enum {
MMBlinkStateNone = 0,
MMBlinkStateOn,
MMBlinkStateOff
};
static NSString *MMSymlinkWarningString =
@"\n\n\tMost likely this is because you have symlinked directly to\n"
"\tthe Vim binary, which Cocoa does not allow. Please use an\n"
"\talias or the mvim shell script instead. If you have not used\n"
"\ta symlink, then your MacVim.app bundle is incomplete.\n\n";
extern GuiFont gui_mch_retain_font(GuiFont font);
@interface NSString (MMServerNameCompare)
- (NSComparisonResult)serverNameCompare:(NSString *)string;
@end
@interface MMBackend (Private)
- (void)clearDrawData;
- (void)didChangeWholeLine;
- (void)waitForDialogReturn;
- (void)insertVimStateMessage;
- (void)processInputQueue;
- (void)handleInputEvent:(int)msgid data:(NSData *)data;
+ (NSDictionary *)specialKeys;
- (void)handleInsertText:(NSString *)text;
- (void)handleKeyDown:(NSString *)key modifiers:(int)mods;
- (void)queueMessage:(int)msgid data:(NSData *)data;
- (void)connectionDidDie:(NSNotification *)notification;
- (void)blinkTimerFired:(NSTimer *)timer;
- (void)focusChange:(BOOL)on;
- (void)handleToggleToolbar;
- (void)handleScrollbarEvent:(NSData *)data;
- (void)handleSetFont:(NSData *)data;
- (void)handleDropFiles:(NSData *)data;
- (void)handleDropString:(NSData *)data;
- (void)startOdbEditWithArguments:(NSDictionary *)args;
- (void)handleXcodeMod:(NSData *)data;
- (void)handleOpenWithArguments:(NSDictionary *)args;
- (BOOL)checkForModifiedBuffers;
- (void)addInput:(NSString *)input;
- (BOOL)unusedEditor;
- (void)redrawScreen;
- (void)handleFindReplace:(NSDictionary *)args;
@end
@interface MMBackend (ClientServer)
- (NSString *)connectionNameFromServerName:(NSString *)name;
- (NSConnection *)connectionForServerName:(NSString *)name;
- (NSConnection *)connectionForServerPort:(int)port;
- (void)serverConnectionDidDie:(NSNotification *)notification;
- (void)addClient:(NSDistantObject *)client;
- (NSString *)alternateServerNameForName:(NSString *)name;
@end
@implementation MMBackend
+ (MMBackend *)sharedInstance
{
static MMBackend *singleton = nil;
return singleton ? singleton : (singleton = [MMBackend new]);
}
- (id)init
{
self = [super init];
if (!self) return nil;
outputQueue = [[NSMutableArray alloc] init];
inputQueue = [[NSMutableArray alloc] init];
drawData = [[NSMutableData alloc] initWithCapacity:1024];
connectionNameDict = [[NSMutableDictionary alloc] init];
clientProxyDict = [[NSMutableDictionary alloc] init];
serverReplyDict = [[NSMutableDictionary alloc] init];
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *path = [mainBundle pathForResource:@"Colors" ofType:@"plist"];
if (path)
colorDict = [[NSDictionary dictionaryWithContentsOfFile:path] retain];
path = [mainBundle pathForResource:@"SystemColors" ofType:@"plist"];
if (path)
sysColorDict = [[NSDictionary dictionaryWithContentsOfFile:path]
retain];
path = [mainBundle pathForResource:@"Actions" ofType:@"plist"];
if (path)
actionDict = [[NSDictionary dictionaryWithContentsOfFile:path] retain];
if (!(colorDict && sysColorDict && actionDict))
NSLog(@"ERROR: Failed to load dictionaries.%@",
MMSymlinkWarningString);
return self;
}
- (void)dealloc
{
//NSLog(@"%@ %s", [self className], _cmd);
[[NSNotificationCenter defaultCenter] removeObserver:self];
gui_mch_free_font(oldWideFont); oldWideFont = NOFONT;
[blinkTimer release]; blinkTimer = nil;
[alternateServerName release]; alternateServerName = nil;
[serverReplyDict release]; serverReplyDict = nil;
[clientProxyDict release]; clientProxyDict = nil;
[connectionNameDict release]; connectionNameDict = nil;
[inputQueue release]; inputQueue = nil;
[outputQueue release]; outputQueue = nil;
[drawData release]; drawData = nil;
[connection release]; connection = nil;
[actionDict release]; actionDict = nil;
[sysColorDict release]; sysColorDict = nil;
[colorDict release]; colorDict = nil;
[super dealloc];
}
- (void)setBackgroundColor:(int)color
{
backgroundColor = MM_COLOR_WITH_TRANSP(color,p_transp);
}
- (void)setForegroundColor:(int)color
{
foregroundColor = MM_COLOR(color);
}
- (void)setSpecialColor:(int)color
{
specialColor = MM_COLOR(color);
}
- (void)setDefaultColorsBackground:(int)bg foreground:(int)fg
{
defaultBackgroundColor = MM_COLOR_WITH_TRANSP(bg,p_transp);
defaultForegroundColor = MM_COLOR(fg);
NSMutableData *data = [NSMutableData data];
[data appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
[data appendBytes:&defaultForegroundColor length:sizeof(unsigned)];
[self queueMessage:SetDefaultColorsMsgID data:data];
}
- (NSConnection *)connection
{
if (!connection) {
// NOTE! If the name of the connection changes here it must also be
// updated in MMAppController.m.
NSString *name = [NSString stringWithFormat:@"%@-connection",
[[NSBundle mainBundle] bundlePath]];
connection = [NSConnection connectionWithRegisteredName:name host:nil];
[connection retain];
}
// NOTE: 'connection' may be nil here.
return connection;
}
- (NSDictionary *)actionDict
{
return actionDict;
}
- (int)initialWindowLayout
{
return initialWindowLayout;
}
- (void)queueMessage:(int)msgid properties:(NSDictionary *)props
{
[self queueMessage:msgid data:[props dictionaryAsData]];
}
- (BOOL)checkin
{
if (![self connection]) {
if (waitForAck) {
// This is a preloaded process and as such should not cause the
// MacVim to be opened. We probably got here as a result of the
// user quitting MacVim while the process was preloading, so exit
// this process too.
// (Don't use mch_exit() since it assumes the process has properly
// started.)
exit(0);
}
NSBundle *mainBundle = [NSBundle mainBundle];
#if 0
OSStatus status;
FSRef ref;
// Launch MacVim using Launch Services (NSWorkspace would be nicer, but
// the API to pass Apple Event parameters is broken on 10.4).
NSString *path = [mainBundle bundlePath];
status = FSPathMakeRef((const UInt8 *)[path UTF8String], &ref, NULL);
if (noErr == status) {
// Pass parameter to the 'Open' Apple Event that tells MacVim not
// to open an untitled window.
NSAppleEventDescriptor *desc =
[NSAppleEventDescriptor recordDescriptor];
[desc setParamDescriptor:
[NSAppleEventDescriptor descriptorWithBoolean:NO]
forKeyword:keyMMUntitledWindow];
LSLaunchFSRefSpec spec = { &ref, 0, NULL, [desc aeDesc],
kLSLaunchDefaults, NULL };
status = LSOpenFromRefSpec(&spec, NULL);
}
if (noErr != status) {
NSLog(@"ERROR: Failed to launch MacVim (path=%@).%@",
path, MMSymlinkWarningString);
return NO;
}
#else
// Launch MacVim using NSTask. For some reason the above code using
// Launch Services sometimes fails on LSOpenFromRefSpec() (when it
// fails, the dock icon starts bouncing and never stops). It seems
// like rebuilding the Launch Services database takes care of this
// problem, but the NSTask way seems more stable so stick with it.
//
// NOTE! Using NSTask to launch the GUI has the negative side-effect
// that the GUI won't be activated (or raised) so there is a hack in
// MMAppController which raises the app when a new window is opened.
NSMutableArray *args = [NSMutableArray arrayWithObjects:
[NSString stringWithFormat:@"-%@", MMNoWindowKey], @"yes", nil];
NSString *exeName = [[mainBundle infoDictionary]
objectForKey:@"CFBundleExecutable"];
NSString *path = [mainBundle pathForAuxiliaryExecutable:exeName];
if (!path) {
NSLog(@"ERROR: Could not find MacVim executable in bundle.%@",
MMSymlinkWarningString);
return NO;
}
[NSTask launchedTaskWithLaunchPath:path arguments:args];
#endif
// HACK! Poll the mach bootstrap server until it returns a valid
// connection to detect that MacVim has finished launching. Also set a
// time-out date so that we don't get stuck doing this forever.
NSDate *timeOutDate = [NSDate dateWithTimeIntervalSinceNow:10];
while (![self connection] &&
NSOrderedDescending == [timeOutDate compare:[NSDate date]])
[[NSRunLoop currentRunLoop]
runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:.1]];
// NOTE: [self connection] will set 'connection' as a side-effect.
if (!connection) {
NSLog(@"WARNING: Timed-out waiting for GUI to launch.");
return NO;
}
}
@try {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(connectionDidDie:)
name:NSConnectionDidDieNotification object:connection];
appProxy = [[connection rootProxy] retain];
[appProxy setProtocolForProxy:@protocol(MMAppProtocol)];
// NOTE: We do not set any new timeout values for the connection to the
// frontend. This means that if the frontend is "stuck" (e.g. in a
// modal loop) then any calls to the frontend will block indefinitely
// (the default timeouts are huge).
int pid = [[NSProcessInfo processInfo] processIdentifier];
identifier = [appProxy connectBackend:self pid:pid];
return YES;
}
@catch (NSException *e) {
NSLog(@"Exception caught when trying to connect backend: \"%@\"", e);
}
return NO;
}
- (BOOL)openGUIWindow
{
[self queueMessage:OpenWindowMsgID data:nil];
return YES;
}
- (void)clearAll
{
int type = ClearAllDrawType;
// Any draw commands in queue are effectively obsolete since this clearAll
// will negate any effect they have, therefore we may as well clear the
// draw queue.
[self clearDrawData];
[drawData appendBytes:&type length:sizeof(int)];
}
- (void)clearBlockFromRow:(int)row1 column:(int)col1
toRow:(int)row2 column:(int)col2
{
int type = ClearBlockDrawType;
[drawData appendBytes:&type length:sizeof(int)];
[drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
[drawData appendBytes:&row1 length:sizeof(int)];
[drawData appendBytes:&col1 length:sizeof(int)];
[drawData appendBytes:&row2 length:sizeof(int)];
[drawData appendBytes:&col2 length:sizeof(int)];
}
- (void)deleteLinesFromRow:(int)row count:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
{
int type = DeleteLinesDrawType;
[drawData appendBytes:&type length:sizeof(int)];
[drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
[drawData appendBytes:&row length:sizeof(int)];
[drawData appendBytes:&count length:sizeof(int)];
[drawData appendBytes:&bottom length:sizeof(int)];
[drawData appendBytes:&left length:sizeof(int)];
[drawData appendBytes:&right length:sizeof(int)];
if (left == 0 && right == gui.num_cols-1)
[self didChangeWholeLine];
}
- (void)drawString:(char*)s length:(int)len row:(int)row column:(int)col
cells:(int)cells flags:(int)flags
{
if (len <= 0 || cells <= 0) return;
int type = DrawStringDrawType;
[drawData appendBytes:&type length:sizeof(int)];
[drawData appendBytes:&backgroundColor length:sizeof(unsigned)];
[drawData appendBytes:&foregroundColor length:sizeof(unsigned)];
[drawData appendBytes:&specialColor length:sizeof(unsigned)];
[drawData appendBytes:&row length:sizeof(int)];
[drawData appendBytes:&col length:sizeof(int)];
[drawData appendBytes:&cells length:sizeof(int)];
[drawData appendBytes:&flags length:sizeof(int)];
[drawData appendBytes:&len length:sizeof(int)];
[drawData appendBytes:s length:len];
}
- (void)insertLinesFromRow:(int)row count:(int)count
scrollBottom:(int)bottom left:(int)left right:(int)right
{
int type = InsertLinesDrawType;
[drawData appendBytes:&type length:sizeof(int)];
[drawData appendBytes:&defaultBackgroundColor length:sizeof(unsigned)];
[drawData appendBytes:&row length:sizeof(int)];
[drawData appendBytes:&count length:sizeof(int)];
[drawData appendBytes:&bottom length:sizeof(int)];
[drawData appendBytes:&left length:sizeof(int)];
[drawData appendBytes:&right length:sizeof(int)];
if (left == 0 && right == gui.num_cols-1)
[self didChangeWholeLine];
}
- (void)drawCursorAtRow:(int)row column:(int)col shape:(int)shape
fraction:(int)percent color:(int)color
{
int type = DrawCursorDrawType;
unsigned uc = MM_COLOR(color);
[drawData appendBytes:&type length:sizeof(int)];
[drawData appendBytes:&uc length:sizeof(unsigned)];
[drawData appendBytes:&row length:sizeof(int)];
[drawData appendBytes:&col length:sizeof(int)];
[drawData appendBytes:&shape length:sizeof(int)];
[drawData appendBytes:&percent length:sizeof(int)];
}
- (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nr
numColumns:(int)nc invert:(int)invert
{
int type = DrawInvertedRectDrawType;
[drawData appendBytes:&type length:sizeof(int)];
[drawData appendBytes:&row length:sizeof(int)];
[drawData appendBytes:&col length:sizeof(int)];
[drawData appendBytes:&nr length:sizeof(int)];
[drawData appendBytes:&nc length:sizeof(int)];
[drawData appendBytes:&invert length:sizeof(int)];
}
- (void)update
{
// Keep running the run-loop until there is no more input to process.
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true)
== kCFRunLoopRunHandledSource)
; // do nothing
}
- (void)flushQueue:(BOOL)force
{
// NOTE: This variable allows for better control over when the queue is
// flushed. It can be set to YES at the beginning of a sequence of calls
// that may potentially add items to the queue, and then restored back to
// NO.
if (flushDisabled) return;
if ([drawData length] > 0) {
// HACK! Detect changes to 'guifontwide'.
if (gui.wide_font != oldWideFont) {
gui_mch_free_font(oldWideFont);
oldWideFont = gui_mch_retain_font(gui.wide_font);
[self setFont:oldWideFont wide:YES];
}
int type = SetCursorPosDrawType;
[drawData appendBytes:&type length:sizeof(type)];
[drawData appendBytes:&gui.row length:sizeof(gui.row)];
[drawData appendBytes:&gui.col length:sizeof(gui.col)];
[self queueMessage:BatchDrawMsgID data:[drawData copy]];
[self clearDrawData];
}
if ([outputQueue count] > 0) {
[self insertVimStateMessage];
@try {
//NSLog(@"[%s] Flushing (count=%d)", _cmd, [outputQueue count]);
[appProxy processInput:outputQueue forIdentifier:identifier];
}
@catch (NSException *e) {
NSLog(@"[%s] Exception caught: \"%@\"", _cmd, e);
NSLog(@"outputQueue(len:%d)=%@", [outputQueue count]/2,
outputQueue);
if (![connection isValid]) {
NSLog(@"WARNING! Connection is invalid, exit now!");
NSLog(@"waitForAck=%d got_int=%d", waitForAck, got_int);
mch_exit(-1);
}
}
[outputQueue removeAllObjects];
}
}
- (BOOL)waitForInput:(int)milliseconds
{
// Return NO if we timed out waiting for input, otherwise return YES.
BOOL inputReceived = NO;
// Only start the run loop if the input queue is empty, otherwise process
// the input first so that the input on queue isn't delayed.
if ([inputQueue count]) {
inputReceived = YES;
} else {
// Wait for the specified amount of time, unless 'milliseconds' is
// negative in which case we wait "forever" (1e6 seconds translates to
// approximately 11 days).
CFTimeInterval dt = (milliseconds >= 0 ? .001*milliseconds : 1e6);
while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, dt, true)
== kCFRunLoopRunHandledSource) {
// In order to ensure that all input on the run-loop has been
// processed we set the timeout to 0 and keep processing until the
// run-loop times out.
dt = 0.0;
inputReceived = YES;
}
}
// The above calls may have placed messages on the input queue so process
// it now. This call may enter a blocking loop.
if ([inputQueue count] > 0)
[self processInputQueue];
return inputReceived;
}
- (void)exit
{
// NOTE: This is called if mch_exit() is called. Since we assume here that
// the process has started properly, be sure to use exit() instead of
// mch_exit() to prematurely terminate a process (or set 'isTerminating'
// first).
// Make sure no connectionDidDie: notification is received now that we are
// already exiting.
[[NSNotificationCenter defaultCenter] removeObserver:self];
// The 'isTerminating' flag indicates that the frontend is also exiting so
// there is no need to flush any more output since the frontend won't look
// at it anyway.
if (!isTerminating && [connection isValid]) {
@try {
// Flush the entire queue in case a VimLeave autocommand added
// something to the queue.
[self queueMessage:CloseWindowMsgID data:nil];
[appProxy processInput:outputQueue forIdentifier:identifier];
}
@catch (NSException *e) {
NSLog(@"Exception caught when sending CloseWindowMsgID: \"%@\"", e);
}
// NOTE: If Cmd-w was pressed to close the window the menu is briefly
// highlighted and during this pause the frontend won't receive any DO
// messages. If the Vim process exits before this highlighting has
// finished Cocoa will emit the following error message:
// *** -[NSMachPort handlePortMessage:]: dropping incoming DO message
// because the connection or ports are invalid
// To avoid this warning we delay here. If the warning still appears
// this delay may need to be increased.
usleep(150000);
}
#ifdef MAC_CLIENTSERVER
// The default connection is used for the client/server code.
[[NSConnection defaultConnection] setRootObject:nil];
[[NSConnection defaultConnection] invalidate];
#endif
}
- (void)selectTab:(int)index
{
//NSLog(@"%s%d", _cmd, index);
index -= 1;
NSData *data = [NSData dataWithBytes:&index length:sizeof(int)];
[self queueMessage:SelectTabMsgID data:data];
}
- (void)updateTabBar
{
//NSLog(@"%s", _cmd);
NSMutableData *data = [NSMutableData data];
int idx = tabpage_index(curtab) - 1;
[data appendBytes:&idx length:sizeof(int)];
tabpage_T *tp;
for (tp = first_tabpage; tp != NULL; tp = tp->tp_next) {
// Count the number of windows in the tabpage.
//win_T *wp = tp->tp_firstwin;
//int wincount;
//for (wincount = 0; wp != NULL; wp = wp->w_next, ++wincount);
//[data appendBytes:&wincount length:sizeof(int)];
int tabProp = MMTabInfoCount;
[data appendBytes:&tabProp length:sizeof(int)];
for (tabProp = MMTabLabel; tabProp < MMTabInfoCount; ++tabProp) {
// This function puts the label of the tab in the global 'NameBuff'.
get_tabline_label(tp, (tabProp == MMTabToolTip));
NSString *s = [NSString stringWithVimString:NameBuff];
int len = [s lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if (len < 0)
len = 0;
[data appendBytes:&len length:sizeof(int)];
if (len > 0)
[data appendBytes:[s UTF8String] length:len];
}
}
[self queueMessage:UpdateTabBarMsgID data:data];
}
- (BOOL)tabBarVisible
{
return tabBarVisible;
}
- (void)showTabBar:(BOOL)enable
{
tabBarVisible = enable;
int msgid = enable ? ShowTabBarMsgID : HideTabBarMsgID;
[self queueMessage:msgid data:nil];
}
- (void)setRows:(int)rows columns:(int)cols
{
//NSLog(@"[VimTask] setRows:%d columns:%d", rows, cols);
int dim[] = { rows, cols };
NSData *data = [NSData dataWithBytes:&dim length:2*sizeof(int)];
[self queueMessage:SetTextDimensionsMsgID data:data];
}
- (void)setWindowTitle:(char *)title
{
NSMutableData *data = [NSMutableData data];
int len = strlen(title);
if (len <= 0) return;
[data appendBytes:&len length:sizeof(int)];
[data appendBytes:title length:len];
[self queueMessage:SetWindowTitleMsgID data:data];
}
- (void)setDocumentFilename:(char *)filename
{
NSMutableData *data = [NSMutableData data];
int len = filename ? strlen(filename) : 0;
[data appendBytes:&len length:sizeof(int)];
if (len > 0)
[data appendBytes:filename length:len];
[self queueMessage:SetDocumentFilenameMsgID data:data];
}
- (char *)browseForFileWithAttributes:(NSDictionary *)attr
{
char_u *s = NULL;
[self queueMessage:BrowseForFileMsgID properties:attr];
[self flushQueue:YES];
@try {
[self waitForDialogReturn];
if (dialogReturn && [dialogReturn isKindOfClass:[NSString class]])
s = [dialogReturn vimStringSave];
[dialogReturn release]; dialogReturn = nil;
}
@catch (NSException *e) {
NSLog(@"[%s] Exception caught: \"%@\"", _cmd, e);
}
return (char *)s;
}
- (oneway void)setDialogReturn:(in bycopy id)obj
{
// NOTE: This is called by
// - [MMVimController panelDidEnd:::], and
// - [MMVimController alertDidEnd:::],
// to indicate that a save/open panel or alert has finished.
// We want to distinguish between "no dialog return yet" and "dialog
// returned nothing". The former can be tested with dialogReturn == nil,
// the latter with dialogReturn == [NSNull null].
if (!obj) obj = [NSNull null];
if (obj != dialogReturn) {
[dialogReturn release];
dialogReturn = [obj retain];
}
}
- (int)showDialogWithAttributes:(NSDictionary *)attr textField:(char *)txtfield
{
int retval = 0;
[self queueMessage:ShowDialogMsgID properties:attr];
[self flushQueue:YES];
@try {
[self waitForDialogReturn];
if (dialogReturn && [dialogReturn isKindOfClass:[NSArray class]]
&& [dialogReturn count]) {
retval = [[dialogReturn objectAtIndex:0] intValue];
if (txtfield && [dialogReturn count] > 1) {
NSString *retString = [dialogReturn objectAtIndex:1];
char_u *ret = (char_u*)[retString UTF8String];
#ifdef FEAT_MBYTE
ret = CONVERT_FROM_UTF8(ret);
#endif
vim_strncpy((char_u*)txtfield, ret, IOSIZE - 1);
#ifdef FEAT_MBYTE
CONVERT_FROM_UTF8_FREE(ret);
#endif
}
}
[dialogReturn release]; dialogReturn = nil;
}
@catch (NSException *e) {
NSLog(@"[%s] Exception caught: \"%@\"", _cmd, e);
}
return retval;
}
- (void)showToolbar:(int)enable flags:(int)flags
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&enable length:sizeof(int)];
[data appendBytes:&flags length:sizeof(int)];
[self queueMessage:ShowToolbarMsgID data:data];
}
- (void)createScrollbarWithIdentifier:(long)ident type:(int)type
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&ident length:sizeof(long)];
[data appendBytes:&type length:sizeof(int)];
[self queueMessage:CreateScrollbarMsgID data:data];
}
- (void)destroyScrollbarWithIdentifier:(long)ident
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&ident length:sizeof(long)];
[self queueMessage:DestroyScrollbarMsgID data:data];
}
- (void)showScrollbarWithIdentifier:(long)ident state:(int)visible
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&ident length:sizeof(long)];
[data appendBytes:&visible length:sizeof(int)];
[self queueMessage:ShowScrollbarMsgID data:data];
}
- (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&ident length:sizeof(long)];
[data appendBytes:&pos length:sizeof(int)];
[data appendBytes:&len length:sizeof(int)];
[self queueMessage:SetScrollbarPositionMsgID data:data];
}
- (void)setScrollbarThumbValue:(long)val size:(long)size max:(long)max
identifier:(long)ident
{
float fval = max-size+1 > 0 ? (float)val/(max-size+1) : 0;
float prop = (float)size/(max+1);
if (fval < 0) fval = 0;
else if (fval > 1.0f) fval = 1.0f;
if (prop < 0) prop = 0;
else if (prop > 1.0f) prop = 1.0f;
NSMutableData *data = [NSMutableData data];
[data appendBytes:&ident length:sizeof(long)];
[data appendBytes:&fval length:sizeof(float)];
[data appendBytes:&prop length:sizeof(float)];
[self queueMessage:SetScrollbarThumbMsgID data:data];
}
- (void)setFont:(GuiFont)font wide:(BOOL)wide
{
NSString *fontName = (NSString *)font;
float size = 0;
NSArray *components = [fontName componentsSeparatedByString:@":"];
if ([components count] == 2) {
size = [[components lastObject] floatValue];
fontName = [components objectAtIndex:0];
}
int len = [fontName lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *data = [NSMutableData data];
[data appendBytes:&size length:sizeof(float)];
[data appendBytes:&len length:sizeof(int)];
if (len > 0)
[data appendBytes:[fontName UTF8String] length:len];
else if (!wide)
return; // Only the wide font can be set to nothing
[self queueMessage:(wide ? SetWideFontMsgID : SetFontMsgID) data:data];
}
- (void)executeActionWithName:(NSString *)name
{
int len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if (len > 0) {
NSMutableData *data = [NSMutableData data];
[data appendBytes:&len length:sizeof(int)];
[data appendBytes:[name UTF8String] length:len];
[self queueMessage:ExecuteActionMsgID data:data];
}
}
- (void)setMouseShape:(int)shape
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&shape length:sizeof(int)];
[self queueMessage:SetMouseShapeMsgID data:data];
}
- (void)setBlinkWait:(int)wait on:(int)on off:(int)off
{
// Vim specifies times in milliseconds, whereas Cocoa wants them in
// seconds.
blinkWaitInterval = .001f*wait;
blinkOnInterval = .001f*on;
blinkOffInterval = .001f*off;
}
- (void)startBlink
{
if (blinkTimer) {
[blinkTimer invalidate];
[blinkTimer release];
blinkTimer = nil;
}
if (blinkWaitInterval > 0 && blinkOnInterval > 0 && blinkOffInterval > 0
&& gui.in_focus) {
blinkState = MMBlinkStateOn;
blinkTimer =
[[NSTimer scheduledTimerWithTimeInterval:blinkWaitInterval
target:self
selector:@selector(blinkTimerFired:)
userInfo:nil repeats:NO] retain];
gui_update_cursor(TRUE, FALSE);
[self flushQueue:YES];
}
}
- (void)stopBlink
{
if (MMBlinkStateOff == blinkState) {
gui_update_cursor(TRUE, FALSE);
[self flushQueue:YES];
}
blinkState = MMBlinkStateNone;
}
- (void)adjustLinespace:(int)linespace
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&linespace length:sizeof(int)];
[self queueMessage:AdjustLinespaceMsgID data:data];
}
- (void)activate
{
[self queueMessage:ActivateMsgID data:nil];
}
- (void)setPreEditRow:(int)row column:(int)col
{
NSMutableData *data = [NSMutableData data];
[data appendBytes:&row length:sizeof(int)];
[data appendBytes:&col length:sizeof(int)];
[self queueMessage:SetPreEditPositionMsgID data:data];
}
- (int)lookupColorWithKey:(NSString *)key
{
if (!(key && [key length] > 0))
return INVALCOLOR;
NSString *stripKey = [[[[key lowercaseString]
stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
componentsSeparatedByString:@" "]
componentsJoinedByString:@""];
if (stripKey && [stripKey length] > 0) {
// First of all try to lookup key in the color dictionary; note that
// all keys in this dictionary are lowercase with no whitespace.
id obj = [colorDict objectForKey:stripKey];
if (obj) return [obj intValue];
// The key was not in the dictionary; is it perhaps of the form
// #rrggbb?
if ([stripKey length] > 1 && [stripKey characterAtIndex:0] == '#') {
NSScanner *scanner = [NSScanner scannerWithString:stripKey];
[scanner setScanLocation:1];
unsigned hex = 0;
if ([scanner scanHexInt:&hex]) {
return (int)hex;
}
}
// As a last resort, check if it is one of the system defined colors.
// The keys in this dictionary are also lowercase with no whitespace.
obj = [sysColorDict objectForKey:stripKey];
if (obj) {
NSColor *col = [NSColor performSelector:NSSelectorFromString(obj)];
if (col) {
float r, g, b, a;
col = [col colorUsingColorSpaceName:NSCalibratedRGBColorSpace];
[col getRed:&r green:&g blue:&b alpha:&a];
return (((int)(r*255+.5f) & 0xff) << 16)
+ (((int)(g*255+.5f) & 0xff) << 8)
+ ((int)(b*255+.5f) & 0xff);
}
}
}
//NSLog(@"WARNING: No color with key %@ found.", stripKey);
return INVALCOLOR;
}
- (BOOL)hasSpecialKeyWithValue:(NSString *)value
{
NSEnumerator *e = [[MMBackend specialKeys] objectEnumerator];
id obj;
while ((obj = [e nextObject])) {
if ([value isEqual:obj])
return YES;
}
return NO;
}