Fix problems with 'fullscreen' and :mksession
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blob0f6ed175d8b3e934a1301af9f2c4ae190cdf7035
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     //NSLog(@"%s%@", _cmd, event);
232     NSString *chars = [event characters];
233     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
234     NSMutableData *data = [NSMutableData data];
236     if (len <= 0)
237         return NO;
239     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
240     // can clear the shift flag as it is already included in 'unmodchars'.
241     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
242     // an English keyboard).
243     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
244         flags &= ~NSShiftKeyMask;
246     if (0x3 == [unmodchars characterAtIndex:0]) {
247         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
248         // handle it separately (else Cmd-enter turns into Ctrl-C).
249         unmodchars = MMKeypadEnterString;
250         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
251     }
253     [data appendBytes:&flags length:sizeof(int)];
254     [data appendBytes:&len length:sizeof(int)];
255     [data appendBytes:[unmodchars UTF8String] length:len];
257     [[self vimController] sendMessage:CmdKeyMsgID data:data];
259     return YES;
262 - (void)scrollWheel:(NSEvent *)event
264     if ([event deltaY] == 0)
265         return;
267     // Don't send the event straight away because lots of these events may be
268     // received in rapid succession.  Instead, accumulate the events and send
269     // off the scroll total at a predetermined maximum rate.  This avoids
270     // clogging up the DO messaging system on faster machines.
271     if (0 == scrollWheelAccumulator)
272         [self performSelector:@selector(handleScrollWheelEvent:)
273                    withObject:event
274                    afterDelay:MMScrollWheelDelay];
276     scrollWheelAccumulator += [event deltaY];
279 - (void)mouseDown:(NSEvent *)event
281     int row, col;
282     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
283     if (![textView convertPoint:pt toRow:&row column:&col])
284         return;
286     int button = [event buttonNumber];
287     int flags = [event modifierFlags];
288     int count = [event clickCount];
289     NSMutableData *data = [NSMutableData data];
291     // If desired, intepret Ctrl-Click as a right mouse click.
292     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
293             boolForKey:MMTranslateCtrlClickKey];
294     flags = flags & NSDeviceIndependentModifierFlagsMask;
295     if (translateCtrlClick && button == 0 &&
296             (flags == NSControlKeyMask ||
297              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
298         button = 1;
299         flags &= ~NSControlKeyMask;
300     }
302     [data appendBytes:&row length:sizeof(int)];
303     [data appendBytes:&col length:sizeof(int)];
304     [data appendBytes:&button length:sizeof(int)];
305     [data appendBytes:&flags length:sizeof(int)];
306     [data appendBytes:&count length:sizeof(int)];
308     [[self vimController] sendMessage:MouseDownMsgID data:data];
311 - (void)mouseUp:(NSEvent *)event
313     int row, col;
314     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
315     if (![textView convertPoint:pt toRow:&row column:&col])
316         return;
318     int flags = [event modifierFlags];
319     NSMutableData *data = [NSMutableData data];
321     [data appendBytes:&row length:sizeof(int)];
322     [data appendBytes:&col length:sizeof(int)];
323     [data appendBytes:&flags length:sizeof(int)];
325     [[self vimController] sendMessage:MouseUpMsgID data:data];
327     isDragging = NO;
330 - (void)mouseDragged:(NSEvent *)event
332     int flags = [event modifierFlags];
333     int row, col;
334     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
335     if (![textView convertPoint:pt toRow:&row column:&col])
336         return;
338     // Autoscrolling is done in dragTimerFired:
339     if (!isAutoscrolling) {
340         NSMutableData *data = [NSMutableData data];
342         [data appendBytes:&row length:sizeof(int)];
343         [data appendBytes:&col length:sizeof(int)];
344         [data appendBytes:&flags length:sizeof(int)];
346         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
347     }
349     dragPoint = pt;
350     dragRow = row;
351     dragColumn = col;
352     dragFlags = flags;
354     if (!isDragging) {
355         [self startDragTimerWithInterval:.5];
356         isDragging = YES;
357     }
360 - (void)mouseMoved:(NSEvent *)event
362     // HACK! NSTextView has a nasty habit of resetting the cursor to the
363     // default I-beam cursor at random moments.  The only reliable way we know
364     // of to work around this is to set the cursor each time the mouse moves.
365     [self setCursor];
367     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
368     int row, col;
369     if (![textView convertPoint:pt toRow:&row column:&col])
370         return;
372     // HACK! It seems impossible to get the tracking rects set up before the
373     // view is visible, which means that the first mouseEntered: or
374     // mouseExited: events are never received.  This forces us to check if the
375     // mouseMoved: event really happened over the text.
376     int rows, cols;
377     [textView getMaxRows:&rows columns:&cols];
378     if (row >= 0 && row < rows && col >= 0 && col < cols) {
379         NSMutableData *data = [NSMutableData data];
381         [data appendBytes:&row length:sizeof(int)];
382         [data appendBytes:&col length:sizeof(int)];
384         [[self vimController] sendMessage:MouseMovedMsgID data:data];
386         //NSLog(@"Moved %d %d\n", col, row);
387     }
390 - (void)mouseEntered:(NSEvent *)event
392     //NSLog(@"%s", _cmd);
394     // NOTE: This event is received even when the window is not key; thus we
395     // have to take care not to enable mouse moved events unless our window is
396     // key.
397     if ([[textView window] isKeyWindow]) {
398         [[textView window] setAcceptsMouseMovedEvents:YES];
399     }
402 - (void)mouseExited:(NSEvent *)event
404     //NSLog(@"%s", _cmd);
406     [[textView window] setAcceptsMouseMovedEvents:NO];
408     // NOTE: This event is received even when the window is not key; if the
409     // mouse shape is set when our window is not key, the hollow (unfocused)
410     // cursor will become a block (focused) cursor.
411     if ([[textView window] isKeyWindow]) {
412         int shape = 0;
413         NSMutableData *data = [NSMutableData data];
414         [data appendBytes:&shape length:sizeof(int)];
415         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
416     }
419 - (void)setFrame:(NSRect)frame
421     //NSLog(@"%s", _cmd);
423     // When the frame changes we also need to update the tracking rect.
424     [textView removeTrackingRect:trackingRectTag];
425     trackingRectTag = [textView addTrackingRect:[self trackingRect]
426                                           owner:textView
427                                        userData:NULL
428                                    assumeInside:YES];
431 - (void)viewDidMoveToWindow
433     //NSLog(@"%s (window=%@)", _cmd, [self window]);
435     // Set a tracking rect which covers the text.
436     // NOTE: While the mouse cursor is in this rect the view will receive
437     // 'mouseMoved:' events so that Vim can take care of updating the mouse
438     // cursor.
439     if ([textView window]) {
440         [[textView window] setAcceptsMouseMovedEvents:YES];
441         trackingRectTag = [textView addTrackingRect:[self trackingRect]
442                                               owner:textView
443                                            userData:NULL
444                                        assumeInside:YES];
445     }
448 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
450     //NSLog(@"%s%@", _cmd, newWindow);
452     // Remove tracking rect if view moves or is removed.
453     if ([textView window] && trackingRectTag) {
454         [textView removeTrackingRect:trackingRectTag];
455         trackingRectTag = 0;
456     }
459 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
461     NSPasteboard *pboard = [sender draggingPasteboard];
463     if ([[pboard types] containsObject:NSStringPboardType]) {
464         NSString *string = [pboard stringForType:NSStringPboardType];
465         [[self vimController] dropString:string];
466         return YES;
467     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
468         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
469         [[self vimController] dropFiles:files forceOpen:NO];
470         return YES;
471     }
473     return NO;
476 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
478     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
479     NSPasteboard *pboard = [sender draggingPasteboard];
481     if ( [[pboard types] containsObject:NSFilenamesPboardType]
482             && (sourceDragMask & NSDragOperationCopy) )
483         return NSDragOperationCopy;
484     if ( [[pboard types] containsObject:NSStringPboardType]
485             && (sourceDragMask & NSDragOperationCopy) )
486         return NSDragOperationCopy;
488     return NSDragOperationNone;
491 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
493     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
494     NSPasteboard *pboard = [sender draggingPasteboard];
496     if ( [[pboard types] containsObject:NSFilenamesPboardType]
497             && (sourceDragMask & NSDragOperationCopy) )
498         return NSDragOperationCopy;
499     if ( [[pboard types] containsObject:NSStringPboardType]
500             && (sourceDragMask & NSDragOperationCopy) )
501         return NSDragOperationCopy;
503     return NSDragOperationNone;
506 - (void)setMouseShape:(int)shape
508     mouseShape = shape;
509     [self setCursor];
512 @end // MMTextViewHelper
517 @implementation MMTextViewHelper (Private)
519 - (MMWindowController *)windowController
521     id windowController = [[textView window] windowController];
522     if ([windowController isKindOfClass:[MMWindowController class]])
523         return (MMWindowController*)windowController;
524     return nil;
527 - (MMVimController *)vimController
529     return [[self windowController] vimController];
532 - (void)dispatchKeyEvent:(NSEvent *)event
534     // Only handle the command if it came from a keyDown event
535     if ([event type] != NSKeyDown)
536         return;
538     NSString *chars = [event characters];
539     NSString *unmodchars = [event charactersIgnoringModifiers];
540     unichar c = [chars characterAtIndex:0];
541     unichar imc = [unmodchars characterAtIndex:0];
542     int len = 0;
543     const char *bytes = 0;
544     int mods = [event modifierFlags];
546     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
547     //        _cmd, c, imc, chars, unmodchars);
549     if (' ' == imc && 0xa0 != c) {
550         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
551         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
552         // should be passed on as is.)
553         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
554         bytes = [unmodchars UTF8String];
555     } else if (imc == c && '2' == c) {
556         // HACK!  Translate Ctrl+2 to <C-@>.
557         static char ctrl_at = 0;
558         len = 1;  bytes = &ctrl_at;
559     } else if (imc == c && '6' == c) {
560         // HACK!  Translate Ctrl+6 to <C-^>.
561         static char ctrl_hat = 0x1e;
562         len = 1;  bytes = &ctrl_hat;
563     } else if (c == 0x19 && imc == 0x19) {
564         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
565         // separately (else Ctrl-Y doesn't work).
566         static char tab = 0x9;
567         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
568     } else {
569         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
570         bytes = [chars UTF8String];
571     }
573     [self sendKeyDown:bytes length:len modifiers:mods];
576 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
578     if (chars && len > 0) {
579         NSMutableData *data = [NSMutableData data];
581         [data appendBytes:&flags length:sizeof(int)];
582         [data appendBytes:&len length:sizeof(int)];
583         [data appendBytes:chars length:len];
585         [self hideMouseCursor];
587         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
588         [[self vimController] sendMessage:KeyDownMsgID data:data];
589     }
592 - (void)hideMouseCursor
594     // Check 'mousehide' option
595     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
596     if (mh && ![mh boolValue])
597         [NSCursor setHiddenUntilMouseMoves:NO];
598     else
599         [NSCursor setHiddenUntilMouseMoves:YES];
602 - (void)startDragTimerWithInterval:(NSTimeInterval)t
604     [NSTimer scheduledTimerWithTimeInterval:t target:self
605                                    selector:@selector(dragTimerFired:)
606                                    userInfo:nil repeats:NO];
609 - (void)dragTimerFired:(NSTimer *)timer
611     // TODO: Autoscroll in horizontal direction?
612     static unsigned tick = 1;
614     isAutoscrolling = NO;
616     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
617         // HACK! If the mouse cursor is outside the text area, then send a
618         // dragged event.  However, if row&col hasn't changed since the last
619         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
620         // Thus we fiddle with the column to make sure something happens.
621         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
622         NSMutableData *data = [NSMutableData data];
624         [data appendBytes:&dragRow length:sizeof(int)];
625         [data appendBytes:&col length:sizeof(int)];
626         [data appendBytes:&dragFlags length:sizeof(int)];
628         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
630         isAutoscrolling = YES;
631     }
633     if (isDragging) {
634         // Compute timer interval depending on how far away the mouse cursor is
635         // from the text view.
636         NSRect rect = [self trackingRect];
637         float dy = 0;
638         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
639         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
640         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
642         NSTimeInterval t = MMDragTimerMaxInterval -
643             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
645         [self startDragTimerWithInterval:t];
646     }
648     ++tick;
651 - (void)setCursor
653     static NSCursor *customIbeamCursor = nil;
655     if (!customIbeamCursor) {
656         // Use a custom Ibeam cursor that has better contrast against dark
657         // backgrounds.
658         // TODO: Is the hotspot ok?
659         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
660         if (ibeamImage) {
661             NSSize size = [ibeamImage size];
662             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
664             customIbeamCursor = [[NSCursor alloc]
665                     initWithImage:ibeamImage hotSpot:hotSpot];
666         }
667         if (!customIbeamCursor) {
668             NSLog(@"WARNING: Failed to load custom Ibeam cursor");
669             customIbeamCursor = [NSCursor IBeamCursor];
670         }
671     }
673     // This switch should match mshape_names[] in misc2.c.
674     //
675     // TODO: Add missing cursor shapes.
676     switch (mouseShape) {
677         case 2: [customIbeamCursor set]; break;
678         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
679         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
680         case 9: [[NSCursor crosshairCursor] set]; break;
681         case 10: [[NSCursor pointingHandCursor] set]; break;
682         case 11: [[NSCursor openHandCursor] set]; break;
683         default:
684             [[NSCursor arrowCursor] set]; break;
685     }
687     // Shape 1 indicates that the mouse cursor should be hidden.
688     if (1 == mouseShape)
689         [NSCursor setHiddenUntilMouseMoves:YES];
692 - (NSRect)trackingRect
694     NSRect rect = [textView frame];
695     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
696     int left = [ud integerForKey:MMTextInsetLeftKey];
697     int top = [ud integerForKey:MMTextInsetTopKey];
698     int right = [ud integerForKey:MMTextInsetRightKey];
699     int bot = [ud integerForKey:MMTextInsetBottomKey];
701     rect.origin.x = left;
702     rect.origin.y = top;
703     rect.size.width -= left + right - 1;
704     rect.size.height -= top + bot - 1;
706     return rect;
709 - (void)handleScrollWheelEvent:(id)event
711     if (0 == scrollWheelAccumulator)
712         return;
714     int row, col;
715     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
716     if ([textView convertPoint:pt toRow:&row column:&col]) {
717         int flags = [event modifierFlags];
718         NSMutableData *data = [NSMutableData data];
720         [data appendBytes:&row length:sizeof(int)];
721         [data appendBytes:&col length:sizeof(int)];
722         [data appendBytes:&flags length:sizeof(int)];
723         [data appendBytes:&scrollWheelAccumulator length:sizeof(float)];
725         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
726     }
728     scrollWheelAccumulator = 0;
731 @end // MMTextViewHelper (Private)