fcd1106655aba48d9b3d640ed1c5c15bb888354c
[MacVim.git] / src / MacVim / MMTextViewHelper.m
blobfcd1106655aba48d9b3d640ed1c5c15bb888354c
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 + 1;
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     rect.origin = [textView convertPoint:rect.origin toView:nil];
775     rect.origin = [[textView window] convertBaseToScreen:rect.origin];
777     return rect;
780 - (void)setImControl:(BOOL)enable
782     // This flag corresponds to the (negation of the) 'imd' option.  When
783     // enabled changes to the input method are detected and forwarded to the
784     // backend.  On >=10.5 and later we do not forward changes to the input
785     // method, instead we let Vim be in complete control.
787 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
788     // The TIS symbols are weakly linked.
789     if (NULL != TISCopyCurrentKeyboardInputSource) {
790         // We get here when compiled on >=10.5 and running on >=10.5.
792         if (asciiImSource) {
793             CFRelease(asciiImSource);
794             asciiImSource = NULL;
795         }
796         if (lastImSource) {
797             CFRelease(lastImSource);
798             lastImSource = NULL;
799         }
800         if (enable) {
801             // Save current locale input source for use when IM is active and
802             // get an ASCII source for use when IM is deactivated (by Vim).
803             asciiImSource = TISCopyCurrentASCIICapableKeyboardInputSource();
804             NSString *locale = [[NSLocale currentLocale] localeIdentifier];
805             lastImSource = TISCopyInputSourceForLanguage((CFStringRef)locale);
806         }
807     }
808 #endif
810     imControl = enable;
811     ASLogInfo(@"IM control %sabled", enable ? "en" : "dis");
814 - (void)activateIm:(BOOL)enable
816     ASLogInfo(@"Activate IM=%d", enable);
818     // HACK: If there is marked text when switching IM it will be inserted as
819     // normal text.  To avoid this we abandon the marked text before switching.
820     [self abandonMarkedText];
822     imState = enable;
824 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
825     // The TIS symbols are weakly linked.
826     if (NULL != TISCopyCurrentKeyboardInputSource) {
827         // We get here when compiled on >=10.5 and running on >=10.5.
829         // Enable IM: switch back to input source used when IM was last on
830         // Disable IM: switch back to ASCII input source (set in setImControl:)
831         TISInputSourceRef ref = enable ? lastImSource : asciiImSource;
832         if (ref) {
833             ASLogDebug(@"Change input source: %@",
834                     TISGetInputSourceProperty(ref, kTISPropertyInputSourceID));
835             TISSelectInputSource(ref);
836         }
838         return;
839     }
841     // We get here when compiled on >=10.5 but running on 10.4 -- fall through
842     // and use old IM code...
843 #endif
844 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
845     // NOTE: The IM code is delegated to the frontend since calling it in
846     // the backend caused weird bugs (second dock icon appearing etc.).
847     KeyScript(enable ? smKeySysScript : smKeyRoman);
848 #endif
851 - (BOOL)useInlineIm
853 #ifdef INCLUDE_OLD_IM_CODE
854     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
855     return [ud boolForKey:MMUseInlineImKey];
856 #else
857     return YES;
858 #endif // INCLUDE_OLD_IM_CODE
861 @end // MMTextViewHelper
866 @implementation MMTextViewHelper (Private)
868 - (MMWindowController *)windowController
870     id windowController = [[textView window] windowController];
871     if ([windowController isKindOfClass:[MMWindowController class]])
872         return (MMWindowController*)windowController;
873     return nil;
876 - (MMVimController *)vimController
878     return [[self windowController] vimController];
881 - (void)doKeyDown:(NSString *)key
883     if (!currentEvent) {
884         ASLogDebug(@"No current event; ignore key");
885         return;
886     }
888     const char *chars = [key UTF8String];
889     unsigned length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
890     unsigned keyCode = [currentEvent keyCode];
891     unsigned flags = [currentEvent modifierFlags];
893     // The low 16 bits are not used for modifier flags by NSEvent.  Use
894     // these bits for custom flags.
895     flags &= NSDeviceIndependentModifierFlagsMask;
896     if ([currentEvent isARepeat])
897         flags |= 1;
899     NSMutableData *data = [NSMutableData data];
900     [data appendBytes:&flags length:sizeof(unsigned)];
901     [data appendBytes:&keyCode length:sizeof(unsigned)];
902     [data appendBytes:&length length:sizeof(unsigned)];
903     if (length > 0)
904         [data appendBytes:chars length:length];
906     [[self vimController] sendMessage:KeyDownMsgID data:data];
909 - (void)doInsertText:(NSString *)text
911     unsigned length = [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
912     if (0 == length)
913         return;
915     const char *chars = [text UTF8String];
916     unsigned keyCode = 0;
917     unsigned flags = 0;
919     // HACK! insertText: can be called from outside a keyDown: event in which
920     // case currentEvent is nil.  This happens e.g. when the "Special
921     // Characters" palette is used to insert text.  In this situation we assume
922     // that the key is not a repeat (if there was a palette that did auto
923     // repeat of input we might have to rethink this).
924     if (currentEvent) {
925         // HACK! Keys on the numeric key pad are treated as special keys by Vim
926         // so we need to pass on key code and modifier flags in this situation.
927         unsigned mods = [currentEvent modifierFlags];
928         if (mods & NSNumericPadKeyMask) {
929             flags = mods & NSDeviceIndependentModifierFlagsMask;
930             keyCode = [currentEvent keyCode];
931         }
933         if ([currentEvent isARepeat])
934             flags |= 1;
935     }
937     NSMutableData *data = [NSMutableData data];
938     [data appendBytes:&flags length:sizeof(unsigned)];
939     [data appendBytes:&keyCode length:sizeof(unsigned)];
940     [data appendBytes:&length length:sizeof(unsigned)];
941     [data appendBytes:chars length:length];
943     [[self vimController] sendMessage:KeyDownMsgID data:data];
946 - (void)checkImState
948 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5)
949     if (NULL != TISCopyCurrentKeyboardInputSource) {
950         // We get here when compiled on >=10.5 and running on >=10.5.
951         TISInputSourceRef cur = TISCopyCurrentKeyboardInputSource();
952         BOOL state = !KeyboardInputSourcesEqual(asciiImSource, cur);
953         BOOL isChanged = !KeyboardInputSourcesEqual(lastImSource, cur);
954         if (state && isChanged) {
955             // Remember current input source so we can switch back to it
956             // when IM is once more enabled.
957             ASLogDebug(@"Remember last input source: %@",
958                 TISGetInputSourceProperty(cur, kTISPropertyInputSourceID));
959             if (lastImSource) CFRelease(lastImSource);
960             lastImSource = cur;
961         } else {
962             CFRelease(cur);
963         }
964         if (imState != state) {
965             imState = state;
966             int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
967             [[self vimController] sendMessage:msgid data:nil];
968         }
969         return;
970     }
971 #endif
972 #if (MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5)
973     // Compiled for <=10.4, running on 10.4
975     // IM is active whenever the current script is the system script and the
976     // system script isn't roman.  (Hence IM can only be active when using
977     // non-roman scripts.)
979     // NOTE: The IM code is delegated to the frontend since calling it in the
980     // backend caused weird bugs (second dock icon appearing etc.).
981     SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
982     SInt32 systemScript = GetScriptManagerVariable(smSysScript);
983     BOOL state = currentScript != smRoman && currentScript == systemScript;
984     if (imState != state) {
985         imState = state;
986         int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
987         [[self vimController] sendMessage:msgid data:nil];
988     }
989 #endif
992 - (void)hideMouseCursor
994     // Check 'mousehide' option
995     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
996     if (mh && ![mh boolValue])
997         [NSCursor setHiddenUntilMouseMoves:NO];
998     else
999         [NSCursor setHiddenUntilMouseMoves:YES];
1002 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1004     [NSTimer scheduledTimerWithTimeInterval:t target:self
1005                                    selector:@selector(dragTimerFired:)
1006                                    userInfo:nil repeats:NO];
1009 - (void)dragTimerFired:(NSTimer *)timer
1011     // TODO: Autoscroll in horizontal direction?
1012     static unsigned tick = 1;
1014     isAutoscrolling = NO;
1016     if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
1017         // HACK! If the mouse cursor is outside the text area, then send a
1018         // dragged event.  However, if row&col hasn't changed since the last
1019         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1020         // Thus we fiddle with the column to make sure something happens.
1021         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1022         NSMutableData *data = [NSMutableData data];
1024         [data appendBytes:&dragRow length:sizeof(int)];
1025         [data appendBytes:&col length:sizeof(int)];
1026         [data appendBytes:&dragFlags length:sizeof(int)];
1028         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1030         isAutoscrolling = YES;
1031     }
1033     if (isDragging) {
1034         // Compute timer interval depending on how far away the mouse cursor is
1035         // from the text view.
1036         NSRect rect = [self trackingRect];
1037         float dy = 0;
1038         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1039         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1040         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1042         NSTimeInterval t = MMDragTimerMaxInterval -
1043             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1045         [self startDragTimerWithInterval:t];
1046     }
1048     ++tick;
1051 - (void)setCursor
1053     static NSCursor *customIbeamCursor = nil;
1055     if (!customIbeamCursor) {
1056         // Use a custom Ibeam cursor that has better contrast against dark
1057         // backgrounds.
1058         // TODO: Is the hotspot ok?
1059         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1060         if (ibeamImage) {
1061             NSSize size = [ibeamImage size];
1062             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1064             customIbeamCursor = [[NSCursor alloc]
1065                     initWithImage:ibeamImage hotSpot:hotSpot];
1066         }
1067         if (!customIbeamCursor) {
1068             ASLogWarn(@"Failed to load custom Ibeam cursor");
1069             customIbeamCursor = [NSCursor IBeamCursor];
1070         }
1071     }
1073     // This switch should match mshape_names[] in misc2.c.
1074     //
1075     // TODO: Add missing cursor shapes.
1076     switch (mouseShape) {
1077         case 2: [customIbeamCursor set]; break;
1078         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1079         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1080         case 9: [[NSCursor crosshairCursor] set]; break;
1081         case 10: [[NSCursor pointingHandCursor] set]; break;
1082         case 11: [[NSCursor openHandCursor] set]; break;
1083         default:
1084             [[NSCursor arrowCursor] set]; break;
1085     }
1087     // Shape 1 indicates that the mouse cursor should be hidden.
1088     if (1 == mouseShape)
1089         [NSCursor setHiddenUntilMouseMoves:YES];
1092 - (NSRect)trackingRect
1094     NSRect rect = [textView frame];
1095     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1096     int left = [ud integerForKey:MMTextInsetLeftKey];
1097     int top = [ud integerForKey:MMTextInsetTopKey];
1098     int right = [ud integerForKey:MMTextInsetRightKey];
1099     int bot = [ud integerForKey:MMTextInsetBottomKey];
1101     rect.origin.x = left;
1102     rect.origin.y = top;
1103     rect.size.width -= left + right - 1;
1104     rect.size.height -= top + bot - 1;
1106     return rect;
1109 - (BOOL)inputManagerHandleMouseEvent:(NSEvent *)event
1111     // NOTE: The input manager usually handles events like mouse clicks (e.g.
1112     // the Kotoeri manager "commits" the text on left clicks).
1114     if (event) {
1115         NSInputManager *imgr = [NSInputManager currentInputManager];
1116         if ([imgr wantsToHandleMouseEvents])
1117             return [imgr handleMouseEvent:event];
1118     }
1120     return NO;
1123 - (void)sendMarkedText:(NSString *)text position:(int32_t)pos
1125     if (![self useInlineIm])
1126         return;
1128     NSMutableData *data = [NSMutableData data];
1129     unsigned len = text == nil ? 0
1130                     : [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1132     [data appendBytes:&pos length:sizeof(int32_t)];
1133     [data appendBytes:&len length:sizeof(unsigned)];
1134     if (len > 0) {
1135         [data appendBytes:[text UTF8String] length:len];
1136         [data appendBytes:"\x00" length:1];
1137     }
1139     [[self vimController] sendMessage:SetMarkedTextMsgID data:data];
1142 - (void)abandonMarkedText
1144     [self unmarkText];
1146     // Send an empty marked text message with position set to -1 to indicate
1147     // that the marked text should be abandoned.  (If pos is set to 0 Vim will
1148     // send backspace sequences to delete the old marked text.)
1149     [self sendMarkedText:nil position:-1];
1150     [[NSInputManager currentInputManager] markedTextAbandoned:self];
1153 @end // MMTextViewHelper (Private)