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
54 [markedText release]; markedText = nil;
59 - (void)setTextView:(id)view
61 // Only keep a weak reference to owning text view.
65 - (void)setInsertionPointColor:(NSColor *)color
67 if (color != insertionPointColor) {
68 [insertionPointColor release];
69 insertionPointColor = [color retain];
73 - (NSColor *)insertionPointColor
75 return insertionPointColor;
78 - (void)keyDown:(NSEvent *)event
80 //NSLog(@"%s %@", _cmd, event);
81 // HACK! If control modifier is held, don't pass the event along to
82 // interpretKeyEvents: since some keys are bound to multiple commands which
83 // means doCommandBySelector: is called several times. Do the same for
84 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
85 // commands). This hack may break input management, but unless we can
86 // figure out a way to disable key bindings there seems little else to do.
88 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
89 // affecting input management.
91 // When the Input Method is activated, some special key inputs
92 // should be treated as key inputs for Input Method.
93 if ([textView hasMarkedText]) {
94 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
95 [textView setNeedsDisplay:YES];
99 int flags = [event modifierFlags];
100 if ((flags & NSControlKeyMask) ||
101 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
102 NSString *unmod = [event charactersIgnoringModifiers];
103 if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
104 && [unmod characterAtIndex:0] >= 0x60) {
105 // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
106 // as normal text to be added to the Vim input buffer. This must
107 // be done in order for the backend to be able to separate e.g.
108 // Ctrl-i and Ctrl-tab.
109 [self insertText:[event characters]];
111 [self dispatchKeyEvent:event];
114 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
118 - (void)insertText:(id)string
120 //NSLog(@"%s %@", _cmd, string);
121 // NOTE! This method is called for normal key presses but also for
122 // Option-key presses --- even when Ctrl is held as well as Option. When
123 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
124 // so 'string' need not be a printable character! In this case it still
125 // works to pass 'string' on to Vim as a printable character (since
126 // modifiers are already included and should not be added to the input
127 // buffer using CSI, K_MODIFIER).
129 if ([textView hasMarkedText]) {
130 [textView unmarkText];
133 NSEvent *event = [NSApp currentEvent];
135 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
136 // to watch for them here.
137 if ([event type] == NSKeyDown
138 && [[event charactersIgnoringModifiers] length] > 0
139 && [event modifierFlags]
140 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
141 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
143 // <S-M-Tab> translates to 0x19
144 if (' ' == c || 0x19 == c) {
145 [self dispatchKeyEvent:event];
150 [self hideMouseCursor];
152 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
153 // do not support attributes, simply pass the corresponding NSString in the
155 if ([string isKindOfClass:[NSAttributedString class]])
156 string = [string string];
158 //NSLog(@"send InsertTextMsgID: %@", string);
160 [[self vimController] sendMessage:InsertTextMsgID
161 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
164 - (void)doCommandBySelector:(SEL)selector
166 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
167 // By ignoring the selector we effectively disable the key binding
168 // mechanism of Cocoa. Hopefully this is what the user will expect
169 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
172 // We usually end up here if the user pressed Ctrl+key (but not
175 NSEvent *event = [NSApp currentEvent];
177 if (selector == @selector(cancelOperation:)
178 || selector == @selector(insertNewline:)) {
179 // HACK! If there was marked text which got abandoned as a result of
180 // hitting escape or enter, then 'insertText:' is called with the
181 // abandoned text but '[event characters]' includes the abandoned text
182 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
183 // must intercept these keys here or the abandonded text gets inserted
185 NSString *key = [event charactersIgnoringModifiers];
186 const char *chars = [key UTF8String];
187 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
189 if (0x3 == chars[0]) {
190 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
191 // handle it separately (else Ctrl-C doesn't work).
192 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
193 chars = MMKeypadEnter;
196 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
198 [self dispatchKeyEvent:event];
202 - (BOOL)performKeyEquivalent:(NSEvent *)event
204 //NSLog(@"%s %@", _cmd, event);
205 // Called for Cmd+key keystrokes, function keys, arrow keys, page
206 // up/down, home, end.
208 // NOTE: This message cannot be ignored since Cmd+letter keys never are
209 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
210 // strokes, unless the key is a function key.
212 // NOTE: If the event that triggered this method represents a function key
213 // down then we do nothing, otherwise the input method never gets the key
214 // stroke (some input methods use e.g. arrow keys). The function key down
215 // event will still reach Vim though (via keyDown:). The exceptions to
216 // this rule are: PageUp/PageDown (keycode 116/121).
217 int flags = [event modifierFlags];
218 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
219 && !(116 == [event keyCode] || 121 == [event keyCode]))
222 // HACK! KeyCode 50 represent the key which switches between windows
223 // within an application (like Cmd+Tab is used to switch between
224 // applications). Return NO here, else the window switching does not work.
225 if ([event keyCode] == 50)
228 // HACK! Let the main menu try to handle any key down event, before
229 // passing it on to vim, otherwise key equivalents for menus will
230 // effectively be disabled.
231 if ([[NSApp mainMenu] performKeyEquivalent:event])
234 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
235 if (flags & NSControlKeyMask) {
236 [self keyDown:event];
240 // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard.
241 NSString *unmodchars = [event charactersIgnoringModifiers];
242 if ([unmodchars isEqual:@"?"])
245 // Cmd-. is hard-wired to send an interrupt (like Ctrl-C).
246 if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
247 [unmodchars isEqual:@"."]) {
248 [[self vimController] sendMessage:InterruptMsgID data:nil];
252 //NSLog(@"%s%@", _cmd, event);
254 NSString *chars = [event characters];
255 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
256 NSMutableData *data = [NSMutableData data];
261 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
262 // can clear the shift flag as it is already included in 'unmodchars'.
263 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
264 // an English keyboard).
265 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
266 flags &= ~NSShiftKeyMask;
268 if (0x3 == [unmodchars characterAtIndex:0]) {
269 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
270 // handle it separately (else Cmd-enter turns into Ctrl-C).
271 unmodchars = MMKeypadEnterString;
272 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
275 [data appendBytes:&flags length:sizeof(int)];
276 [data appendBytes:&len length:sizeof(int)];
277 [data appendBytes:[unmodchars UTF8String] length:len];
279 [[self vimController] sendMessage:CmdKeyMsgID data:data];
284 - (void)scrollWheel:(NSEvent *)event
286 if ([event deltaY] == 0)
290 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
291 if ([textView convertPoint:pt toRow:&row column:&col]) {
292 int flags = [event modifierFlags];
293 float dy = [event deltaY];
294 NSMutableData *data = [NSMutableData data];
296 [data appendBytes:&row length:sizeof(int)];
297 [data appendBytes:&col length:sizeof(int)];
298 [data appendBytes:&flags length:sizeof(int)];
299 [data appendBytes:&dy length:sizeof(float)];
301 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
305 - (void)mouseDown:(NSEvent *)event
308 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
309 if (![textView convertPoint:pt toRow:&row column:&col])
312 int button = [event buttonNumber];
313 int flags = [event modifierFlags];
314 int count = [event clickCount];
315 NSMutableData *data = [NSMutableData data];
317 // If desired, intepret Ctrl-Click as a right mouse click.
318 BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
319 boolForKey:MMTranslateCtrlClickKey];
320 flags = flags & NSDeviceIndependentModifierFlagsMask;
321 if (translateCtrlClick && button == 0 &&
322 (flags == NSControlKeyMask ||
323 flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
325 flags &= ~NSControlKeyMask;
328 [data appendBytes:&row length:sizeof(int)];
329 [data appendBytes:&col length:sizeof(int)];
330 [data appendBytes:&button length:sizeof(int)];
331 [data appendBytes:&flags length:sizeof(int)];
332 [data appendBytes:&count length:sizeof(int)];
334 [[self vimController] sendMessage:MouseDownMsgID data:data];
337 - (void)mouseUp:(NSEvent *)event
340 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
341 if (![textView convertPoint:pt toRow:&row column:&col])
344 int flags = [event modifierFlags];
345 NSMutableData *data = [NSMutableData data];
347 [data appendBytes:&row length:sizeof(int)];
348 [data appendBytes:&col length:sizeof(int)];
349 [data appendBytes:&flags length:sizeof(int)];
351 [[self vimController] sendMessage:MouseUpMsgID data:data];
356 - (void)mouseDragged:(NSEvent *)event
358 int flags = [event modifierFlags];
360 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
361 if (![textView convertPoint:pt toRow:&row column:&col])
364 // Autoscrolling is done in dragTimerFired:
365 if (!isAutoscrolling) {
366 NSMutableData *data = [NSMutableData data];
368 [data appendBytes:&row length:sizeof(int)];
369 [data appendBytes:&col length:sizeof(int)];
370 [data appendBytes:&flags length:sizeof(int)];
372 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
381 [self startDragTimerWithInterval:.5];
386 - (void)mouseMoved:(NSEvent *)event
388 // HACK! NSTextView has a nasty habit of resetting the cursor to the
389 // default I-beam cursor at random moments. The only reliable way we know
390 // of to work around this is to set the cursor each time the mouse moves.
393 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
395 if (![textView convertPoint:pt toRow:&row column:&col])
398 // HACK! It seems impossible to get the tracking rects set up before the
399 // view is visible, which means that the first mouseEntered: or
400 // mouseExited: events are never received. This forces us to check if the
401 // mouseMoved: event really happened over the text.
403 [textView getMaxRows:&rows columns:&cols];
404 if (row >= 0 && row < rows && col >= 0 && col < cols) {
405 NSMutableData *data = [NSMutableData data];
407 [data appendBytes:&row length:sizeof(int)];
408 [data appendBytes:&col length:sizeof(int)];
410 [[self vimController] sendMessage:MouseMovedMsgID data:data];
412 //NSLog(@"Moved %d %d\n", col, row);
416 - (void)mouseEntered:(NSEvent *)event
418 //NSLog(@"%s", _cmd);
420 // NOTE: This event is received even when the window is not key; thus we
421 // have to take care not to enable mouse moved events unless our window is
423 if ([[textView window] isKeyWindow]) {
424 [[textView window] setAcceptsMouseMovedEvents:YES];
428 - (void)mouseExited:(NSEvent *)event
430 //NSLog(@"%s", _cmd);
432 [[textView window] setAcceptsMouseMovedEvents:NO];
434 // NOTE: This event is received even when the window is not key; if the
435 // mouse shape is set when our window is not key, the hollow (unfocused)
436 // cursor will become a block (focused) cursor.
437 if ([[textView window] isKeyWindow]) {
439 NSMutableData *data = [NSMutableData data];
440 [data appendBytes:&shape length:sizeof(int)];
441 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
445 - (void)setFrame:(NSRect)frame
447 //NSLog(@"%s", _cmd);
449 // When the frame changes we also need to update the tracking rect.
450 [textView removeTrackingRect:trackingRectTag];
451 trackingRectTag = [textView addTrackingRect:[self trackingRect]
457 - (void)viewDidMoveToWindow
459 //NSLog(@"%s (window=%@)", _cmd, [self window]);
461 // Set a tracking rect which covers the text.
462 // NOTE: While the mouse cursor is in this rect the view will receive
463 // 'mouseMoved:' events so that Vim can take care of updating the mouse
465 if ([textView window]) {
466 [[textView window] setAcceptsMouseMovedEvents:YES];
467 trackingRectTag = [textView addTrackingRect:[self trackingRect]
474 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
476 //NSLog(@"%s%@", _cmd, newWindow);
478 // Remove tracking rect if view moves or is removed.
479 if ([textView window] && trackingRectTag) {
480 [textView removeTrackingRect:trackingRectTag];
485 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
487 NSPasteboard *pboard = [sender draggingPasteboard];
489 if ([[pboard types] containsObject:NSStringPboardType]) {
490 NSString *string = [pboard stringForType:NSStringPboardType];
491 [[self vimController] dropString:string];
493 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
494 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
495 [[self vimController] dropFiles:files forceOpen:NO];
502 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
504 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
505 NSPasteboard *pboard = [sender draggingPasteboard];
507 if ( [[pboard types] containsObject:NSFilenamesPboardType]
508 && (sourceDragMask & NSDragOperationCopy) )
509 return NSDragOperationCopy;
510 if ( [[pboard types] containsObject:NSStringPboardType]
511 && (sourceDragMask & NSDragOperationCopy) )
512 return NSDragOperationCopy;
514 return NSDragOperationNone;
517 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
519 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
520 NSPasteboard *pboard = [sender draggingPasteboard];
522 if ( [[pboard types] containsObject:NSFilenamesPboardType]
523 && (sourceDragMask & NSDragOperationCopy) )
524 return NSDragOperationCopy;
525 if ( [[pboard types] containsObject:NSStringPboardType]
526 && (sourceDragMask & NSDragOperationCopy) )
527 return NSDragOperationCopy;
529 return NSDragOperationNone;
532 - (void)setMouseShape:(int)shape
538 - (BOOL)hasMarkedText
540 return markedRange.length > 0 ? YES : NO;
543 - (NSRange)markedRange
545 if ([self hasMarkedText])
548 return NSMakeRange(NSNotFound, 0);
551 - (NSDictionary *)markedTextAttributes
553 return markedTextAttributes;
556 - (void)setMarkedTextAttributes:(NSDictionary *)attr
558 if (attr != markedTextAttributes) {
559 [markedTextAttributes release];
560 markedTextAttributes = [attr retain];
564 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
568 if (!(text && [text length] > 0))
571 // HACK! Determine if the marked text is wide or normal width. This seems
572 // to always use 'wide' when there are both wide and normal width
574 NSString *string = text;
575 NSFont *theFont = [textView font];
576 if ([text isKindOfClass:[NSAttributedString class]]) {
577 theFont = [textView fontWide];
578 string = [text string];
581 // TODO: Use special colors for marked text.
582 [self setMarkedTextAttributes:
583 [NSDictionary dictionaryWithObjectsAndKeys:
584 theFont, NSFontAttributeName,
585 [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
586 [textView defaultForegroundColor], NSForegroundColorAttributeName,
589 markedText = [[NSMutableAttributedString alloc]
590 initWithString:string
591 attributes:[self markedTextAttributes]];
593 markedRange = NSMakeRange(0, [markedText length]);
594 if (markedRange.length) {
595 [markedText addAttribute:NSUnderlineStyleAttributeName
596 value:[NSNumber numberWithInt:1]
601 [markedText addAttribute:NSUnderlineStyleAttributeName
602 value:[NSNumber numberWithInt:2]
606 [textView setNeedsDisplay:YES];
611 imRange = NSMakeRange(0, 0);
612 markedRange = NSMakeRange(NSNotFound, 0);
613 [markedText release];
617 - (NSMutableAttributedString *)markedText
622 - (void)setPreEditRow:(int)row column:(int)col
635 return preEditColumn;
638 - (void)setImRange:(NSRange)range
648 - (void)setMarkedRange:(NSRange)range
653 - (NSRect)firstRectForCharacterRange:(NSRange)range
655 // This method is called when the input manager wants to pop up an
656 // auxiliary window. The position where this should be is controlled by
657 // Vim by sending SetPreEditPositionMsgID so compute a position based on
658 // the pre-edit (row,column) pair.
659 int col = preEditColumn;
660 int row = preEditRow + 1;
662 NSFont *theFont = [[textView markedTextAttributes]
663 valueForKey:NSFontAttributeName];
664 if (theFont == [textView fontWide]) {
665 col += imRange.location * 2;
666 if (col >= [textView maxColumns] - 1) {
667 row += (col / [textView maxColumns]);
668 col = col % 2 ? col % [textView maxColumns] + 1 :
669 col % [textView maxColumns];
672 col += imRange.location;
673 if (col >= [textView maxColumns]) {
674 row += (col / [textView maxColumns]);
675 col = col % [textView maxColumns];
679 NSRect rect = [textView rectForRow:row
682 numColumns:range.length];
684 rect.origin = [textView convertPoint:rect.origin toView:nil];
685 rect.origin = [[textView window] convertBaseToScreen:rect.origin];
690 @end // MMTextViewHelper
695 @implementation MMTextViewHelper (Private)
697 - (MMWindowController *)windowController
699 id windowController = [[textView window] windowController];
700 if ([windowController isKindOfClass:[MMWindowController class]])
701 return (MMWindowController*)windowController;
705 - (MMVimController *)vimController
707 return [[self windowController] vimController];
710 - (void)dispatchKeyEvent:(NSEvent *)event
712 // Only handle the command if it came from a keyDown event
713 if ([event type] != NSKeyDown)
716 NSString *chars = [event characters];
717 NSString *unmodchars = [event charactersIgnoringModifiers];
718 unichar c = [chars characterAtIndex:0];
719 unichar imc = [unmodchars characterAtIndex:0];
721 const char *bytes = 0;
722 int mods = [event modifierFlags];
724 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
725 // _cmd, c, imc, chars, unmodchars);
727 if (' ' == imc && 0xa0 != c) {
728 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
729 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
730 // should be passed on as is.)
731 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
732 bytes = [unmodchars UTF8String];
733 } else if (imc == c && '2' == c) {
734 // HACK! Translate Ctrl+2 to <C-@>.
735 static char ctrl_at = 0;
736 len = 1; bytes = &ctrl_at;
737 } else if (imc == c && '6' == c) {
738 // HACK! Translate Ctrl+6 to <C-^>.
739 static char ctrl_hat = 0x1e;
740 len = 1; bytes = &ctrl_hat;
741 } else if (c == 0x19 && imc == 0x19) {
742 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
743 // separately (else Ctrl-Y doesn't work).
744 static char tab = 0x9;
745 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
747 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
748 bytes = [chars UTF8String];
751 [self sendKeyDown:bytes length:len modifiers:mods];
754 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
756 if (chars && len > 0) {
757 NSMutableData *data = [NSMutableData data];
759 [data appendBytes:&flags length:sizeof(int)];
760 [data appendBytes:&len length:sizeof(int)];
761 [data appendBytes:chars length:len];
763 [self hideMouseCursor];
765 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
766 [[self vimController] sendMessage:KeyDownMsgID data:data];
770 - (void)hideMouseCursor
772 // Check 'mousehide' option
773 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
774 if (mh && ![mh boolValue])
775 [NSCursor setHiddenUntilMouseMoves:NO];
777 [NSCursor setHiddenUntilMouseMoves:YES];
780 - (void)startDragTimerWithInterval:(NSTimeInterval)t
782 [NSTimer scheduledTimerWithTimeInterval:t target:self
783 selector:@selector(dragTimerFired:)
784 userInfo:nil repeats:NO];
787 - (void)dragTimerFired:(NSTimer *)timer
789 // TODO: Autoscroll in horizontal direction?
790 static unsigned tick = 1;
792 isAutoscrolling = NO;
794 if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
795 // HACK! If the mouse cursor is outside the text area, then send a
796 // dragged event. However, if row&col hasn't changed since the last
797 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
798 // Thus we fiddle with the column to make sure something happens.
799 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
800 NSMutableData *data = [NSMutableData data];
802 [data appendBytes:&dragRow length:sizeof(int)];
803 [data appendBytes:&col length:sizeof(int)];
804 [data appendBytes:&dragFlags length:sizeof(int)];
806 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
808 isAutoscrolling = YES;
812 // Compute timer interval depending on how far away the mouse cursor is
813 // from the text view.
814 NSRect rect = [self trackingRect];
816 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
817 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
818 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
820 NSTimeInterval t = MMDragTimerMaxInterval -
821 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
823 [self startDragTimerWithInterval:t];
831 static NSCursor *customIbeamCursor = nil;
833 if (!customIbeamCursor) {
834 // Use a custom Ibeam cursor that has better contrast against dark
836 // TODO: Is the hotspot ok?
837 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
839 NSSize size = [ibeamImage size];
840 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
842 customIbeamCursor = [[NSCursor alloc]
843 initWithImage:ibeamImage hotSpot:hotSpot];
845 if (!customIbeamCursor) {
846 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
847 customIbeamCursor = [NSCursor IBeamCursor];
851 // This switch should match mshape_names[] in misc2.c.
853 // TODO: Add missing cursor shapes.
854 switch (mouseShape) {
855 case 2: [customIbeamCursor set]; break;
856 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
857 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
858 case 9: [[NSCursor crosshairCursor] set]; break;
859 case 10: [[NSCursor pointingHandCursor] set]; break;
860 case 11: [[NSCursor openHandCursor] set]; break;
862 [[NSCursor arrowCursor] set]; break;
865 // Shape 1 indicates that the mouse cursor should be hidden.
867 [NSCursor setHiddenUntilMouseMoves:YES];
870 - (NSRect)trackingRect
872 NSRect rect = [textView frame];
873 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
874 int left = [ud integerForKey:MMTextInsetLeftKey];
875 int top = [ud integerForKey:MMTextInsetTopKey];
876 int right = [ud integerForKey:MMTextInsetRightKey];
877 int bot = [ud integerForKey:MMTextInsetBottomKey];
879 rect.origin.x = left;
881 rect.size.width -= left + right - 1;
882 rect.size.height -= top + bot - 1;
887 @end // MMTextViewHelper (Private)