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
125 [super drawRect:rect];
127 if (shouldDrawInsertionPoint) {
128 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
130 NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
131 column:insertionPointColumn];
132 ipRect.origin.x += [self textContainerOrigin].x;
133 ipRect.origin.y += [self textContainerOrigin].y;
135 if (MMInsertionPointHorizontal == insertionPointShape) {
136 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
137 ipRect.origin.y += ipRect.size.height - frac;
138 ipRect.size.height = frac;
139 } else if (MMInsertionPointVertical == insertionPointShape) {
140 int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
141 ipRect.size.width = frac;
144 [[self insertionPointColor] set];
145 if (MMInsertionPointHollow == insertionPointShape) {
151 // NOTE: We only draw the cursor once and rely on Vim to say when it
152 // should be drawn again.
153 shouldDrawInsertionPoint = NO;
155 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
156 // NSStringFromRect(ipRect), insertionPointShape,
157 // [self insertionPointColor]);
160 // this code invalidates the shadow, so we don't
161 // get shifting ghost text on scroll and resize
162 // but makes speed unusable
163 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
164 if ([ts defaultBackgroundAlpha] < 1.0f) {
165 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
167 [[self window] setHasShadow:NO];
168 [[self window] setHasShadow:YES];
171 [[self window] invalidateShadow];
177 - (void)keyDown:(NSEvent *)event
179 //NSLog(@"%s %@", _cmd, event);
180 // HACK! If a modifier is held, don't pass the event along to
181 // interpretKeyEvents: since some keys are bound to multiple commands which
182 // means doCommandBySelector: is called several times.
184 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
185 // affecting input management.
187 if ([event modifierFlags] & NSControlKeyMask)
188 [self dispatchKeyEvent:event];
190 [super keyDown:event];
193 - (void)insertText:(id)string
195 //NSLog(@"%s %@", _cmd, string);
196 // NOTE! This method is called for normal key presses but also for
197 // Option-key presses --- even when Ctrl is held as well as Option. When
198 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
199 // so 'string' need not be a printable character! In this case it still
200 // works to pass 'string' on to Vim as a printable character (since
201 // modifiers are already included and should not be added to the input
202 // buffer using CSI, K_MODIFIER).
204 [self hideMarkedTextField];
206 NSEvent *event = [NSApp currentEvent];
208 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
209 // to watch for them here.
210 if ([event type] == NSKeyDown
211 && [[event charactersIgnoringModifiers] length] > 0
212 && [event modifierFlags]
213 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
214 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
216 // <S-M-Tab> translates to 0x19
217 if (' ' == c || 0x19 == c) {
218 [self dispatchKeyEvent:event];
223 // TODO: Support 'mousehide' (check p_mh)
224 [NSCursor setHiddenUntilMouseMoves:YES];
226 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
227 // do not support attributes, simply pass the corresponding NSString in the
229 if ([string isKindOfClass:[NSAttributedString class]])
230 string = [string string];
232 //NSLog(@"send InsertTextMsgID: %@", string);
234 [[self vimController] sendMessage:InsertTextMsgID
235 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
239 - (void)doCommandBySelector:(SEL)selector
241 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
242 // By ignoring the selector we effectively disable the key binding
243 // mechanism of Cocoa. Hopefully this is what the user will expect
244 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
247 // We usually end up here if the user pressed Ctrl+key (but not
250 NSEvent *event = [NSApp currentEvent];
252 if (selector == @selector(cancelOperation:)
253 || selector == @selector(insertNewline:)) {
254 // HACK! If there was marked text which got abandoned as a result of
255 // hitting escape or enter, then 'insertText:' is called with the
256 // abandoned text but '[event characters]' includes the abandoned text
257 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
258 // must intercept these keys here or the abandonded text gets inserted
260 NSString *key = [event charactersIgnoringModifiers];
261 const char *chars = [key UTF8String];
262 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
264 if (0x3 == chars[0]) {
265 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
266 // handle it separately (else Ctrl-C doesn't work).
267 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
268 chars = MMKeypadEnter;
271 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
273 [self dispatchKeyEvent:event];
277 - (BOOL)performKeyEquivalent:(NSEvent *)event
279 //NSLog(@"%s %@", _cmd, event);
280 // Called for Cmd+key keystrokes, function keys, arrow keys, page
281 // up/down, home, end.
283 // NOTE: This message cannot be ignored since Cmd+letter keys never are
284 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
285 // strokes, unless the key is a function key.
287 // NOTE: If the event that triggered this method represents a function key
288 // down then we do nothing, otherwise the input method never gets the key
289 // stroke (some input methods use e.g. arrow keys). The function key down
290 // event will still reach Vim though (via keyDown:). The exceptions to
291 // this rule are: PageUp/PageDown (keycode 116/121).
292 int flags = [event modifierFlags];
293 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
294 && !(116 == [event keyCode] || 121 == [event keyCode]))
297 // HACK! Let the main menu try to handle any key down event, before
298 // passing it on to vim, otherwise key equivalents for menus will
299 // effectively be disabled.
300 if ([[NSApp mainMenu] performKeyEquivalent:event])
303 // HACK! KeyCode 50 represent the key which switches between windows
304 // within an application (like Cmd+Tab is used to switch between
305 // applications). Return NO here, else the window switching does not work.
307 // Will this hack work for all languages / keyboard layouts?
308 if ([event keyCode] == 50)
311 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
312 if (flags & NSControlKeyMask) {
313 [self dispatchKeyEvent:event];
317 //NSLog(@"%s%@", _cmd, event);
319 NSString *chars = [event characters];
320 NSString *unmodchars = [event charactersIgnoringModifiers];
321 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
322 NSMutableData *data = [NSMutableData data];
327 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
328 // can clear the shift flag as it is already included in 'unmodchars'.
329 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
330 // an English keyboard).
331 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
332 flags &= ~NSShiftKeyMask;
334 if (0x3 == [unmodchars characterAtIndex:0]) {
335 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
336 // handle it separately (else Cmd-enter turns into Ctrl-C).
337 unmodchars = MMKeypadEnterString;
338 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
341 [data appendBytes:&flags length:sizeof(int)];
342 [data appendBytes:&len length:sizeof(int)];
343 [data appendBytes:[unmodchars UTF8String] length:len];
345 [[self vimController] sendMessage:CmdKeyMsgID data:data];
350 - (BOOL)hasMarkedText
352 //NSLog(@"%s", _cmd);
353 return markedTextField && [[markedTextField stringValue] length] > 0;
356 - (NSRange)markedRange
358 //NSLog(@"%s", _cmd);
359 unsigned len = [[markedTextField stringValue] length];
360 return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
363 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
365 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
366 // NSStringFromRange(range));
368 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
371 if (!markedTextField) {
372 // Create a text field and put it inside a floating panel. This field
373 // is used to display marked text.
374 NSSize cellSize = [ts cellSize];
375 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
377 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
378 [markedTextField setEditable:NO];
379 [markedTextField setSelectable:NO];
380 [markedTextField setBezeled:NO];
381 [markedTextField setBordered:YES];
383 NSPanel *panel = [[NSPanel alloc]
384 initWithContentRect:cellRect
385 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
386 backing:NSBackingStoreBuffered
389 //[panel setHidesOnDeactivate:NO];
390 [panel setFloatingPanel:YES];
391 [panel setBecomesKeyOnlyIfNeeded:YES];
392 [panel setContentView:markedTextField];
395 if (text && [text length] > 0) {
396 [markedTextField setFont:[ts font]];
397 if ([text isKindOfClass:[NSAttributedString class]])
398 [markedTextField setAttributedStringValue:text];
400 [markedTextField setStringValue:text];
402 [markedTextField sizeToFit];
403 NSSize size = [markedTextField frame].size;
405 // Convert coordinates (row,col) -> view -> window base -> screen
407 if (![self convertRow:preEditRow+1 column:preEditColumn
410 origin = [self convertPoint:origin toView:nil];
411 origin = [[self window] convertBaseToScreen:origin];
413 NSWindow *win = [markedTextField window];
414 [win setContentSize:size];
415 [win setFrameOrigin:origin];
416 [win orderFront:nil];
418 [self hideMarkedTextField];
424 //NSLog(@"%s", _cmd);
425 [self hideMarkedTextField];
428 - (NSRect)firstRectForCharacterRange:(NSRange)range
430 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
431 // HACK! This method is called when the input manager wants to pop up an
432 // auxiliary window. The position where this should be is controller by
433 // Vim by sending SetPreEditPositionMsgID so compute a position based on
434 // the pre-edit (row,column) pair.
435 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
437 NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
438 column:preEditColumn];
439 rect.origin.x += [self textContainerOrigin].x;
440 rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
442 rect.origin = [self convertPoint:rect.origin toView:nil];
443 rect.origin = [[self window] convertBaseToScreen:rect.origin];
448 - (void)scrollWheel:(NSEvent *)event
450 if ([event deltaY] == 0)
454 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
455 if (![self convertPoint:pt toRow:&row column:&col])
458 int flags = [event modifierFlags];
459 float dy = [event deltaY];
460 NSMutableData *data = [NSMutableData data];
462 [data appendBytes:&row length:sizeof(int)];
463 [data appendBytes:&col length:sizeof(int)];
464 [data appendBytes:&flags length:sizeof(int)];
465 [data appendBytes:&dy length:sizeof(float)];
467 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
470 - (void)mouseDown:(NSEvent *)event
473 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
474 if (![self convertPoint:pt toRow:&row column:&col])
477 lastMouseDownEvent = [event copy];
479 int button = [event buttonNumber];
480 int flags = [event modifierFlags];
481 int count = [event clickCount];
482 NSMutableData *data = [NSMutableData data];
484 // If desired, intepret Ctrl-Click as a right mouse click.
485 if ([[NSUserDefaults standardUserDefaults]
486 boolForKey:MMTranslateCtrlClickKey]
487 && button == 0 && flags & NSControlKeyMask) {
489 flags &= ~NSControlKeyMask;
492 [data appendBytes:&row length:sizeof(int)];
493 [data appendBytes:&col length:sizeof(int)];
494 [data appendBytes:&button length:sizeof(int)];
495 [data appendBytes:&flags length:sizeof(int)];
496 [data appendBytes:&count length:sizeof(int)];
498 [[self vimController] sendMessage:MouseDownMsgID data:data];
501 - (void)rightMouseDown:(NSEvent *)event
503 [self mouseDown:event];
506 - (void)otherMouseDown:(NSEvent *)event
508 [self mouseDown:event];
511 - (void)mouseUp:(NSEvent *)event
514 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
515 if (![self convertPoint:pt toRow:&row column:&col])
518 int flags = [event modifierFlags];
519 NSMutableData *data = [NSMutableData data];
521 [data appendBytes:&row length:sizeof(int)];
522 [data appendBytes:&col length:sizeof(int)];
523 [data appendBytes:&flags length:sizeof(int)];
525 [[self vimController] sendMessage:MouseUpMsgID data:data];
530 - (void)rightMouseUp:(NSEvent *)event
532 [self mouseUp:event];
535 - (void)otherMouseUp:(NSEvent *)event
537 [self mouseUp:event];
540 - (void)mouseDragged:(NSEvent *)event
542 int flags = [event modifierFlags];
544 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
545 if (![self convertPoint:pt toRow:&row column:&col])
548 // Autoscrolling is done in dragTimerFired:
549 if (!isAutoscrolling) {
550 NSMutableData *data = [NSMutableData data];
552 [data appendBytes:&row length:sizeof(int)];
553 [data appendBytes:&col length:sizeof(int)];
554 [data appendBytes:&flags length:sizeof(int)];
556 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
560 dragRow = row; dragColumn = col; dragFlags = flags;
562 [self startDragTimerWithInterval:.5];
567 - (void)rightMouseDragged:(NSEvent *)event
569 [self mouseDragged:event];
572 - (void)otherMouseDragged:(NSEvent *)event
574 [self mouseDragged:event];
577 - (void)mouseMoved:(NSEvent *)event
579 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
582 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
584 if (![self convertPoint:pt toRow:&row column:&col])
587 // HACK! It seems impossible to get the tracking rects set up before the
588 // view is visible, which means that the first mouseEntered: or
589 // mouseExited: events are never received. This forces us to check if the
590 // mouseMoved: event really happened over the text.
592 [ts getMaxRows:&rows columns:&cols];
593 if (row >= 0 && row < rows && col >= 0 && col < cols) {
594 NSMutableData *data = [NSMutableData data];
596 [data appendBytes:&row length:sizeof(int)];
597 [data appendBytes:&col length:sizeof(int)];
599 [[self vimController] sendMessage:MouseMovedMsgID data:data];
603 - (void)mouseEntered:(NSEvent *)event
605 //NSLog(@"%s", _cmd);
607 // NOTE: This event is received even when the window is not key; thus we
608 // have to take care not to enable mouse moved events unless our window is
610 if ([[self window] isKeyWindow])
611 [[self window] setAcceptsMouseMovedEvents:YES];
614 - (void)mouseExited:(NSEvent *)event
616 //NSLog(@"%s", _cmd);
618 [[self window] setAcceptsMouseMovedEvents:NO];
620 // NOTE: This event is received even when the window is not key; if the
621 // mouse shape is set when our window is not key, the hollow (unfocused)
622 // cursor will become a block (focused) cursor.
623 if ([[self window] isKeyWindow]) {
625 NSMutableData *data = [NSMutableData data];
626 [data appendBytes:&shape length:sizeof(int)];
627 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
631 - (void)setFrame:(NSRect)frame
633 //NSLog(@"%s", _cmd);
635 // When the frame changes we also need to update the tracking rect.
636 [super setFrame:frame];
637 [self removeTrackingRect:trackingRectTag];
638 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
639 userData:NULL assumeInside:YES];
642 - (void)viewDidMoveToWindow
644 //NSLog(@"%s (window=%@)", _cmd, [self window]);
646 // Set a tracking rect which covers the text.
647 // NOTE: While the mouse cursor is in this rect the view will receive
648 // 'mouseMoved:' events so that Vim can take care of updating the mouse
651 [[self window] setAcceptsMouseMovedEvents:YES];
652 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
653 userData:NULL assumeInside:YES];
657 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
659 //NSLog(@"%s%@", _cmd, newWindow);
661 // Remove tracking rect if view moves or is removed.
662 if ([self window] && trackingRectTag) {
663 [self removeTrackingRect:trackingRectTag];
668 - (NSMenu*)menuForEvent:(NSEvent *)event
670 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
671 // own). Called when user Ctrl-clicks in the view (this is already handled
672 // in rightMouseDown:).
676 - (NSArray *)acceptableDragTypes
678 return [NSArray arrayWithObjects:NSFilenamesPboardType,
679 NSStringPboardType, nil];
682 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
684 NSPasteboard *pboard = [sender draggingPasteboard];
686 if ([[pboard types] containsObject:NSStringPboardType]) {
687 NSString *string = [pboard stringForType:NSStringPboardType];
688 [[self vimController] dropString:string];
690 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
691 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
692 [[self vimController] dropFiles:files];
699 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
701 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
702 NSPasteboard *pboard = [sender draggingPasteboard];
704 if ( [[pboard types] containsObject:NSFilenamesPboardType]
705 && (sourceDragMask & NSDragOperationCopy) )
706 return NSDragOperationCopy;
707 if ( [[pboard types] containsObject:NSStringPboardType]
708 && (sourceDragMask & NSDragOperationCopy) )
709 return NSDragOperationCopy;
711 return NSDragOperationNone;
714 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
716 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
717 NSPasteboard *pboard = [sender draggingPasteboard];
719 if ( [[pboard types] containsObject:NSFilenamesPboardType]
720 && (sourceDragMask & NSDragOperationCopy) )
721 return NSDragOperationCopy;
722 if ( [[pboard types] containsObject:NSStringPboardType]
723 && (sourceDragMask & NSDragOperationCopy) )
724 return NSDragOperationCopy;
726 return NSDragOperationNone;
729 - (void)changeFont:(id)sender
731 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
734 NSFont *oldFont = [ts font];
735 NSFont *newFont = [sender convertFont:oldFont];
738 NSString *name = [newFont displayName];
739 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
741 NSMutableData *data = [NSMutableData data];
742 float pointSize = [newFont pointSize];
744 [data appendBytes:&pointSize length:sizeof(float)];
746 ++len; // include NUL byte
747 [data appendBytes:&len length:sizeof(unsigned)];
748 [data appendBytes:[name UTF8String] length:len];
750 [[self vimController] sendMessage:SetFontMsgID data:data];
755 - (void)resetCursorRects
757 // No need to set up cursor rects since Vim handles cursor changes.
760 - (void)updateFontPanel
762 // The font panel is updated whenever the font is set.
765 - (void)viewWillStartLiveResize
767 id windowController = [[self window] windowController];
768 [windowController liveResizeWillStart];
770 [super viewWillStartLiveResize];
773 - (void)viewDidEndLiveResize
775 id windowController = [[self window] windowController];
776 [windowController liveResizeDidEnd];
778 [super viewDidEndLiveResize];
786 @implementation MMTextView (Private)
788 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
790 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
791 NSSize cellSize = [ts cellSize];
792 if (!(cellSize.width > 0 && cellSize.height > 0))
794 NSPoint origin = [self textContainerOrigin];
796 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
797 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
799 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
805 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
807 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
808 NSSize cellSize = [ts cellSize];
809 if (!(point && cellSize.width > 0 && cellSize.height > 0))
812 *point = [self textContainerOrigin];
813 point->x += column * cellSize.width;
814 point->y += row * cellSize.height;
819 - (NSRect)trackingRect
821 NSRect rect = [self frame];
822 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
823 int left = [ud integerForKey:MMTextInsetLeftKey];
824 int top = [ud integerForKey:MMTextInsetTopKey];
825 int right = [ud integerForKey:MMTextInsetRightKey];
826 int bot = [ud integerForKey:MMTextInsetBottomKey];
828 rect.origin.x = left;
830 rect.size.width -= left + right - 1;
831 rect.size.height -= top + bot - 1;
836 - (void)dispatchKeyEvent:(NSEvent *)event
838 // Only handle the command if it came from a keyDown event
839 if ([event type] != NSKeyDown)
842 NSString *chars = [event characters];
843 NSString *unmodchars = [event charactersIgnoringModifiers];
844 unichar c = [chars characterAtIndex:0];
845 unichar imc = [unmodchars characterAtIndex:0];
847 const char *bytes = 0;
848 int mods = [event modifierFlags];
850 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
851 // _cmd, c, imc, chars, unmodchars);
853 if (' ' == imc && 0xa0 != c) {
854 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
855 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
856 // should be passed on as is.)
857 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
858 bytes = [unmodchars UTF8String];
859 } else if (imc == c && '2' == c) {
860 // HACK! Translate Ctrl+2 to <C-@>.
861 static char ctrl_at = 0;
862 len = 1; bytes = &ctrl_at;
863 } else if (imc == c && '6' == c) {
864 // HACK! Translate Ctrl+6 to <C-^>.
865 static char ctrl_hat = 0x1e;
866 len = 1; bytes = &ctrl_hat;
867 } else if (c == 0x19 && imc == 0x19) {
868 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
869 // separately (else Ctrl-Y doesn't work).
870 static char tab = 0x9;
871 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
873 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
874 bytes = [chars UTF8String];
877 [self sendKeyDown:bytes length:len modifiers:mods];
880 - (MMVimController *)vimController
882 id windowController = [[self window] windowController];
884 // TODO: Make sure 'windowController' is a MMWindowController before type
886 return [(MMWindowController*)windowController vimController];
889 - (void)startDragTimerWithInterval:(NSTimeInterval)t
891 [NSTimer scheduledTimerWithTimeInterval:t target:self
892 selector:@selector(dragTimerFired:)
893 userInfo:nil repeats:NO];
896 - (void)dragTimerFired:(NSTimer *)timer
898 // TODO: Autoscroll in horizontal direction?
899 static unsigned tick = 1;
900 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
902 isAutoscrolling = NO;
904 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
905 // HACK! If the mouse cursor is outside the text area, then send a
906 // dragged event. However, if row&col hasn't changed since the last
907 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
908 // Thus we fiddle with the column to make sure something happens.
909 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
910 NSMutableData *data = [NSMutableData data];
912 [data appendBytes:&dragRow length:sizeof(int)];
913 [data appendBytes:&col length:sizeof(int)];
914 [data appendBytes:&dragFlags length:sizeof(int)];
916 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
918 isAutoscrolling = YES;
922 // Compute timer interval depending on how far away the mouse cursor is
923 // from the text view.
924 NSRect rect = [self trackingRect];
926 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
927 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
928 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
930 NSTimeInterval t = MMDragTimerMaxInterval -
931 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
933 [self startDragTimerWithInterval:t];
939 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
941 if (chars && len > 0) {
942 NSMutableData *data = [NSMutableData data];
944 [data appendBytes:&flags length:sizeof(int)];
945 [data appendBytes:&len length:sizeof(int)];
946 [data appendBytes:chars length:len];
948 // TODO: Support 'mousehide' (check p_mh)
949 [NSCursor setHiddenUntilMouseMoves:YES];
951 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
952 [[self vimController] sendMessage:KeyDownMsgID data:data];
956 @end // MMTextView (Private)