1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
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.
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.
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;
40 - (void)hideMouseCursor;
41 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
42 - (void)dragTimerFired:(NSTimer *)timer;
44 - (NSRect)trackingRect;
45 - (BOOL)inputManagerHandleMouseEvent:(NSEvent *)event;
46 - (void)sendMarkedText:(NSString *)text position:(unsigned)pos;
52 #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
54 KeyboardInputSourcesEqual(TISInputSourceRef a, TISInputSourceRef b)
56 // Define two sources to be equal iff both are non-NULL and they have
57 // identical source ID strings.
62 NSString *as = TISGetInputSourceProperty(a, kTISPropertyInputSourceID);
63 NSString *bs = TISGetInputSourceProperty(b, kTISPropertyInputSourceID);
65 return [as isEqualToString:bs];
70 @implementation MMTextViewHelper
76 [insertionPointColor release]; insertionPointColor = nil;
77 [markedText release]; markedText = nil;
78 [markedTextAttributes release]; markedTextAttributes = nil;
80 #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
82 CFRelease(asciiImSource);
86 CFRelease(lastImSource);
94 - (void)setTextView:(id)view
96 // Only keep a weak reference to owning text view.
100 - (void)setInsertionPointColor:(NSColor *)color
102 if (color != insertionPointColor) {
103 [insertionPointColor release];
104 insertionPointColor = [color retain];
108 - (NSColor *)insertionPointColor
110 return insertionPointColor;
113 - (void)keyDown:(NSEvent *)event
115 ASLogDebug(@"%@", event);
117 // NOTE: Keyboard handling is complicated by the fact that we must call
118 // interpretKeyEvents: otherwise key equivalents set up by input methods do
119 // not work (e.g. Ctrl-Shift-; would not work under Kotoeri).
121 // NOTE: insertText: and doCommandBySelector: may need to extract data from
122 // the key down event so keep a local reference to the event. This is
123 // released and set to nil at the end of this method. Don't make any early
124 // returns from this method without releasing and resetting this reference!
125 currentEvent = [event retain];
127 if ([self hasMarkedText]) {
128 // HACK! Need to redisplay manually otherwise the marked text may not
129 // be correctly displayed (e.g. it is still visible after pressing Esc
130 // even though the text has been unmarked).
131 [textView setNeedsDisplay:YES];
134 [self hideMouseCursor];
136 unsigned flags = [event modifierFlags];
137 id mmta = [[[self vimController] vimState] objectForKey:@"p_mmta"];
138 NSString *string = [event characters];
139 NSString *unmod = [event charactersIgnoringModifiers];
141 // Alt key presses should not be interpreted if the 'macmeta' option is
142 // set. We still have to call interpretKeyEvents: for keys
143 // like Enter, Esc, etc. to work as usual so only skip interpretation for
144 // ASCII chars in the range after space (0x20) and before backspace (0x7f).
145 // Note that this implies that 'mmta' (if enabled) breaks input methods
146 // when the Alt key is held.
147 if ((flags & NSAlternateKeyMask) && [mmta boolValue] && [unmod length] == 1
148 && [unmod characterAtIndex:0] > 0x20
149 && [unmod characterAtIndex:0] < 0x7f) {
150 ASLogDebug(@"MACMETA key, don't interpret it");
153 // HACK! interpretKeyEvents: may call insertText: or
154 // doCommandBySelector:, or it may swallow the key (most likely the
155 // current input method used it). In the first two cases we have to
156 // manually set the below flag to NO if the key wasn't handled.
157 interpretKeyEventsSwallowedKey = YES;
158 [textView interpretKeyEvents:[NSArray arrayWithObject:event]];
159 if (interpretKeyEventsSwallowedKey)
161 else if (flags & NSCommandKeyMask) {
162 // HACK! When Command is held we have to more or less guess whether
163 // we should use characters or charactersIgnoringModifiers. The
164 // following heuristic seems to work but it may have to change.
165 // Note that the Shift and Alt flags may be cleared before passing
166 // the event on to Vim (see doKeyDown:).
167 if ((flags & NSShiftKeyMask && !(flags & NSAlternateKeyMask))
168 || flags & NSControlKeyMask)
174 [self doKeyDown:string];
176 // NOTE: Check IM state _after_ key has been interpreted or we'll pick up
177 // the old IM state when it has been switched via a keyboard shortcut.
181 [currentEvent release];
185 - (void)insertText:(id)string
187 if ([self hasMarkedText]) {
188 [self sendMarkedText:nil position:0];
190 // NOTE: If this call is left out then the marked text isn't properly
191 // erased when Return is used to accept the text.
192 // The input manager only ever sets new marked text, it never actually
193 // calls to have it unmarked. It seems that whenever insertText: is
194 // called the input manager expects the marked text to be unmarked
195 // automatically, hence the explicit unmarkText: call here.
199 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
200 // do not support attributes, simply pass the corresponding NSString in the
202 if ([string isKindOfClass:[NSAttributedString class]])
203 string = [string string];
205 //int len = [string length];
206 //ASLogDebug(@"len=%d char[0]=%#x char[1]=%#x string='%@'", [string length],
207 // [string characterAtIndex:0],
208 // len > 1 ? [string characterAtIndex:1] : 0, string);
210 [self doInsertText:string];
213 - (void)doCommandBySelector:(SEL)sel
215 ASLogDebug(@"%@", NSStringFromSelector(sel));
217 // Translate Ctrl-2 -> Ctrl-@ (see also Resources/KeyBinding.plist)
218 if (@selector(keyCtrlAt:) == sel)
219 [self doKeyDown:@"\x00"];
220 // Translate Ctrl-6 -> Ctrl-^ (see also Resources/KeyBinding.plist)
221 else if (@selector(keyCtrlHat:) == sel)
222 [self doKeyDown:@"\x1e"];
224 // Check for selectors from AppKit.framework/StandardKeyBinding.dict and
225 // send the corresponding key directly on to the backend. The reason for
226 // not just letting all of these fall through is that -[NSEvent characters]
227 // sometimes includes marked text as well as the actual key, but the marked
228 // text is also passed to insertText:. For example, pressing Ctrl-i Return
229 // on a US keyboard would call insertText:@"^" but the key event for the
230 // Return press will contain "^\x0d" -- if we fell through the result would
231 // be that "^^\x0d" got sent to the backend (i.e. one extra "^" would
233 // For this reason we also have to make sure that there are key bindings to
234 // all combinations of modifier with certain keys (these are set up in
235 // KeyBinding.plist in the Resources folder).
236 else if (@selector(insertTab:) == sel ||
237 @selector(selectNextKeyView:) == sel ||
238 @selector(insertTabIgnoringFieldEditor:) == sel)
239 [self doKeyDown:@"\x09"];
240 else if (@selector(insertNewline:) == sel ||
241 @selector(insertLineBreak:) == sel ||
242 @selector(insertNewlineIgnoringFieldEditor:) == sel)
243 [self doKeyDown:@"\x0d"];
244 else if (@selector(cancelOperation:) == sel ||
245 @selector(complete:) == sel)
246 [self doKeyDown:@"\x1b"];
247 else if (@selector(insertBackTab:) == sel ||
248 @selector(selectPreviousKeyView:) == sel)
249 [self doKeyDown:@"\x19"];
250 else if (@selector(deleteBackward:) == sel ||
251 @selector(deleteWordBackward:) == sel ||
252 @selector(deleteBackwardByDecomposingPreviousCharacter:) == sel ||
253 @selector(deleteToBeginningOfLine:) == sel)
254 [self doKeyDown:@"\x08"];
255 else if (@selector(keySpace:) == sel)
256 [self doKeyDown:@" "];
257 else if (@selector(cancel:) == sel)
258 kill([[self vimController] pid], SIGINT);
259 else interpretKeyEventsSwallowedKey = NO;
262 - (BOOL)performKeyEquivalent:(NSEvent *)event
265 if ([event type] != NSKeyDown)
268 // NOTE: Key equivalent handling was fixed in Leopard. That is, an
269 // unhandled key equivalent is passed to keyDown: -- contrast this with
270 // pre-Leopard where unhandled key equivalents would simply disappear
271 // (hence the ugly hack below for Tiger).
272 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_4)
275 // HACK! KeyCode 50 represent the key which switches between windows
276 // within an application (like Cmd+Tab is used to switch between
277 // applications). Return NO here, else the window switching does not work.
278 if ([event keyCode] == 50)
281 // HACK! The -[NSRespoder cancelOperation:] indicates that Cmd-. is handled
282 // in a special way by the key window. Indeed, if we pass this event on to
283 // keyDown: it will result in doCommandBySelector: being called with
284 // cancelOperation: as selector, otherwise it is called with cancel: as the
285 // selector (and we respond to cancel: there).
286 int flags = [event modifierFlags] & NSDeviceIndependentModifierFlagsMask;
287 NSString *unmod = [event charactersIgnoringModifiers];
288 if (flags == NSCommandKeyMask && [unmod isEqual:@"."])
291 // HACK! Let the main menu try to handle any key down event, before
292 // passing it on to vim, otherwise key equivalents for menus will
293 // effectively be disabled.
294 if ([[NSApp mainMenu] performKeyEquivalent:event])
297 // HACK! Pass the event on or it may disappear (Tiger does not pass Cmd-key
298 // events to keyDown:).
299 [self keyDown:event];
303 - (void)scrollWheel:(NSEvent *)event
305 if ([self hasMarkedText]) {
306 // We must clear the marked text since the cursor may move if the
307 // marked text moves outside the view as a result of scrolling.
308 [self sendMarkedText:nil position:0];
310 [[NSInputManager currentInputManager] markedTextAbandoned:self];
313 if ([event deltaY] == 0)
317 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
318 if ([textView convertPoint:pt toRow:&row column:&col]) {
319 int flags = [event modifierFlags];
320 float dy = [event deltaY];
321 NSMutableData *data = [NSMutableData data];
323 [data appendBytes:&row length:sizeof(int)];
324 [data appendBytes:&col length:sizeof(int)];
325 [data appendBytes:&flags length:sizeof(int)];
326 [data appendBytes:&dy length:sizeof(float)];
328 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
332 - (void)mouseDown:(NSEvent *)event
334 if ([self inputManagerHandleMouseEvent:event])
338 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
339 if (![textView convertPoint:pt toRow:&row column:&col])
342 int button = [event buttonNumber];
343 int flags = [event modifierFlags];
344 int count = [event clickCount];
345 NSMutableData *data = [NSMutableData data];
347 // If desired, intepret Ctrl-Click as a right mouse click.
348 BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
349 boolForKey:MMTranslateCtrlClickKey];
350 flags = flags & NSDeviceIndependentModifierFlagsMask;
351 if (translateCtrlClick && button == 0 &&
352 (flags == NSControlKeyMask ||
353 flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
355 flags &= ~NSControlKeyMask;
358 [data appendBytes:&row length:sizeof(int)];
359 [data appendBytes:&col length:sizeof(int)];
360 [data appendBytes:&button length:sizeof(int)];
361 [data appendBytes:&flags length:sizeof(int)];
362 [data appendBytes:&count length:sizeof(int)];
364 [[self vimController] sendMessage:MouseDownMsgID data:data];
367 - (void)mouseUp:(NSEvent *)event
369 if ([self inputManagerHandleMouseEvent:event])
373 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
374 if (![textView convertPoint:pt toRow:&row column:&col])
377 int flags = [event modifierFlags];
378 NSMutableData *data = [NSMutableData data];
380 [data appendBytes:&row length:sizeof(int)];
381 [data appendBytes:&col length:sizeof(int)];
382 [data appendBytes:&flags length:sizeof(int)];
384 [[self vimController] sendMessage:MouseUpMsgID data:data];
389 - (void)mouseDragged:(NSEvent *)event
391 if ([self inputManagerHandleMouseEvent:event])
394 int flags = [event modifierFlags];
396 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
397 if (![textView convertPoint:pt toRow:&row column:&col])
400 // Autoscrolling is done in dragTimerFired:
401 if (!isAutoscrolling) {
402 NSMutableData *data = [NSMutableData data];
404 [data appendBytes:&row length:sizeof(int)];
405 [data appendBytes:&col length:sizeof(int)];
406 [data appendBytes:&flags length:sizeof(int)];
408 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
417 [self startDragTimerWithInterval:.5];
422 - (void)mouseMoved:(NSEvent *)event
424 if ([self inputManagerHandleMouseEvent:event])
427 // HACK! NSTextView has a nasty habit of resetting the cursor to the
428 // default I-beam cursor at random moments. The only reliable way we know
429 // of to work around this is to set the cursor each time the mouse moves.
432 NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil];
434 if (![textView convertPoint:pt toRow:&row column:&col])
437 // HACK! It seems impossible to get the tracking rects set up before the
438 // view is visible, which means that the first mouseEntered: or
439 // mouseExited: events are never received. This forces us to check if the
440 // mouseMoved: event really happened over the text.
442 [textView getMaxRows:&rows columns:&cols];
443 if (row >= 0 && row < rows && col >= 0 && col < cols) {
444 NSMutableData *data = [NSMutableData data];
446 [data appendBytes:&row length:sizeof(int)];
447 [data appendBytes:&col length:sizeof(int)];
449 [[self vimController] sendMessage:MouseMovedMsgID data:data];
453 - (void)mouseEntered:(NSEvent *)event
455 // NOTE: This event is received even when the window is not key; thus we
456 // have to take care not to enable mouse moved events unless our window is
458 if ([[textView window] isKeyWindow]) {
459 [[textView window] setAcceptsMouseMovedEvents:YES];
463 - (void)mouseExited:(NSEvent *)event
465 [[textView window] setAcceptsMouseMovedEvents:NO];
467 // NOTE: This event is received even when the window is not key; if the
468 // mouse shape is set when our window is not key, the hollow (unfocused)
469 // cursor will become a block (focused) cursor.
470 if ([[textView window] isKeyWindow]) {
472 NSMutableData *data = [NSMutableData data];
473 [data appendBytes:&shape length:sizeof(int)];
474 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
478 - (void)setFrame:(NSRect)frame
480 // When the frame changes we also need to update the tracking rect.
481 [textView removeTrackingRect:trackingRectTag];
482 trackingRectTag = [textView addTrackingRect:[self trackingRect]
488 - (void)viewDidMoveToWindow
490 // Set a tracking rect which covers the text.
491 // NOTE: While the mouse cursor is in this rect the view will receive
492 // 'mouseMoved:' events so that Vim can take care of updating the mouse
494 if ([textView window]) {
495 [[textView window] setAcceptsMouseMovedEvents:YES];
496 trackingRectTag = [textView addTrackingRect:[self trackingRect]
503 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
505 // Remove tracking rect if view moves or is removed.
506 if ([textView window] && trackingRectTag) {
507 [textView removeTrackingRect:trackingRectTag];
512 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
514 NSPasteboard *pboard = [sender draggingPasteboard];
516 if ([[pboard types] containsObject:NSStringPboardType]) {
517 NSString *string = [pboard stringForType:NSStringPboardType];
518 [[self vimController] dropString:string];
520 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
521 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
522 [[self vimController] dropFiles:files forceOpen:NO];
529 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
531 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
532 NSPasteboard *pboard = [sender draggingPasteboard];
534 if ( [[pboard types] containsObject:NSFilenamesPboardType]
535 && (sourceDragMask & NSDragOperationCopy) )
536 return NSDragOperationCopy;
537 if ( [[pboard types] containsObject:NSStringPboardType]
538 && (sourceDragMask & NSDragOperationCopy) )
539 return NSDragOperationCopy;
541 return NSDragOperationNone;
544 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
546 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
547 NSPasteboard *pboard = [sender draggingPasteboard];
549 if ( [[pboard types] containsObject:NSFilenamesPboardType]
550 && (sourceDragMask & NSDragOperationCopy) )
551 return NSDragOperationCopy;
552 if ( [[pboard types] containsObject:NSStringPboardType]
553 && (sourceDragMask & NSDragOperationCopy) )
554 return NSDragOperationCopy;
556 return NSDragOperationNone;
559 - (void)setMouseShape:(int)shape
565 - (void)changeFont:(id)sender
567 NSFont *newFont = [sender convertFont:[textView font]];
568 NSFont *newFontWide = [sender convertFont:[textView fontWide]];
571 NSString *name = [newFont displayName];
572 NSString *wideName = [newFontWide displayName];
573 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
574 unsigned wideLen = [wideName lengthOfBytesUsingEncoding:
575 NSUTF8StringEncoding];
577 NSMutableData *data = [NSMutableData data];
578 float pointSize = [newFont pointSize];
580 [data appendBytes:&pointSize length:sizeof(float)];
582 ++len; // include NUL byte
583 [data appendBytes:&len length:sizeof(unsigned)];
584 [data appendBytes:[name UTF8String] length:len];
587 ++wideLen; // include NUL byte
588 [data appendBytes:&wideLen length:sizeof(unsigned)];
589 [data appendBytes:[wideName UTF8String] length:wideLen];
591 [data appendBytes:&wideLen length:sizeof(unsigned)];
594 [[self vimController] sendMessage:SetFontMsgID data:data];
599 - (BOOL)hasMarkedText
601 return markedRange.length > 0 ? YES : NO;
604 - (NSRange)markedRange
606 if ([self hasMarkedText])
609 return NSMakeRange(NSNotFound, 0);
612 - (NSDictionary *)markedTextAttributes
614 return markedTextAttributes;
617 - (void)setMarkedTextAttributes:(NSDictionary *)attr
619 ASLogDebug(@"%@", attr);
620 if (attr != markedTextAttributes) {
621 [markedTextAttributes release];
622 markedTextAttributes = [attr retain];
626 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
628 ASLogDebug(@"text='%@' range=%@", text, NSStringFromRange(range));
631 if ([self useInlineIm]) {
632 if ([text isKindOfClass:[NSAttributedString class]])
633 text = [text string];
635 if ([text length] > 0) {
636 markedRange = NSMakeRange(0, [text length]);
640 [self sendMarkedText:text position:range.location];
644 #ifdef INCLUDE_OLD_IM_CODE
645 if (!(text && [text length] > 0))
648 // HACK! Determine if the marked text is wide or normal width. This seems
649 // to always use 'wide' when there are both wide and normal width
651 NSString *string = text;
652 NSFont *theFont = [textView font];
653 if ([text isKindOfClass:[NSAttributedString class]]) {
654 theFont = [textView fontWide];
655 string = [text string];
658 // TODO: Use special colors for marked text.
659 [self setMarkedTextAttributes:
660 [NSDictionary dictionaryWithObjectsAndKeys:
661 theFont, NSFontAttributeName,
662 [textView defaultBackgroundColor], NSBackgroundColorAttributeName,
663 [textView defaultForegroundColor], NSForegroundColorAttributeName,
666 markedText = [[NSMutableAttributedString alloc]
667 initWithString:string
668 attributes:[self markedTextAttributes]];
670 markedRange = NSMakeRange(0, [markedText length]);
671 if (markedRange.length) {
672 [markedText addAttribute:NSUnderlineStyleAttributeName
673 value:[NSNumber numberWithInt:1]
678 [markedText addAttribute:NSUnderlineStyleAttributeName
679 value:[NSNumber numberWithInt:2]
683 [textView setNeedsDisplay:YES];
684 #endif // INCLUDE_OLD_IM_CODE
690 imRange = NSMakeRange(0, 0);
691 markedRange = NSMakeRange(NSNotFound, 0);
692 [markedText release];
696 - (NSMutableAttributedString *)markedText
701 - (void)setPreEditRow:(int)row column:(int)col
714 return preEditColumn;
717 - (void)setImRange:(NSRange)range
727 - (void)setMarkedRange:(NSRange)range
732 - (NSRect)firstRectForCharacterRange:(NSRange)range
734 // This method is called when the input manager wants to pop up an
735 // auxiliary window. The position where this should be is controlled by
736 // Vim by sending SetPreEditPositionMsgID so compute a position based on
737 // the pre-edit (row,column) pair.
738 int col = preEditColumn;
739 int row = preEditRow + 1;
741 NSFont *theFont = [[textView markedTextAttributes]
742 valueForKey:NSFontAttributeName];
743 if (theFont == [textView fontWide]) {
744 col += imRange.location * 2;
745 if (col >= [textView maxColumns] - 1) {
746 row += (col / [textView maxColumns]);
747 col = col % 2 ? col % [textView maxColumns] + 1 :
748 col % [textView maxColumns];
751 col += imRange.location;
752 if (col >= [textView maxColumns]) {
753 row += (col / [textView maxColumns]);
754 col = col % [textView maxColumns];
758 NSRect rect = [textView rectForRow:row
761 numColumns:range.length];
763 rect.origin = [textView convertPoint:rect.origin toView:nil];
764 rect.origin = [[textView window] convertBaseToScreen:rect.origin];
769 - (void)setImControl:(BOOL)enable
771 // This flag corresponds to the (negation of the) 'imd' option. When
772 // enabled changes to the input method are detected and forwarded to the
773 // backend. On >=10.5 and later we do not forward changes to the input
774 // method, instead we let Vim be in complete control.
776 #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
777 // The TIS symbols are weakly linked.
778 if (NULL != TISCopyCurrentKeyboardInputSource) {
779 // We get here when compiled on =>10.5 and running on >=10.5.
782 CFRelease(asciiImSource);
783 asciiImSource = NULL;
786 CFRelease(lastImSource);
790 // Save current input source for use when IM is active and get an
791 // ASCII source for use when IM is deactivated (by Vim).
792 asciiImSource = TISCopyCurrentASCIICapableKeyboardInputSource();
793 lastImSource = TISCopyCurrentKeyboardInputSource();
798 // The imControl flag is only used on 10.4 -- on >=10.5 we wait for Vim to
799 // call activateIm: and never explicitly check if the input source changes.
801 ASLogInfo(@"IM control %sabled", enable ? "en" : "dis");
804 - (void)activateIm:(BOOL)enable
806 ASLogInfo(@"Activate IM=%d", enable);
808 #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
809 // The TIS symbols are weakly linked.
810 if (NULL != TISCopyCurrentKeyboardInputSource) {
811 // We get here when compiled on >=10.5 and running on >=10.5.
813 TISInputSourceRef ref = NULL;
815 // Enable IM: switch back to input source used when IM was last on.
818 // Disable IM: switch back to ASCII input source that was used when
822 TISInputSourceRef cur = TISCopyCurrentKeyboardInputSource();
823 if (!KeyboardInputSourcesEqual(asciiImSource, cur)) {
824 // Remember current input source so we can switch back to it
825 // when IM is once more enabled. Note that Vim will call this
826 // method with "enable=NO" even when the ASCII input source is
827 // in use which is why we only remember the current input
828 // source unless it is the ASCII source.
829 ASLogDebug(@"Remember last input source: %@",
830 TISGetInputSourceProperty(cur, kTISPropertyInputSourceID));
831 if (lastImSource) CFRelease(lastImSource);
840 ASLogDebug(@"Change input source: %@",
841 TISGetInputSourceProperty(ref, kTISPropertyInputSourceID));
842 TISSelectInputSource(ref);
848 // We get here when compiled on >=10.5 but running on 10.4 -- fall through
849 // and use old IM code...
851 #if (MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4)
852 // NOTE: The IM code is delegated to the frontend since calling it in
853 // the backend caused weird bugs (second dock icon appearing etc.).
854 KeyScript(enable ? smKeySysScript : smKeyRoman);
860 #ifdef INCLUDE_OLD_IM_CODE
861 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
862 return [ud boolForKey:MMUseInlineImKey];
865 #endif // INCLUDE_OLD_IM_CODE
868 @end // MMTextViewHelper
873 @implementation MMTextViewHelper (Private)
875 - (MMWindowController *)windowController
877 id windowController = [[textView window] windowController];
878 if ([windowController isKindOfClass:[MMWindowController class]])
879 return (MMWindowController*)windowController;
883 - (MMVimController *)vimController
885 return [[self windowController] vimController];
888 - (void)doKeyDown:(NSString *)key
891 ASLogDebug(@"No current event; ignore key");
895 const char *chars = [key UTF8String];
896 unsigned length = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
897 unsigned keyCode = [currentEvent keyCode];
898 unsigned flags = [currentEvent modifierFlags];
900 if (flags & NSCommandKeyMask) {
901 // The Shift flag is already included in the key when the Command key
902 // is held. The same goes for Alt, unless Ctrl is held or 'macmeta' is
904 flags &= ~NSShiftKeyMask;
905 if (!(flags & NSControlKeyMask)) {
906 id mmta = [[[self vimController] vimState] objectForKey:@"p_mmta"];
907 if (![mmta boolValue])
908 flags &= ~NSAlternateKeyMask;
912 // The low 16 bits are not used for modifier flags by NSEvent. Use
913 // these bits for custom flags.
914 flags &= NSDeviceIndependentModifierFlagsMask;
915 if ([currentEvent isARepeat])
918 NSMutableData *data = [NSMutableData data];
919 [data appendBytes:&flags length:sizeof(unsigned)];
920 [data appendBytes:&keyCode length:sizeof(unsigned)];
921 [data appendBytes:&length length:sizeof(unsigned)];
923 [data appendBytes:chars length:length];
925 [[self vimController] sendMessage:KeyDownMsgID data:data];
928 - (void)doInsertText:(NSString *)text
930 unsigned length = [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
934 const char *chars = [text UTF8String];
935 unsigned keyCode = 0;
938 // HACK! insertText: can be called from outside a keyDown: event in which
939 // case currentEvent is nil. This happens e.g. when the "Special
940 // Characters" palette is used to insert text. In this situation we assume
941 // that the key is not a repeat (if there was a palette that did auto
942 // repeat of input we might have to rethink this).
944 // HACK! Keys on the numeric key pad are treated as special keys by Vim
945 // so we need to pass on key code and modifier flags in this situation.
946 unsigned mods = [currentEvent modifierFlags];
947 if (mods & NSNumericPadKeyMask) {
948 flags = mods & NSDeviceIndependentModifierFlagsMask;
949 keyCode = [currentEvent keyCode];
952 if ([currentEvent isARepeat])
956 NSMutableData *data = [NSMutableData data];
957 [data appendBytes:&flags length:sizeof(unsigned)];
958 [data appendBytes:&keyCode length:sizeof(unsigned)];
959 [data appendBytes:&length length:sizeof(unsigned)];
960 [data appendBytes:chars length:length];
962 [[self vimController] sendMessage:KeyDownMsgID data:data];
967 #if (MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4)
968 #if (MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_4)
969 if (NULL != TISCopyCurrentKeyboardInputSource)
970 return; // Compiled for >=10.4, running on >=10.5
972 // Compiled for >=10.4, running on 10.4
974 // IM is active whenever the current script is the system script and the
975 // system script isn't roman. (Hence IM can only be active when using
976 // non-roman scripts.)
978 // NOTE: The IM code is delegated to the frontend since calling it in the
979 // backend caused weird bugs (second dock icon appearing etc.).
980 SInt32 currentScript = GetScriptManagerVariable(smKeyScript);
981 SInt32 systemScript = GetScriptManagerVariable(smSysScript);
982 BOOL state = currentScript != smRoman && currentScript == systemScript;
983 if (imState != state) {
985 int msgid = state ? ActivatedImMsgID : DeactivatedImMsgID;
986 [[self vimController] sendMessage:msgid data:nil];
991 - (void)hideMouseCursor
993 // Check 'mousehide' option
994 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
995 if (mh && ![mh boolValue])
996 [NSCursor setHiddenUntilMouseMoves:NO];
998 [NSCursor setHiddenUntilMouseMoves:YES];
1001 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1003 [NSTimer scheduledTimerWithTimeInterval:t target:self
1004 selector:@selector(dragTimerFired:)
1005 userInfo:nil repeats:NO];
1008 - (void)dragTimerFired:(NSTimer *)timer
1010 // TODO: Autoscroll in horizontal direction?
1011 static unsigned tick = 1;
1013 isAutoscrolling = NO;
1015 if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) {
1016 // HACK! If the mouse cursor is outside the text area, then send a
1017 // dragged event. However, if row&col hasn't changed since the last
1018 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1019 // Thus we fiddle with the column to make sure something happens.
1020 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1021 NSMutableData *data = [NSMutableData data];
1023 [data appendBytes:&dragRow length:sizeof(int)];
1024 [data appendBytes:&col length:sizeof(int)];
1025 [data appendBytes:&dragFlags length:sizeof(int)];
1027 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1029 isAutoscrolling = YES;
1033 // Compute timer interval depending on how far away the mouse cursor is
1034 // from the text view.
1035 NSRect rect = [self trackingRect];
1037 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1038 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1039 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1041 NSTimeInterval t = MMDragTimerMaxInterval -
1042 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1044 [self startDragTimerWithInterval:t];
1052 static NSCursor *customIbeamCursor = nil;
1054 if (!customIbeamCursor) {
1055 // Use a custom Ibeam cursor that has better contrast against dark
1057 // TODO: Is the hotspot ok?
1058 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1060 NSSize size = [ibeamImage size];
1061 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1063 customIbeamCursor = [[NSCursor alloc]
1064 initWithImage:ibeamImage hotSpot:hotSpot];
1066 if (!customIbeamCursor) {
1067 ASLogWarn(@"Failed to load custom Ibeam cursor");
1068 customIbeamCursor = [NSCursor IBeamCursor];
1072 // This switch should match mshape_names[] in misc2.c.
1074 // TODO: Add missing cursor shapes.
1075 switch (mouseShape) {
1076 case 2: [customIbeamCursor set]; break;
1077 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1078 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1079 case 9: [[NSCursor crosshairCursor] set]; break;
1080 case 10: [[NSCursor pointingHandCursor] set]; break;
1081 case 11: [[NSCursor openHandCursor] set]; break;
1083 [[NSCursor arrowCursor] set]; break;
1086 // Shape 1 indicates that the mouse cursor should be hidden.
1087 if (1 == mouseShape)
1088 [NSCursor setHiddenUntilMouseMoves:YES];
1091 - (NSRect)trackingRect
1093 NSRect rect = [textView frame];
1094 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1095 int left = [ud integerForKey:MMTextInsetLeftKey];
1096 int top = [ud integerForKey:MMTextInsetTopKey];
1097 int right = [ud integerForKey:MMTextInsetRightKey];
1098 int bot = [ud integerForKey:MMTextInsetBottomKey];
1100 rect.origin.x = left;
1101 rect.origin.y = top;
1102 rect.size.width -= left + right - 1;
1103 rect.size.height -= top + bot - 1;
1108 - (BOOL)inputManagerHandleMouseEvent:(NSEvent *)event
1110 // NOTE: The input manager usually handles events like mouse clicks (e.g.
1111 // the Kotoeri manager "commits" the text on left clicks).
1114 NSInputManager *imgr = [NSInputManager currentInputManager];
1115 if ([imgr wantsToHandleMouseEvents])
1116 return [imgr handleMouseEvent:event];
1122 - (void)sendMarkedText:(NSString *)text position:(unsigned)pos
1124 if (![self useInlineIm])
1127 NSMutableData *data = [NSMutableData data];
1128 unsigned len = text == nil ? 0
1129 : [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1131 [data appendBytes:&pos length:sizeof(unsigned)];
1132 [data appendBytes:&len length:sizeof(unsigned)];
1134 [data appendBytes:[text UTF8String] length:len];
1135 [data appendBytes:"\x00" length:1];
1138 [[self vimController] sendMessage:SetMarkedTextMsgID data:data];
1141 @end // MMTextViewHelper (Private)