Fix placement of auxiliary IM window for Core Text
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blobce7e2984bf79808eeb53783ec3abb0c530beb0db
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 // The max/min drag timer interval in seconds
27 static NSTimeInterval MMDragTimerMaxInterval = 0.3;
28 static NSTimeInterval MMDragTimerMinInterval = 0.01;
30 // The number of pixels in which the drag timer interval changes
31 static float MMDragAreaSize = 73.0f;
34 @interface MMTextViewHelper (Private)
35 - (MMWindowController *)windowController;
36 - (MMVimController *)vimController;
37 - (void)doKeyDown:(NSString *)key;
38 - (void)doInsertText:(NSString *)text;
39 - (void)checkImState;
40 - (void)hideMouseCursor;
41 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
42 - (void)dragTimerFired:(NSTimer *)timer;
43 - (void)setCursor;
44 - (NSRect)trackingRect;
45 - (BOOL)inputManagerHandleMouseEvent:(NSEvent *)event;
46 - (void)sendMarkedText:(NSString *)text position:(int32_t)pos;
47 - (void)abandonMarkedText;
48 @end
53 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
54     static BOOL
55 KeyboardInputSourcesEqual(TISInputSourceRef a, TISInputSourceRef b)
57     // Define two sources to be equal iff both are non-NULL and they have
58     // identical source ID strings.
60     if (!(a && b))
61         return NO;
63     NSString *as = TISGetInputSourceProperty(a, kTISPropertyInputSourceID);
64     NSString *bs = TISGetInputSourceProperty(b, kTISPropertyInputSourceID);
66     return [as isEqualToString:bs];
68 #endif
71 @implementation MMTextViewHelper
73 - (void)dealloc
75     ASLogDebug(@"");
77     [insertionPointColor release];  insertionPointColor = nil;
78     [markedText release];  markedText = nil;
79     [markedTextAttributes release];  markedTextAttributes = nil;
81 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
82     if (asciiImSource) {
83         CFRelease(asciiImSource);
84         asciiImSource = NULL;
85     }
86     if (lastImSource) {
87         CFRelease(lastImSource);
88         lastImSource = NULL;
89     }
90 #endif
92     [super dealloc];
95 - (void)setTextView:(id)view
97     // Only keep a weak reference to owning text view.
98     textView = view;
101 - (void)setInsertionPointColor:(NSColor *)color
103     if (color != insertionPointColor) {
104         [insertionPointColor release];
105         insertionPointColor = [color retain];
106     }
109 - (NSColor *)insertionPointColor
111     return insertionPointColor;
114 - (void)keyDown:(NSEvent *)event
116     ASLogDebug(@"%@", event);
118     // NOTE: Check IM state _before_ key has been interpreted or we'll pick up
119     // the old IM state when it has been switched via a keyboard shortcut that
120     // MacVim cannot handle.
121     if (imControl)
122         [self checkImState];
124     // NOTE: Keyboard handling is complicated by the fact that we must call
125     // interpretKeyEvents: otherwise key equivalents set up by input methods do
126     // not work (e.g. Ctrl-Shift-; would not work under Kotoeri).
128     // NOTE: insertText: and doCommandBySelector: may need to extract data from
129     // the key down event so keep a local reference to the event.  This is
130     // released and set to nil at the end of this method.  Don't make any early
131     // returns from this method without releasing and resetting this reference!
132     currentEvent = [event retain];
134     if ([self hasMarkedText]) {
135         // HACK! Need to redisplay manually otherwise the marked text may not
136         // be correctly displayed (e.g. it is still visible after pressing Esc
137         // even though the text has been unmarked).
138         [textView setNeedsDisplay:YES];
139     }
141     [self hideMouseCursor];
143     unsigned flags = [event modifierFlags];
144     id mmta = [[[self vimController] vimState] objectForKey:@"p_mmta"];
145     NSString *string = [event characters];
146     NSString *unmod  = [event charactersIgnoringModifiers];
148     // Alt key presses should not be interpreted if the 'macmeta' option is
149     // set.  We still have to call interpretKeyEvents: for keys
150     // like Enter, Esc, etc. to work as usual so only skip interpretation for
151     // ASCII chars in the range after space (0x20) and before backspace (0x7f).
152     // Note that this implies that 'mmta' (if enabled) breaks input methods
153     // when the Alt key is held.
154     if ((flags & NSAlternateKeyMask) && [mmta boolValue] && [unmod length] == 1
155             && [unmod characterAtIndex:0] > 0x20
156             && [unmod characterAtIndex:0] < 0x7f) {
157         ASLogDebug(@"MACMETA key, don't interpret it");
158         string = unmod;
159     } else if (imState && (flags & NSControlKeyMask)
160             && !(flags & (NSAlternateKeyMask|NSCommandKeyMask))
161             && [unmod length] == 1
162             && ([unmod characterAtIndex:0] == '6' ||
163                 [unmod characterAtIndex:0] == '^')) {
164         // HACK!  interpretKeyEvents: does not call doCommandBySelector:
165         // with Ctrl-6 or Ctrl-^ when IM is active.
166         [self doKeyDown:@"\x1e"];
167         string = nil;
168     } else {
169         // HACK!  interpretKeyEvents: may call insertText: or
170         // doCommandBySelector:, or it may swallow the key (most likely the
171         // current input method used it).  In the first two cases we have to
172         // manually set the below flag to NO if the key wasn't handled.
173         interpretKeyEventsSwallowedKey = YES;
174         [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
175         if (interpretKeyEventsSwallowedKey)
176             string = nil;
177         else if (flags & NSCommandKeyMask) {
178             // HACK! When Command is held we have to more or less guess whether
179             // we should use characters or charactersIgnoringModifiers.  The
180             // following heuristic seems to work but it may have to change.
181             // Note that the Shift and Alt flags may also need to be cleared
182             // (see doKeyDown:keyCode:modifiers: in MMBackend).
183             if ((flags & NSShiftKeyMask && !(flags & NSAlternateKeyMask))
184                     || flags & NSControlKeyMask)
185                 string = unmod;
186         }
187     }
189     if (string)
190         [self doKeyDown:string];
192     [currentEvent release];
193     currentEvent = nil;
196 - (void)insertText:(id)string
198     if ([self hasMarkedText]) {
199         [self sendMarkedText:nil position:0];
201         // NOTE: If this call is left out then the marked text isn't properly
202         // erased when Return is used to accept the text.
203         // The input manager only ever sets new marked text, it never actually
204         // calls to have it unmarked.  It seems that whenever insertText: is
205         // called the input manager expects the marked text to be unmarked
206         // automatically, hence the explicit unmarkText: call here.
207         [self unmarkText];
208     }
210     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
211     // do not support attributes, simply pass the corresponding NSString in the
212     // latter case.
213     if ([string isKindOfClass:[NSAttributedString class]])
214         string = [string string];
216     //int len = [string length];
217     //ASLogDebug(@"len=%d char[0]=%#x char[1]=%#x string='%@'", [string length],
218     //        [string characterAtIndex:0],
219     //        len > 1 ? [string characterAtIndex:1] : 0, string);
221     [self doInsertText:string];
224 - (void)doCommandBySelector:(SEL)sel
226     ASLogDebug(@"%@", NSStringFromSelector(sel));
228     // Translate Ctrl-2 -> Ctrl-@ (see also Resources/KeyBinding.plist)
229     if (@selector(keyCtrlAt:) == sel)
230         [self doKeyDown:@"\x00"];
231     // Translate Ctrl-6 -> Ctrl-^ (see also Resources/KeyBinding.plist)
232     else if (@selector(keyCtrlHat:) == sel)
233         [self doKeyDown:@"\x1e"];
234     //
235     // Check for selectors from AppKit.framework/StandardKeyBinding.dict and
236     // send the corresponding key directly on to the backend.  The reason for
237     // not just letting all of these fall through is that -[NSEvent characters]
238     // sometimes includes marked text as well as the actual key, but the marked
239     // text is also passed to insertText:.  For example, pressing Ctrl-i Return
240     // on a US keyboard would call insertText:@"^" but the key event for the
241     // Return press will contain "^\x0d" -- if we fell through the result would
242     // be that "^^\x0d" got sent to the backend (i.e. one extra "^" would
243     // appear).
244     // For this reason we also have to make sure that there are key bindings to
245     // all combinations of modifier with certain keys (these are set up in
246     // KeyBinding.plist in the Resources folder).
247     else if (@selector(insertTab:) == sel ||
248              @selector(selectNextKeyView:) == sel ||
249              @selector(insertTabIgnoringFieldEditor:) == sel)
250         [self doKeyDown:@"\x09"];
251     else if (@selector(insertNewline:) == sel ||
252              @selector(insertLineBreak:) == sel ||
253              @selector(insertNewlineIgnoringFieldEditor:) == sel)
254         [self doKeyDown:@"\x0d"];
255     else if (@selector(cancelOperation:) == sel ||
256              @selector(complete:) == sel)
257         [self doKeyDown:@"\x1b"];
258     else if (@selector(insertBackTab:) == sel ||
259              @selector(selectPreviousKeyView:) == sel)
260         [self doKeyDown:@"\x19"];
261     else if (@selector(deleteBackward:) == sel ||
262              @selector(deleteWordBackward:) == sel ||
263              @selector(deleteBackwardByDecomposingPreviousCharacter:) == sel ||
264              @selector(deleteToBeginningOfLine:) == sel)
265         [self doKeyDown:@"\x08"];
266     else if (@selector(keySpace:) == sel)
267         [self doKeyDown:@" "];
268     else if (@selector(cancel:) == sel)
269         kill([[self vimController] pid], SIGINT);
270     else interpretKeyEventsSwallowedKey = NO;
273 - (BOOL)performKeyEquivalent:(NSEvent *)event
275     ASLogDebug(@"");
276     if ([event type] != NSKeyDown)
277         return NO;
279     // NOTE: Key equivalent handling was fixed in Leopard.  That is, an
280     // unhandled key equivalent is passed to keyDown: -- contrast this with
281     // pre-Leopard where unhandled key equivalents would simply disappear
282     // (hence the ugly hack below for Tiger).
283     if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_4)
284         return NO;
286     // HACK! KeyCode 50 represent the key which switches between windows
287     // within an application (like Cmd+Tab is used to switch between
288     // applications).  Return NO here, else the window switching does not work.
289     if ([event keyCode] == 50)
290         return NO;
292     // HACK! The -[NSRespoder cancelOperation:] indicates that Cmd-. is handled
293     // in a special way by the key window.  Indeed, if we pass this event on to
294     // keyDown: it will result in doCommandBySelector: being called with
295     // cancelOperation: as selector, otherwise it is called with cancel: as the
296     // selector (and we respond to cancel: there).
297     int flags = [event modifierFlags] & NSDeviceIndependentModifierFlagsMask;
298     NSString *unmod = [event charactersIgnoringModifiers];
299     if (flags == NSCommandKeyMask && [unmod isEqual:@"."])
300         return NO;
302     // HACK! Let the main menu try to handle any key down event, before
303     // passing it on to vim, otherwise key equivalents for menus will
304     // effectively be disabled.
305     if ([[NSApp mainMenu] performKeyEquivalent:event])
306         return YES;
308     // HACK! Pass the event on or it may disappear (Tiger does not pass Cmd-key
309     // events to keyDown:).
310     [self keyDown:event];
311     return YES;
314 - (void)scrollWheel:(NSEvent *)event
316     if ([self hasMarkedText]) {
317         // We must clear the marked text since the cursor may move if the
318         // marked text moves outside the view as a result of scrolling.
319         [self sendMarkedText:nil position:0];
320         [self unmarkText];
321         [[NSInputManager currentInputManager] markedTextAbandoned:self];
322     }
324     if ([event deltaY] == 0)
325         return;
327     int row, col;
328     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
329     if ([textView convertPoint:pt toRow:&row column:&col]) {
330         int flags = [event modifierFlags];
331         float dy = [event deltaY];
332         NSMutableData *data = [NSMutableData data];
334         [data appendBytes:&row length:sizeof(int)];
335         [data appendBytes:&col length:sizeof(int)];
336         [data appendBytes:&flags length:sizeof(int)];
337         [data appendBytes:&dy length:sizeof(float)];
339         [[self vimController] sendMessage:ScrollWheelMsgID data:data];
340     }
343 - (void)mouseDown:(NSEvent *)event
345     if ([self inputManagerHandleMouseEvent:event])
346         return;
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     if ([self inputManagerHandleMouseEvent:event])
381         return;
383     int row, col;
384     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
385     if (![textView convertPoint:pt toRow:&row column:&col])
386         return;
388     int flags = [event modifierFlags];
389     NSMutableData *data = [NSMutableData data];
391     [data appendBytes:&row length:sizeof(int)];
392     [data appendBytes:&col length:sizeof(int)];
393     [data appendBytes:&flags length:sizeof(int)];
395     [[self vimController] sendMessage:MouseUpMsgID data:data];
397     isDragging = NO;
400 - (void)mouseDragged:(NSEvent *)event
402     if ([self inputManagerHandleMouseEvent:event])
403         return;
405     int flags = [event modifierFlags];
406     int row, col;
407     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
408     if (![textView convertPoint:pt toRow:&row column:&col])
409         return;
411     // Autoscrolling is done in dragTimerFired:
412     if (!isAutoscrolling) {
413         NSMutableData *data = [NSMutableData data];
415         [data appendBytes:&row length:sizeof(int)];
416         [data appendBytes:&col length:sizeof(int)];
417         [data appendBytes:&flags length:sizeof(int)];
419         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
420     }
422     dragPoint = pt;
423     dragRow = row;
424     dragColumn = col;
425     dragFlags = flags;
427     if (!isDragging) {
428         [self startDragTimerWithInterval:.5];
429         isDragging = YES;
430     }
433 - (void)mouseMoved:(NSEvent *)event
435     if ([self inputManagerHandleMouseEvent:event])
436         return;
438     // HACK! NSTextView has a nasty habit of resetting the cursor to the
439     // default I-beam cursor at random moments.  The only reliable way we know
440     // of to work around this is to set the cursor each time the mouse moves.
441     [self setCursor];
443     NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
444     int row, col;
445     if (![textView convertPoint:pt toRow:&row column:&col])
446         return;
448     // HACK! It seems impossible to get the tracking rects set up before the
449     // view is visible, which means that the first mouseEntered: or
450     // mouseExited: events are never received.  This forces us to check if the
451     // mouseMoved: event really happened over the text.
452     int rows, cols;
453     [textView getMaxRows:&rows columns:&cols];
454     if (row >= 0 && row < rows && col >= 0 && col < cols) {
455         NSMutableData *data = [NSMutableData data];
457         [data appendBytes:&row length:sizeof(int)];
458         [data appendBytes:&col length:sizeof(int)];
460         [[self vimController] sendMessage:MouseMovedMsgID data:data];
461     }
464 - (void)mouseEntered:(NSEvent *)event
466     // NOTE: This event is received even when the window is not key; thus we
467     // have to take care not to enable mouse moved events unless our window is
468     // key.
469     if ([[textView window] isKeyWindow]) {
470         [[textView window] setAcceptsMouseMovedEvents:YES];
471     }
474 - (void)mouseExited:(NSEvent *)event
476     [[textView window] setAcceptsMouseMovedEvents:NO];
478     // NOTE: This event is received even when the window is not key; if the
479     // mouse shape is set when our window is not key, the hollow (unfocused)
480     // cursor will become a block (focused) cursor.
481     if ([[textView window] isKeyWindow]) {
482         int shape = 0;
483         NSMutableData *data = [NSMutableData data];
484         [data appendBytes:&shape length:sizeof(int)];
485         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
486     }
489 - (void)setFrame:(NSRect)frame
491     // When the frame changes we also need to update the tracking rect.
492     [textView removeTrackingRect:trackingRectTag];
493     trackingRectTag = [textView addTrackingRect:[self trackingRect]
494                                           owner:textView
495                                        userData:NULL
496                                    assumeInside:YES];
499 - (void)viewDidMoveToWindow
501     // Set a tracking rect which covers the text.
502     // NOTE: While the mouse cursor is in this rect the view will receive
503     // 'mouseMoved:' events so that Vim can take care of updating the mouse
504     // cursor.
505     if ([textView window]) {
506         [[textView window] setAcceptsMouseMovedEvents:YES];
507         trackingRectTag = [textView addTrackingRect:[self trackingRect]
508                                               owner:textView
509                                            userData:NULL
510                                        assumeInside:YES];
511     }
514 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
516     // Remove tracking rect if view moves or is removed.
517     if ([textView window] && trackingRectTag) {
518         [textView removeTrackingRect:trackingRectTag];
519         trackingRectTag = 0;
520     }
523 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
525     NSPasteboard *pboard = [sender draggingPasteboard];
527     if ([[pboard types] containsObject:NSStringPboardType]) {
528         NSString *string = [pboard stringForType:NSStringPboardType];
529         [[self vimController] dropString:string];
530         return YES;
531     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
532         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
533         [[self vimController] dropFiles:files forceOpen:NO];
534         return YES;
535     }
537     return NO;
540 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
542     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
543     NSPasteboard *pboard = [sender draggingPasteboard];
545     if ( [[pboard types] containsObject:NSFilenamesPboardType]
546             && (sourceDragMask & NSDragOperationCopy) )
547         return NSDragOperationCopy;
548     if ( [[pboard types] containsObject:NSStringPboardType]
549             && (sourceDragMask & NSDragOperationCopy) )
550         return NSDragOperationCopy;
552     return NSDragOperationNone;
555 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
557     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
558     NSPasteboard *pboard = [sender draggingPasteboard];
560     if ( [[pboard types] containsObject:NSFilenamesPboardType]
561             && (sourceDragMask & NSDragOperationCopy) )
562         return NSDragOperationCopy;
563     if ( [[pboard types] containsObject:NSStringPboardType]
564             && (sourceDragMask & NSDragOperationCopy) )
565         return NSDragOperationCopy;
567     return NSDragOperationNone;
570 - (void)setMouseShape:(int)shape
572     mouseShape = shape;
573     [self setCursor];
576 - (void)changeFont:(id)sender
578     NSFont *newFont = [sender convertFont:[textView font]];
579     NSFont *newFontWide = [sender convertFont:[textView fontWide]];
581     if (newFont) {
582         NSString *name = [newFont displayName];
583         NSString *wideName = [newFontWide displayName];
584         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
585         unsigned wideLen = [wideName lengthOfBytesUsingEncoding:
586                                                         NSUTF8StringEncoding];
587         if (len > 0) {
588             NSMutableData *data = [NSMutableData data];
589             float pointSize = [newFont pointSize];
591             [data appendBytes:&pointSize length:sizeof(float)];
593             ++len;  // include NUL byte
594             [data appendBytes:&len length:sizeof(unsigned)];
595             [data appendBytes:[name UTF8String] length:len];
597             if (wideLen > 0) {
598                 ++wideLen;  // include NUL byte
599                 [data appendBytes:&wideLen length:sizeof(unsigned)];
600                 [data appendBytes:[wideName UTF8String] length:wideLen];
601             } else {
602                 [data appendBytes:&wideLen length:sizeof(unsigned)];
603             }
605             [[self vimController] sendMessage:SetFontMsgID data:data];
606         }
607     }
610 - (BOOL)hasMarkedText
612     return markedRange.length > 0 ? YES : NO;
615 - (NSRange)markedRange
617     if ([self hasMarkedText])
618         return markedRange;
619     else
620         return NSMakeRange(NSNotFound, 0);
623 - (NSDictionary *)markedTextAttributes
625     return markedTextAttributes;
628 - (void)setMarkedTextAttributes:(NSDictionary *)attr
630     ASLogDebug(@"%@", attr);
631     if (attr != markedTextAttributes) {
632         [markedTextAttributes release];
633         markedTextAttributes = [attr retain];
634     }
637 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
639     ASLogDebug(@"text='%@' range=%@", text, NSStringFromRange(range));
640     [self unmarkText];
642     if ([self useInlineIm]) {
643         if ([text isKindOfClass:[NSAttributedString class]])
644             text = [text string];
646         if ([text length] > 0) {
647             markedRange = NSMakeRange(0, [text length]);
648             imRange = range;
649         }
651         [self sendMarkedText:text position:range.location];
652         return;
653     }
655 #ifdef INCLUDE_OLD_IM_CODE
656     if (!(text && [text length] > 0))
657         return;
659     // HACK! Determine if the marked text is wide or normal width.  This seems
660     // to always use 'wide' when there are both wide and normal width
661     // characters.
662     NSString *string = text;
663     NSFont *theFont = [textView font];
664     if ([text isKindOfClass:[NSAttributedString class]]) {
665         theFont = [textView fontWide];
666         string = [text string];
667     }
669     // TODO: Use special colors for marked text.
670     [self setMarkedTextAttributes:
671         [NSDictionary dictionaryWithObjectsAndKeys:
672             theFont, NSFontAttributeName,
673             [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
674             [textView defaultForegroundColor], NSForegroundColorAttributeName,
675             nil]];
677     markedText = [[NSMutableAttributedString alloc]
678            initWithString:string
679                attributes:[self markedTextAttributes]];
681     markedRange = NSMakeRange(0, [markedText length]);
682     if (markedRange.length) {
683         [markedText addAttribute:NSUnderlineStyleAttributeName
684                            value:[NSNumber numberWithInt:1]
685                            range:markedRange];
686     }
687     imRange = range;
688     if (range.length) {
689         [markedText addAttribute:NSUnderlineStyleAttributeName
690                            value:[NSNumber numberWithInt:2]
691                            range:range];
692     }
694     [textView setNeedsDisplay:YES];
695 #endif // INCLUDE_OLD_IM_CODE
698 - (void)unmarkText
700     ASLogDebug(@"");
701     imRange = NSMakeRange(0, 0);
702     markedRange = NSMakeRange(NSNotFound, 0);
703     [markedText release];
704     markedText = nil;
707 - (NSMutableAttributedString *)markedText
709     return markedText;
712 - (void)setPreEditRow:(int)row column:(int)col
714     preEditRow = row;
715     preEditColumn = col;
718 - (int)preEditRow
720     return preEditRow;
723 - (int)preEditColumn
725     return preEditColumn;
728 - (void)setImRange:(NSRange)range
730     imRange = range;
733 - (NSRange)imRange
735     return imRange;
738 - (void)setMarkedRange:(NSRange)range
740     markedRange = range;
743 - (NSRect)firstRectForCharacterRange:(NSRange)range
745     // This method is called when the input manager wants to pop up an
746     // auxiliary window.  The position where this should be is controlled by
747     // Vim by sending SetPreEditPositionMsgID so compute a position based on
748     // the pre-edit (row,column) pair.
749     int col = preEditColumn;
750     int row = preEditRow;
752     NSFont *theFont = [[textView markedTextAttributes]
753             valueForKey:NSFontAttributeName];
754     if (theFont == [textView fontWide]) {
755         col += imRange.location * 2;
756         if (col >= [textView maxColumns] - 1) {
757             row += (col / [textView maxColumns]);
758             col = col % 2 ? col % [textView maxColumns] + 1 :
759                             col % [textView maxColumns];
760         }
761     } else {
762         col += imRange.location;
763         if (col >= [textView maxColumns]) {
764             row += (col / [textView maxColumns]);
765             col = col % [textView maxColumns];
766         }
767     }
769     NSRect rect = [textView rectForRow:row
770                                 column:col
771                                numRows:1
772                             numColumns:range.length];
774     // NOTE: If the text view is flipped then 'rect' has its origin in the top
775     // left corner of the rect, but the methods below expect it to be in the
776     // lower left corner.  Compensate for this here.
777     // TODO: Maybe the above method should always return rects where the origin
778     // is in the lower left corner?
779     if ([textView isFlipped])
780         rect.origin.y += rect.size.height;
782     rect.origin = [textView convertPoint:rect.origin toView:nil];
783     rect.origin = [[textView window] convertBaseToScreen:rect.origin];
785     return rect;
788 - (void)setImControl:(BOOL)enable
790     // This flag corresponds to the (negation of the) 'imd' option.  When
791     // enabled changes to the input method are detected and forwarded to the
792     // backend.  On >=10.5 and later we do not forward changes to the input
793     // method, instead we let Vim be in complete control.
795 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
796     // The TIS symbols are weakly linked.
797     if (NULL != TISCopyCurrentKeyboardInputSource) {
798         // We get here when compiled on >=10.5 and running on >=10.5.
800         if (asciiImSource) {
801             CFRelease(asciiImSource);
802             asciiImSource = NULL;
803         }
804         if (lastImSource) {
805             CFRelease(lastImSource);
806             lastImSource = NULL;
807         }
808         if (enable) {
809             // Save current locale input source for use when IM is active and
810             // get an ASCII source for use when IM is deactivated (by Vim).
811             asciiImSource = TISCopyCurrentASCIICapableKeyboardInputSource();
812             NSString *locale = [[NSLocale currentLocale] localeIdentifier];
813             lastImSource = TISCopyInputSourceForLanguage((CFStringRef)locale);
814         }
815     }
816 #endif
818     imControl = enable;
819     ASLogInfo(@"IM control %sabled", enable ? "en" : "dis");
822 - (void)activateIm:(BOOL)enable
824     ASLogInfo(@"Activate IM=%d", enable);
826     // HACK: If there is marked text when switching IM it will be inserted as
827     // normal text.  To avoid this we abandon the marked text before switching.
828     [self abandonMarkedText];
830     imState = enable;
832 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
833     // The TIS symbols are weakly linked.
834     if (NULL != TISCopyCurrentKeyboardInputSource) {
835         // We get here when compiled on >=10.5 and running on >=10.5.
837         // Enable IM: switch back to input source used when IM was last on
838         // Disable IM: switch back to ASCII input source (set in setImControl:)
839         TISInputSourceRef ref = enable ? lastImSource : asciiImSource;
840         if (ref) {
841             ASLogDebug(@"Change input source: %@",
842                     TISGetInputSourceProperty(ref, kTISPropertyInputSourceID));
843             TISSelectInputSource(ref);
844         }
846         return;
847     }
849     // We get here when compiled on >=10.5 but running on 10.4 -- fall through
850     // and use old IM code...
851 #endif
852 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
853     // NOTE: The IM code is delegated to the frontend since calling it in
854     // the backend caused weird bugs (second dock icon appearing etc.).
855     KeyScript(enable ? smKeySysScript : smKeyRoman);
856 #endif
859 - (BOOL)useInlineIm
861 #ifdef INCLUDE_OLD_IM_CODE
862     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
863     return [ud boolForKey:MMUseInlineImKey];
864 #else
865     return YES;
866 #endif // INCLUDE_OLD_IM_CODE
869 @end // MMTextViewHelper
874 @implementation MMTextViewHelper (Private)
876 - (MMWindowController *)windowController
878     id windowController = [[textView window] windowController];
879     if ([windowController isKindOfClass:[MMWindowController class]])
880         return (MMWindowController*)windowController;
881     return nil;
884 - (MMVimController *)vimController
886     return [[self windowController] vimController];
889 - (void)doKeyDown:(NSString *)key
891     if (!currentEvent) {
892         ASLogDebug(@"No current event; ignore key");
893         return;
894     }
896     const char *chars = [key UTF8String];
897     unsigned length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
898     unsigned keyCode = [currentEvent keyCode];
899     unsigned flags = [currentEvent modifierFlags];
901     // The low 16 bits are not used for modifier flags by NSEvent.  Use
902     // these bits for custom flags.
903     flags &= NSDeviceIndependentModifierFlagsMask;
904     if ([currentEvent isARepeat])
905         flags |= 1;
907     NSMutableData *data = [NSMutableData data];
908     [data appendBytes:&flags length:sizeof(unsigned)];
909     [data appendBytes:&keyCode length:sizeof(unsigned)];
910     [data appendBytes:&length length:sizeof(unsigned)];
911     if (length > 0)
912         [data appendBytes:chars length:length];
914     [[self vimController] sendMessage:KeyDownMsgID data:data];
917 - (void)doInsertText:(NSString *)text
919     unsigned length = [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
920     if (0 == length)
921         return;
923     const char *chars = [text UTF8String];
924     unsigned keyCode = 0;
925     unsigned flags = 0;
927     // HACK! insertText: can be called from outside a keyDown: event in which
928     // case currentEvent is nil.  This happens e.g. when the "Special
929     // Characters" palette is used to insert text.  In this situation we assume
930     // that the key is not a repeat (if there was a palette that did auto
931     // repeat of input we might have to rethink this).
932     if (currentEvent) {
933         // HACK! Keys on the numeric key pad are treated as special keys by Vim
934         // so we need to pass on key code and modifier flags in this situation.
935         unsigned mods = [currentEvent modifierFlags];
936         if (mods & NSNumericPadKeyMask) {
937             flags = mods & NSDeviceIndependentModifierFlagsMask;
938             keyCode = [currentEvent keyCode];
939         }
941         if ([currentEvent isARepeat])
942             flags |= 1;
943     }
945     NSMutableData *data = [NSMutableData data];
946     [data appendBytes:&flags length:sizeof(unsigned)];
947     [data appendBytes:&keyCode length:sizeof(unsigned)];
948     [data appendBytes:&length length:sizeof(unsigned)];
949     [data appendBytes:chars length:length];
951     [[self vimController] sendMessage:KeyDownMsgID data:data];
954 - (void)checkImState
956 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
957     if (NULL != TISCopyCurrentKeyboardInputSource) {
958         // We get here when compiled on >=10.5 and running on >=10.5.
959         TISInputSourceRef cur = TISCopyCurrentKeyboardInputSource();
960         BOOL state = !KeyboardInputSourcesEqual(asciiImSource, cur);
961         BOOL isChanged = !KeyboardInputSourcesEqual(lastImSource, cur);
962         if (state && isChanged) {
963             // Remember current input source so we can switch back to it
964             // when IM is once more enabled.
965             ASLogDebug(@"Remember last input source: %@",
966                 TISGetInputSourceProperty(cur, kTISPropertyInputSourceID));
967             if (lastImSource) CFRelease(lastImSource);
968             lastImSource = cur;
969         } else {
970             CFRelease(cur);
971         }
972         if (imState != state) {
973             imState = state;
974             int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
975             [[self vimController] sendMessage:msgid data:nil];
976         }
977         return;
978     }
979 #endif
980 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
981     // Compiled for <=10.4, running on 10.4
983     // IM is active whenever the current script is the system script and the
984     // system script isn't roman.  (Hence IM can only be active when using
985     // non-roman scripts.)
987     // NOTE: The IM code is delegated to the frontend since calling it in the
988     // backend caused weird bugs (second dock icon appearing etc.).
989     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
990     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
991     BOOL state = currentScript != smRoman && currentScript == systemScript;
992     if (imState != state) {
993         imState = state;
994         int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
995         [[self vimController] sendMessage:msgid data:nil];
996     }
997 #endif
1000 - (void)hideMouseCursor
1002     // Check 'mousehide' option
1003     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
1004     if (mh && ![mh boolValue])
1005         [NSCursor setHiddenUntilMouseMoves:NO];
1006     else
1007         [NSCursor setHiddenUntilMouseMoves:YES];
1010 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1012     [NSTimer scheduledTimerWithTimeInterval:t target:self
1013                                    selector:@selector(dragTimerFired:)
1014                                    userInfo:nil repeats:NO];
1017 - (void)dragTimerFired:(NSTimer *)timer
1019     // TODO: Autoscroll in horizontal direction?
1020     static unsigned tick = 1;
1022     isAutoscrolling = NO;
1024     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
1025         // HACK! If the mouse cursor is outside the text area, then send a
1026         // dragged event.  However, if row&col hasn't changed since the last
1027         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1028         // Thus we fiddle with the column to make sure something happens.
1029         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1030         NSMutableData *data = [NSMutableData data];
1032         [data appendBytes:&dragRow length:sizeof(int)];
1033         [data appendBytes:&col length:sizeof(int)];
1034         [data appendBytes:&dragFlags length:sizeof(int)];
1036         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1038         isAutoscrolling = YES;
1039     }
1041     if (isDragging) {
1042         // Compute timer interval depending on how far away the mouse cursor is
1043         // from the text view.
1044         NSRect rect = [self trackingRect];
1045         float dy = 0;
1046         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1047         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1048         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1050         NSTimeInterval t = MMDragTimerMaxInterval -
1051             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1053         [self startDragTimerWithInterval:t];
1054     }
1056     ++tick;
1059 - (void)setCursor
1061     static NSCursor *customIbeamCursor = nil;
1063     if (!customIbeamCursor) {
1064         // Use a custom Ibeam cursor that has better contrast against dark
1065         // backgrounds.
1066         // TODO: Is the hotspot ok?
1067         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1068         if (ibeamImage) {
1069             NSSize size = [ibeamImage size];
1070             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1072             customIbeamCursor = [[NSCursor alloc]
1073                     initWithImage:ibeamImage hotSpot:hotSpot];
1074         }
1075         if (!customIbeamCursor) {
1076             ASLogWarn(@"Failed to load custom Ibeam cursor");
1077             customIbeamCursor = [NSCursor IBeamCursor];
1078         }
1079     }
1081     // This switch should match mshape_names[] in misc2.c.
1082     //
1083     // TODO: Add missing cursor shapes.
1084     switch (mouseShape) {
1085         case 2: [customIbeamCursor set]; break;
1086         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1087         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1088         case 9: [[NSCursor crosshairCursor] set]; break;
1089         case 10: [[NSCursor pointingHandCursor] set]; break;
1090         case 11: [[NSCursor openHandCursor] set]; break;
1091         default:
1092             [[NSCursor arrowCursor] set]; break;
1093     }
1095     // Shape 1 indicates that the mouse cursor should be hidden.
1096     if (1 == mouseShape)
1097         [NSCursor setHiddenUntilMouseMoves:YES];
1100 - (NSRect)trackingRect
1102     NSRect rect = [textView frame];
1103     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1104     int left = [ud integerForKey:MMTextInsetLeftKey];
1105     int top = [ud integerForKey:MMTextInsetTopKey];
1106     int right = [ud integerForKey:MMTextInsetRightKey];
1107     int bot = [ud integerForKey:MMTextInsetBottomKey];
1109     rect.origin.x = left;
1110     rect.origin.y = top;
1111     rect.size.width -= left + right - 1;
1112     rect.size.height -= top + bot - 1;
1114     return rect;
1117 - (BOOL)inputManagerHandleMouseEvent:(NSEvent *)event
1119     // NOTE: The input manager usually handles events like mouse clicks (e.g.
1120     // the Kotoeri manager "commits" the text on left clicks).
1122     if (event) {
1123         NSInputManager *imgr = [NSInputManager currentInputManager];
1124         if ([imgr wantsToHandleMouseEvents])
1125             return [imgr handleMouseEvent:event];
1126     }
1128     return NO;
1131 - (void)sendMarkedText:(NSString *)text position:(int32_t)pos
1133     if (![self useInlineIm])
1134         return;
1136     NSMutableData *data = [NSMutableData data];
1137     unsigned len = text == nil ? 0
1138                     : [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1140     [data appendBytes:&pos length:sizeof(int32_t)];
1141     [data appendBytes:&len length:sizeof(unsigned)];
1142     if (len > 0) {
1143         [data appendBytes:[text UTF8String] length:len];
1144         [data appendBytes:"\x00" length:1];
1145     }
1147     [[self vimController] sendMessage:SetMarkedTextMsgID data:data];
1150 - (void)abandonMarkedText
1152     [self unmarkText];
1154     // Send an empty marked text message with position set to -1 to indicate
1155     // that the marked text should be abandoned.  (If pos is set to 0 Vim will
1156     // send backspace sequences to delete the old marked text.)
1157     [self sendMarkedText:nil position:-1];
1158     [[NSInputManager currentInputManager] markedTextAbandoned:self];
1161 @end // MMTextViewHelper (Private)