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 isARepeat:(BOOL)isARepeat;
43 - (void)hideMouseCursor;
44 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
45 - (void)dragTimerFired:(NSTimer *)timer;
47 - (NSRect)trackingRect;
51 @implementation MMTextViewHelper
55 [insertionPointColor release]; insertionPointColor = nil;
56 [markedText release]; markedText = nil;
57 [markedTextAttributes release]; markedTextAttributes = nil;
62 - (void)setTextView:(id)view
64 // Only keep a weak reference to owning text view.
68 - (void)setInsertionPointColor:(NSColor *)color
70 if (color != insertionPointColor) {
71 [insertionPointColor release];
72 insertionPointColor = [color retain];
76 - (NSColor *)insertionPointColor
78 return insertionPointColor;
81 - (void)keyDown:(NSEvent *)event
83 //NSLog(@"%s %@", _cmd, event);
84 // HACK! If control modifier is held, don't pass the event along to
85 // interpretKeyEvents: since some keys are bound to multiple commands which
86 // means doCommandBySelector: is called several times. Do the same for
87 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
88 // commands). This hack may break input management, but unless we can
89 // figure out a way to disable key bindings there seems little else to do.
91 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
92 // affecting input management.
94 // When the Input Method is activated, some special key inputs
95 // should be treated as key inputs for Input Method.
96 if ([textView hasMarkedText]) {
97 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
98 [textView setNeedsDisplay:YES];
102 int flags = [event modifierFlags];
103 if ((flags & NSControlKeyMask) ||
104 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
105 NSString *chars = [event characters];
106 if ([chars length] == 1 && [chars characterAtIndex:0] < 0x20) {
107 // HACK! Send unprintable characters (such as C-@, C-[, C-\, C-],
108 // C-^, C-_) as normal text to be added to the Vim input buffer.
109 // This must be done in order for the backend to be able to
110 // separate e.g. Ctrl-i and Ctrl-tab.
111 [self insertText:chars];
113 [self dispatchKeyEvent:event];
115 } else if ((flags & NSAlternateKeyMask) &&
116 [[[[self vimController] vimState] objectForKey:@"p_mmta"]
118 // If the 'macmeta' option is set, then send Alt+key presses directly
119 // to Vim without interpreting the key press.
120 NSString *unmod = [event charactersIgnoringModifiers];
121 int len = [unmod lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
122 const char *bytes = [unmod UTF8String];
124 [self sendKeyDown:bytes length:len modifiers:flags
125 isARepeat:[event isARepeat]];
127 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
131 - (void)insertText:(id)string
133 //NSLog(@"%s %@", _cmd, string);
134 // NOTE! This method is called for normal key presses but also for
135 // Option-key presses --- even when Ctrl is held as well as Option. When
136 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
137 // so 'string' need not be a printable character! In this case it still
138 // works to pass 'string' on to Vim as a printable character (since
139 // modifiers are already included and should not be added to the input
140 // buffer using CSI, K_MODIFIER).
142 if ([textView hasMarkedText]) {
143 [textView unmarkText];
146 NSEvent *event = [NSApp currentEvent];
148 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
149 // to watch for them here.
150 if ([event type] == NSKeyDown
151 && [[event charactersIgnoringModifiers] length] > 0
152 && [event modifierFlags]
153 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
154 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
156 // <S-M-Tab> translates to 0x19
157 if (' ' == c || 0x19 == c) {
158 [self dispatchKeyEvent:event];
163 [self hideMouseCursor];
165 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
166 // do not support attributes, simply pass the corresponding NSString in the
168 if ([string isKindOfClass:[NSAttributedString class]])
169 string = [string string];
171 //NSLog(@"send InsertTextMsgID: %@", string);
173 NSMutableData *data = [NSMutableData data];
174 int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
175 int flags = [event modifierFlags] & 0xffff0000U;
176 if ([event type] == NSKeyDown && [event isARepeat])
179 [data appendBytes:&flags length:sizeof(int)];
180 [data appendBytes:&len length:sizeof(int)];
181 [data appendBytes:[string UTF8String] length:len];
183 [[self vimController] sendMessage:InsertTextMsgID data:data];
186 - (void)doCommandBySelector:(SEL)selector
188 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
189 // By ignoring the selector we effectively disable the key binding
190 // mechanism of Cocoa. Hopefully this is what the user will expect
191 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
194 // We usually end up here if the user pressed Ctrl+key (but not
197 NSEvent *event = [NSApp currentEvent];
199 if (selector == @selector(cancelOperation:)
200 || selector == @selector(insertNewline:)) {
201 // HACK! If there was marked text which got abandoned as a result of
202 // hitting escape or enter, then 'insertText:' is called with the
203 // abandoned text but '[event characters]' includes the abandoned text
204 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
205 // must intercept these keys here or the abandonded text gets inserted
207 NSString *key = [event charactersIgnoringModifiers];
208 const char *chars = [key UTF8String];
209 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
211 if (0x3 == chars[0]) {
212 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
213 // handle it separately (else Ctrl-C doesn't work).
214 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
215 chars = MMKeypadEnter;
218 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]
219 isARepeat:[event isARepeat]];
221 [self dispatchKeyEvent:event];
225 - (BOOL)performKeyEquivalent:(NSEvent *)event
227 //NSLog(@"%s %@", _cmd, event);
228 // Called for Cmd+key keystrokes, function keys, arrow keys, page
229 // up/down, home, end.
231 // NOTE: This message cannot be ignored since Cmd+letter keys never are
232 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
233 // strokes, unless the key is a function key.
235 // NOTE: If the event that triggered this method represents a function key
236 // down then we do nothing, otherwise the input method never gets the key
237 // stroke (some input methods use e.g. arrow keys). The function key down
238 // event will still reach Vim though (via keyDown:). The exceptions to
239 // this rule are: PageUp/PageDown (keycode 116/121).
240 int flags = [event modifierFlags] & 0xffff0000U;
241 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
242 && !(116 == [event keyCode] || 121 == [event keyCode]))
245 // HACK! KeyCode 50 represent the key which switches between windows
246 // within an application (like Cmd+Tab is used to switch between
247 // applications). Return NO here, else the window switching does not work.
248 if ([event keyCode] == 50)
251 // HACK! Let the main menu try to handle any key down event, before
252 // passing it on to vim, otherwise key equivalents for menus will
253 // effectively be disabled.
254 if ([[NSApp mainMenu] performKeyEquivalent:event])
257 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
258 if (flags & NSControlKeyMask) {
259 [self keyDown:event];
263 // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard.
264 NSString *unmodchars = [event charactersIgnoringModifiers];
265 if ([unmodchars isEqual:@"?"])
268 // Cmd-. is hard-wired to send SIGINT unlike Ctrl-C which is just another
269 // key press which Vim has to interpret. This means that Cmd-. always
270 // works to interrupt a Vim process whereas Ctrl-C can suffer from problems
271 // such as dropped DO messages (or if Vim is stuck in a loop without
272 // checking for keyboard input).
273 if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
274 [unmodchars isEqual:@"."]) {
275 kill([[self vimController] pid], SIGINT);
279 //NSLog(@"%s%@", _cmd, event);
281 NSString *chars = [event characters];
282 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
283 NSMutableData *data = [NSMutableData data];
288 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
289 // can clear the shift flag as it is already included in 'unmodchars'.
290 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
291 // an English keyboard).
292 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
293 flags &= ~NSShiftKeyMask;
295 if (0x3 == [unmodchars characterAtIndex:0]) {
296 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
297 // handle it separately (else Cmd-enter turns into Ctrl-C).
298 unmodchars = MMKeypadEnterString;
299 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
302 if ([event isARepeat])
305 [data appendBytes:&flags length:sizeof(int)];
306 [data appendBytes:&len length:sizeof(int)];
307 [data appendBytes:[unmodchars UTF8String] length:len];
309 [[self vimController] sendMessage:CmdKeyMsgID data:data];
314 - (void)scrollWheel:(NSEvent *)event
316 if ([event deltaY] == 0)
320 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
321 if ([textView convertPoint:pt toRow:&row column:&col]) {
322 int flags = [event modifierFlags];
323 float dy = [event deltaY];
324 NSMutableData *data = [NSMutableData data];
326 [data appendBytes:&row length:sizeof(int)];
327 [data appendBytes:&col length:sizeof(int)];
328 [data appendBytes:&flags length:sizeof(int)];
329 [data appendBytes:&dy length:sizeof(float)];
331 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
335 - (void)mouseDown:(NSEvent *)event
338 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
339 if (![textView convertPoint:pt toRow:&row column:&col])
342 int button = [event buttonNumber];
343 int flags = [event modifierFlags];
344 int count = [event clickCount];
345 NSMutableData *data = [NSMutableData data];
347 // If desired, intepret Ctrl-Click as a right mouse click.
348 BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
349 boolForKey:MMTranslateCtrlClickKey];
350 flags = flags & NSDeviceIndependentModifierFlagsMask;
351 if (translateCtrlClick && button == 0 &&
352 (flags == NSControlKeyMask ||
353 flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
355 flags &= ~NSControlKeyMask;
358 [data appendBytes:&row length:sizeof(int)];
359 [data appendBytes:&col length:sizeof(int)];
360 [data appendBytes:&button length:sizeof(int)];
361 [data appendBytes:&flags length:sizeof(int)];
362 [data appendBytes:&count length:sizeof(int)];
364 [[self vimController] sendMessage:MouseDownMsgID data:data];
367 - (void)mouseUp:(NSEvent *)event
370 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
371 if (![textView convertPoint:pt toRow:&row column:&col])
374 int flags = [event modifierFlags];
375 NSMutableData *data = [NSMutableData data];
377 [data appendBytes:&row length:sizeof(int)];
378 [data appendBytes:&col length:sizeof(int)];
379 [data appendBytes:&flags length:sizeof(int)];
381 [[self vimController] sendMessage:MouseUpMsgID data:data];
386 - (void)mouseDragged:(NSEvent *)event
388 int flags = [event modifierFlags];
390 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
391 if (![textView convertPoint:pt toRow:&row column:&col])
394 // Autoscrolling is done in dragTimerFired:
395 if (!isAutoscrolling) {
396 NSMutableData *data = [NSMutableData data];
398 [data appendBytes:&row length:sizeof(int)];
399 [data appendBytes:&col length:sizeof(int)];
400 [data appendBytes:&flags length:sizeof(int)];
402 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
411 [self startDragTimerWithInterval:.5];
416 - (void)mouseMoved:(NSEvent *)event
418 // HACK! NSTextView has a nasty habit of resetting the cursor to the
419 // default I-beam cursor at random moments. The only reliable way we know
420 // of to work around this is to set the cursor each time the mouse moves.
423 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
425 if (![textView convertPoint:pt toRow:&row column:&col])
428 // HACK! It seems impossible to get the tracking rects set up before the
429 // view is visible, which means that the first mouseEntered: or
430 // mouseExited: events are never received. This forces us to check if the
431 // mouseMoved: event really happened over the text.
433 [textView getMaxRows:&rows columns:&cols];
434 if (row >= 0 && row < rows && col >= 0 && col < cols) {
435 NSMutableData *data = [NSMutableData data];
437 [data appendBytes:&row length:sizeof(int)];
438 [data appendBytes:&col length:sizeof(int)];
440 [[self vimController] sendMessage:MouseMovedMsgID data:data];
442 //NSLog(@"Moved %d %d\n", col, row);
446 - (void)mouseEntered:(NSEvent *)event
448 //NSLog(@"%s", _cmd);
450 // NOTE: This event is received even when the window is not key; thus we
451 // have to take care not to enable mouse moved events unless our window is
453 if ([[textView window] isKeyWindow]) {
454 [[textView window] setAcceptsMouseMovedEvents:YES];
458 - (void)mouseExited:(NSEvent *)event
460 //NSLog(@"%s", _cmd);
462 [[textView window] setAcceptsMouseMovedEvents:NO];
464 // NOTE: This event is received even when the window is not key; if the
465 // mouse shape is set when our window is not key, the hollow (unfocused)
466 // cursor will become a block (focused) cursor.
467 if ([[textView window] isKeyWindow]) {
469 NSMutableData *data = [NSMutableData data];
470 [data appendBytes:&shape length:sizeof(int)];
471 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
475 - (void)setFrame:(NSRect)frame
477 //NSLog(@"%s", _cmd);
479 // When the frame changes we also need to update the tracking rect.
480 [textView removeTrackingRect:trackingRectTag];
481 trackingRectTag = [textView addTrackingRect:[self trackingRect]
487 - (void)viewDidMoveToWindow
489 //NSLog(@"%s (window=%@)", _cmd, [self window]);
491 // Set a tracking rect which covers the text.
492 // NOTE: While the mouse cursor is in this rect the view will receive
493 // 'mouseMoved:' events so that Vim can take care of updating the mouse
495 if ([textView window]) {
496 [[textView window] setAcceptsMouseMovedEvents:YES];
497 trackingRectTag = [textView addTrackingRect:[self trackingRect]
504 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
506 //NSLog(@"%s%@", _cmd, newWindow);
508 // Remove tracking rect if view moves or is removed.
509 if ([textView window] && trackingRectTag) {
510 [textView removeTrackingRect:trackingRectTag];
515 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
517 NSPasteboard *pboard = [sender draggingPasteboard];
519 if ([[pboard types] containsObject:NSStringPboardType]) {
520 NSString *string = [pboard stringForType:NSStringPboardType];
521 [[self vimController] dropString:string];
523 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
524 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
525 [[self vimController] dropFiles:files forceOpen:NO];
532 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
534 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
535 NSPasteboard *pboard = [sender draggingPasteboard];
537 if ( [[pboard types] containsObject:NSFilenamesPboardType]
538 && (sourceDragMask & NSDragOperationCopy) )
539 return NSDragOperationCopy;
540 if ( [[pboard types] containsObject:NSStringPboardType]
541 && (sourceDragMask & NSDragOperationCopy) )
542 return NSDragOperationCopy;
544 return NSDragOperationNone;
547 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
549 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
550 NSPasteboard *pboard = [sender draggingPasteboard];
552 if ( [[pboard types] containsObject:NSFilenamesPboardType]
553 && (sourceDragMask & NSDragOperationCopy) )
554 return NSDragOperationCopy;
555 if ( [[pboard types] containsObject:NSStringPboardType]
556 && (sourceDragMask & NSDragOperationCopy) )
557 return NSDragOperationCopy;
559 return NSDragOperationNone;
562 - (void)setMouseShape:(int)shape
568 - (BOOL)hasMarkedText
570 return markedRange.length > 0 ? YES : NO;
573 - (NSRange)markedRange
575 if ([self hasMarkedText])
578 return NSMakeRange(NSNotFound, 0);
581 - (NSDictionary *)markedTextAttributes
583 return markedTextAttributes;
586 - (void)setMarkedTextAttributes:(NSDictionary *)attr
588 if (attr != markedTextAttributes) {
589 [markedTextAttributes release];
590 markedTextAttributes = [attr retain];
594 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
598 if (!(text && [text length] > 0))
601 // HACK! Determine if the marked text is wide or normal width. This seems
602 // to always use 'wide' when there are both wide and normal width
604 NSString *string = text;
605 NSFont *theFont = [textView font];
606 if ([text isKindOfClass:[NSAttributedString class]]) {
607 theFont = [textView fontWide];
608 string = [text string];
611 // TODO: Use special colors for marked text.
612 [self setMarkedTextAttributes:
613 [NSDictionary dictionaryWithObjectsAndKeys:
614 theFont, NSFontAttributeName,
615 [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
616 [textView defaultForegroundColor], NSForegroundColorAttributeName,
619 markedText = [[NSMutableAttributedString alloc]
620 initWithString:string
621 attributes:[self markedTextAttributes]];
623 markedRange = NSMakeRange(0, [markedText length]);
624 if (markedRange.length) {
625 [markedText addAttribute:NSUnderlineStyleAttributeName
626 value:[NSNumber numberWithInt:1]
631 [markedText addAttribute:NSUnderlineStyleAttributeName
632 value:[NSNumber numberWithInt:2]
636 [textView setNeedsDisplay:YES];
641 imRange = NSMakeRange(0, 0);
642 markedRange = NSMakeRange(NSNotFound, 0);
643 [markedText release];
647 - (NSMutableAttributedString *)markedText
652 - (void)setPreEditRow:(int)row column:(int)col
665 return preEditColumn;
668 - (void)setImRange:(NSRange)range
678 - (void)setMarkedRange:(NSRange)range
683 - (NSRect)firstRectForCharacterRange:(NSRange)range
685 // This method is called when the input manager wants to pop up an
686 // auxiliary window. The position where this should be is controlled by
687 // Vim by sending SetPreEditPositionMsgID so compute a position based on
688 // the pre-edit (row,column) pair.
689 int col = preEditColumn;
690 int row = preEditRow + 1;
692 NSFont *theFont = [[textView markedTextAttributes]
693 valueForKey:NSFontAttributeName];
694 if (theFont == [textView fontWide]) {
695 col += imRange.location * 2;
696 if (col >= [textView maxColumns] - 1) {
697 row += (col / [textView maxColumns]);
698 col = col % 2 ? col % [textView maxColumns] + 1 :
699 col % [textView maxColumns];
702 col += imRange.location;
703 if (col >= [textView maxColumns]) {
704 row += (col / [textView maxColumns]);
705 col = col % [textView maxColumns];
709 NSRect rect = [textView rectForRow:row
712 numColumns:range.length];
714 rect.origin = [textView convertPoint:rect.origin toView:nil];
715 rect.origin = [[textView window] convertBaseToScreen:rect.origin];
720 @end // MMTextViewHelper
725 @implementation MMTextViewHelper (Private)
727 - (MMWindowController *)windowController
729 id windowController = [[textView window] windowController];
730 if ([windowController isKindOfClass:[MMWindowController class]])
731 return (MMWindowController*)windowController;
735 - (MMVimController *)vimController
737 return [[self windowController] vimController];
740 - (void)dispatchKeyEvent:(NSEvent *)event
742 // Only handle the command if it came from a keyDown event
743 if ([event type] != NSKeyDown)
746 NSString *chars = [event characters];
747 NSString *unmodchars = [event charactersIgnoringModifiers];
748 unichar c = [chars characterAtIndex:0];
749 unichar imc = [unmodchars length] > 0 ? [unmodchars characterAtIndex:0] : 0;
751 const char *bytes = 0;
752 int mods = [event modifierFlags];
754 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
755 // _cmd, c, imc, chars, unmodchars);
757 if (' ' == imc && 0xa0 != c) {
758 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
759 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
760 // should be passed on as is.)
761 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
762 bytes = [unmodchars UTF8String];
763 } else if (imc == c && '2' == c) {
764 // HACK! Translate Ctrl+2 to <C-@>.
765 static char ctrl_at = 0;
766 len = 1; bytes = &ctrl_at;
767 } else if (imc == c && '6' == c) {
768 // HACK! Translate Ctrl+6 to <C-^>.
769 static char ctrl_hat = 0x1e;
770 len = 1; bytes = &ctrl_hat;
771 } else if (c == 0x19 && imc == 0x19) {
772 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
773 // separately (else Ctrl-Y doesn't work).
774 static char tab = 0x9;
775 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
777 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
778 bytes = [chars UTF8String];
781 [self sendKeyDown:bytes length:len modifiers:mods
782 isARepeat:[event isARepeat]];
785 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
786 isARepeat:(BOOL)isARepeat
788 if (chars && len > 0) {
789 NSMutableData *data = [NSMutableData data];
791 // The low 16 bits are not used for modifier flags by NSEvent. Use
792 // these bits for custom flags.
797 [data appendBytes:&flags length:sizeof(int)];
798 [data appendBytes:&len length:sizeof(int)];
799 [data appendBytes:chars length:len];
801 [self hideMouseCursor];
803 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
804 [[self vimController] sendMessage:KeyDownMsgID data:data];
808 - (void)hideMouseCursor
810 // Check 'mousehide' option
811 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
812 if (mh && ![mh boolValue])
813 [NSCursor setHiddenUntilMouseMoves:NO];
815 [NSCursor setHiddenUntilMouseMoves:YES];
818 - (void)startDragTimerWithInterval:(NSTimeInterval)t
820 [NSTimer scheduledTimerWithTimeInterval:t target:self
821 selector:@selector(dragTimerFired:)
822 userInfo:nil repeats:NO];
825 - (void)dragTimerFired:(NSTimer *)timer
827 // TODO: Autoscroll in horizontal direction?
828 static unsigned tick = 1;
830 isAutoscrolling = NO;
832 if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
833 // HACK! If the mouse cursor is outside the text area, then send a
834 // dragged event. However, if row&col hasn't changed since the last
835 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
836 // Thus we fiddle with the column to make sure something happens.
837 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
838 NSMutableData *data = [NSMutableData data];
840 [data appendBytes:&dragRow length:sizeof(int)];
841 [data appendBytes:&col length:sizeof(int)];
842 [data appendBytes:&dragFlags length:sizeof(int)];
844 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
846 isAutoscrolling = YES;
850 // Compute timer interval depending on how far away the mouse cursor is
851 // from the text view.
852 NSRect rect = [self trackingRect];
854 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
855 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
856 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
858 NSTimeInterval t = MMDragTimerMaxInterval -
859 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
861 [self startDragTimerWithInterval:t];
869 static NSCursor *customIbeamCursor = nil;
871 if (!customIbeamCursor) {
872 // Use a custom Ibeam cursor that has better contrast against dark
874 // TODO: Is the hotspot ok?
875 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
877 NSSize size = [ibeamImage size];
878 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
880 customIbeamCursor = [[NSCursor alloc]
881 initWithImage:ibeamImage hotSpot:hotSpot];
883 if (!customIbeamCursor) {
884 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
885 customIbeamCursor = [NSCursor IBeamCursor];
889 // This switch should match mshape_names[] in misc2.c.
891 // TODO: Add missing cursor shapes.
892 switch (mouseShape) {
893 case 2: [customIbeamCursor set]; break;
894 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
895 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
896 case 9: [[NSCursor crosshairCursor] set]; break;
897 case 10: [[NSCursor pointingHandCursor] set]; break;
898 case 11: [[NSCursor openHandCursor] set]; break;
900 [[NSCursor arrowCursor] set]; break;
903 // Shape 1 indicates that the mouse cursor should be hidden.
905 [NSCursor setHiddenUntilMouseMoves:YES];
908 - (NSRect)trackingRect
910 NSRect rect = [textView frame];
911 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
912 int left = [ud integerForKey:MMTextInsetLeftKey];
913 int top = [ud integerForKey:MMTextInsetTopKey];
914 int right = [ud integerForKey:MMTextInsetRightKey];
915 int bot = [ud integerForKey:MMTextInsetBottomKey];
917 rect.origin.x = left;
919 rect.size.width -= left + right - 1;
920 rect.size.height -= top + bot - 1;
925 @end // MMTextViewHelper (Private)