Don't drop non-repeating keyboard input
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blob6142b11082e4c524f3c1375ef1f6e80630958683
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
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.
9  */
11  * MMTextViewHelper
12  *
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.
17  */
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           isARepeat:(BOOL)isARepeat;
43 - (void)hideMouseCursor;
44 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
45 - (void)dragTimerFired:(NSTimer *)timer;
46 - (void)setCursor;
47 - (NSRect)trackingRect;
48 @end
51 @implementation MMTextViewHelper
53 - (void)dealloc
55     [markedText release];  markedText = nil;
57     [super dealloc];
60 - (void)setTextView:(id)view
62     // Only keep a weak reference to owning text view.
63     textView = view;
66 - (void)setInsertionPointColor:(NSColor *)color
68     if (color != insertionPointColor) {
69         [insertionPointColor release];
70         insertionPointColor = [color retain];
71     }
74 - (NSColor *)insertionPointColor
76     return insertionPointColor;
79 - (void)keyDown:(NSEvent *)event
81     //NSLog(@"%s %@", _cmd, event);
82     // HACK! If control modifier is held, don't pass the event along to
83     // interpretKeyEvents: since some keys are bound to multiple commands which
84     // means doCommandBySelector: is called several times.  Do the same for
85     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
86     // commands).  This hack may break input management, but unless we can
87     // figure out a way to disable key bindings there seems little else to do.
88     //
89     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
90     // affecting input management.
92     // When the Input Method is activated, some special key inputs
93     // should be treated as key inputs for Input Method.
94     if ([textView hasMarkedText]) {
95         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
96         [textView setNeedsDisplay:YES];
97         return;
98     }
100     int flags = [event modifierFlags];
101     if ((flags & NSControlKeyMask) ||
102             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
103         NSString *unmod = [event charactersIgnoringModifiers];
104         if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
105                                 && [unmod characterAtIndex:0] >= 0x60) {
106             // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
107             // as normal text to be added to the Vim input buffer.  This must
108             // be done in order for the backend to be able to separate e.g.
109             // Ctrl-i and Ctrl-tab.
110             [self insertText:[event characters]];
111         } else {
112             [self dispatchKeyEvent:event];
113         }
114     } else {
115         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
116     }
119 - (void)insertText:(id)string
121     //NSLog(@"%s %@", _cmd, string);
122     // NOTE!  This method is called for normal key presses but also for
123     // Option-key presses --- even when Ctrl is held as well as Option.  When
124     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
125     // so 'string' need not be a printable character!  In this case it still
126     // works to pass 'string' on to Vim as a printable character (since
127     // modifiers are already included and should not be added to the input
128     // buffer using CSI, K_MODIFIER).
130     if ([textView hasMarkedText]) {
131         [textView unmarkText];
132     }
134     NSEvent *event = [NSApp currentEvent];
136     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
137     // to watch for them here.
138     if ([event type] == NSKeyDown
139             && [[event charactersIgnoringModifiers] length] > 0
140             && [event modifierFlags]
141                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
142         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
144         // <S-M-Tab> translates to 0x19 
145         if (' ' == c || 0x19 == c) {
146             [self dispatchKeyEvent:event];
147             return;
148         }
149     }
151     [self hideMouseCursor];
153     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
154     // do not support attributes, simply pass the corresponding NSString in the
155     // latter case.
156     if ([string isKindOfClass:[NSAttributedString class]])
157         string = [string string];
159     //NSLog(@"send InsertTextMsgID: %@", string);
161     NSMutableData *data = [NSMutableData data];
162     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
163     int flags = [event modifierFlags] & 0xffff0000U;
164     if ([event isARepeat])
165         flags |= 1;
167     [data appendBytes:&flags length:sizeof(int)];
168     [data appendBytes:&len length:sizeof(int)];
169     [data appendBytes:[string UTF8String] length:len];
171     [[self vimController] sendMessage:InsertTextMsgID data:data];
174 - (void)doCommandBySelector:(SEL)selector
176     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
177     // By ignoring the selector we effectively disable the key binding
178     // mechanism of Cocoa.  Hopefully this is what the user will expect
179     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
180     // match, etc.).
181     //
182     // We usually end up here if the user pressed Ctrl+key (but not
183     // Ctrl+Option+key).
185     NSEvent *event = [NSApp currentEvent];
187     if (selector == @selector(cancelOperation:)
188             || selector == @selector(insertNewline:)) {
189         // HACK! If there was marked text which got abandoned as a result of
190         // hitting escape or enter, then 'insertText:' is called with the
191         // abandoned text but '[event characters]' includes the abandoned text
192         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
193         // must intercept these keys here or the abandonded text gets inserted
194         // twice.
195         NSString *key = [event charactersIgnoringModifiers];
196         const char *chars = [key UTF8String];
197         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
199         if (0x3 == chars[0]) {
200             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
201             // handle it separately (else Ctrl-C doesn't work).
202             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
203             chars = MMKeypadEnter;
204         }
206         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]
207                 isARepeat:[event isARepeat]];
208     } else {
209         [self dispatchKeyEvent:event];
210     }
213 - (BOOL)performKeyEquivalent:(NSEvent *)event
215     //NSLog(@"%s %@", _cmd, event);
216     // Called for Cmd+key keystrokes, function keys, arrow keys, page
217     // up/down, home, end.
218     //
219     // NOTE: This message cannot be ignored since Cmd+letter keys never are
220     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
221     // strokes, unless the key is a function key.
223     // NOTE: If the event that triggered this method represents a function key
224     // down then we do nothing, otherwise the input method never gets the key
225     // stroke (some input methods use e.g. arrow keys).  The function key down
226     // event will still reach Vim though (via keyDown:).  The exceptions to
227     // this rule are: PageUp/PageDown (keycode 116/121).
228     int flags = [event modifierFlags] & 0xffff0000U;
229     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
230             && !(116 == [event keyCode] || 121 == [event keyCode]))
231         return NO;
233     // HACK!  KeyCode 50 represent the key which switches between windows
234     // within an application (like Cmd+Tab is used to switch between
235     // applications).  Return NO here, else the window switching does not work.
236     if ([event keyCode] == 50)
237         return NO;
239     // HACK!  Let the main menu try to handle any key down event, before
240     // passing it on to vim, otherwise key equivalents for menus will
241     // effectively be disabled.
242     if ([[NSApp mainMenu] performKeyEquivalent:event])
243         return YES;
245     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
246     if (flags & NSControlKeyMask) {
247         [self keyDown:event];
248         return YES;
249     }
251     // HACK!  Don't handle Cmd-? or the "Help" menu does not work on Leopard.
252     NSString *unmodchars = [event charactersIgnoringModifiers];
253     if ([unmodchars isEqual:@"?"])
254         return NO;
256     // Cmd-. is hard-wired to send an interrupt (like Ctrl-C).
257     if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
258             [unmodchars isEqual:@"."]) {
259         [[self vimController] sendMessage:InterruptMsgID data:nil];
260         return YES;
261     }
263     //NSLog(@"%s%@", _cmd, event);
265     NSString *chars = [event characters];
266     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
267     NSMutableData *data = [NSMutableData data];
269     if (len <= 0)
270         return NO;
272     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
273     // can clear the shift flag as it is already included in 'unmodchars'.
274     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
275     // an English keyboard).
276     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
277         flags &= ~NSShiftKeyMask;
279     if (0x3 == [unmodchars characterAtIndex:0]) {
280         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
281         // handle it separately (else Cmd-enter turns into Ctrl-C).
282         unmodchars = MMKeypadEnterString;
283         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
284     }
286     if ([event isARepeat])
287         flags |= 1;
289     [data appendBytes:&flags length:sizeof(int)];
290     [data appendBytes:&len length:sizeof(int)];
291     [data appendBytes:[unmodchars UTF8String] length:len];
293     [[self vimController] sendMessage:CmdKeyMsgID data:data];
295     return YES;
298 - (void)scrollWheel:(NSEvent *)event
300     if ([event deltaY] == 0)
301         return;
303     int row, col;
304     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
305     if ([textView convertPoint:pt toRow:&row column:&col]) {
306         int flags = [event modifierFlags];
307         float dy = [event deltaY];
308         NSMutableData *data = [NSMutableData data];
310         [data appendBytes:&row length:sizeof(int)];
311         [data appendBytes:&col length:sizeof(int)];
312         [data appendBytes:&flags length:sizeof(int)];
313         [data appendBytes:&dy length:sizeof(float)];
315         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
316     }
319 - (void)mouseDown:(NSEvent *)event
321     int row, col;
322     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
323     if (![textView convertPoint:pt toRow:&row column:&col])
324         return;
326     int button = [event buttonNumber];
327     int flags = [event modifierFlags];
328     int count = [event clickCount];
329     NSMutableData *data = [NSMutableData data];
331     // If desired, intepret Ctrl-Click as a right mouse click.
332     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
333             boolForKey:MMTranslateCtrlClickKey];
334     flags = flags & NSDeviceIndependentModifierFlagsMask;
335     if (translateCtrlClick && button == 0 &&
336             (flags == NSControlKeyMask ||
337              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
338         button = 1;
339         flags &= ~NSControlKeyMask;
340     }
342     [data appendBytes:&row length:sizeof(int)];
343     [data appendBytes:&col length:sizeof(int)];
344     [data appendBytes:&button length:sizeof(int)];
345     [data appendBytes:&flags length:sizeof(int)];
346     [data appendBytes:&count length:sizeof(int)];
348     [[self vimController] sendMessage:MouseDownMsgID data:data];
351 - (void)mouseUp:(NSEvent *)event
353     int row, col;
354     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
355     if (![textView convertPoint:pt toRow:&row column:&col])
356         return;
358     int flags = [event modifierFlags];
359     NSMutableData *data = [NSMutableData data];
361     [data appendBytes:&row length:sizeof(int)];
362     [data appendBytes:&col length:sizeof(int)];
363     [data appendBytes:&flags length:sizeof(int)];
365     [[self vimController] sendMessage:MouseUpMsgID data:data];
367     isDragging = NO;
370 - (void)mouseDragged:(NSEvent *)event
372     int flags = [event modifierFlags];
373     int row, col;
374     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
375     if (![textView convertPoint:pt toRow:&row column:&col])
376         return;
378     // Autoscrolling is done in dragTimerFired:
379     if (!isAutoscrolling) {
380         NSMutableData *data = [NSMutableData data];
382         [data appendBytes:&row length:sizeof(int)];
383         [data appendBytes:&col length:sizeof(int)];
384         [data appendBytes:&flags length:sizeof(int)];
386         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
387     }
389     dragPoint = pt;
390     dragRow = row;
391     dragColumn = col;
392     dragFlags = flags;
394     if (!isDragging) {
395         [self startDragTimerWithInterval:.5];
396         isDragging = YES;
397     }
400 - (void)mouseMoved:(NSEvent *)event
402     // HACK! NSTextView has a nasty habit of resetting the cursor to the
403     // default I-beam cursor at random moments.  The only reliable way we know
404     // of to work around this is to set the cursor each time the mouse moves.
405     [self setCursor];
407     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
408     int row, col;
409     if (![textView convertPoint:pt toRow:&row column:&col])
410         return;
412     // HACK! It seems impossible to get the tracking rects set up before the
413     // view is visible, which means that the first mouseEntered: or
414     // mouseExited: events are never received.  This forces us to check if the
415     // mouseMoved: event really happened over the text.
416     int rows, cols;
417     [textView getMaxRows:&rows columns:&cols];
418     if (row >= 0 && row < rows && col >= 0 && col < cols) {
419         NSMutableData *data = [NSMutableData data];
421         [data appendBytes:&row length:sizeof(int)];
422         [data appendBytes:&col length:sizeof(int)];
424         [[self vimController] sendMessage:MouseMovedMsgID data:data];
426         //NSLog(@"Moved %d %d\n", col, row);
427     }
430 - (void)mouseEntered:(NSEvent *)event
432     //NSLog(@"%s", _cmd);
434     // NOTE: This event is received even when the window is not key; thus we
435     // have to take care not to enable mouse moved events unless our window is
436     // key.
437     if ([[textView window] isKeyWindow]) {
438         [[textView window] setAcceptsMouseMovedEvents:YES];
439     }
442 - (void)mouseExited:(NSEvent *)event
444     //NSLog(@"%s", _cmd);
446     [[textView window] setAcceptsMouseMovedEvents:NO];
448     // NOTE: This event is received even when the window is not key; if the
449     // mouse shape is set when our window is not key, the hollow (unfocused)
450     // cursor will become a block (focused) cursor.
451     if ([[textView window] isKeyWindow]) {
452         int shape = 0;
453         NSMutableData *data = [NSMutableData data];
454         [data appendBytes:&shape length:sizeof(int)];
455         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
456     }
459 - (void)setFrame:(NSRect)frame
461     //NSLog(@"%s", _cmd);
463     // When the frame changes we also need to update the tracking rect.
464     [textView removeTrackingRect:trackingRectTag];
465     trackingRectTag = [textView addTrackingRect:[self trackingRect]
466                                           owner:textView
467                                        userData:NULL
468                                    assumeInside:YES];
471 - (void)viewDidMoveToWindow
473     //NSLog(@"%s (window=%@)", _cmd, [self window]);
475     // Set a tracking rect which covers the text.
476     // NOTE: While the mouse cursor is in this rect the view will receive
477     // 'mouseMoved:' events so that Vim can take care of updating the mouse
478     // cursor.
479     if ([textView window]) {
480         [[textView window] setAcceptsMouseMovedEvents:YES];
481         trackingRectTag = [textView addTrackingRect:[self trackingRect]
482                                               owner:textView
483                                            userData:NULL
484                                        assumeInside:YES];
485     }
488 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
490     //NSLog(@"%s%@", _cmd, newWindow);
492     // Remove tracking rect if view moves or is removed.
493     if ([textView window] && trackingRectTag) {
494         [textView removeTrackingRect:trackingRectTag];
495         trackingRectTag = 0;
496     }
499 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
501     NSPasteboard *pboard = [sender draggingPasteboard];
503     if ([[pboard types] containsObject:NSStringPboardType]) {
504         NSString *string = [pboard stringForType:NSStringPboardType];
505         [[self vimController] dropString:string];
506         return YES;
507     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
508         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
509         [[self vimController] dropFiles:files forceOpen:NO];
510         return YES;
511     }
513     return NO;
516 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
518     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
519     NSPasteboard *pboard = [sender draggingPasteboard];
521     if ( [[pboard types] containsObject:NSFilenamesPboardType]
522             && (sourceDragMask & NSDragOperationCopy) )
523         return NSDragOperationCopy;
524     if ( [[pboard types] containsObject:NSStringPboardType]
525             && (sourceDragMask & NSDragOperationCopy) )
526         return NSDragOperationCopy;
528     return NSDragOperationNone;
531 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
533     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
534     NSPasteboard *pboard = [sender draggingPasteboard];
536     if ( [[pboard types] containsObject:NSFilenamesPboardType]
537             && (sourceDragMask & NSDragOperationCopy) )
538         return NSDragOperationCopy;
539     if ( [[pboard types] containsObject:NSStringPboardType]
540             && (sourceDragMask & NSDragOperationCopy) )
541         return NSDragOperationCopy;
543     return NSDragOperationNone;
546 - (void)setMouseShape:(int)shape
548     mouseShape = shape;
549     [self setCursor];
552 - (BOOL)hasMarkedText
554     return markedRange.length > 0 ? YES : NO;
557 - (NSRange)markedRange
559     if ([self hasMarkedText])
560         return markedRange;
561     else
562         return NSMakeRange(NSNotFound, 0);
565 - (NSDictionary *)markedTextAttributes
567     return markedTextAttributes;
570 - (void)setMarkedTextAttributes:(NSDictionary *)attr
572     if (attr != markedTextAttributes) {
573         [markedTextAttributes release];
574         markedTextAttributes = [attr retain];
575     }
578 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
580     [self unmarkText];
582     if (!(text && [text length] > 0))
583         return;
585     // HACK! Determine if the marked text is wide or normal width.  This seems
586     // to always use 'wide' when there are both wide and normal width
587     // characters.
588     NSString *string = text;
589     NSFont *theFont = [textView font];
590     if ([text isKindOfClass:[NSAttributedString class]]) {
591         theFont = [textView fontWide];
592         string = [text string];
593     }
595     // TODO: Use special colors for marked text.
596     [self setMarkedTextAttributes:
597         [NSDictionary dictionaryWithObjectsAndKeys:
598             theFont, NSFontAttributeName,
599             [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
600             [textView defaultForegroundColor], NSForegroundColorAttributeName,
601             nil]];
603     markedText = [[NSMutableAttributedString alloc]
604            initWithString:string
605                attributes:[self markedTextAttributes]];
607     markedRange = NSMakeRange(0, [markedText length]);
608     if (markedRange.length) {
609         [markedText addAttribute:NSUnderlineStyleAttributeName
610                            value:[NSNumber numberWithInt:1]
611                            range:markedRange];
612     }
613     imRange = range;
614     if (range.length) {
615         [markedText addAttribute:NSUnderlineStyleAttributeName
616                            value:[NSNumber numberWithInt:2]
617                            range:range];
618     }
620     [textView setNeedsDisplay:YES];
623 - (void)unmarkText
625     imRange = NSMakeRange(0, 0);
626     markedRange = NSMakeRange(NSNotFound, 0);
627     [markedText release];
628     markedText = nil;
631 - (NSMutableAttributedString *)markedText
633     return markedText;
636 - (void)setPreEditRow:(int)row column:(int)col
638     preEditRow = row;
639     preEditColumn = col;
642 - (int)preEditRow
644     return preEditRow;
647 - (int)preEditColumn
649     return preEditColumn;
652 - (void)setImRange:(NSRange)range
654     imRange = range;
657 - (NSRange)imRange
659     return imRange;
662 - (void)setMarkedRange:(NSRange)range
664     markedRange = range;
667 - (NSRect)firstRectForCharacterRange:(NSRange)range
669     // This method is called when the input manager wants to pop up an
670     // auxiliary window.  The position where this should be is controlled by
671     // Vim by sending SetPreEditPositionMsgID so compute a position based on
672     // the pre-edit (row,column) pair.
673     int col = preEditColumn;
674     int row = preEditRow + 1;
676     NSFont *theFont = [[textView markedTextAttributes]
677             valueForKey:NSFontAttributeName];
678     if (theFont == [textView fontWide]) {
679         col += imRange.location * 2;
680         if (col >= [textView maxColumns] - 1) {
681             row += (col / [textView maxColumns]);
682             col = col % 2 ? col % [textView maxColumns] + 1 :
683                             col % [textView maxColumns];
684         }
685     } else {
686         col += imRange.location;
687         if (col >= [textView maxColumns]) {
688             row += (col / [textView maxColumns]);
689             col = col % [textView maxColumns];
690         }
691     }
693     NSRect rect = [textView rectForRow:row
694                                 column:col
695                                numRows:1
696                             numColumns:range.length];
698     rect.origin = [textView convertPoint:rect.origin toView:nil];
699     rect.origin = [[textView window] convertBaseToScreen:rect.origin];
701     return rect;
704 @end // MMTextViewHelper
709 @implementation MMTextViewHelper (Private)
711 - (MMWindowController *)windowController
713     id windowController = [[textView window] windowController];
714     if ([windowController isKindOfClass:[MMWindowController class]])
715         return (MMWindowController*)windowController;
716     return nil;
719 - (MMVimController *)vimController
721     return [[self windowController] vimController];
724 - (void)dispatchKeyEvent:(NSEvent *)event
726     // Only handle the command if it came from a keyDown event
727     if ([event type] != NSKeyDown)
728         return;
730     NSString *chars = [event characters];
731     NSString *unmodchars = [event charactersIgnoringModifiers];
732     unichar c = [chars characterAtIndex:0];
733     unichar imc = [unmodchars characterAtIndex:0];
734     int len = 0;
735     const char *bytes = 0;
736     int mods = [event modifierFlags];
738     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
739     //        _cmd, c, imc, chars, unmodchars);
741     if (' ' == imc && 0xa0 != c) {
742         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
743         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
744         // should be passed on as is.)
745         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
746         bytes = [unmodchars UTF8String];
747     } else if (imc == c && '2' == c) {
748         // HACK!  Translate Ctrl+2 to <C-@>.
749         static char ctrl_at = 0;
750         len = 1;  bytes = &ctrl_at;
751     } else if (imc == c && '6' == c) {
752         // HACK!  Translate Ctrl+6 to <C-^>.
753         static char ctrl_hat = 0x1e;
754         len = 1;  bytes = &ctrl_hat;
755     } else if (c == 0x19 && imc == 0x19) {
756         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
757         // separately (else Ctrl-Y doesn't work).
758         static char tab = 0x9;
759         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
760     } else {
761         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
762         bytes = [chars UTF8String];
763     }
765     [self sendKeyDown:bytes length:len modifiers:mods
766             isARepeat:[event isARepeat]];
769 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
770           isARepeat:(BOOL)isARepeat
772     if (chars && len > 0) {
773         NSMutableData *data = [NSMutableData data];
775         // The low 16 bits are not used for modifier flags by NSEvent.  Use
776         // these bits for custom flags.
777         flags &= 0xffff0000;
778         if (isARepeat)
779             flags |= 1;
781         [data appendBytes:&flags length:sizeof(int)];
782         [data appendBytes:&len length:sizeof(int)];
783         [data appendBytes:chars length:len];
785         [self hideMouseCursor];
787         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
788         [[self vimController] sendMessage:KeyDownMsgID data:data];
789     }
792 - (void)hideMouseCursor
794     // Check 'mousehide' option
795     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
796     if (mh && ![mh boolValue])
797         [NSCursor setHiddenUntilMouseMoves:NO];
798     else
799         [NSCursor setHiddenUntilMouseMoves:YES];
802 - (void)startDragTimerWithInterval:(NSTimeInterval)t
804     [NSTimer scheduledTimerWithTimeInterval:t target:self
805                                    selector:@selector(dragTimerFired:)
806                                    userInfo:nil repeats:NO];
809 - (void)dragTimerFired:(NSTimer *)timer
811     // TODO: Autoscroll in horizontal direction?
812     static unsigned tick = 1;
814     isAutoscrolling = NO;
816     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
817         // HACK! If the mouse cursor is outside the text area, then send a
818         // dragged event.  However, if row&col hasn't changed since the last
819         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
820         // Thus we fiddle with the column to make sure something happens.
821         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
822         NSMutableData *data = [NSMutableData data];
824         [data appendBytes:&dragRow length:sizeof(int)];
825         [data appendBytes:&col length:sizeof(int)];
826         [data appendBytes:&dragFlags length:sizeof(int)];
828         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
830         isAutoscrolling = YES;
831     }
833     if (isDragging) {
834         // Compute timer interval depending on how far away the mouse cursor is
835         // from the text view.
836         NSRect rect = [self trackingRect];
837         float dy = 0;
838         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
839         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
840         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
842         NSTimeInterval t = MMDragTimerMaxInterval -
843             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
845         [self startDragTimerWithInterval:t];
846     }
848     ++tick;
851 - (void)setCursor
853     static NSCursor *customIbeamCursor = nil;
855     if (!customIbeamCursor) {
856         // Use a custom Ibeam cursor that has better contrast against dark
857         // backgrounds.
858         // TODO: Is the hotspot ok?
859         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
860         if (ibeamImage) {
861             NSSize size = [ibeamImage size];
862             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
864             customIbeamCursor = [[NSCursor alloc]
865                     initWithImage:ibeamImage hotSpot:hotSpot];
866         }
867         if (!customIbeamCursor) {
868             NSLog(@"WARNING: Failed to load custom Ibeam cursor");
869             customIbeamCursor = [NSCursor IBeamCursor];
870         }
871     }
873     // This switch should match mshape_names[] in misc2.c.
874     //
875     // TODO: Add missing cursor shapes.
876     switch (mouseShape) {
877         case 2: [customIbeamCursor set]; break;
878         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
879         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
880         case 9: [[NSCursor crosshairCursor] set]; break;
881         case 10: [[NSCursor pointingHandCursor] set]; break;
882         case 11: [[NSCursor openHandCursor] set]; break;
883         default:
884             [[NSCursor arrowCursor] set]; break;
885     }
887     // Shape 1 indicates that the mouse cursor should be hidden.
888     if (1 == mouseShape)
889         [NSCursor setHiddenUntilMouseMoves:YES];
892 - (NSRect)trackingRect
894     NSRect rect = [textView frame];
895     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
896     int left = [ud integerForKey:MMTextInsetLeftKey];
897     int top = [ud integerForKey:MMTextInsetTopKey];
898     int right = [ud integerForKey:MMTextInsetRightKey];
899     int bot = [ud integerForKey:MMTextInsetBottomKey];
901     rect.origin.x = left;
902     rect.origin.y = top;
903     rect.size.width -= left + right - 1;
904     rect.size.height -= top + bot - 1;
906     return rect;
909 @end // MMTextViewHelper (Private)