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 * Dispatches keyboard and mouse input to the backend. Handles drag-n-drop of
16 * Support for input managers is somewhat hacked together. Marked text is
17 * displayed in a popup window instead of 'in-line' (because it is easier).
20 #import "MMTextView.h"
21 #import "MMTextStorage.h"
22 #import "MMWindowController.h"
23 #import "MMVimController.h"
28 // The max/min drag timer interval in seconds
29 static NSTimeInterval MMDragTimerMaxInterval = .3f;
30 static NSTimeInterval MMDragTimerMinInterval = .01f;
32 // The number of pixels in which the drag timer interval changes
33 static float MMDragAreaSize = 73.0f;
35 static char MMKeypadEnter[2] = { 'K', 'A' };
36 static NSString *MMKeypadEnterString = @"KA";
40 @interface MMTextView (Private)
41 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
42 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
43 - (NSRect)trackingRect;
44 - (void)dispatchKeyEvent:(NSEvent *)event;
45 - (MMVimController *)vimController;
46 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
47 - (void)dragTimerFired:(NSTimer *)timer;
48 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
53 @implementation MMTextView
57 if (markedTextField) {
58 [[markedTextField window] autorelease];
59 [markedTextField release];
60 markedTextField = nil;
63 [lastMouseDownEvent release];
67 - (NSEvent *)lastMouseDownEvent
69 return lastMouseDownEvent;
72 - (BOOL)shouldDrawInsertionPoint
74 // NOTE: The insertion point is drawn manually in drawRect:. It would be
75 // nice to be able to use the insertion point related methods of
76 // NSTextView, but it seems impossible to get them to work properly (search
77 // the cocoabuilder archives).
81 - (void)setShouldDrawInsertionPoint:(BOOL)on
83 shouldDrawInsertionPoint = on;
86 - (void)setPreEditRow:(int)row column:(int)col
92 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
93 fraction:(int)percent color:(NSColor *)color
95 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
96 // row, col, shape, color);
98 // This only stores where to draw the insertion point, the actual drawing
99 // is done in drawRect:.
100 shouldDrawInsertionPoint = YES;
101 insertionPointRow = row;
102 insertionPointColumn = col;
103 insertionPointShape = shape;
104 insertionPointFraction = percent;
106 [self setInsertionPointColor:color];
109 - (void)hideMarkedTextField
111 if (markedTextField) {
112 NSWindow *win = [markedTextField window];
114 [markedTextField setStringValue:@""];
123 - (void)drawRect:(NSRect)rect
127 - (void)keyDown:(NSEvent *)event
129 //NSLog(@"%s %@", _cmd, event);
130 // HACK! If a modifier is held, don't pass the event along to
131 // interpretKeyEvents: since some keys are bound to multiple commands which
132 // means doCommandBySelector: is called several times.
134 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
135 // affecting input management.
137 if ([event modifierFlags] & NSControlKeyMask)
138 [self dispatchKeyEvent:event];
140 [super keyDown:event];
143 - (void)insertText:(id)string
145 //NSLog(@"%s %@", _cmd, string);
146 // NOTE! This method is called for normal key presses but also for
147 // Option-key presses --- even when Ctrl is held as well as Option. When
148 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
149 // so 'string' need not be a printable character! In this case it still
150 // works to pass 'string' on to Vim as a printable character (since
151 // modifiers are already included and should not be added to the input
152 // buffer using CSI, K_MODIFIER).
154 [self hideMarkedTextField];
156 NSEvent *event = [NSApp currentEvent];
158 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
159 // to watch for them here.
160 if ([event type] == NSKeyDown
161 && [[event charactersIgnoringModifiers] length] > 0
162 && [event modifierFlags]
163 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
164 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
166 // <S-M-Tab> translates to 0x19
167 if (' ' == c || 0x19 == c) {
168 [self dispatchKeyEvent:event];
173 // TODO: Support 'mousehide' (check p_mh)
174 [NSCursor setHiddenUntilMouseMoves:YES];
176 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
177 // do not support attributes, simply pass the corresponding NSString in the
179 if ([string isKindOfClass:[NSAttributedString class]])
180 string = [string string];
182 //NSLog(@"send InsertTextMsgID: %@", string);
184 [[self vimController] sendMessage:InsertTextMsgID
185 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
189 - (void)doCommandBySelector:(SEL)selector
191 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
192 // By ignoring the selector we effectively disable the key binding
193 // mechanism of Cocoa. Hopefully this is what the user will expect
194 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
197 // We usually end up here if the user pressed Ctrl+key (but not
200 NSEvent *event = [NSApp currentEvent];
202 if (selector == @selector(cancelOperation:)
203 || selector == @selector(insertNewline:)) {
204 // HACK! If there was marked text which got abandoned as a result of
205 // hitting escape or enter, then 'insertText:' is called with the
206 // abandoned text but '[event characters]' includes the abandoned text
207 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
208 // must intercept these keys here or the abandonded text gets inserted
210 NSString *key = [event charactersIgnoringModifiers];
211 const char *chars = [key UTF8String];
212 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
214 if (0x3 == chars[0]) {
215 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
216 // handle it separately (else Ctrl-C doesn't work).
217 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
218 chars = MMKeypadEnter;
221 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
223 [self dispatchKeyEvent:event];
227 - (BOOL)performKeyEquivalent:(NSEvent *)event
229 //NSLog(@"%s %@", _cmd, event);
230 // Called for Cmd+key keystrokes, function keys, arrow keys, page
231 // up/down, home, end.
233 // NOTE: This message cannot be ignored since Cmd+letter keys never are
234 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
235 // strokes, unless the key is a function key.
237 // NOTE: If the event that triggered this method represents a function key
238 // down then we do nothing, otherwise the input method never gets the key
239 // stroke (some input methods use e.g. arrow keys). The function key down
240 // event will still reach Vim though (via keyDown:). The exceptions to
241 // this rule are: PageUp/PageDown (keycode 116/121).
242 int flags = [event modifierFlags];
243 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
244 && !(116 == [event keyCode] || 121 == [event keyCode]))
247 // HACK! Let the main menu try to handle any key down event, before
248 // passing it on to vim, otherwise key equivalents for menus will
249 // effectively be disabled.
250 if ([[NSApp mainMenu] performKeyEquivalent:event])
253 // HACK! KeyCode 50 represent the key which switches between windows
254 // within an application (like Cmd+Tab is used to switch between
255 // applications). Return NO here, else the window switching does not work.
257 // Will this hack work for all languages / keyboard layouts?
258 if ([event keyCode] == 50)
261 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
262 if (flags & NSControlKeyMask) {
263 [self dispatchKeyEvent:event];
267 //NSLog(@"%s%@", _cmd, event);
269 NSString *chars = [event characters];
270 NSString *unmodchars = [event charactersIgnoringModifiers];
271 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
272 NSMutableData *data = [NSMutableData data];
277 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
278 // can clear the shift flag as it is already included in 'unmodchars'.
279 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
280 // an English keyboard).
281 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
282 flags &= ~NSShiftKeyMask;
284 if (0x3 == [unmodchars characterAtIndex:0]) {
285 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
286 // handle it separately (else Cmd-enter turns into Ctrl-C).
287 unmodchars = MMKeypadEnterString;
288 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
291 [data appendBytes:&flags length:sizeof(int)];
292 [data appendBytes:&len length:sizeof(int)];
293 [data appendBytes:[unmodchars UTF8String] length:len];
295 [[self vimController] sendMessage:CmdKeyMsgID data:data];
300 - (BOOL)hasMarkedText
302 //NSLog(@"%s", _cmd);
303 return markedTextField && [[markedTextField stringValue] length] > 0;
306 - (NSRange)markedRange
308 //NSLog(@"%s", _cmd);
309 unsigned len = [[markedTextField stringValue] length];
310 return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
313 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
315 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
316 // NSStringFromRange(range));
318 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
321 if (!markedTextField) {
322 // Create a text field and put it inside a floating panel. This field
323 // is used to display marked text.
324 NSSize cellSize = [ts cellSize];
325 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
327 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
328 [markedTextField setEditable:NO];
329 [markedTextField setSelectable:NO];
330 [markedTextField setBezeled:NO];
331 [markedTextField setBordered:YES];
333 NSPanel *panel = [[NSPanel alloc]
334 initWithContentRect:cellRect
335 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
336 backing:NSBackingStoreBuffered
339 //[panel setHidesOnDeactivate:NO];
340 [panel setFloatingPanel:YES];
341 [panel setBecomesKeyOnlyIfNeeded:YES];
342 [panel setContentView:markedTextField];
345 if (text && [text length] > 0) {
346 [markedTextField setFont:[ts font]];
347 if ([text isKindOfClass:[NSAttributedString class]])
348 [markedTextField setAttributedStringValue:text];
350 [markedTextField setStringValue:text];
352 [markedTextField sizeToFit];
353 NSSize size = [markedTextField frame].size;
355 // Convert coordinates (row,col) -> view -> window base -> screen
357 if (![self convertRow:preEditRow+1 column:preEditColumn
360 origin = [self convertPoint:origin toView:nil];
361 origin = [[self window] convertBaseToScreen:origin];
363 NSWindow *win = [markedTextField window];
364 [win setContentSize:size];
365 [win setFrameOrigin:origin];
366 [win orderFront:nil];
368 [self hideMarkedTextField];
374 //NSLog(@"%s", _cmd);
375 [self hideMarkedTextField];
378 - (NSRect)firstRectForCharacterRange:(NSRange)range
380 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
381 // HACK! This method is called when the input manager wants to pop up an
382 // auxiliary window. The position where this should be is controller by
383 // Vim by sending SetPreEditPositionMsgID so compute a position based on
384 // the pre-edit (row,column) pair.
385 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
387 NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
388 column:preEditColumn];
389 rect.origin.x += [self textContainerOrigin].x;
390 rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
392 rect.origin = [self convertPoint:rect.origin toView:nil];
393 rect.origin = [[self window] convertBaseToScreen:rect.origin];
398 - (void)scrollWheel:(NSEvent *)event
400 if ([event deltaY] == 0)
404 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
405 if (![self convertPoint:pt toRow:&row column:&col])
408 int flags = [event modifierFlags];
409 float dy = [event deltaY];
410 NSMutableData *data = [NSMutableData data];
412 [data appendBytes:&row length:sizeof(int)];
413 [data appendBytes:&col length:sizeof(int)];
414 [data appendBytes:&flags length:sizeof(int)];
415 [data appendBytes:&dy length:sizeof(float)];
417 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
420 - (void)mouseDown:(NSEvent *)event
423 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
424 if (![self convertPoint:pt toRow:&row column:&col])
427 lastMouseDownEvent = [event copy];
429 int button = [event buttonNumber];
430 int flags = [event modifierFlags];
431 int count = [event clickCount];
432 NSMutableData *data = [NSMutableData data];
434 // If desired, intepret Ctrl-Click as a right mouse click.
435 if ([[NSUserDefaults standardUserDefaults]
436 boolForKey:MMTranslateCtrlClickKey]
437 && button == 0 && flags & NSControlKeyMask) {
439 flags &= ~NSControlKeyMask;
442 [data appendBytes:&row length:sizeof(int)];
443 [data appendBytes:&col length:sizeof(int)];
444 [data appendBytes:&button length:sizeof(int)];
445 [data appendBytes:&flags length:sizeof(int)];
446 [data appendBytes:&count length:sizeof(int)];
448 [[self vimController] sendMessage:MouseDownMsgID data:data];
451 - (void)rightMouseDown:(NSEvent *)event
453 [self mouseDown:event];
456 - (void)otherMouseDown:(NSEvent *)event
458 [self mouseDown:event];
461 - (void)mouseUp:(NSEvent *)event
464 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
465 if (![self convertPoint:pt toRow:&row column:&col])
468 int flags = [event modifierFlags];
469 NSMutableData *data = [NSMutableData data];
471 [data appendBytes:&row length:sizeof(int)];
472 [data appendBytes:&col length:sizeof(int)];
473 [data appendBytes:&flags length:sizeof(int)];
475 [[self vimController] sendMessage:MouseUpMsgID data:data];
480 - (void)rightMouseUp:(NSEvent *)event
482 [self mouseUp:event];
485 - (void)otherMouseUp:(NSEvent *)event
487 [self mouseUp:event];
490 - (void)mouseDragged:(NSEvent *)event
492 int flags = [event modifierFlags];
494 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
495 if (![self convertPoint:pt toRow:&row column:&col])
498 // Autoscrolling is done in dragTimerFired:
499 if (!isAutoscrolling) {
500 NSMutableData *data = [NSMutableData data];
502 [data appendBytes:&row length:sizeof(int)];
503 [data appendBytes:&col length:sizeof(int)];
504 [data appendBytes:&flags length:sizeof(int)];
506 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
510 dragRow = row; dragColumn = col; dragFlags = flags;
512 [self startDragTimerWithInterval:.5];
517 - (void)rightMouseDragged:(NSEvent *)event
519 [self mouseDragged:event];
522 - (void)otherMouseDragged:(NSEvent *)event
524 [self mouseDragged:event];
527 - (void)mouseMoved:(NSEvent *)event
529 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
532 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
534 if (![self convertPoint:pt toRow:&row column:&col])
537 // HACK! It seems impossible to get the tracking rects set up before the
538 // view is visible, which means that the first mouseEntered: or
539 // mouseExited: events are never received. This forces us to check if the
540 // mouseMoved: event really happened over the text.
542 [ts getMaxRows:&rows columns:&cols];
543 if (row >= 0 && row < rows && col >= 0 && col < cols) {
544 NSMutableData *data = [NSMutableData data];
546 [data appendBytes:&row length:sizeof(int)];
547 [data appendBytes:&col length:sizeof(int)];
549 [[self vimController] sendMessage:MouseMovedMsgID data:data];
553 - (void)mouseEntered:(NSEvent *)event
555 //NSLog(@"%s", _cmd);
557 // NOTE: This event is received even when the window is not key; thus we
558 // have to take care not to enable mouse moved events unless our window is
560 if ([[self window] isKeyWindow])
561 [[self window] setAcceptsMouseMovedEvents:YES];
564 - (void)mouseExited:(NSEvent *)event
566 //NSLog(@"%s", _cmd);
568 [[self window] setAcceptsMouseMovedEvents:NO];
570 // NOTE: This event is received even when the window is not key; if the
571 // mouse shape is set when our window is not key, the hollow (unfocused)
572 // cursor will become a block (focused) cursor.
573 if ([[self window] isKeyWindow]) {
575 NSMutableData *data = [NSMutableData data];
576 [data appendBytes:&shape length:sizeof(int)];
577 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
581 - (void)setFrame:(NSRect)frame
583 //NSLog(@"%s", _cmd);
585 // When the frame changes we also need to update the tracking rect.
586 [super setFrame:frame];
587 [self removeTrackingRect:trackingRectTag];
588 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
589 userData:NULL assumeInside:YES];
592 - (void)viewDidMoveToWindow
594 //NSLog(@"%s (window=%@)", _cmd, [self window]);
596 // Set a tracking rect which covers the text.
597 // NOTE: While the mouse cursor is in this rect the view will receive
598 // 'mouseMoved:' events so that Vim can take care of updating the mouse
601 [[self window] setAcceptsMouseMovedEvents:YES];
602 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
603 userData:NULL assumeInside:YES];
607 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
609 //NSLog(@"%s%@", _cmd, newWindow);
611 // Remove tracking rect if view moves or is removed.
612 if ([self window] && trackingRectTag) {
613 [self removeTrackingRect:trackingRectTag];
618 - (NSMenu*)menuForEvent:(NSEvent *)event
620 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
621 // own). Called when user Ctrl-clicks in the view (this is already handled
622 // in rightMouseDown:).
626 - (NSArray *)acceptableDragTypes
628 return [NSArray arrayWithObjects:NSFilenamesPboardType,
629 NSStringPboardType, nil];
632 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
634 NSPasteboard *pboard = [sender draggingPasteboard];
636 if ([[pboard types] containsObject:NSStringPboardType]) {
637 NSString *string = [pboard stringForType:NSStringPboardType];
638 [[self vimController] dropString:string];
640 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
641 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
642 [[self vimController] dropFiles:files];
649 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
651 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
652 NSPasteboard *pboard = [sender draggingPasteboard];
654 if ( [[pboard types] containsObject:NSFilenamesPboardType]
655 && (sourceDragMask & NSDragOperationCopy) )
656 return NSDragOperationCopy;
657 if ( [[pboard types] containsObject:NSStringPboardType]
658 && (sourceDragMask & NSDragOperationCopy) )
659 return NSDragOperationCopy;
661 return NSDragOperationNone;
664 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
666 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
667 NSPasteboard *pboard = [sender draggingPasteboard];
669 if ( [[pboard types] containsObject:NSFilenamesPboardType]
670 && (sourceDragMask & NSDragOperationCopy) )
671 return NSDragOperationCopy;
672 if ( [[pboard types] containsObject:NSStringPboardType]
673 && (sourceDragMask & NSDragOperationCopy) )
674 return NSDragOperationCopy;
676 return NSDragOperationNone;
679 - (void)changeFont:(id)sender
681 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
684 NSFont *oldFont = [ts font];
685 NSFont *newFont = [sender convertFont:oldFont];
688 NSString *name = [newFont displayName];
689 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
691 NSMutableData *data = [NSMutableData data];
692 float pointSize = [newFont pointSize];
694 [data appendBytes:&pointSize length:sizeof(float)];
696 ++len; // include NUL byte
697 [data appendBytes:&len length:sizeof(unsigned)];
698 [data appendBytes:[name UTF8String] length:len];
700 [[self vimController] sendMessage:SetFontMsgID data:data];
705 - (void)resetCursorRects
707 // No need to set up cursor rects since Vim handles cursor changes.
710 - (void)updateFontPanel
712 // The font panel is updated whenever the font is set.
715 - (void)viewWillStartLiveResize
717 id windowController = [[self window] windowController];
718 [windowController liveResizeWillStart];
720 [super viewWillStartLiveResize];
723 - (void)viewDidEndLiveResize
725 id windowController = [[self window] windowController];
726 [windowController liveResizeDidEnd];
728 [super viewDidEndLiveResize];
731 - (NSPoint)textContainerOrigin
733 return NSMakePoint(0, 0);
736 - (void)setInsertionPointColor:(NSColor *)color
738 insertionPointColor = color;
741 - (NSColor *)insertionPointColor
743 return insertionPointColor;
746 - (MMTextStorage *)textStorage
751 - (void)setTextStorage:(MMTextStorage *)aTextStorage
753 textStorage = aTextStorage;
756 - (void)setBackgroundColor:(NSColor *)color
758 backgroundColor = color;
761 - (NSColor *)backgroundColor
763 return backgroundColor;
766 - (void)setTextContainerInset:(NSSize)inset
768 textContainerInset = inset;
771 - (NSSize)textContainerInset
773 return textContainerInset;
781 @implementation MMTextView (Private)
783 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
785 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
786 NSSize cellSize = [ts cellSize];
787 if (!(cellSize.width > 0 && cellSize.height > 0))
789 NSPoint origin = [self textContainerOrigin];
791 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
792 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
794 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
800 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
802 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
803 NSSize cellSize = [ts cellSize];
804 if (!(point && cellSize.width > 0 && cellSize.height > 0))
807 *point = [self textContainerOrigin];
808 point->x += column * cellSize.width;
809 point->y += row * cellSize.height;
814 - (NSRect)trackingRect
816 NSRect rect = [self frame];
817 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
818 int left = [ud integerForKey:MMTextInsetLeftKey];
819 int top = [ud integerForKey:MMTextInsetTopKey];
820 int right = [ud integerForKey:MMTextInsetRightKey];
821 int bot = [ud integerForKey:MMTextInsetBottomKey];
823 rect.origin.x = left;
825 rect.size.width -= left + right - 1;
826 rect.size.height -= top + bot - 1;
831 - (void)dispatchKeyEvent:(NSEvent *)event
833 // Only handle the command if it came from a keyDown event
834 if ([event type] != NSKeyDown)
837 NSString *chars = [event characters];
838 NSString *unmodchars = [event charactersIgnoringModifiers];
839 unichar c = [chars characterAtIndex:0];
840 unichar imc = [unmodchars characterAtIndex:0];
842 const char *bytes = 0;
843 int mods = [event modifierFlags];
845 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
846 // _cmd, c, imc, chars, unmodchars);
848 if (' ' == imc && 0xa0 != c) {
849 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
850 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
851 // should be passed on as is.)
852 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
853 bytes = [unmodchars UTF8String];
854 } else if (imc == c && '2' == c) {
855 // HACK! Translate Ctrl+2 to <C-@>.
856 static char ctrl_at = 0;
857 len = 1; bytes = &ctrl_at;
858 } else if (imc == c && '6' == c) {
859 // HACK! Translate Ctrl+6 to <C-^>.
860 static char ctrl_hat = 0x1e;
861 len = 1; bytes = &ctrl_hat;
862 } else if (c == 0x19 && imc == 0x19) {
863 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
864 // separately (else Ctrl-Y doesn't work).
865 static char tab = 0x9;
866 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
868 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
869 bytes = [chars UTF8String];
872 [self sendKeyDown:bytes length:len modifiers:mods];
875 - (MMVimController *)vimController
877 id windowController = [[self window] windowController];
879 // TODO: Make sure 'windowController' is a MMWindowController before type
881 return [(MMWindowController*)windowController vimController];
884 - (void)startDragTimerWithInterval:(NSTimeInterval)t
886 [NSTimer scheduledTimerWithTimeInterval:t target:self
887 selector:@selector(dragTimerFired:)
888 userInfo:nil repeats:NO];
891 - (void)dragTimerFired:(NSTimer *)timer
893 // TODO: Autoscroll in horizontal direction?
894 static unsigned tick = 1;
895 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
897 isAutoscrolling = NO;
899 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
900 // HACK! If the mouse cursor is outside the text area, then send a
901 // dragged event. However, if row&col hasn't changed since the last
902 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
903 // Thus we fiddle with the column to make sure something happens.
904 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
905 NSMutableData *data = [NSMutableData data];
907 [data appendBytes:&dragRow length:sizeof(int)];
908 [data appendBytes:&col length:sizeof(int)];
909 [data appendBytes:&dragFlags length:sizeof(int)];
911 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
913 isAutoscrolling = YES;
917 // Compute timer interval depending on how far away the mouse cursor is
918 // from the text view.
919 NSRect rect = [self trackingRect];
921 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
922 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
923 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
925 NSTimeInterval t = MMDragTimerMaxInterval -
926 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
928 [self startDragTimerWithInterval:t];
934 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
936 if (chars && len > 0) {
937 NSMutableData *data = [NSMutableData data];
939 [data appendBytes:&flags length:sizeof(int)];
940 [data appendBytes:&len length:sizeof(int)];
941 [data appendBytes:chars length:len];
943 // TODO: Support 'mousehide' (check p_mh)
944 [NSCursor setHiddenUntilMouseMoves:YES];
946 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
947 [[self vimController] sendMessage:KeyDownMsgID data:data];
951 @end // MMTextView (Private)