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. Also handles drag&drop.
16 #import "MMTextView.h"
17 #import "MMTextStorage.h"
18 #import "MMWindowController.h"
19 #import "MMVimController.h"
24 // The max/min drag timer interval in seconds
25 static NSTimeInterval MMDragTimerMaxInterval = .3f;
26 static NSTimeInterval MMDragTimerMinInterval = .01f;
28 // The number of pixels in which the drag timer interval changes
29 static float MMDragAreaSize = 73.0f;
31 static char MMKeypadEnter[2] = { 'K', 'A' };
32 static NSString *MMKeypadEnterString = @"KA";
36 @interface MMTextView (Private)
37 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
38 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
39 - (NSRect)trackingRect;
40 - (void)dispatchKeyEvent:(NSEvent *)event;
41 - (MMVimController *)vimController;
42 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
43 - (void)dragTimerFired:(NSTimer *)timer;
44 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
49 @implementation MMTextView
53 if (markedTextField) {
54 [[markedTextField window] autorelease];
55 [markedTextField release];
56 markedTextField = nil;
59 [lastMouseDownEvent release];
63 - (NSEvent *)lastMouseDownEvent
65 return lastMouseDownEvent;
68 - (BOOL)shouldDrawInsertionPoint
70 // NOTE: The insertion point is drawn manually in drawRect:. It would be
71 // nice to be able to use the insertion point related methods of
72 // NSTextView, but it seems impossible to get them to work properly (search
73 // the cocoabuilder archives).
77 - (void)setShouldDrawInsertionPoint:(BOOL)on
79 shouldDrawInsertionPoint = on;
82 - (void)setPreEditRow:(int)row column:(int)col
88 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
89 fraction:(int)percent color:(NSColor *)color
91 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
92 // row, col, shape, color);
94 // This only stores where to draw the insertion point, the actual drawing
95 // is done in drawRect:.
96 shouldDrawInsertionPoint = YES;
97 insertionPointRow = row;
98 insertionPointColumn = col;
99 insertionPointShape = shape;
100 insertionPointFraction = percent;
102 [self setInsertionPointColor:color];
105 - (void)hideMarkedTextField
107 if (markedTextField) {
108 NSWindow *win = [markedTextField window];
110 [markedTextField setStringValue:@""];
119 - (void)drawRect:(NSRect)rect
121 [super drawRect:rect];
123 if (shouldDrawInsertionPoint) {
124 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
126 NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
127 column:insertionPointColumn];
128 ipRect.origin.x += [self textContainerOrigin].x;
129 ipRect.origin.y += [self textContainerOrigin].y;
131 if (MMInsertionPointHorizontal == insertionPointShape) {
132 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
133 ipRect.origin.y += ipRect.size.height - frac;
134 ipRect.size.height = frac;
135 } else if (MMInsertionPointVertical == insertionPointShape) {
136 int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
137 ipRect.size.width = frac;
140 [[self insertionPointColor] set];
141 if (MMInsertionPointHollow == insertionPointShape) {
147 // NOTE: We only draw the cursor once and rely on Vim to say when it
148 // should be drawn again.
149 shouldDrawInsertionPoint = NO;
151 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
152 // NSStringFromRect(ipRect), insertionPointShape,
153 // [self insertionPointColor]);
156 // this code invalidates the shadow, so we don't
157 // get shifting ghost text on scroll and resize
158 // but makes speed unusable
159 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
160 if ([ts defaultBackgroundAlpha] < 1.0f) {
161 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
163 [[self window] setHasShadow:NO];
164 [[self window] setHasShadow:YES];
167 [[self window] invalidateShadow];
173 - (void)keyDown:(NSEvent *)event
175 //NSLog(@"%s %@", _cmd, event);
176 // HACK! If a modifier is held, don't pass the event along to
177 // interpretKeyEvents: since some keys are bound to multiple commands which
178 // means doCommandBySelector: is called several times.
180 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
181 // affecting input management.
183 if ([event modifierFlags] & NSControlKeyMask)
184 [self dispatchKeyEvent:event];
186 [super keyDown:event];
189 - (void)insertText:(id)string
191 //NSLog(@"%s %@", _cmd, string);
192 // NOTE! This method is called for normal key presses but also for
193 // Option-key presses --- even when Ctrl is held as well as Option. When
194 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
195 // so 'string' need not be a printable character! In this case it still
196 // works to pass 'string' on to Vim as a printable character (since
197 // modifiers are already included and should not be added to the input
198 // buffer using CSI, K_MODIFIER).
200 [self hideMarkedTextField];
202 NSEvent *event = [NSApp currentEvent];
204 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
205 // to watch for them here.
206 if ([event type] == NSKeyDown
207 && [[event charactersIgnoringModifiers] length] > 0
208 && [event modifierFlags]
209 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
210 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
212 // <S-M-Tab> translates to 0x19
213 if (' ' == c || 0x19 == c) {
214 [self dispatchKeyEvent:event];
219 // TODO: Support 'mousehide' (check p_mh)
220 [NSCursor setHiddenUntilMouseMoves:YES];
222 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
223 // do not support attributes, simply pass the corresponding NSString in the
225 if ([string isKindOfClass:[NSAttributedString class]])
226 string = [string string];
228 [[self vimController] sendMessage:InsertTextMsgID
229 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
233 - (void)doCommandBySelector:(SEL)selector
235 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
236 // By ignoring the selector we effectively disable the key binding
237 // mechanism of Cocoa. Hopefully this is what the user will expect
238 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
241 // We usually end up here if the user pressed Ctrl+key (but not
244 NSEvent *event = [NSApp currentEvent];
246 if (selector == @selector(cancelOperation:)
247 || selector == @selector(insertNewline:)) {
248 // HACK! If there was marked text which got abandoned as a result of
249 // hitting escape or enter, then 'insertText:' is called with the
250 // abandoned text but '[event characters]' includes the abandoned text
251 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
252 // must intercept these keys here or the abandonded text gets inserted
254 NSString *key = [event charactersIgnoringModifiers];
255 const char *chars = [key UTF8String];
256 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
258 if (0x3 == chars[0]) {
259 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
260 // handle it separately (else Ctrl-C doesn't work).
261 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
262 chars = MMKeypadEnter;
265 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
267 [self dispatchKeyEvent:event];
271 - (BOOL)performKeyEquivalent:(NSEvent *)event
273 //NSLog(@"%s %@", _cmd, event);
274 // Called for Cmd+key keystrokes, function keys, arrow keys, page
275 // up/down, home, end.
277 // NOTE: This message cannot be ignored since Cmd+letter keys never are
278 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
279 // strokes, unless the key is a function key.
281 // NOTE: If the event that triggered this method represents a function key
282 // down then we do nothing, otherwise the input method never gets the key
283 // stroke (some input methods use e.g. arrow keys). The function key down
284 // event will still reach Vim though (via keyDown:). The exceptions to
285 // this rule are: PageUp/PageDown (keycode 116/121).
286 int flags = [event modifierFlags];
287 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
288 && !(116 == [event keyCode] || 121 == [event keyCode]))
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! KeyCode 50 represent the key which switches between windows
298 // within an application (like Cmd+Tab is used to switch between
299 // applications). Return NO here, else the window switching does not work.
301 // Will this hack work for all languages / keyboard layouts?
302 if ([event keyCode] == 50)
305 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
306 if (flags & NSControlKeyMask) {
307 [self dispatchKeyEvent:event];
311 //NSLog(@"%s%@", _cmd, event);
313 NSString *chars = [event characters];
314 NSString *unmodchars = [event charactersIgnoringModifiers];
315 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
316 NSMutableData *data = [NSMutableData data];
321 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
322 // can clear the shift flag as it is already included in 'unmodchars'.
323 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
324 // an English keyboard).
325 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
326 flags &= ~NSShiftKeyMask;
328 if (0x3 == [unmodchars characterAtIndex:0]) {
329 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
330 // handle it separately (else Cmd-enter turns into Ctrl-C).
331 unmodchars = MMKeypadEnterString;
332 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
335 [data appendBytes:&flags length:sizeof(int)];
336 [data appendBytes:&len length:sizeof(int)];
337 [data appendBytes:[unmodchars UTF8String] length:len];
339 [[self vimController] sendMessage:CmdKeyMsgID data:data];
344 - (BOOL)hasMarkedText
346 //NSLog(@"%s", _cmd);
347 return markedTextField && [[markedTextField stringValue] length] > 0;
350 - (NSRange)markedRange
352 //NSLog(@"%s", _cmd);
353 // HACK! If a valid range is returned, then NSTextView changes the
354 // background color of the returned range. Since marked text is displayed
355 // in a separate popup window this behaviour is not wanted. By setting the
356 // location of the returned range to NSNotFound NSTextView does nothing.
357 // This hack is continued in 'firstRectForCharacterRange:'.
358 return NSMakeRange(NSNotFound, 0);
361 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
363 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
364 // NSStringFromRange(range));
366 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
369 if (!markedTextField) {
370 // Create a text field and put it inside a floating panel. This field
371 // is used to display marked text.
372 NSSize cellSize = [ts cellSize];
373 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
375 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
376 [markedTextField setEditable:NO];
377 [markedTextField setSelectable:NO];
378 [markedTextField setBezeled:NO];
379 [markedTextField setBordered:YES];
381 NSPanel *panel = [[NSPanel alloc]
382 initWithContentRect:cellRect
383 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
384 backing:NSBackingStoreBuffered
387 //[panel setHidesOnDeactivate:NO];
388 [panel setFloatingPanel:YES];
389 [panel setBecomesKeyOnlyIfNeeded:YES];
390 [panel setContentView:markedTextField];
393 if (text && [text length] > 0) {
394 [markedTextField setFont:[ts font]];
395 if ([text isKindOfClass:[NSAttributedString class]])
396 [markedTextField setAttributedStringValue:text];
398 [markedTextField setStringValue:text];
400 [markedTextField sizeToFit];
401 NSSize size = [markedTextField frame].size;
403 // Convert coordinates (row,col) -> view -> window base -> screen
405 if (![self convertRow:preEditRow+1 column:preEditColumn
408 origin = [self convertPoint:origin toView:nil];
409 origin = [[self window] convertBaseToScreen:origin];
411 NSWindow *win = [markedTextField window];
412 [win setContentSize:size];
413 [win setFrameOrigin:origin];
414 [win orderFront:nil];
416 [self hideMarkedTextField];
422 //NSLog(@"%s", _cmd);
423 [self hideMarkedTextField];
426 - (NSRect)firstRectForCharacterRange:(NSRange)range
428 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
430 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
431 NSLayoutManager *lm = [self layoutManager];
432 NSTextContainer *tc = [self textContainer];
434 // HACK! Since we always return marked text to have location NSNotFound,
435 // this method will be called with 'range.location == NSNotFound' whenever
436 // the input manager tries to position a popup window at the pre-edit
437 // point. The pre-edit point itself is set by the IM routines in Vim
438 // (MacVim is notified via the SetPreEditPositionMsgID).
439 if (!(ts && lm && tc) || NSNotFound != range.location)
440 return [super firstRectForCharacterRange:range];
442 NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
443 column:preEditColumn];
444 rect.origin.x += [self textContainerOrigin].x;
445 rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
447 rect.origin = [self convertPoint:rect.origin toView:nil];
448 rect.origin = [[self window] convertBaseToScreen:rect.origin];
453 - (void)scrollWheel:(NSEvent *)event
455 if ([event deltaY] == 0)
459 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
460 if (![self convertPoint:pt toRow:&row column:&col])
463 int flags = [event modifierFlags];
464 float dy = [event deltaY];
465 NSMutableData *data = [NSMutableData data];
467 [data appendBytes:&row length:sizeof(int)];
468 [data appendBytes:&col length:sizeof(int)];
469 [data appendBytes:&flags length:sizeof(int)];
470 [data appendBytes:&dy length:sizeof(float)];
472 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
475 - (void)mouseDown:(NSEvent *)event
478 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
479 if (![self convertPoint:pt toRow:&row column:&col])
482 lastMouseDownEvent = [event copy];
484 int button = [event buttonNumber];
485 int flags = [event modifierFlags];
486 int count = [event clickCount];
487 NSMutableData *data = [NSMutableData data];
489 // If desired, intepret Ctrl-Click as a right mouse click.
490 if ([[NSUserDefaults standardUserDefaults]
491 boolForKey:MMTranslateCtrlClickKey]
492 && button == 0 && flags & NSControlKeyMask) {
494 flags &= ~NSControlKeyMask;
497 [data appendBytes:&row length:sizeof(int)];
498 [data appendBytes:&col length:sizeof(int)];
499 [data appendBytes:&button length:sizeof(int)];
500 [data appendBytes:&flags length:sizeof(int)];
501 [data appendBytes:&count length:sizeof(int)];
503 [[self vimController] sendMessage:MouseDownMsgID data:data];
506 - (void)rightMouseDown:(NSEvent *)event
508 [self mouseDown:event];
511 - (void)otherMouseDown:(NSEvent *)event
513 [self mouseDown:event];
516 - (void)mouseUp:(NSEvent *)event
519 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
520 if (![self convertPoint:pt toRow:&row column:&col])
523 int flags = [event modifierFlags];
524 NSMutableData *data = [NSMutableData data];
526 [data appendBytes:&row length:sizeof(int)];
527 [data appendBytes:&col length:sizeof(int)];
528 [data appendBytes:&flags length:sizeof(int)];
530 [[self vimController] sendMessage:MouseUpMsgID data:data];
535 - (void)rightMouseUp:(NSEvent *)event
537 [self mouseUp:event];
540 - (void)otherMouseUp:(NSEvent *)event
542 [self mouseUp:event];
545 - (void)mouseDragged:(NSEvent *)event
547 int flags = [event modifierFlags];
549 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
550 if (![self convertPoint:pt toRow:&row column:&col])
553 // Autoscrolling is done in dragTimerFired:
554 if (!isAutoscrolling) {
555 NSMutableData *data = [NSMutableData data];
557 [data appendBytes:&row length:sizeof(int)];
558 [data appendBytes:&col length:sizeof(int)];
559 [data appendBytes:&flags length:sizeof(int)];
561 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
565 dragRow = row; dragColumn = col; dragFlags = flags;
567 [self startDragTimerWithInterval:.5];
572 - (void)rightMouseDragged:(NSEvent *)event
574 [self mouseDragged:event];
577 - (void)otherMouseDragged:(NSEvent *)event
579 [self mouseDragged:event];
582 - (void)mouseMoved:(NSEvent *)event
584 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
587 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
589 if (![self convertPoint:pt toRow:&row column:&col])
592 // HACK! It seems impossible to get the tracking rects set up before the
593 // view is visible, which means that the first mouseEntered: or
594 // mouseExited: events are never received. This forces us to check if the
595 // mouseMoved: event really happened over the text.
597 [ts getMaxRows:&rows columns:&cols];
598 if (row >= 0 && row < rows && col >= 0 && col < cols) {
599 NSMutableData *data = [NSMutableData data];
601 [data appendBytes:&row length:sizeof(int)];
602 [data appendBytes:&col length:sizeof(int)];
604 [[self vimController] sendMessage:MouseMovedMsgID data:data];
608 - (void)mouseEntered:(NSEvent *)event
610 //NSLog(@"%s", _cmd);
612 // NOTE: This event is received even when the window is not key; thus we
613 // have to take care not to enable mouse moved events unless our window is
615 if ([[self window] isKeyWindow])
616 [[self window] setAcceptsMouseMovedEvents:YES];
619 - (void)mouseExited:(NSEvent *)event
621 //NSLog(@"%s", _cmd);
623 [[self window] setAcceptsMouseMovedEvents:NO];
625 // NOTE: This event is received even when the window is not key; if the
626 // mouse shape is set when our window is not key, the hollow (unfocused)
627 // cursor will become a block (focused) cursor.
628 if ([[self window] isKeyWindow]) {
630 NSMutableData *data = [NSMutableData data];
631 [data appendBytes:&shape length:sizeof(int)];
632 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
636 - (void)setFrame:(NSRect)frame
638 //NSLog(@"%s", _cmd);
640 // When the frame changes we also need to update the tracking rect.
641 [super setFrame:frame];
642 [self removeTrackingRect:trackingRectTag];
643 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
644 userData:NULL assumeInside:YES];
647 - (void)viewDidMoveToWindow
649 //NSLog(@"%s (window=%@)", _cmd, [self window]);
651 // Set a tracking rect which covers the text.
652 // NOTE: While the mouse cursor is in this rect the view will receive
653 // 'mouseMoved:' events so that Vim can take care of updating the mouse
656 [[self window] setAcceptsMouseMovedEvents:YES];
657 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
658 userData:NULL assumeInside:YES];
662 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
664 //NSLog(@"%s%@", _cmd, newWindow);
666 // Remove tracking rect if view moves or is removed.
667 if ([self window] && trackingRectTag) {
668 [self removeTrackingRect:trackingRectTag];
673 - (NSMenu*)menuForEvent:(NSEvent *)event
675 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
676 // own). Called when user Ctrl-clicks in the view (this is already handled
677 // in rightMouseDown:).
681 - (NSArray *)acceptableDragTypes
683 return [NSArray arrayWithObjects:NSFilenamesPboardType,
684 NSStringPboardType, nil];
687 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
689 NSPasteboard *pboard = [sender draggingPasteboard];
691 if ([[pboard types] containsObject:NSStringPboardType]) {
692 NSString *string = [pboard stringForType:NSStringPboardType];
693 [[self vimController] dropString:string];
695 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
696 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
697 [[self vimController] dropFiles:files];
704 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
706 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
707 NSPasteboard *pboard = [sender draggingPasteboard];
709 if ( [[pboard types] containsObject:NSFilenamesPboardType]
710 && (sourceDragMask & NSDragOperationCopy) )
711 return NSDragOperationCopy;
712 if ( [[pboard types] containsObject:NSStringPboardType]
713 && (sourceDragMask & NSDragOperationCopy) )
714 return NSDragOperationCopy;
716 return NSDragOperationNone;
719 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
721 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
722 NSPasteboard *pboard = [sender draggingPasteboard];
724 if ( [[pboard types] containsObject:NSFilenamesPboardType]
725 && (sourceDragMask & NSDragOperationCopy) )
726 return NSDragOperationCopy;
727 if ( [[pboard types] containsObject:NSStringPboardType]
728 && (sourceDragMask & NSDragOperationCopy) )
729 return NSDragOperationCopy;
731 return NSDragOperationNone;
734 - (void)changeFont:(id)sender
736 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
739 NSFont *oldFont = [ts font];
740 NSFont *newFont = [sender convertFont:oldFont];
743 NSString *name = [newFont displayName];
744 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
746 NSMutableData *data = [NSMutableData data];
747 float pointSize = [newFont pointSize];
749 [data appendBytes:&pointSize length:sizeof(float)];
751 ++len; // include NUL byte
752 [data appendBytes:&len length:sizeof(unsigned)];
753 [data appendBytes:[name UTF8String] length:len];
755 [[self vimController] sendMessage:SetFontMsgID data:data];
760 - (void)resetCursorRects
762 // No need to set up cursor rects since Vim handles cursor changes.
765 - (void)updateFontPanel
767 // The font panel is updated whenever the font is set.
770 - (void)viewWillStartLiveResize
772 id windowController = [[self window] windowController];
773 [windowController liveResizeWillStart];
775 [super viewWillStartLiveResize];
778 - (void)viewDidEndLiveResize
780 id windowController = [[self window] windowController];
781 [windowController liveResizeDidEnd];
783 [super viewDidEndLiveResize];
791 @implementation MMTextView (Private)
793 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
796 NSLayoutManager *lm = [self layoutManager];
797 NSTextContainer *tc = [self textContainer];
798 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
800 if (!(lm && tc && ts))
803 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
804 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
806 int mod = [ts maxColumns] + 1;
808 if (row) *row = (int)(charIdx / mod);
809 if (column) *column = (int)(charIdx % mod);
811 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
816 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
817 NSSize cellSize = [ts cellSize];
818 if (!(cellSize.width > 0 && cellSize.height > 0))
820 NSPoint origin = [self textContainerOrigin];
822 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
823 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
825 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
832 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
834 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
835 NSSize cellSize = [ts cellSize];
836 if (!(point && cellSize.width > 0 && cellSize.height > 0))
839 *point = [self textContainerOrigin];
840 point->x += column * cellSize.width;
841 point->y += row * cellSize.height;
846 - (NSRect)trackingRect
848 NSRect rect = [self frame];
849 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
850 int left = [ud integerForKey:MMTextInsetLeftKey];
851 int top = [ud integerForKey:MMTextInsetTopKey];
852 int right = [ud integerForKey:MMTextInsetRightKey];
853 int bot = [ud integerForKey:MMTextInsetBottomKey];
855 rect.origin.x = left;
857 rect.size.width -= left + right - 1;
858 rect.size.height -= top + bot - 1;
863 - (void)dispatchKeyEvent:(NSEvent *)event
865 // Only handle the command if it came from a keyDown event
866 if ([event type] != NSKeyDown)
869 NSString *chars = [event characters];
870 NSString *unmodchars = [event charactersIgnoringModifiers];
871 unichar c = [chars characterAtIndex:0];
872 unichar imc = [unmodchars characterAtIndex:0];
874 const char *bytes = 0;
875 int mods = [event modifierFlags];
877 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
878 // _cmd, c, imc, chars, unmodchars);
880 if (' ' == imc && 0xa0 != c) {
881 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
882 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
883 // should be passed on as is.)
884 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
885 bytes = [unmodchars UTF8String];
886 } else if (imc == c && '2' == c) {
887 // HACK! Translate Ctrl+2 to <C-@>.
888 static char ctrl_at = 0;
889 len = 1; bytes = &ctrl_at;
890 } else if (imc == c && '6' == c) {
891 // HACK! Translate Ctrl+6 to <C-^>.
892 static char ctrl_hat = 0x1e;
893 len = 1; bytes = &ctrl_hat;
894 } else if (c == 0x19 && imc == 0x19) {
895 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
896 // separately (else Ctrl-Y doesn't work).
897 static char tab = 0x9;
898 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
900 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
901 bytes = [chars UTF8String];
904 [self sendKeyDown:bytes length:len modifiers:mods];
907 - (MMVimController *)vimController
909 id windowController = [[self window] windowController];
911 // TODO: Make sure 'windowController' is a MMWindowController before type
913 return [(MMWindowController*)windowController vimController];
916 - (void)startDragTimerWithInterval:(NSTimeInterval)t
918 [NSTimer scheduledTimerWithTimeInterval:t target:self
919 selector:@selector(dragTimerFired:)
920 userInfo:nil repeats:NO];
923 - (void)dragTimerFired:(NSTimer *)timer
925 // TODO: Autoscroll in horizontal direction?
926 static unsigned tick = 1;
927 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
929 isAutoscrolling = NO;
931 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
932 // HACK! If the mouse cursor is outside the text area, then send a
933 // dragged event. However, if row&col hasn't changed since the last
934 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
935 // Thus we fiddle with the column to make sure something happens.
936 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
937 NSMutableData *data = [NSMutableData data];
939 [data appendBytes:&dragRow length:sizeof(int)];
940 [data appendBytes:&col length:sizeof(int)];
941 [data appendBytes:&dragFlags length:sizeof(int)];
943 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
945 isAutoscrolling = YES;
949 // Compute timer interval depending on how far away the mouse cursor is
950 // from the text view.
951 NSRect rect = [self trackingRect];
953 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
954 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
955 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
957 NSTimeInterval t = MMDragTimerMaxInterval -
958 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
960 [self startDragTimerWithInterval:t];
966 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
968 if (chars && len > 0) {
969 NSMutableData *data = [NSMutableData data];
971 [data appendBytes:&flags length:sizeof(int)];
972 [data appendBytes:&len length:sizeof(int)];
973 [data appendBytes:chars length:len];
975 // TODO: Support 'mousehide' (check p_mh)
976 [NSCursor setHiddenUntilMouseMoves:YES];
978 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
979 [[self vimController] sendMessage:KeyDownMsgID data:data];
983 @end // MMTextView (Private)