Cmd-. sends interrupt
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blob77f3314b773182267fbf2fc63f086e1d7ca906fc
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;
36 // Number of seconds to delay before sending scroll wheel events.  (A delay of
37 // 0.05 seconds equals an update frequency of 20 Hz.)
38 static NSTimeInterval MMScrollWheelDelay = 0.05;
41 @interface MMTextViewHelper (Private)
42 - (MMWindowController *)windowController;
43 - (MMVimController *)vimController;
44 - (void)dispatchKeyEvent:(NSEvent *)event;
45 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
46 - (void)hideMouseCursor;
47 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
48 - (void)dragTimerFired:(NSTimer *)timer;
49 - (void)setCursor;
50 - (NSRect)trackingRect;
51 - (void)handleScrollWheelEvent:(id)event;
52 @end
55 @implementation MMTextViewHelper
57 - (void)setTextView:(id)view
59     // Only keep a weak reference to owning text view.
60     textView = view;
63 - (void)keyDown:(NSEvent *)event
65     //NSLog(@"%s %@", _cmd, event);
66     // HACK! If control modifier is held, don't pass the event along to
67     // interpretKeyEvents: since some keys are bound to multiple commands which
68     // means doCommandBySelector: is called several times.  Do the same for
69     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
70     // commands).  This hack may break input management, but unless we can
71     // figure out a way to disable key bindings there seems little else to do.
72     //
73     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
74     // affecting input management.
76     // When the Input Method is activated, some special key inputs
77     // should be treated as key inputs for Input Method.
78     if ([textView hasMarkedText]) {
79         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
80         [textView setNeedsDisplay:YES];
81         return;
82     }
84     int flags = [event modifierFlags];
85     if ((flags & NSControlKeyMask) ||
86             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
87         NSString *unmod = [event charactersIgnoringModifiers];
88         if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
89                                 && [unmod characterAtIndex:0] >= 0x60) {
90             // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
91             // as normal text to be added to the Vim input buffer.  This must
92             // be done in order for the backend to be able to separate e.g.
93             // Ctrl-i and Ctrl-tab.
94             [self insertText:[event characters]];
95         } else {
96             [self dispatchKeyEvent:event];
97         }
98     } else {
99         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
100     }
103 - (void)insertText:(id)string
105     //NSLog(@"%s %@", _cmd, string);
106     // NOTE!  This method is called for normal key presses but also for
107     // Option-key presses --- even when Ctrl is held as well as Option.  When
108     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
109     // so 'string' need not be a printable character!  In this case it still
110     // works to pass 'string' on to Vim as a printable character (since
111     // modifiers are already included and should not be added to the input
112     // buffer using CSI, K_MODIFIER).
114     if ([textView hasMarkedText]) {
115         [textView unmarkText];
116     }
118     NSEvent *event = [NSApp currentEvent];
120     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
121     // to watch for them here.
122     if ([event type] == NSKeyDown
123             && [[event charactersIgnoringModifiers] length] > 0
124             && [event modifierFlags]
125                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
126         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
128         // <S-M-Tab> translates to 0x19 
129         if (' ' == c || 0x19 == c) {
130             [self dispatchKeyEvent:event];
131             return;
132         }
133     }
135     [self hideMouseCursor];
137     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
138     // do not support attributes, simply pass the corresponding NSString in the
139     // latter case.
140     if ([string isKindOfClass:[NSAttributedString class]])
141         string = [string string];
143     //NSLog(@"send InsertTextMsgID: %@", string);
145     [[self vimController] sendMessage:InsertTextMsgID
146                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
149 - (void)doCommandBySelector:(SEL)selector
151     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
152     // By ignoring the selector we effectively disable the key binding
153     // mechanism of Cocoa.  Hopefully this is what the user will expect
154     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
155     // match, etc.).
156     //
157     // We usually end up here if the user pressed Ctrl+key (but not
158     // Ctrl+Option+key).
160     NSEvent *event = [NSApp currentEvent];
162     if (selector == @selector(cancelOperation:)
163             || selector == @selector(insertNewline:)) {
164         // HACK! If there was marked text which got abandoned as a result of
165         // hitting escape or enter, then 'insertText:' is called with the
166         // abandoned text but '[event characters]' includes the abandoned text
167         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
168         // must intercept these keys here or the abandonded text gets inserted
169         // twice.
170         NSString *key = [event charactersIgnoringModifiers];
171         const char *chars = [key UTF8String];
172         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
174         if (0x3 == chars[0]) {
175             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
176             // handle it separately (else Ctrl-C doesn't work).
177             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
178             chars = MMKeypadEnter;
179         }
181         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
182     } else {
183         [self dispatchKeyEvent:event];
184     }
187 - (BOOL)performKeyEquivalent:(NSEvent *)event
189     //NSLog(@"%s %@", _cmd, event);
190     // Called for Cmd+key keystrokes, function keys, arrow keys, page
191     // up/down, home, end.
192     //
193     // NOTE: This message cannot be ignored since Cmd+letter keys never are
194     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
195     // strokes, unless the key is a function key.
197     // NOTE: If the event that triggered this method represents a function key
198     // down then we do nothing, otherwise the input method never gets the key
199     // stroke (some input methods use e.g. arrow keys).  The function key down
200     // event will still reach Vim though (via keyDown:).  The exceptions to
201     // this rule are: PageUp/PageDown (keycode 116/121).
202     int flags = [event modifierFlags];
203     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
204             && !(116 == [event keyCode] || 121 == [event keyCode]))
205         return NO;
207     // HACK!  KeyCode 50 represent the key which switches between windows
208     // within an application (like Cmd+Tab is used to switch between
209     // applications).  Return NO here, else the window switching does not work.
210     if ([event keyCode] == 50)
211         return NO;
213     // HACK!  Let the main menu try to handle any key down event, before
214     // passing it on to vim, otherwise key equivalents for menus will
215     // effectively be disabled.
216     if ([[NSApp mainMenu] performKeyEquivalent:event])
217         return YES;
219     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
220     if (flags & NSControlKeyMask) {
221         [self keyDown:event];
222         return YES;
223     }
225     // HACK!  Don't handle Cmd-? or the "Help" menu does not work on Leopard.
226     NSString *unmodchars = [event charactersIgnoringModifiers];
227     if ([unmodchars isEqual:@"?"])
228         return NO;
230     // Cmd-. is hard-wired to send an interrupt (like Ctrl-C).
231     if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
232             [unmodchars isEqual:@"."]) {
233         [[self vimController] sendMessage:InterruptMsgID data:nil];
234         return YES;
235     }
237     //NSLog(@"%s%@", _cmd, event);
239     NSString *chars = [event characters];
240     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
241     NSMutableData *data = [NSMutableData data];
243     if (len <= 0)
244         return NO;
246     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
247     // can clear the shift flag as it is already included in 'unmodchars'.
248     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
249     // an English keyboard).
250     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
251         flags &= ~NSShiftKeyMask;
253     if (0x3 == [unmodchars characterAtIndex:0]) {
254         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
255         // handle it separately (else Cmd-enter turns into Ctrl-C).
256         unmodchars = MMKeypadEnterString;
257         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
258     }
260     [data appendBytes:&flags length:sizeof(int)];
261     [data appendBytes:&len length:sizeof(int)];
262     [data appendBytes:[unmodchars UTF8String] length:len];
264     [[self vimController] sendMessage:CmdKeyMsgID data:data];
266     return YES;
269 - (void)scrollWheel:(NSEvent *)event
271     if ([event deltaY] == 0)
272         return;
274     // Don't send the event straight away because lots of these events may be
275     // received in rapid succession.  Instead, accumulate the events and send
276     // off the scroll total at a predetermined maximum rate.  This avoids
277     // clogging up the DO messaging system on faster machines.
278     if (0 == scrollWheelAccumulator)
279         [self performSelector:@selector(handleScrollWheelEvent:)
280                    withObject:event
281                    afterDelay:MMScrollWheelDelay];
283     scrollWheelAccumulator += [event deltaY];
286 - (void)mouseDown:(NSEvent *)event
288     int row, col;
289     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
290     if (![textView convertPoint:pt toRow:&row column:&col])
291         return;
293     int button = [event buttonNumber];
294     int flags = [event modifierFlags];
295     int count = [event clickCount];
296     NSMutableData *data = [NSMutableData data];
298     // If desired, intepret Ctrl-Click as a right mouse click.
299     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
300             boolForKey:MMTranslateCtrlClickKey];
301     flags = flags & NSDeviceIndependentModifierFlagsMask;
302     if (translateCtrlClick && button == 0 &&
303             (flags == NSControlKeyMask ||
304              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
305         button = 1;
306         flags &= ~NSControlKeyMask;
307     }
309     [data appendBytes:&row length:sizeof(int)];
310     [data appendBytes:&col length:sizeof(int)];
311     [data appendBytes:&button length:sizeof(int)];
312     [data appendBytes:&flags length:sizeof(int)];
313     [data appendBytes:&count length:sizeof(int)];
315     [[self vimController] sendMessage:MouseDownMsgID data:data];
318 - (void)mouseUp:(NSEvent *)event
320     int row, col;
321     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
322     if (![textView convertPoint:pt toRow:&row column:&col])
323         return;
325     int flags = [event modifierFlags];
326     NSMutableData *data = [NSMutableData data];
328     [data appendBytes:&row length:sizeof(int)];
329     [data appendBytes:&col length:sizeof(int)];
330     [data appendBytes:&flags length:sizeof(int)];
332     [[self vimController] sendMessage:MouseUpMsgID data:data];
334     isDragging = NO;
337 - (void)mouseDragged:(NSEvent *)event
339     int flags = [event modifierFlags];
340     int row, col;
341     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
342     if (![textView convertPoint:pt toRow:&row column:&col])
343         return;
345     // Autoscrolling is done in dragTimerFired:
346     if (!isAutoscrolling) {
347         NSMutableData *data = [NSMutableData data];
349         [data appendBytes:&row length:sizeof(int)];
350         [data appendBytes:&col length:sizeof(int)];
351         [data appendBytes:&flags length:sizeof(int)];
353         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
354     }
356     dragPoint = pt;
357     dragRow = row;
358     dragColumn = col;
359     dragFlags = flags;
361     if (!isDragging) {
362         [self startDragTimerWithInterval:.5];
363         isDragging = YES;
364     }
367 - (void)mouseMoved:(NSEvent *)event
369     // HACK! NSTextView has a nasty habit of resetting the cursor to the
370     // default I-beam cursor at random moments.  The only reliable way we know
371     // of to work around this is to set the cursor each time the mouse moves.
372     [self setCursor];
374     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
375     int row, col;
376     if (![textView convertPoint:pt toRow:&row column:&col])
377         return;
379     // HACK! It seems impossible to get the tracking rects set up before the
380     // view is visible, which means that the first mouseEntered: or
381     // mouseExited: events are never received.  This forces us to check if the
382     // mouseMoved: event really happened over the text.
383     int rows, cols;
384     [textView getMaxRows:&rows columns:&cols];
385     if (row >= 0 && row < rows && col >= 0 && col < cols) {
386         NSMutableData *data = [NSMutableData data];
388         [data appendBytes:&row length:sizeof(int)];
389         [data appendBytes:&col length:sizeof(int)];
391         [[self vimController] sendMessage:MouseMovedMsgID data:data];
393         //NSLog(@"Moved %d %d\n", col, row);
394     }
397 - (void)mouseEntered:(NSEvent *)event
399     //NSLog(@"%s", _cmd);
401     // NOTE: This event is received even when the window is not key; thus we
402     // have to take care not to enable mouse moved events unless our window is
403     // key.
404     if ([[textView window] isKeyWindow]) {
405         [[textView window] setAcceptsMouseMovedEvents:YES];
406     }
409 - (void)mouseExited:(NSEvent *)event
411     //NSLog(@"%s", _cmd);
413     [[textView window] setAcceptsMouseMovedEvents:NO];
415     // NOTE: This event is received even when the window is not key; if the
416     // mouse shape is set when our window is not key, the hollow (unfocused)
417     // cursor will become a block (focused) cursor.
418     if ([[textView window] isKeyWindow]) {
419         int shape = 0;
420         NSMutableData *data = [NSMutableData data];
421         [data appendBytes:&shape length:sizeof(int)];
422         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
423     }
426 - (void)setFrame:(NSRect)frame
428     //NSLog(@"%s", _cmd);
430     // When the frame changes we also need to update the tracking rect.
431     [textView removeTrackingRect:trackingRectTag];
432     trackingRectTag = [textView addTrackingRect:[self trackingRect]
433                                           owner:textView
434                                        userData:NULL
435                                    assumeInside:YES];
438 - (void)viewDidMoveToWindow
440     //NSLog(@"%s (window=%@)", _cmd, [self window]);
442     // Set a tracking rect which covers the text.
443     // NOTE: While the mouse cursor is in this rect the view will receive
444     // 'mouseMoved:' events so that Vim can take care of updating the mouse
445     // cursor.
446     if ([textView window]) {
447         [[textView window] setAcceptsMouseMovedEvents:YES];
448         trackingRectTag = [textView addTrackingRect:[self trackingRect]
449                                               owner:textView
450                                            userData:NULL
451                                        assumeInside:YES];
452     }
455 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
457     //NSLog(@"%s%@", _cmd, newWindow);
459     // Remove tracking rect if view moves or is removed.
460     if ([textView window] && trackingRectTag) {
461         [textView removeTrackingRect:trackingRectTag];
462         trackingRectTag = 0;
463     }
466 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
468     NSPasteboard *pboard = [sender draggingPasteboard];
470     if ([[pboard types] containsObject:NSStringPboardType]) {
471         NSString *string = [pboard stringForType:NSStringPboardType];
472         [[self vimController] dropString:string];
473         return YES;
474     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
475         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
476         [[self vimController] dropFiles:files forceOpen:NO];
477         return YES;
478     }
480     return NO;
483 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
485     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
486     NSPasteboard *pboard = [sender draggingPasteboard];
488     if ( [[pboard types] containsObject:NSFilenamesPboardType]
489             && (sourceDragMask & NSDragOperationCopy) )
490         return NSDragOperationCopy;
491     if ( [[pboard types] containsObject:NSStringPboardType]
492             && (sourceDragMask & NSDragOperationCopy) )
493         return NSDragOperationCopy;
495     return NSDragOperationNone;
498 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
500     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
501     NSPasteboard *pboard = [sender draggingPasteboard];
503     if ( [[pboard types] containsObject:NSFilenamesPboardType]
504             && (sourceDragMask & NSDragOperationCopy) )
505         return NSDragOperationCopy;
506     if ( [[pboard types] containsObject:NSStringPboardType]
507             && (sourceDragMask & NSDragOperationCopy) )
508         return NSDragOperationCopy;
510     return NSDragOperationNone;
513 - (void)setMouseShape:(int)shape
515     mouseShape = shape;
516     [self setCursor];
519 @end // MMTextViewHelper
524 @implementation MMTextViewHelper (Private)
526 - (MMWindowController *)windowController
528     id windowController = [[textView window] windowController];
529     if ([windowController isKindOfClass:[MMWindowController class]])
530         return (MMWindowController*)windowController;
531     return nil;
534 - (MMVimController *)vimController
536     return [[self windowController] vimController];
539 - (void)dispatchKeyEvent:(NSEvent *)event
541     // Only handle the command if it came from a keyDown event
542     if ([event type] != NSKeyDown)
543         return;
545     NSString *chars = [event characters];
546     NSString *unmodchars = [event charactersIgnoringModifiers];
547     unichar c = [chars characterAtIndex:0];
548     unichar imc = [unmodchars characterAtIndex:0];
549     int len = 0;
550     const char *bytes = 0;
551     int mods = [event modifierFlags];
553     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
554     //        _cmd, c, imc, chars, unmodchars);
556     if (' ' == imc && 0xa0 != c) {
557         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
558         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
559         // should be passed on as is.)
560         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
561         bytes = [unmodchars UTF8String];
562     } else if (imc == c && '2' == c) {
563         // HACK!  Translate Ctrl+2 to <C-@>.
564         static char ctrl_at = 0;
565         len = 1;  bytes = &ctrl_at;
566     } else if (imc == c && '6' == c) {
567         // HACK!  Translate Ctrl+6 to <C-^>.
568         static char ctrl_hat = 0x1e;
569         len = 1;  bytes = &ctrl_hat;
570     } else if (c == 0x19 && imc == 0x19) {
571         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
572         // separately (else Ctrl-Y doesn't work).
573         static char tab = 0x9;
574         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
575     } else {
576         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
577         bytes = [chars UTF8String];
578     }
580     [self sendKeyDown:bytes length:len modifiers:mods];
583 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
585     if (chars && len > 0) {
586         NSMutableData *data = [NSMutableData data];
588         [data appendBytes:&flags length:sizeof(int)];
589         [data appendBytes:&len length:sizeof(int)];
590         [data appendBytes:chars length:len];
592         [self hideMouseCursor];
594         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
595         [[self vimController] sendMessage:KeyDownMsgID data:data];
596     }
599 - (void)hideMouseCursor
601     // Check 'mousehide' option
602     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
603     if (mh && ![mh boolValue])
604         [NSCursor setHiddenUntilMouseMoves:NO];
605     else
606         [NSCursor setHiddenUntilMouseMoves:YES];
609 - (void)startDragTimerWithInterval:(NSTimeInterval)t
611     [NSTimer scheduledTimerWithTimeInterval:t target:self
612                                    selector:@selector(dragTimerFired:)
613                                    userInfo:nil repeats:NO];
616 - (void)dragTimerFired:(NSTimer *)timer
618     // TODO: Autoscroll in horizontal direction?
619     static unsigned tick = 1;
621     isAutoscrolling = NO;
623     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
624         // HACK! If the mouse cursor is outside the text area, then send a
625         // dragged event.  However, if row&col hasn't changed since the last
626         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
627         // Thus we fiddle with the column to make sure something happens.
628         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
629         NSMutableData *data = [NSMutableData data];
631         [data appendBytes:&dragRow length:sizeof(int)];
632         [data appendBytes:&col length:sizeof(int)];
633         [data appendBytes:&dragFlags length:sizeof(int)];
635         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
637         isAutoscrolling = YES;
638     }
640     if (isDragging) {
641         // Compute timer interval depending on how far away the mouse cursor is
642         // from the text view.
643         NSRect rect = [self trackingRect];
644         float dy = 0;
645         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
646         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
647         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
649         NSTimeInterval t = MMDragTimerMaxInterval -
650             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
652         [self startDragTimerWithInterval:t];
653     }
655     ++tick;
658 - (void)setCursor
660     static NSCursor *customIbeamCursor = nil;
662     if (!customIbeamCursor) {
663         // Use a custom Ibeam cursor that has better contrast against dark
664         // backgrounds.
665         // TODO: Is the hotspot ok?
666         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
667         if (ibeamImage) {
668             NSSize size = [ibeamImage size];
669             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
671             customIbeamCursor = [[NSCursor alloc]
672                     initWithImage:ibeamImage hotSpot:hotSpot];
673         }
674         if (!customIbeamCursor) {
675             NSLog(@"WARNING: Failed to load custom Ibeam cursor");
676             customIbeamCursor = [NSCursor IBeamCursor];
677         }
678     }
680     // This switch should match mshape_names[] in misc2.c.
681     //
682     // TODO: Add missing cursor shapes.
683     switch (mouseShape) {
684         case 2: [customIbeamCursor set]; break;
685         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
686         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
687         case 9: [[NSCursor crosshairCursor] set]; break;
688         case 10: [[NSCursor pointingHandCursor] set]; break;
689         case 11: [[NSCursor openHandCursor] set]; break;
690         default:
691             [[NSCursor arrowCursor] set]; break;
692     }
694     // Shape 1 indicates that the mouse cursor should be hidden.
695     if (1 == mouseShape)
696         [NSCursor setHiddenUntilMouseMoves:YES];
699 - (NSRect)trackingRect
701     NSRect rect = [textView frame];
702     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
703     int left = [ud integerForKey:MMTextInsetLeftKey];
704     int top = [ud integerForKey:MMTextInsetTopKey];
705     int right = [ud integerForKey:MMTextInsetRightKey];
706     int bot = [ud integerForKey:MMTextInsetBottomKey];
708     rect.origin.x = left;
709     rect.origin.y = top;
710     rect.size.width -= left + right - 1;
711     rect.size.height -= top + bot - 1;
713     return rect;
716 - (void)handleScrollWheelEvent:(id)event
718     if (0 == scrollWheelAccumulator)
719         return;
721     int row, col;
722     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
723     if ([textView convertPoint:pt toRow:&row column:&col]) {
724         int flags = [event modifierFlags];
725         NSMutableData *data = [NSMutableData data];
727         [data appendBytes:&row length:sizeof(int)];
728         [data appendBytes:&col length:sizeof(int)];
729         [data appendBytes:&flags length:sizeof(int)];
730         [data appendBytes:&scrollWheelAccumulator length:sizeof(float)];
732         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
733     }
735     scrollWheelAccumulator = 0;
738 @end // MMTextViewHelper (Private)