Exit full-screen if the window moves
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blobf2930052e439af9fc5cc4273a75f8d1f001423c0
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     [insertionPointColor release];  insertionPointColor = nil;
56     [markedText release];  markedText = nil;
57     [markedTextAttributes release];  markedTextAttributes = nil;
59     [super dealloc];
62 - (void)setTextView:(id)view
64     // Only keep a weak reference to owning text view.
65     textView = view;
68 - (void)setInsertionPointColor:(NSColor *)color
70     if (color != insertionPointColor) {
71         [insertionPointColor release];
72         insertionPointColor = [color retain];
73     }
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.
90     //
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];
99         return;
100     }
102     int flags = [event modifierFlags];
103     if ((flags & NSControlKeyMask) ||
104             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
105         BOOL unmodIsPrintable = YES;
106         NSString *unmod = [event charactersIgnoringModifiers];
107         if (unmod && [unmod length] > 0 && [unmod characterAtIndex:0] < 0x20)
108             unmodIsPrintable = NO;
110         NSString *chars = [event characters];
111         if ([chars length] == 1 && [chars characterAtIndex:0] < 0x20
112                 && unmodIsPrintable) {
113             // HACK! Send unprintable characters (such as C-@, C-[, C-\, C-],
114             // C-^, C-_) as normal text to be added to the Vim input buffer.
115             // This must be done in order for the backend to be able to
116             // separate e.g. Ctrl-i and Ctrl-tab.
117             [self insertText:chars];
118         } else {
119             [self dispatchKeyEvent:event];
120         }
121     } else if ((flags & NSAlternateKeyMask) &&
122             [[[[self vimController] vimState] objectForKey:@"p_mmta"]
123                                                                 boolValue]) {
124         // If the 'macmeta' option is set, then send Alt+key presses directly
125         // to Vim without interpreting the key press.
126         NSString *unmod = [event charactersIgnoringModifiers];
127         int len = [unmod lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
128         const char *bytes = [unmod UTF8String];
130         [self sendKeyDown:bytes length:len modifiers:flags
131                 isARepeat:[event isARepeat]];
132     } else {
133         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
134     }
137 - (void)insertText:(id)string
139     //NSLog(@"%s %@", _cmd, string);
140     // NOTE!  This method is called for normal key presses but also for
141     // Option-key presses --- even when Ctrl is held as well as Option.  When
142     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
143     // so 'string' need not be a printable character!  In this case it still
144     // works to pass 'string' on to Vim as a printable character (since
145     // modifiers are already included and should not be added to the input
146     // buffer using CSI, K_MODIFIER).
148     if ([textView hasMarkedText]) {
149         [textView unmarkText];
150     }
152     NSEvent *event = [NSApp currentEvent];
154     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
155     // to watch for them here.
156     if ([event type] == NSKeyDown
157             && [[event charactersIgnoringModifiers] length] > 0
158             && [event modifierFlags]
159                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
160         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
162         // <S-M-Tab> translates to 0x19 
163         if (' ' == c || 0x19 == c) {
164             [self dispatchKeyEvent:event];
165             return;
166         }
167     }
169     [self hideMouseCursor];
171     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
172     // do not support attributes, simply pass the corresponding NSString in the
173     // latter case.
174     if ([string isKindOfClass:[NSAttributedString class]])
175         string = [string string];
177     //NSLog(@"send InsertTextMsgID: %@", string);
179     NSMutableData *data = [NSMutableData data];
180     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
181     int flags = [event modifierFlags] & 0xffff0000U;
182     if ([event type] == NSKeyDown && [event isARepeat])
183         flags |= 1;
185     [data appendBytes:&flags length:sizeof(int)];
186     [data appendBytes:&len length:sizeof(int)];
187     [data appendBytes:[string UTF8String] length:len];
189     [[self vimController] sendMessage:InsertTextMsgID data:data];
192 - (void)doCommandBySelector:(SEL)selector
194     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
195     // By ignoring the selector we effectively disable the key binding
196     // mechanism of Cocoa.  Hopefully this is what the user will expect
197     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
198     // match, etc.).
199     //
200     // We usually end up here if the user pressed Ctrl+key (but not
201     // Ctrl+Option+key).
203     NSEvent *event = [NSApp currentEvent];
205     if (selector == @selector(cancelOperation:)
206             || selector == @selector(insertNewline:)) {
207         // HACK! If there was marked text which got abandoned as a result of
208         // hitting escape or enter, then 'insertText:' is called with the
209         // abandoned text but '[event characters]' includes the abandoned text
210         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
211         // must intercept these keys here or the abandonded text gets inserted
212         // twice.
213         NSString *key = [event charactersIgnoringModifiers];
214         const char *chars = [key UTF8String];
215         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
217         if (0x3 == chars[0]) {
218             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
219             // handle it separately (else Ctrl-C doesn't work).
220             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
221             chars = MMKeypadEnter;
222         }
224         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]
225                 isARepeat:[event isARepeat]];
226     } else {
227         [self dispatchKeyEvent:event];
228     }
231 - (BOOL)performKeyEquivalent:(NSEvent *)event
233     //NSLog(@"%s %@", _cmd, event);
234     // Called for Cmd+key keystrokes, function keys, arrow keys, page
235     // up/down, home, end.
236     //
237     // NOTE: This message cannot be ignored since Cmd+letter keys never are
238     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
239     // strokes, unless the key is a function key.
241     // NOTE: If the event that triggered this method represents a function key
242     // down then we do nothing, otherwise the input method never gets the key
243     // stroke (some input methods use e.g. arrow keys).  The function key down
244     // event will still reach Vim though (via keyDown:).  The exceptions to
245     // this rule are: PageUp/PageDown (keycode 116/121).
246     int flags = [event modifierFlags] & 0xffff0000U;
247     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
248             && !(116 == [event keyCode] || 121 == [event keyCode]))
249         return NO;
251     // HACK!  KeyCode 50 represent the key which switches between windows
252     // within an application (like Cmd+Tab is used to switch between
253     // applications).  Return NO here, else the window switching does not work.
254     if ([event keyCode] == 50)
255         return NO;
257     // HACK!  Let the main menu try to handle any key down event, before
258     // passing it on to vim, otherwise key equivalents for menus will
259     // effectively be disabled.
260     if ([[NSApp mainMenu] performKeyEquivalent:event])
261         return YES;
263     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
264     if (flags & NSControlKeyMask) {
265         [self keyDown:event];
266         return YES;
267     }
269     // HACK!  Don't handle Cmd-? or the "Help" menu does not work on Leopard.
270     NSString *unmodchars = [event charactersIgnoringModifiers];
271     if ([unmodchars isEqual:@"?"])
272         return NO;
274     // Cmd-. is hard-wired to send SIGINT unlike Ctrl-C which is just another
275     // key press which Vim has to interpret.  This means that Cmd-. always
276     // works to interrupt a Vim process whereas Ctrl-C can suffer from problems
277     // such as dropped DO messages (or if Vim is stuck in a loop without
278     // checking for keyboard input).
279     if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
280             [unmodchars isEqual:@"."]) {
281         kill([[self vimController] pid], SIGINT);
282         return YES;
283     }
285     //NSLog(@"%s%@", _cmd, event);
287     NSString *chars = [event characters];
288     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
289     NSMutableData *data = [NSMutableData data];
291     if (len <= 0)
292         return NO;
294     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
295     // can clear the shift flag as it is already included in 'unmodchars'.
296     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
297     // an English keyboard).
298     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
299         flags &= ~NSShiftKeyMask;
301     if (0x3 == [unmodchars characterAtIndex:0]) {
302         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
303         // handle it separately (else Cmd-enter turns into Ctrl-C).
304         unmodchars = MMKeypadEnterString;
305         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
306     }
308     if ([event isARepeat])
309         flags |= 1;
311     [data appendBytes:&flags length:sizeof(int)];
312     [data appendBytes:&len length:sizeof(int)];
313     [data appendBytes:[unmodchars UTF8String] length:len];
315     [[self vimController] sendMessage:CmdKeyMsgID data:data];
317     return YES;
320 - (void)scrollWheel:(NSEvent *)event
322     if ([event deltaY] == 0)
323         return;
325     int row, col;
326     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
327     if ([textView convertPoint:pt toRow:&row column:&col]) {
328         int flags = [event modifierFlags];
329         float dy = [event deltaY];
330         NSMutableData *data = [NSMutableData data];
332         [data appendBytes:&row length:sizeof(int)];
333         [data appendBytes:&col length:sizeof(int)];
334         [data appendBytes:&flags length:sizeof(int)];
335         [data appendBytes:&dy length:sizeof(float)];
337         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
338     }
341 - (void)mouseDown:(NSEvent *)event
343     int row, col;
344     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
345     if (![textView convertPoint:pt toRow:&row column:&col])
346         return;
348     int button = [event buttonNumber];
349     int flags = [event modifierFlags];
350     int count = [event clickCount];
351     NSMutableData *data = [NSMutableData data];
353     // If desired, intepret Ctrl-Click as a right mouse click.
354     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
355             boolForKey:MMTranslateCtrlClickKey];
356     flags = flags & NSDeviceIndependentModifierFlagsMask;
357     if (translateCtrlClick && button == 0 &&
358             (flags == NSControlKeyMask ||
359              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
360         button = 1;
361         flags &= ~NSControlKeyMask;
362     }
364     [data appendBytes:&row length:sizeof(int)];
365     [data appendBytes:&col length:sizeof(int)];
366     [data appendBytes:&button length:sizeof(int)];
367     [data appendBytes:&flags length:sizeof(int)];
368     [data appendBytes:&count length:sizeof(int)];
370     [[self vimController] sendMessage:MouseDownMsgID data:data];
373 - (void)mouseUp:(NSEvent *)event
375     int row, col;
376     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
377     if (![textView convertPoint:pt toRow:&row column:&col])
378         return;
380     int flags = [event modifierFlags];
381     NSMutableData *data = [NSMutableData data];
383     [data appendBytes:&row length:sizeof(int)];
384     [data appendBytes:&col length:sizeof(int)];
385     [data appendBytes:&flags length:sizeof(int)];
387     [[self vimController] sendMessage:MouseUpMsgID data:data];
389     isDragging = NO;
392 - (void)mouseDragged:(NSEvent *)event
394     int flags = [event modifierFlags];
395     int row, col;
396     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
397     if (![textView convertPoint:pt toRow:&row column:&col])
398         return;
400     // Autoscrolling is done in dragTimerFired:
401     if (!isAutoscrolling) {
402         NSMutableData *data = [NSMutableData data];
404         [data appendBytes:&row length:sizeof(int)];
405         [data appendBytes:&col length:sizeof(int)];
406         [data appendBytes:&flags length:sizeof(int)];
408         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
409     }
411     dragPoint = pt;
412     dragRow = row;
413     dragColumn = col;
414     dragFlags = flags;
416     if (!isDragging) {
417         [self startDragTimerWithInterval:.5];
418         isDragging = YES;
419     }
422 - (void)mouseMoved:(NSEvent *)event
424     // HACK! NSTextView has a nasty habit of resetting the cursor to the
425     // default I-beam cursor at random moments.  The only reliable way we know
426     // of to work around this is to set the cursor each time the mouse moves.
427     [self setCursor];
429     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
430     int row, col;
431     if (![textView convertPoint:pt toRow:&row column:&col])
432         return;
434     // HACK! It seems impossible to get the tracking rects set up before the
435     // view is visible, which means that the first mouseEntered: or
436     // mouseExited: events are never received.  This forces us to check if the
437     // mouseMoved: event really happened over the text.
438     int rows, cols;
439     [textView getMaxRows:&rows columns:&cols];
440     if (row >= 0 && row < rows && col >= 0 && col < cols) {
441         NSMutableData *data = [NSMutableData data];
443         [data appendBytes:&row length:sizeof(int)];
444         [data appendBytes:&col length:sizeof(int)];
446         [[self vimController] sendMessage:MouseMovedMsgID data:data];
448         //NSLog(@"Moved %d %d\n", col, row);
449     }
452 - (void)mouseEntered:(NSEvent *)event
454     //NSLog(@"%s", _cmd);
456     // NOTE: This event is received even when the window is not key; thus we
457     // have to take care not to enable mouse moved events unless our window is
458     // key.
459     if ([[textView window] isKeyWindow]) {
460         [[textView window] setAcceptsMouseMovedEvents:YES];
461     }
464 - (void)mouseExited:(NSEvent *)event
466     //NSLog(@"%s", _cmd);
468     [[textView window] setAcceptsMouseMovedEvents:NO];
470     // NOTE: This event is received even when the window is not key; if the
471     // mouse shape is set when our window is not key, the hollow (unfocused)
472     // cursor will become a block (focused) cursor.
473     if ([[textView window] isKeyWindow]) {
474         int shape = 0;
475         NSMutableData *data = [NSMutableData data];
476         [data appendBytes:&shape length:sizeof(int)];
477         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
478     }
481 - (void)setFrame:(NSRect)frame
483     //NSLog(@"%s", _cmd);
485     // When the frame changes we also need to update the tracking rect.
486     [textView removeTrackingRect:trackingRectTag];
487     trackingRectTag = [textView addTrackingRect:[self trackingRect]
488                                           owner:textView
489                                        userData:NULL
490                                    assumeInside:YES];
493 - (void)viewDidMoveToWindow
495     //NSLog(@"%s (window=%@)", _cmd, [self window]);
497     // Set a tracking rect which covers the text.
498     // NOTE: While the mouse cursor is in this rect the view will receive
499     // 'mouseMoved:' events so that Vim can take care of updating the mouse
500     // cursor.
501     if ([textView window]) {
502         [[textView window] setAcceptsMouseMovedEvents:YES];
503         trackingRectTag = [textView addTrackingRect:[self trackingRect]
504                                               owner:textView
505                                            userData:NULL
506                                        assumeInside:YES];
507     }
510 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
512     //NSLog(@"%s%@", _cmd, newWindow);
514     // Remove tracking rect if view moves or is removed.
515     if ([textView window] && trackingRectTag) {
516         [textView removeTrackingRect:trackingRectTag];
517         trackingRectTag = 0;
518     }
521 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
523     NSPasteboard *pboard = [sender draggingPasteboard];
525     if ([[pboard types] containsObject:NSStringPboardType]) {
526         NSString *string = [pboard stringForType:NSStringPboardType];
527         [[self vimController] dropString:string];
528         return YES;
529     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
530         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
531         [[self vimController] dropFiles:files forceOpen:NO];
532         return YES;
533     }
535     return NO;
538 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
540     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
541     NSPasteboard *pboard = [sender draggingPasteboard];
543     if ( [[pboard types] containsObject:NSFilenamesPboardType]
544             && (sourceDragMask & NSDragOperationCopy) )
545         return NSDragOperationCopy;
546     if ( [[pboard types] containsObject:NSStringPboardType]
547             && (sourceDragMask & NSDragOperationCopy) )
548         return NSDragOperationCopy;
550     return NSDragOperationNone;
553 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
555     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
556     NSPasteboard *pboard = [sender draggingPasteboard];
558     if ( [[pboard types] containsObject:NSFilenamesPboardType]
559             && (sourceDragMask & NSDragOperationCopy) )
560         return NSDragOperationCopy;
561     if ( [[pboard types] containsObject:NSStringPboardType]
562             && (sourceDragMask & NSDragOperationCopy) )
563         return NSDragOperationCopy;
565     return NSDragOperationNone;
568 - (void)setMouseShape:(int)shape
570     mouseShape = shape;
571     [self setCursor];
574 - (BOOL)hasMarkedText
576     return markedRange.length > 0 ? YES : NO;
579 - (NSRange)markedRange
581     if ([self hasMarkedText])
582         return markedRange;
583     else
584         return NSMakeRange(NSNotFound, 0);
587 - (NSDictionary *)markedTextAttributes
589     return markedTextAttributes;
592 - (void)setMarkedTextAttributes:(NSDictionary *)attr
594     if (attr != markedTextAttributes) {
595         [markedTextAttributes release];
596         markedTextAttributes = [attr retain];
597     }
600 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
602     [self unmarkText];
604     if (!(text && [text length] > 0))
605         return;
607     // HACK! Determine if the marked text is wide or normal width.  This seems
608     // to always use 'wide' when there are both wide and normal width
609     // characters.
610     NSString *string = text;
611     NSFont *theFont = [textView font];
612     if ([text isKindOfClass:[NSAttributedString class]]) {
613         theFont = [textView fontWide];
614         string = [text string];
615     }
617     // TODO: Use special colors for marked text.
618     [self setMarkedTextAttributes:
619         [NSDictionary dictionaryWithObjectsAndKeys:
620             theFont, NSFontAttributeName,
621             [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
622             [textView defaultForegroundColor], NSForegroundColorAttributeName,
623             nil]];
625     markedText = [[NSMutableAttributedString alloc]
626            initWithString:string
627                attributes:[self markedTextAttributes]];
629     markedRange = NSMakeRange(0, [markedText length]);
630     if (markedRange.length) {
631         [markedText addAttribute:NSUnderlineStyleAttributeName
632                            value:[NSNumber numberWithInt:1]
633                            range:markedRange];
634     }
635     imRange = range;
636     if (range.length) {
637         [markedText addAttribute:NSUnderlineStyleAttributeName
638                            value:[NSNumber numberWithInt:2]
639                            range:range];
640     }
642     [textView setNeedsDisplay:YES];
645 - (void)unmarkText
647     imRange = NSMakeRange(0, 0);
648     markedRange = NSMakeRange(NSNotFound, 0);
649     [markedText release];
650     markedText = nil;
653 - (NSMutableAttributedString *)markedText
655     return markedText;
658 - (void)setPreEditRow:(int)row column:(int)col
660     preEditRow = row;
661     preEditColumn = col;
664 - (int)preEditRow
666     return preEditRow;
669 - (int)preEditColumn
671     return preEditColumn;
674 - (void)setImRange:(NSRange)range
676     imRange = range;
679 - (NSRange)imRange
681     return imRange;
684 - (void)setMarkedRange:(NSRange)range
686     markedRange = range;
689 - (NSRect)firstRectForCharacterRange:(NSRange)range
691     // This method is called when the input manager wants to pop up an
692     // auxiliary window.  The position where this should be is controlled by
693     // Vim by sending SetPreEditPositionMsgID so compute a position based on
694     // the pre-edit (row,column) pair.
695     int col = preEditColumn;
696     int row = preEditRow + 1;
698     NSFont *theFont = [[textView markedTextAttributes]
699             valueForKey:NSFontAttributeName];
700     if (theFont == [textView fontWide]) {
701         col += imRange.location * 2;
702         if (col >= [textView maxColumns] - 1) {
703             row += (col / [textView maxColumns]);
704             col = col % 2 ? col % [textView maxColumns] + 1 :
705                             col % [textView maxColumns];
706         }
707     } else {
708         col += imRange.location;
709         if (col >= [textView maxColumns]) {
710             row += (col / [textView maxColumns]);
711             col = col % [textView maxColumns];
712         }
713     }
715     NSRect rect = [textView rectForRow:row
716                                 column:col
717                                numRows:1
718                             numColumns:range.length];
720     rect.origin = [textView convertPoint:rect.origin toView:nil];
721     rect.origin = [[textView window] convertBaseToScreen:rect.origin];
723     return rect;
726 @end // MMTextViewHelper
731 @implementation MMTextViewHelper (Private)
733 - (MMWindowController *)windowController
735     id windowController = [[textView window] windowController];
736     if ([windowController isKindOfClass:[MMWindowController class]])
737         return (MMWindowController*)windowController;
738     return nil;
741 - (MMVimController *)vimController
743     return [[self windowController] vimController];
746 - (void)dispatchKeyEvent:(NSEvent *)event
748     // Only handle the command if it came from a keyDown event
749     if ([event type] != NSKeyDown)
750         return;
752     NSString *chars = [event characters];
753     NSString *unmodchars = [event charactersIgnoringModifiers];
754     unichar c = [chars characterAtIndex:0];
755     unichar imc = [unmodchars length] > 0 ? [unmodchars characterAtIndex:0] : 0;
756     int len = 0;
757     const char *bytes = 0;
758     int mods = [event modifierFlags];
760     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
761     //        _cmd, c, imc, chars, unmodchars);
763     if (' ' == imc && 0xa0 != c) {
764         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
765         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
766         // should be passed on as is.)
767         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
768         bytes = [unmodchars UTF8String];
769     } else if (imc == c && '2' == c) {
770         // HACK!  Translate Ctrl+2 to <C-@>.
771         static char ctrl_at = 0;
772         len = 1;  bytes = &ctrl_at;
773     } else if (imc == c && '6' == c) {
774         // HACK!  Translate Ctrl+6 to <C-^>.
775         static char ctrl_hat = 0x1e;
776         len = 1;  bytes = &ctrl_hat;
777     } else if (c == 0x19 && imc == 0x19) {
778         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
779         // separately (else Ctrl-Y doesn't work).
780         static char tab = 0x9;
781         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
782     } else {
783         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
784         bytes = [chars UTF8String];
785     }
787     [self sendKeyDown:bytes length:len modifiers:mods
788             isARepeat:[event isARepeat]];
791 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
792           isARepeat:(BOOL)isARepeat
794     if (chars && len > 0) {
795         NSMutableData *data = [NSMutableData data];
797         // The low 16 bits are not used for modifier flags by NSEvent.  Use
798         // these bits for custom flags.
799         flags &= 0xffff0000;
800         if (isARepeat)
801             flags |= 1;
803         [data appendBytes:&flags length:sizeof(int)];
804         [data appendBytes:&len length:sizeof(int)];
805         [data appendBytes:chars length:len];
807         [self hideMouseCursor];
809         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
810         [[self vimController] sendMessage:KeyDownMsgID data:data];
811     }
814 - (void)hideMouseCursor
816     // Check 'mousehide' option
817     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
818     if (mh && ![mh boolValue])
819         [NSCursor setHiddenUntilMouseMoves:NO];
820     else
821         [NSCursor setHiddenUntilMouseMoves:YES];
824 - (void)startDragTimerWithInterval:(NSTimeInterval)t
826     [NSTimer scheduledTimerWithTimeInterval:t target:self
827                                    selector:@selector(dragTimerFired:)
828                                    userInfo:nil repeats:NO];
831 - (void)dragTimerFired:(NSTimer *)timer
833     // TODO: Autoscroll in horizontal direction?
834     static unsigned tick = 1;
836     isAutoscrolling = NO;
838     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
839         // HACK! If the mouse cursor is outside the text area, then send a
840         // dragged event.  However, if row&col hasn't changed since the last
841         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
842         // Thus we fiddle with the column to make sure something happens.
843         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
844         NSMutableData *data = [NSMutableData data];
846         [data appendBytes:&dragRow length:sizeof(int)];
847         [data appendBytes:&col length:sizeof(int)];
848         [data appendBytes:&dragFlags length:sizeof(int)];
850         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
852         isAutoscrolling = YES;
853     }
855     if (isDragging) {
856         // Compute timer interval depending on how far away the mouse cursor is
857         // from the text view.
858         NSRect rect = [self trackingRect];
859         float dy = 0;
860         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
861         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
862         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
864         NSTimeInterval t = MMDragTimerMaxInterval -
865             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
867         [self startDragTimerWithInterval:t];
868     }
870     ++tick;
873 - (void)setCursor
875     static NSCursor *customIbeamCursor = nil;
877     if (!customIbeamCursor) {
878         // Use a custom Ibeam cursor that has better contrast against dark
879         // backgrounds.
880         // TODO: Is the hotspot ok?
881         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
882         if (ibeamImage) {
883             NSSize size = [ibeamImage size];
884             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
886             customIbeamCursor = [[NSCursor alloc]
887                     initWithImage:ibeamImage hotSpot:hotSpot];
888         }
889         if (!customIbeamCursor) {
890             NSLog(@"WARNING: Failed to load custom Ibeam cursor");
891             customIbeamCursor = [NSCursor IBeamCursor];
892         }
893     }
895     // This switch should match mshape_names[] in misc2.c.
896     //
897     // TODO: Add missing cursor shapes.
898     switch (mouseShape) {
899         case 2: [customIbeamCursor set]; break;
900         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
901         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
902         case 9: [[NSCursor crosshairCursor] set]; break;
903         case 10: [[NSCursor pointingHandCursor] set]; break;
904         case 11: [[NSCursor openHandCursor] set]; break;
905         default:
906             [[NSCursor arrowCursor] set]; break;
907     }
909     // Shape 1 indicates that the mouse cursor should be hidden.
910     if (1 == mouseShape)
911         [NSCursor setHiddenUntilMouseMoves:YES];
914 - (NSRect)trackingRect
916     NSRect rect = [textView frame];
917     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
918     int left = [ud integerForKey:MMTextInsetLeftKey];
919     int top = [ud integerForKey:MMTextInsetTopKey];
920     int right = [ud integerForKey:MMTextInsetRightKey];
921     int bot = [ud integerForKey:MMTextInsetBottomKey];
923     rect.origin.x = left;
924     rect.origin.y = top;
925     rect.size.width -= left + right - 1;
926     rect.size.height -= top + bot - 1;
928     return rect;
931 @end // MMTextViewHelper (Private)