Replace NSLog() with ASLogXXX()
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blob1bb1ab12be31db694ba17b15e18557003c3be7e0
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)checkImState;
44 - (void)hideMouseCursor;
45 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
46 - (void)dragTimerFired:(NSTimer *)timer;
47 - (void)setCursor;
48 - (NSRect)trackingRect;
49 @end
52 @implementation MMTextViewHelper
54 - (void)dealloc
56     ASLogDebug(@"");
58     [insertionPointColor release];  insertionPointColor = nil;
59     [markedText release];  markedText = nil;
60     [markedTextAttributes release];  markedTextAttributes = nil;
62     [super dealloc];
65 - (void)setTextView:(id)view
67     // Only keep a weak reference to owning text view.
68     textView = view;
71 - (void)setInsertionPointColor:(NSColor *)color
73     if (color != insertionPointColor) {
74         [insertionPointColor release];
75         insertionPointColor = [color retain];
76     }
79 - (NSColor *)insertionPointColor
81     return insertionPointColor;
84 - (void)keyDown:(NSEvent *)event
86     //ASLogDebug(@"%@", event);
87     // HACK! If control modifier is held, don't pass the event along to
88     // interpretKeyEvents: since some keys are bound to multiple commands which
89     // means doCommandBySelector: is called several times.  Do the same for
90     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
91     // commands).  This hack may break input management, but unless we can
92     // figure out a way to disable key bindings there seems little else to do.
93     //
94     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
95     // affecting input management.
97     if (imControl)
98         [self checkImState];
100     // When the Input Method is activated, some special key inputs
101     // should be treated as key inputs for Input Method.
102     if ([textView hasMarkedText]) {
103         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
104         [textView setNeedsDisplay:YES];
105         return;
106     }
108     int flags = [event modifierFlags];
109     if ((flags & NSControlKeyMask) ||
110             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
111         BOOL unmodIsPrintable = YES;
112         NSString *unmod = [event charactersIgnoringModifiers];
113         if (unmod && [unmod length] > 0 && [unmod characterAtIndex:0] < 0x20)
114             unmodIsPrintable = NO;
116         NSString *chars = [event characters];
117         if ([chars length] == 1 && [chars characterAtIndex:0] < 0x20
118                 && unmodIsPrintable) {
119             // HACK! Send unprintable characters (such as C-@, C-[, C-\, C-],
120             // C-^, C-_) as normal text to be added to the Vim input buffer.
121             // This must be done in order for the backend to be able to
122             // separate e.g. Ctrl-i and Ctrl-tab.
123             [self insertText:chars];
124         } else {
125             [self dispatchKeyEvent:event];
126         }
127     } else if ((flags & NSAlternateKeyMask) &&
128             [[[[self vimController] vimState] objectForKey:@"p_mmta"]
129                                                                 boolValue]) {
130         // If the 'macmeta' option is set, then send Alt+key presses directly
131         // to Vim without interpreting the key press.
132         NSString *unmod = [event charactersIgnoringModifiers];
133         int len = [unmod lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
134         const char *bytes = [unmod UTF8String];
136         [self sendKeyDown:bytes length:len modifiers:flags
137                 isARepeat:[event isARepeat]];
138     } else {
139         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
140     }
143 - (void)insertText:(id)string
145     //ASLogDebug(@"%@", string);
146     // NOTE!  This method is called for normal key presses but also for
147     // Option-key presses --- even when Ctrl is held as well as Option.  When
148     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
149     // so 'string' need not be a printable character!  In this case it still
150     // works to pass 'string' on to Vim as a printable character (since
151     // modifiers are already included and should not be added to the input
152     // buffer using CSI, K_MODIFIER).
154     if ([textView hasMarkedText]) {
155         [textView unmarkText];
156     }
158     NSEvent *event = [NSApp currentEvent];
160     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
161     // to watch for them here.
162     if ([event type] == NSKeyDown
163             && [[event charactersIgnoringModifiers] length] > 0
164             && [event modifierFlags]
165                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
166         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
168         // <S-M-Tab> translates to 0x19 
169         if (' ' == c || 0x19 == c) {
170             [self dispatchKeyEvent:event];
171             return;
172         }
173     }
175     [self hideMouseCursor];
177     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
178     // do not support attributes, simply pass the corresponding NSString in the
179     // latter case.
180     if ([string isKindOfClass:[NSAttributedString class]])
181         string = [string string];
183     NSMutableData *data = [NSMutableData data];
184     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
185     int flags = [event modifierFlags] & 0xffff0000U;
186     if ([event type] == NSKeyDown && [event isARepeat])
187         flags |= 1;
189     [data appendBytes:&flags length:sizeof(int)];
190     [data appendBytes:&len length:sizeof(int)];
191     [data appendBytes:[string UTF8String] length:len];
193     [[self vimController] sendMessage:InsertTextMsgID data:data];
196 - (void)doCommandBySelector:(SEL)selector
198     //ASLogDebug(@"%@", NSStringFromSelector(selector));
199     // By ignoring the selector we effectively disable the key binding
200     // mechanism of Cocoa.  Hopefully this is what the user will expect
201     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
202     // match, etc.).
203     //
204     // We usually end up here if the user pressed Ctrl+key (but not
205     // Ctrl+Option+key).
207     NSEvent *event = [NSApp currentEvent];
209     if (selector == @selector(cancelOperation:)
210             || selector == @selector(insertNewline:)) {
211         // HACK! If there was marked text which got abandoned as a result of
212         // hitting escape or enter, then 'insertText:' is called with the
213         // abandoned text but '[event characters]' includes the abandoned text
214         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
215         // must intercept these keys here or the abandonded text gets inserted
216         // twice.
217         NSString *key = [event charactersIgnoringModifiers];
218         const char *chars = [key UTF8String];
219         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
221         if (0x3 == chars[0]) {
222             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
223             // handle it separately (else Ctrl-C doesn't work).
224             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
225             chars = MMKeypadEnter;
226         }
228         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]
229                 isARepeat:[event isARepeat]];
230     } else {
231         [self dispatchKeyEvent:event];
232     }
235 - (BOOL)performKeyEquivalent:(NSEvent *)event
237     //ASLogDebug(@"%@", event);
238     // Called for Cmd+key keystrokes, function keys, arrow keys, page
239     // up/down, home, end.
240     //
241     // NOTE: This message cannot be ignored since Cmd+letter keys never are
242     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
243     // strokes, unless the key is a function key.
245     if (imControl)
246         [self checkImState];
248     // NOTE: If the event that triggered this method represents a function key
249     // down then we do nothing, otherwise the input method never gets the key
250     // stroke (some input methods use e.g. arrow keys).  The function key down
251     // event will still reach Vim though (via keyDown:).  The exceptions to
252     // this rule are: PageUp/PageDown (keycode 116/121).
253     int flags = [event modifierFlags] & 0xffff0000U;
254     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
255             && !(116 == [event keyCode] || 121 == [event keyCode]))
256         return NO;
258     // HACK!  KeyCode 50 represent the key which switches between windows
259     // within an application (like Cmd+Tab is used to switch between
260     // applications).  Return NO here, else the window switching does not work.
261     if ([event keyCode] == 50)
262         return NO;
264     // HACK!  Let the main menu try to handle any key down event, before
265     // passing it on to vim, otherwise key equivalents for menus will
266     // effectively be disabled.
267     if ([[NSApp mainMenu] performKeyEquivalent:event])
268         return YES;
270     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
271     if (flags & NSControlKeyMask) {
272         [self keyDown:event];
273         return YES;
274     }
276     // HACK!  Don't handle Cmd-? or the "Help" menu does not work on Leopard.
277     NSString *unmodchars = [event charactersIgnoringModifiers];
278     if ([unmodchars isEqual:@"?"])
279         return NO;
281     // Cmd-. is hard-wired to send SIGINT unlike Ctrl-C which is just another
282     // key press which Vim has to interpret.  This means that Cmd-. always
283     // works to interrupt a Vim process whereas Ctrl-C can suffer from problems
284     // such as dropped DO messages (or if Vim is stuck in a loop without
285     // checking for keyboard input).
286     if ((flags & NSDeviceIndependentModifierFlagsMask) == NSCommandKeyMask &&
287             [unmodchars isEqual:@"."]) {
288         kill([[self vimController] pid], SIGINT);
289         return YES;
290     }
292     NSString *chars = [event characters];
293     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
294     NSMutableData *data = [NSMutableData data];
296     if (len <= 0)
297         return NO;
299     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
300     // can clear the shift flag as it is already included in 'unmodchars'.
301     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
302     // an English keyboard).
303     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
304         flags &= ~NSShiftKeyMask;
306     if (0x3 == [unmodchars characterAtIndex:0]) {
307         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
308         // handle it separately (else Cmd-enter turns into Ctrl-C).
309         unmodchars = MMKeypadEnterString;
310         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
311     }
313     if ([event isARepeat])
314         flags |= 1;
316     [data appendBytes:&flags length:sizeof(int)];
317     [data appendBytes:&len length:sizeof(int)];
318     [data appendBytes:[unmodchars UTF8String] length:len];
320     [[self vimController] sendMessage:CmdKeyMsgID data:data];
322     return YES;
325 - (void)scrollWheel:(NSEvent *)event
327     if ([event deltaY] == 0)
328         return;
330     int row, col;
331     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
332     if ([textView convertPoint:pt toRow:&row column:&col]) {
333         int flags = [event modifierFlags];
334         float dy = [event deltaY];
335         NSMutableData *data = [NSMutableData data];
337         [data appendBytes:&row length:sizeof(int)];
338         [data appendBytes:&col length:sizeof(int)];
339         [data appendBytes:&flags length:sizeof(int)];
340         [data appendBytes:&dy length:sizeof(float)];
342         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
343     }
346 - (void)mouseDown:(NSEvent *)event
348     int row, col;
349     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
350     if (![textView convertPoint:pt toRow:&row column:&col])
351         return;
353     int button = [event buttonNumber];
354     int flags = [event modifierFlags];
355     int count = [event clickCount];
356     NSMutableData *data = [NSMutableData data];
358     // If desired, intepret Ctrl-Click as a right mouse click.
359     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
360             boolForKey:MMTranslateCtrlClickKey];
361     flags = flags & NSDeviceIndependentModifierFlagsMask;
362     if (translateCtrlClick && button == 0 &&
363             (flags == NSControlKeyMask ||
364              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
365         button = 1;
366         flags &= ~NSControlKeyMask;
367     }
369     [data appendBytes:&row length:sizeof(int)];
370     [data appendBytes:&col length:sizeof(int)];
371     [data appendBytes:&button length:sizeof(int)];
372     [data appendBytes:&flags length:sizeof(int)];
373     [data appendBytes:&count length:sizeof(int)];
375     [[self vimController] sendMessage:MouseDownMsgID data:data];
378 - (void)mouseUp:(NSEvent *)event
380     int row, col;
381     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
382     if (![textView convertPoint:pt toRow:&row column:&col])
383         return;
385     int flags = [event modifierFlags];
386     NSMutableData *data = [NSMutableData data];
388     [data appendBytes:&row length:sizeof(int)];
389     [data appendBytes:&col length:sizeof(int)];
390     [data appendBytes:&flags length:sizeof(int)];
392     [[self vimController] sendMessage:MouseUpMsgID data:data];
394     isDragging = NO;
397 - (void)mouseDragged:(NSEvent *)event
399     int flags = [event modifierFlags];
400     int row, col;
401     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
402     if (![textView convertPoint:pt toRow:&row column:&col])
403         return;
405     // Autoscrolling is done in dragTimerFired:
406     if (!isAutoscrolling) {
407         NSMutableData *data = [NSMutableData data];
409         [data appendBytes:&row length:sizeof(int)];
410         [data appendBytes:&col length:sizeof(int)];
411         [data appendBytes:&flags length:sizeof(int)];
413         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
414     }
416     dragPoint = pt;
417     dragRow = row;
418     dragColumn = col;
419     dragFlags = flags;
421     if (!isDragging) {
422         [self startDragTimerWithInterval:.5];
423         isDragging = YES;
424     }
427 - (void)mouseMoved:(NSEvent *)event
429     // HACK! NSTextView has a nasty habit of resetting the cursor to the
430     // default I-beam cursor at random moments.  The only reliable way we know
431     // of to work around this is to set the cursor each time the mouse moves.
432     [self setCursor];
434     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
435     int row, col;
436     if (![textView convertPoint:pt toRow:&row column:&col])
437         return;
439     // HACK! It seems impossible to get the tracking rects set up before the
440     // view is visible, which means that the first mouseEntered: or
441     // mouseExited: events are never received.  This forces us to check if the
442     // mouseMoved: event really happened over the text.
443     int rows, cols;
444     [textView getMaxRows:&rows columns:&cols];
445     if (row >= 0 && row < rows && col >= 0 && col < cols) {
446         NSMutableData *data = [NSMutableData data];
448         [data appendBytes:&row length:sizeof(int)];
449         [data appendBytes:&col length:sizeof(int)];
451         [[self vimController] sendMessage:MouseMovedMsgID data:data];
452     }
455 - (void)mouseEntered:(NSEvent *)event
457     // NOTE: This event is received even when the window is not key; thus we
458     // have to take care not to enable mouse moved events unless our window is
459     // key.
460     if ([[textView window] isKeyWindow]) {
461         [[textView window] setAcceptsMouseMovedEvents:YES];
462     }
465 - (void)mouseExited:(NSEvent *)event
467     [[textView window] setAcceptsMouseMovedEvents:NO];
469     // NOTE: This event is received even when the window is not key; if the
470     // mouse shape is set when our window is not key, the hollow (unfocused)
471     // cursor will become a block (focused) cursor.
472     if ([[textView window] isKeyWindow]) {
473         int shape = 0;
474         NSMutableData *data = [NSMutableData data];
475         [data appendBytes:&shape length:sizeof(int)];
476         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
477     }
480 - (void)setFrame:(NSRect)frame
482     // When the frame changes we also need to update the tracking rect.
483     [textView removeTrackingRect:trackingRectTag];
484     trackingRectTag = [textView addTrackingRect:[self trackingRect]
485                                           owner:textView
486                                        userData:NULL
487                                    assumeInside:YES];
490 - (void)viewDidMoveToWindow
492     // Set a tracking rect which covers the text.
493     // NOTE: While the mouse cursor is in this rect the view will receive
494     // 'mouseMoved:' events so that Vim can take care of updating the mouse
495     // cursor.
496     if ([textView window]) {
497         [[textView window] setAcceptsMouseMovedEvents:YES];
498         trackingRectTag = [textView addTrackingRect:[self trackingRect]
499                                               owner:textView
500                                            userData:NULL
501                                        assumeInside:YES];
502     }
505 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
507     // Remove tracking rect if view moves or is removed.
508     if ([textView window] && trackingRectTag) {
509         [textView removeTrackingRect:trackingRectTag];
510         trackingRectTag = 0;
511     }
514 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
516     NSPasteboard *pboard = [sender draggingPasteboard];
518     if ([[pboard types] containsObject:NSStringPboardType]) {
519         NSString *string = [pboard stringForType:NSStringPboardType];
520         [[self vimController] dropString:string];
521         return YES;
522     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
523         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
524         [[self vimController] dropFiles:files forceOpen:NO];
525         return YES;
526     }
528     return NO;
531 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
533     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
534     NSPasteboard *pboard = [sender draggingPasteboard];
536     if ( [[pboard types] containsObject:NSFilenamesPboardType]
537             && (sourceDragMask & NSDragOperationCopy) )
538         return NSDragOperationCopy;
539     if ( [[pboard types] containsObject:NSStringPboardType]
540             && (sourceDragMask & NSDragOperationCopy) )
541         return NSDragOperationCopy;
543     return NSDragOperationNone;
546 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
548     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
549     NSPasteboard *pboard = [sender draggingPasteboard];
551     if ( [[pboard types] containsObject:NSFilenamesPboardType]
552             && (sourceDragMask & NSDragOperationCopy) )
553         return NSDragOperationCopy;
554     if ( [[pboard types] containsObject:NSStringPboardType]
555             && (sourceDragMask & NSDragOperationCopy) )
556         return NSDragOperationCopy;
558     return NSDragOperationNone;
561 - (void)setMouseShape:(int)shape
563     mouseShape = shape;
564     [self setCursor];
567 - (void)changeFont:(id)sender
569     NSFont *newFont = [sender convertFont:[textView font]];
570     NSFont *newFontWide = [sender convertFont:[textView fontWide]];
572     if (newFont) {
573         NSString *name = [newFont displayName];
574         NSString *wideName = [newFontWide displayName];
575         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
576         unsigned wideLen = [wideName lengthOfBytesUsingEncoding:
577                                                         NSUTF8StringEncoding];
578         if (len > 0) {
579             NSMutableData *data = [NSMutableData data];
580             float pointSize = [newFont pointSize];
582             [data appendBytes:&pointSize length:sizeof(float)];
584             ++len;  // include NUL byte
585             [data appendBytes:&len length:sizeof(unsigned)];
586             [data appendBytes:[name UTF8String] length:len];
588             if (wideLen > 0) {
589                 ++wideLen;  // include NUL byte
590                 [data appendBytes:&wideLen length:sizeof(unsigned)];
591                 [data appendBytes:[wideName UTF8String] length:wideLen];
592             } else {
593                 [data appendBytes:&wideLen length:sizeof(unsigned)];
594             }
596             [[self vimController] sendMessage:SetFontMsgID data:data];
597         }
598     }
601 - (BOOL)hasMarkedText
603     return markedRange.length > 0 ? YES : NO;
606 - (NSRange)markedRange
608     if ([self hasMarkedText])
609         return markedRange;
610     else
611         return NSMakeRange(NSNotFound, 0);
614 - (NSDictionary *)markedTextAttributes
616     return markedTextAttributes;
619 - (void)setMarkedTextAttributes:(NSDictionary *)attr
621     if (attr != markedTextAttributes) {
622         [markedTextAttributes release];
623         markedTextAttributes = [attr retain];
624     }
627 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
629     [self unmarkText];
631     if (!(text && [text length] > 0))
632         return;
634     // HACK! Determine if the marked text is wide or normal width.  This seems
635     // to always use 'wide' when there are both wide and normal width
636     // characters.
637     NSString *string = text;
638     NSFont *theFont = [textView font];
639     if ([text isKindOfClass:[NSAttributedString class]]) {
640         theFont = [textView fontWide];
641         string = [text string];
642     }
644     // TODO: Use special colors for marked text.
645     [self setMarkedTextAttributes:
646         [NSDictionary dictionaryWithObjectsAndKeys:
647             theFont, NSFontAttributeName,
648             [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
649             [textView defaultForegroundColor], NSForegroundColorAttributeName,
650             nil]];
652     markedText = [[NSMutableAttributedString alloc]
653            initWithString:string
654                attributes:[self markedTextAttributes]];
656     markedRange = NSMakeRange(0, [markedText length]);
657     if (markedRange.length) {
658         [markedText addAttribute:NSUnderlineStyleAttributeName
659                            value:[NSNumber numberWithInt:1]
660                            range:markedRange];
661     }
662     imRange = range;
663     if (range.length) {
664         [markedText addAttribute:NSUnderlineStyleAttributeName
665                            value:[NSNumber numberWithInt:2]
666                            range:range];
667     }
669     [textView setNeedsDisplay:YES];
672 - (void)unmarkText
674     imRange = NSMakeRange(0, 0);
675     markedRange = NSMakeRange(NSNotFound, 0);
676     [markedText release];
677     markedText = nil;
680 - (NSMutableAttributedString *)markedText
682     return markedText;
685 - (void)setPreEditRow:(int)row column:(int)col
687     preEditRow = row;
688     preEditColumn = col;
691 - (int)preEditRow
693     return preEditRow;
696 - (int)preEditColumn
698     return preEditColumn;
701 - (void)setImRange:(NSRange)range
703     imRange = range;
706 - (NSRange)imRange
708     return imRange;
711 - (void)setMarkedRange:(NSRange)range
713     markedRange = range;
716 - (NSRect)firstRectForCharacterRange:(NSRange)range
718     // This method is called when the input manager wants to pop up an
719     // auxiliary window.  The position where this should be is controlled by
720     // Vim by sending SetPreEditPositionMsgID so compute a position based on
721     // the pre-edit (row,column) pair.
722     int col = preEditColumn;
723     int row = preEditRow + 1;
725     NSFont *theFont = [[textView markedTextAttributes]
726             valueForKey:NSFontAttributeName];
727     if (theFont == [textView fontWide]) {
728         col += imRange.location * 2;
729         if (col >= [textView maxColumns] - 1) {
730             row += (col / [textView maxColumns]);
731             col = col % 2 ? col % [textView maxColumns] + 1 :
732                             col % [textView maxColumns];
733         }
734     } else {
735         col += imRange.location;
736         if (col >= [textView maxColumns]) {
737             row += (col / [textView maxColumns]);
738             col = col % [textView maxColumns];
739         }
740     }
742     NSRect rect = [textView rectForRow:row
743                                 column:col
744                                numRows:1
745                             numColumns:range.length];
747     rect.origin = [textView convertPoint:rect.origin toView:nil];
748     rect.origin = [[textView window] convertBaseToScreen:rect.origin];
750     return rect;
753 - (void)setImControl:(BOOL)enable
755     // This flag corresponds to the (negation of the) 'imd' option.  When
756     // enabled changes to the input method are detected and forwarded to the
757     // backend.
758     imControl = enable;
761 @end // MMTextViewHelper
766 @implementation MMTextViewHelper (Private)
768 - (MMWindowController *)windowController
770     id windowController = [[textView window] windowController];
771     if ([windowController isKindOfClass:[MMWindowController class]])
772         return (MMWindowController*)windowController;
773     return nil;
776 - (MMVimController *)vimController
778     return [[self windowController] vimController];
781 - (void)dispatchKeyEvent:(NSEvent *)event
783     // Only handle the command if it came from a keyDown event
784     if ([event type] != NSKeyDown)
785         return;
787     NSString *chars = [event characters];
788     NSString *unmodchars = [event charactersIgnoringModifiers];
789     unichar c = [chars characterAtIndex:0];
790     unichar imc = [unmodchars length] > 0 ? [unmodchars characterAtIndex:0] : 0;
791     int len = 0;
792     const char *bytes = 0;
793     int mods = [event modifierFlags];
795     //ASLogDebug(@"chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
796     //           c, imc, chars, unmodchars);
798     if (' ' == imc && 0xa0 != c) {
799         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
800         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
801         // should be passed on as is.)
802         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
803         bytes = [unmodchars UTF8String];
804     } else if (imc == c && '2' == c) {
805         // HACK!  Translate Ctrl+2 to <C-@>.
806         static char ctrl_at = 0;
807         len = 1;  bytes = &ctrl_at;
808     } else if (imc == c && '6' == c) {
809         // HACK!  Translate Ctrl+6 to <C-^>.
810         static char ctrl_hat = 0x1e;
811         len = 1;  bytes = &ctrl_hat;
812     } else if (c == 0x19 && imc == 0x19) {
813         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
814         // separately (else Ctrl-Y doesn't work).
815         static char tab = 0x9;
816         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
817     } else {
818         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
819         bytes = [chars UTF8String];
820     }
822     [self sendKeyDown:bytes length:len modifiers:mods
823             isARepeat:[event isARepeat]];
826 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
827           isARepeat:(BOOL)isARepeat
829     if (chars && len > 0) {
830         NSMutableData *data = [NSMutableData data];
832         // The low 16 bits are not used for modifier flags by NSEvent.  Use
833         // these bits for custom flags.
834         flags &= 0xffff0000;
835         if (isARepeat)
836             flags |= 1;
838         [data appendBytes:&flags length:sizeof(int)];
839         [data appendBytes:&len length:sizeof(int)];
840         [data appendBytes:chars length:len];
842         [self hideMouseCursor];
844         //ASLogDebug(@"len=%d chars=0x%x", len, chars[0]);
845         [[self vimController] sendMessage:KeyDownMsgID data:data];
846     }
849 - (void)checkImState
851     // IM is active whenever the current script is the system script and the
852     // system script isn't roman.  (Hence IM can only be active when using
853     // non-roman scripts.)
855     // NOTE: The IM code is delegated to the frontend since calling it in the
856     // backend caused weird bugs (second dock icon appearing etc.).
857     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
858     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
859     BOOL state = currentScript != smRoman && currentScript == systemScript;
860     if (imState != state) {
861         imState = state;
862         int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
863         [[self vimController] sendMessage:msgid data:nil];
864     }
867 - (void)hideMouseCursor
869     // Check 'mousehide' option
870     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
871     if (mh && ![mh boolValue])
872         [NSCursor setHiddenUntilMouseMoves:NO];
873     else
874         [NSCursor setHiddenUntilMouseMoves:YES];
877 - (void)startDragTimerWithInterval:(NSTimeInterval)t
879     [NSTimer scheduledTimerWithTimeInterval:t target:self
880                                    selector:@selector(dragTimerFired:)
881                                    userInfo:nil repeats:NO];
884 - (void)dragTimerFired:(NSTimer *)timer
886     // TODO: Autoscroll in horizontal direction?
887     static unsigned tick = 1;
889     isAutoscrolling = NO;
891     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
892         // HACK! If the mouse cursor is outside the text area, then send a
893         // dragged event.  However, if row&col hasn't changed since the last
894         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
895         // Thus we fiddle with the column to make sure something happens.
896         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
897         NSMutableData *data = [NSMutableData data];
899         [data appendBytes:&dragRow length:sizeof(int)];
900         [data appendBytes:&col length:sizeof(int)];
901         [data appendBytes:&dragFlags length:sizeof(int)];
903         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
905         isAutoscrolling = YES;
906     }
908     if (isDragging) {
909         // Compute timer interval depending on how far away the mouse cursor is
910         // from the text view.
911         NSRect rect = [self trackingRect];
912         float dy = 0;
913         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
914         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
915         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
917         NSTimeInterval t = MMDragTimerMaxInterval -
918             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
920         [self startDragTimerWithInterval:t];
921     }
923     ++tick;
926 - (void)setCursor
928     static NSCursor *customIbeamCursor = nil;
930     if (!customIbeamCursor) {
931         // Use a custom Ibeam cursor that has better contrast against dark
932         // backgrounds.
933         // TODO: Is the hotspot ok?
934         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
935         if (ibeamImage) {
936             NSSize size = [ibeamImage size];
937             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
939             customIbeamCursor = [[NSCursor alloc]
940                     initWithImage:ibeamImage hotSpot:hotSpot];
941         }
942         if (!customIbeamCursor) {
943             ASLogWarn(@"Failed to load custom Ibeam cursor");
944             customIbeamCursor = [NSCursor IBeamCursor];
945         }
946     }
948     // This switch should match mshape_names[] in misc2.c.
949     //
950     // TODO: Add missing cursor shapes.
951     switch (mouseShape) {
952         case 2: [customIbeamCursor set]; break;
953         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
954         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
955         case 9: [[NSCursor crosshairCursor] set]; break;
956         case 10: [[NSCursor pointingHandCursor] set]; break;
957         case 11: [[NSCursor openHandCursor] set]; break;
958         default:
959             [[NSCursor arrowCursor] set]; break;
960     }
962     // Shape 1 indicates that the mouse cursor should be hidden.
963     if (1 == mouseShape)
964         [NSCursor setHiddenUntilMouseMoves:YES];
967 - (NSRect)trackingRect
969     NSRect rect = [textView frame];
970     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
971     int left = [ud integerForKey:MMTextInsetLeftKey];
972     int top = [ud integerForKey:MMTextInsetTopKey];
973     int right = [ud integerForKey:MMTextInsetRightKey];
974     int bot = [ud integerForKey:MMTextInsetBottomKey];
976     rect.origin.x = left;
977     rect.origin.y = top;
978     rect.size.width -= left + right - 1;
979     rect.size.height -= top + bot - 1;
981     return rect;
984 @end // MMTextViewHelper (Private)