1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
6 * Do ":help uganda" in Vim to read copying and usage conditions.
7 * Do ":help credits" in Vim to see a list of people who contributed.
8 * See README.txt for an overview of the Vim source code.
13 * Contains code shared between the different text renderers. Unfortunately it
14 * is not possible to let the text renderers inherit from this class since
15 * MMTextView needs to inherit from NSTextView whereas MMAtsuiTextView needs to
16 * inherit from NSView.
19 #import "MMTextView.h"
20 #import "MMTextViewHelper.h"
21 #import "MMVimController.h"
22 #import "MMWindowController.h"
23 #import "Miscellaneous.h"
26 static char MMKeypadEnter[2] = { 'K', 'A' };
27 static NSString *MMKeypadEnterString = @"KA";
29 // The max/min drag timer interval in seconds
30 static NSTimeInterval MMDragTimerMaxInterval = 0.3;
31 static NSTimeInterval MMDragTimerMinInterval = 0.01;
33 // The number of pixels in which the drag timer interval changes
34 static float MMDragAreaSize = 73.0f;
37 @interface MMTextViewHelper (Private)
38 - (MMWindowController *)windowController;
39 - (MMVimController *)vimController;
40 - (void)dispatchKeyEvent:(NSEvent *)event;
41 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
42 - (void)hideMouseCursor;
43 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
44 - (void)dragTimerFired:(NSTimer *)timer;
46 - (NSRect)trackingRect;
50 @implementation MMTextViewHelper
52 - (void)setTextView:(id)view
54 // Only keep a weak reference to owning text view.
58 - (void)keyDown:(NSEvent *)event
60 //NSLog(@"%s %@", _cmd, event);
61 // HACK! If control modifier is held, don't pass the event along to
62 // interpretKeyEvents: since some keys are bound to multiple commands which
63 // means doCommandBySelector: is called several times. Do the same for
64 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
65 // commands). This hack may break input management, but unless we can
66 // figure out a way to disable key bindings there seems little else to do.
68 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
69 // affecting input management.
71 // When the Input Method is activated, some special key inputs
72 // should be treated as key inputs for Input Method.
73 if ([textView hasMarkedText]) {
74 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
75 [textView setNeedsDisplay:YES];
79 int flags = [event modifierFlags];
80 if ((flags & NSControlKeyMask) ||
81 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
82 NSString *unmod = [event charactersIgnoringModifiers];
83 if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
84 && [unmod characterAtIndex:0] >= 0x60) {
85 // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
86 // as normal text to be added to the Vim input buffer. This must
87 // be done in order for the backend to be able to separate e.g.
88 // Ctrl-i and Ctrl-tab.
89 [self insertText:[event characters]];
91 [self dispatchKeyEvent:event];
94 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
98 - (void)insertText:(id)string
100 //NSLog(@"%s %@", _cmd, string);
101 // NOTE! This method is called for normal key presses but also for
102 // Option-key presses --- even when Ctrl is held as well as Option. When
103 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
104 // so 'string' need not be a printable character! In this case it still
105 // works to pass 'string' on to Vim as a printable character (since
106 // modifiers are already included and should not be added to the input
107 // buffer using CSI, K_MODIFIER).
109 if ([textView hasMarkedText]) {
110 [textView unmarkText];
113 NSEvent *event = [NSApp currentEvent];
115 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
116 // to watch for them here.
117 if ([event type] == NSKeyDown
118 && [[event charactersIgnoringModifiers] length] > 0
119 && [event modifierFlags]
120 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
121 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
123 // <S-M-Tab> translates to 0x19
124 if (' ' == c || 0x19 == c) {
125 [self dispatchKeyEvent:event];
130 [self hideMouseCursor];
132 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
133 // do not support attributes, simply pass the corresponding NSString in the
135 if ([string isKindOfClass:[NSAttributedString class]])
136 string = [string string];
138 //NSLog(@"send InsertTextMsgID: %@", string);
140 [[self vimController] sendMessage:InsertTextMsgID
141 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
144 - (void)doCommandBySelector:(SEL)selector
146 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
147 // By ignoring the selector we effectively disable the key binding
148 // mechanism of Cocoa. Hopefully this is what the user will expect
149 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
152 // We usually end up here if the user pressed Ctrl+key (but not
155 NSEvent *event = [NSApp currentEvent];
157 if (selector == @selector(cancelOperation:)
158 || selector == @selector(insertNewline:)) {
159 // HACK! If there was marked text which got abandoned as a result of
160 // hitting escape or enter, then 'insertText:' is called with the
161 // abandoned text but '[event characters]' includes the abandoned text
162 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
163 // must intercept these keys here or the abandonded text gets inserted
165 NSString *key = [event charactersIgnoringModifiers];
166 const char *chars = [key UTF8String];
167 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
169 if (0x3 == chars[0]) {
170 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
171 // handle it separately (else Ctrl-C doesn't work).
172 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
173 chars = MMKeypadEnter;
176 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
178 [self dispatchKeyEvent:event];
182 - (BOOL)performKeyEquivalent:(NSEvent *)event
184 //NSLog(@"%s %@", _cmd, event);
185 // Called for Cmd+key keystrokes, function keys, arrow keys, page
186 // up/down, home, end.
188 // NOTE: This message cannot be ignored since Cmd+letter keys never are
189 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
190 // strokes, unless the key is a function key.
192 // NOTE: If the event that triggered this method represents a function key
193 // down then we do nothing, otherwise the input method never gets the key
194 // stroke (some input methods use e.g. arrow keys). The function key down
195 // event will still reach Vim though (via keyDown:). The exceptions to
196 // this rule are: PageUp/PageDown (keycode 116/121).
197 int flags = [event modifierFlags];
198 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
199 && !(116 == [event keyCode] || 121 == [event keyCode]))
202 // HACK! KeyCode 50 represent the key which switches between windows
203 // within an application (like Cmd+Tab is used to switch between
204 // applications). Return NO here, else the window switching does not work.
205 if ([event keyCode] == 50)
208 // HACK! Let the main menu try to handle any key down event, before
209 // passing it on to vim, otherwise key equivalents for menus will
210 // effectively be disabled.
211 if ([[NSApp mainMenu] performKeyEquivalent:event])
214 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
215 if (flags & NSControlKeyMask) {
216 [self keyDown:event];
220 // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard.
221 NSString *unmodchars = [event charactersIgnoringModifiers];
222 if ([unmodchars isEqual:@"?"])
225 // Cmd-. is hard-wired to send an interrupt (like Ctrl-C).
226 if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
227 [unmodchars isEqual:@"."]) {
228 [[self vimController] sendMessage:InterruptMsgID data:nil];
232 //NSLog(@"%s%@", _cmd, event);
234 NSString *chars = [event characters];
235 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
236 NSMutableData *data = [NSMutableData data];
241 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
242 // can clear the shift flag as it is already included in 'unmodchars'.
243 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
244 // an English keyboard).
245 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
246 flags &= ~NSShiftKeyMask;
248 if (0x3 == [unmodchars characterAtIndex:0]) {
249 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
250 // handle it separately (else Cmd-enter turns into Ctrl-C).
251 unmodchars = MMKeypadEnterString;
252 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
255 [data appendBytes:&flags length:sizeof(int)];
256 [data appendBytes:&len length:sizeof(int)];
257 [data appendBytes:[unmodchars UTF8String] length:len];
259 [[self vimController] sendMessage:CmdKeyMsgID data:data];
264 - (void)scrollWheel:(NSEvent *)event
266 if ([event deltaY] == 0)
270 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
271 if ([textView convertPoint:pt toRow:&row column:&col]) {
272 int flags = [event modifierFlags];
273 float dy = [event deltaY];
274 NSMutableData *data = [NSMutableData data];
276 [data appendBytes:&row length:sizeof(int)];
277 [data appendBytes:&col length:sizeof(int)];
278 [data appendBytes:&flags length:sizeof(int)];
279 [data appendBytes:&dy length:sizeof(float)];
281 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
285 - (void)mouseDown:(NSEvent *)event
288 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
289 if (![textView convertPoint:pt toRow:&row column:&col])
292 int button = [event buttonNumber];
293 int flags = [event modifierFlags];
294 int count = [event clickCount];
295 NSMutableData *data = [NSMutableData data];
297 // If desired, intepret Ctrl-Click as a right mouse click.
298 BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
299 boolForKey:MMTranslateCtrlClickKey];
300 flags = flags & NSDeviceIndependentModifierFlagsMask;
301 if (translateCtrlClick && button == 0 &&
302 (flags == NSControlKeyMask ||
303 flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
305 flags &= ~NSControlKeyMask;
308 [data appendBytes:&row length:sizeof(int)];
309 [data appendBytes:&col length:sizeof(int)];
310 [data appendBytes:&button length:sizeof(int)];
311 [data appendBytes:&flags length:sizeof(int)];
312 [data appendBytes:&count length:sizeof(int)];
314 [[self vimController] sendMessage:MouseDownMsgID data:data];
317 - (void)mouseUp:(NSEvent *)event
320 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
321 if (![textView convertPoint:pt toRow:&row column:&col])
324 int flags = [event modifierFlags];
325 NSMutableData *data = [NSMutableData data];
327 [data appendBytes:&row length:sizeof(int)];
328 [data appendBytes:&col length:sizeof(int)];
329 [data appendBytes:&flags length:sizeof(int)];
331 [[self vimController] sendMessage:MouseUpMsgID data:data];
336 - (void)mouseDragged:(NSEvent *)event
338 int flags = [event modifierFlags];
340 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
341 if (![textView convertPoint:pt toRow:&row column:&col])
344 // Autoscrolling is done in dragTimerFired:
345 if (!isAutoscrolling) {
346 NSMutableData *data = [NSMutableData data];
348 [data appendBytes:&row length:sizeof(int)];
349 [data appendBytes:&col length:sizeof(int)];
350 [data appendBytes:&flags length:sizeof(int)];
352 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
361 [self startDragTimerWithInterval:.5];
366 - (void)mouseMoved:(NSEvent *)event
368 // HACK! NSTextView has a nasty habit of resetting the cursor to the
369 // default I-beam cursor at random moments. The only reliable way we know
370 // of to work around this is to set the cursor each time the mouse moves.
373 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
375 if (![textView convertPoint:pt toRow:&row column:&col])
378 // HACK! It seems impossible to get the tracking rects set up before the
379 // view is visible, which means that the first mouseEntered: or
380 // mouseExited: events are never received. This forces us to check if the
381 // mouseMoved: event really happened over the text.
383 [textView getMaxRows:&rows columns:&cols];
384 if (row >= 0 && row < rows && col >= 0 && col < cols) {
385 NSMutableData *data = [NSMutableData data];
387 [data appendBytes:&row length:sizeof(int)];
388 [data appendBytes:&col length:sizeof(int)];
390 [[self vimController] sendMessage:MouseMovedMsgID data:data];
392 //NSLog(@"Moved %d %d\n", col, row);
396 - (void)mouseEntered:(NSEvent *)event
398 //NSLog(@"%s", _cmd);
400 // NOTE: This event is received even when the window is not key; thus we
401 // have to take care not to enable mouse moved events unless our window is
403 if ([[textView window] isKeyWindow]) {
404 [[textView window] setAcceptsMouseMovedEvents:YES];
408 - (void)mouseExited:(NSEvent *)event
410 //NSLog(@"%s", _cmd);
412 [[textView window] setAcceptsMouseMovedEvents:NO];
414 // NOTE: This event is received even when the window is not key; if the
415 // mouse shape is set when our window is not key, the hollow (unfocused)
416 // cursor will become a block (focused) cursor.
417 if ([[textView window] isKeyWindow]) {
419 NSMutableData *data = [NSMutableData data];
420 [data appendBytes:&shape length:sizeof(int)];
421 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
425 - (void)setFrame:(NSRect)frame
427 //NSLog(@"%s", _cmd);
429 // When the frame changes we also need to update the tracking rect.
430 [textView removeTrackingRect:trackingRectTag];
431 trackingRectTag = [textView addTrackingRect:[self trackingRect]
437 - (void)viewDidMoveToWindow
439 //NSLog(@"%s (window=%@)", _cmd, [self window]);
441 // Set a tracking rect which covers the text.
442 // NOTE: While the mouse cursor is in this rect the view will receive
443 // 'mouseMoved:' events so that Vim can take care of updating the mouse
445 if ([textView window]) {
446 [[textView window] setAcceptsMouseMovedEvents:YES];
447 trackingRectTag = [textView addTrackingRect:[self trackingRect]
454 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
456 //NSLog(@"%s%@", _cmd, newWindow);
458 // Remove tracking rect if view moves or is removed.
459 if ([textView window] && trackingRectTag) {
460 [textView removeTrackingRect:trackingRectTag];
465 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
467 NSPasteboard *pboard = [sender draggingPasteboard];
469 if ([[pboard types] containsObject:NSStringPboardType]) {
470 NSString *string = [pboard stringForType:NSStringPboardType];
471 [[self vimController] dropString:string];
473 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
474 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
475 [[self vimController] dropFiles:files forceOpen:NO];
482 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
484 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
485 NSPasteboard *pboard = [sender draggingPasteboard];
487 if ( [[pboard types] containsObject:NSFilenamesPboardType]
488 && (sourceDragMask & NSDragOperationCopy) )
489 return NSDragOperationCopy;
490 if ( [[pboard types] containsObject:NSStringPboardType]
491 && (sourceDragMask & NSDragOperationCopy) )
492 return NSDragOperationCopy;
494 return NSDragOperationNone;
497 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
499 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
500 NSPasteboard *pboard = [sender draggingPasteboard];
502 if ( [[pboard types] containsObject:NSFilenamesPboardType]
503 && (sourceDragMask & NSDragOperationCopy) )
504 return NSDragOperationCopy;
505 if ( [[pboard types] containsObject:NSStringPboardType]
506 && (sourceDragMask & NSDragOperationCopy) )
507 return NSDragOperationCopy;
509 return NSDragOperationNone;
512 - (void)setMouseShape:(int)shape
518 @end // MMTextViewHelper
523 @implementation MMTextViewHelper (Private)
525 - (MMWindowController *)windowController
527 id windowController = [[textView window] windowController];
528 if ([windowController isKindOfClass:[MMWindowController class]])
529 return (MMWindowController*)windowController;
533 - (MMVimController *)vimController
535 return [[self windowController] vimController];
538 - (void)dispatchKeyEvent:(NSEvent *)event
540 // Only handle the command if it came from a keyDown event
541 if ([event type] != NSKeyDown)
544 NSString *chars = [event characters];
545 NSString *unmodchars = [event charactersIgnoringModifiers];
546 unichar c = [chars characterAtIndex:0];
547 unichar imc = [unmodchars characterAtIndex:0];
549 const char *bytes = 0;
550 int mods = [event modifierFlags];
552 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
553 // _cmd, c, imc, chars, unmodchars);
555 if (' ' == imc && 0xa0 != c) {
556 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
557 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
558 // should be passed on as is.)
559 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
560 bytes = [unmodchars UTF8String];
561 } else if (imc == c && '2' == c) {
562 // HACK! Translate Ctrl+2 to <C-@>.
563 static char ctrl_at = 0;
564 len = 1; bytes = &ctrl_at;
565 } else if (imc == c && '6' == c) {
566 // HACK! Translate Ctrl+6 to <C-^>.
567 static char ctrl_hat = 0x1e;
568 len = 1; bytes = &ctrl_hat;
569 } else if (c == 0x19 && imc == 0x19) {
570 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
571 // separately (else Ctrl-Y doesn't work).
572 static char tab = 0x9;
573 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
575 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
576 bytes = [chars UTF8String];
579 [self sendKeyDown:bytes length:len modifiers:mods];
582 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
584 if (chars && len > 0) {
585 NSMutableData *data = [NSMutableData data];
587 [data appendBytes:&flags length:sizeof(int)];
588 [data appendBytes:&len length:sizeof(int)];
589 [data appendBytes:chars length:len];
591 [self hideMouseCursor];
593 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
594 [[self vimController] sendMessage:KeyDownMsgID data:data];
598 - (void)hideMouseCursor
600 // Check 'mousehide' option
601 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
602 if (mh && ![mh boolValue])
603 [NSCursor setHiddenUntilMouseMoves:NO];
605 [NSCursor setHiddenUntilMouseMoves:YES];
608 - (void)startDragTimerWithInterval:(NSTimeInterval)t
610 [NSTimer scheduledTimerWithTimeInterval:t target:self
611 selector:@selector(dragTimerFired:)
612 userInfo:nil repeats:NO];
615 - (void)dragTimerFired:(NSTimer *)timer
617 // TODO: Autoscroll in horizontal direction?
618 static unsigned tick = 1;
620 isAutoscrolling = NO;
622 if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
623 // HACK! If the mouse cursor is outside the text area, then send a
624 // dragged event. However, if row&col hasn't changed since the last
625 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
626 // Thus we fiddle with the column to make sure something happens.
627 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
628 NSMutableData *data = [NSMutableData data];
630 [data appendBytes:&dragRow length:sizeof(int)];
631 [data appendBytes:&col length:sizeof(int)];
632 [data appendBytes:&dragFlags length:sizeof(int)];
634 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
636 isAutoscrolling = YES;
640 // Compute timer interval depending on how far away the mouse cursor is
641 // from the text view.
642 NSRect rect = [self trackingRect];
644 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
645 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
646 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
648 NSTimeInterval t = MMDragTimerMaxInterval -
649 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
651 [self startDragTimerWithInterval:t];
659 static NSCursor *customIbeamCursor = nil;
661 if (!customIbeamCursor) {
662 // Use a custom Ibeam cursor that has better contrast against dark
664 // TODO: Is the hotspot ok?
665 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
667 NSSize size = [ibeamImage size];
668 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
670 customIbeamCursor = [[NSCursor alloc]
671 initWithImage:ibeamImage hotSpot:hotSpot];
673 if (!customIbeamCursor) {
674 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
675 customIbeamCursor = [NSCursor IBeamCursor];
679 // This switch should match mshape_names[] in misc2.c.
681 // TODO: Add missing cursor shapes.
682 switch (mouseShape) {
683 case 2: [customIbeamCursor set]; break;
684 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
685 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
686 case 9: [[NSCursor crosshairCursor] set]; break;
687 case 10: [[NSCursor pointingHandCursor] set]; break;
688 case 11: [[NSCursor openHandCursor] set]; break;
690 [[NSCursor arrowCursor] set]; break;
693 // Shape 1 indicates that the mouse cursor should be hidden.
695 [NSCursor setHiddenUntilMouseMoves:YES];
698 - (NSRect)trackingRect
700 NSRect rect = [textView frame];
701 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
702 int left = [ud integerForKey:MMTextInsetLeftKey];
703 int top = [ud integerForKey:MMTextInsetTopKey];
704 int right = [ud integerForKey:MMTextInsetRightKey];
705 int bot = [ud integerForKey:MMTextInsetBottomKey];
707 rect.origin.x = left;
709 rect.size.width -= left + right - 1;
710 rect.size.height -= top + bot - 1;
715 @end // MMTextViewHelper (Private)