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.
11 #import "MMTextView.h"
12 #import "MMTextStorage.h"
13 #import "MMWindowController.h"
14 #import "MMVimController.h"
19 // The max/min drag timer interval in seconds
20 static NSTimeInterval MMDragTimerMaxInterval = .3f;
21 static NSTimeInterval MMDragTimerMinInterval = .01f;
23 // The number of pixels in which the drag timer interval changes
24 static float MMDragAreaSize = 73.0f;
26 static char MMKeypadEnter[2] = { 'K', 'A' };
27 static NSString *MMKeypadEnterString = @"KA";
31 @interface MMTextView (Private)
32 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
33 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
34 - (NSRect)trackingRect;
35 - (void)dispatchKeyEvent:(NSEvent *)event;
36 - (MMVimController *)vimController;
37 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
38 - (void)dragTimerFired:(NSTimer *)timer;
39 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
44 @implementation MMTextView
48 if (markedTextField) {
49 [[markedTextField window] autorelease];
50 [markedTextField release];
51 markedTextField = nil;
54 [lastMouseDownEvent release];
58 - (NSEvent *)lastMouseDownEvent
60 return lastMouseDownEvent;
63 - (BOOL)shouldDrawInsertionPoint
65 // NOTE: The insertion point is drawn manually in drawRect:. It would be
66 // nice to be able to use the insertion point related methods of
67 // NSTextView, but it seems impossible to get them to work properly (search
68 // the cocoabuilder archives).
72 - (void)setShouldDrawInsertionPoint:(BOOL)on
74 shouldDrawInsertionPoint = on;
77 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
78 fraction:(int)percent color:(NSColor *)color
80 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
81 // row, col, shape, color);
83 // This only stores where to draw the insertion point, the actual drawing
84 // is done in drawRect:.
85 shouldDrawInsertionPoint = YES;
86 insertionPointRow = row;
87 insertionPointColumn = col;
88 insertionPointShape = shape;
89 insertionPointFraction = percent;
91 [self setInsertionPointColor:color];
94 - (void)hideMarkedTextField
96 if (markedTextField) {
97 NSWindow *win = [markedTextField window];
99 [markedTextField setStringValue:@""];
103 - (void)drawRect:(NSRect)rect
105 [super drawRect:rect];
107 if (shouldDrawInsertionPoint) {
108 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
109 NSLayoutManager *lm = [self layoutManager];
110 NSTextContainer *tc = [self textContainer];
112 // Given (row,column), calculate the bounds of the glyph at that spot.
113 // We use the layout manager because this gives us exactly the size and
114 // location of the glyph so that we can match the insertion point to
116 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
117 column:insertionPointColumn];
119 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
120 actualCharacterRange:NULL];
121 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
123 ipRect.origin.x += [self textContainerOrigin].x;
124 ipRect.origin.y += [self textContainerOrigin].y;
126 if (MMInsertionPointHorizontal == insertionPointShape) {
127 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
128 ipRect.origin.y += ipRect.size.height - frac;
129 ipRect.size.height = frac;
130 } else if (MMInsertionPointVertical == insertionPointShape) {
131 int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
132 ipRect.size.width = frac;
135 [[self insertionPointColor] set];
136 if (MMInsertionPointHollow == insertionPointShape) {
142 // NOTE: We only draw the cursor once and rely on Vim to say when it
143 // should be drawn again.
144 shouldDrawInsertionPoint = NO;
146 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
147 // NSStringFromRect(ipRect), insertionPointShape,
148 // [self insertionPointColor]);
152 - (void)keyDown:(NSEvent *)event
154 //NSLog(@"%s %@", _cmd, event);
155 // HACK! If a modifier is held, don't pass the event along to
156 // interpretKeyEvents: since some keys are bound to multiple commands which
157 // means doCommandBySelector: is called several times.
159 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
160 // affecting input management.
162 if ([event modifierFlags] & NSControlKeyMask)
163 [self dispatchKeyEvent:event];
165 [super keyDown:event];
168 - (void)insertText:(id)string
170 //NSLog(@"%s %@", _cmd, string);
171 // NOTE! This method is called for normal key presses but also for
172 // Option-key presses --- even when Ctrl is held as well as Option. When
173 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
174 // so 'string' need not be a printable character! In this case it still
175 // works to pass 'string' on to Vim as a printable character (since
176 // modifiers are already included and should not be added to the input
177 // buffer using CSI, K_MODIFIER).
179 [self hideMarkedTextField];
181 NSEvent *event = [NSApp currentEvent];
183 // HACK! In order to be able to bind to <S-Space> etc. we have to watch
184 // for when space was pressed.
185 if ([event type] == NSKeyDown
186 && [[event charactersIgnoringModifiers] length] > 0
187 && [[event charactersIgnoringModifiers] characterAtIndex:0] == ' '
188 && [event modifierFlags]
189 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask))
191 [self dispatchKeyEvent:event];
195 // TODO: Support 'mousehide' (check p_mh)
196 [NSCursor setHiddenUntilMouseMoves:YES];
198 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
199 // do not support attributes, simply pass the corresponding NSString in the
201 if ([string isKindOfClass:[NSAttributedString class]])
202 string = [string string];
204 [[self vimController] sendMessage:InsertTextMsgID
205 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
209 - (void)doCommandBySelector:(SEL)selector
211 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
212 // By ignoring the selector we effectively disable the key binding
213 // mechanism of Cocoa. Hopefully this is what the user will expect
214 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
217 // We usually end up here if the user pressed Ctrl+key (but not
220 NSEvent *event = [NSApp currentEvent];
222 if (selector == @selector(cancelOperation:)
223 || selector == @selector(insertNewline:)) {
224 // HACK! If there was marked text which got abandoned as a result of
225 // hitting escape or enter, then 'insertText:' is called with the
226 // abandoned text but '[event characters]' includes the abandoned text
227 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
228 // must intercept these keys here or the abandonded text gets inserted
230 NSString *key = [event charactersIgnoringModifiers];
231 const char *chars = [key UTF8String];
232 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
234 if (0x3 == chars[0]) {
235 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
236 // handle it separately (else Ctrl-C doesn't work).
237 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
238 chars = MMKeypadEnter;
241 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
243 [self dispatchKeyEvent:event];
247 - (BOOL)performKeyEquivalent:(NSEvent *)event
249 //NSLog(@"%s %@", _cmd, event);
250 // Called for Cmd+key keystrokes, function keys, arrow keys, page
251 // up/down, home, end.
253 // NOTE: This message cannot be ignored since Cmd+letter keys never are
254 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
255 // strokes, unless the key is a function key.
257 // NOTE: If the event that triggered this method represents a function key
258 // down then we do nothing, otherwise the input method never gets the key
259 // stroke (some input methods use e.g. arrow keys). The function key down
260 // event will still reach Vim though (via keyDown:).
261 int flags = [event modifierFlags];
262 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask)
265 // HACK! Let the main menu try to handle any key down event, before
266 // passing it on to vim, otherwise key equivalents for menus will
267 // effectively be disabled.
268 if ([[NSApp mainMenu] performKeyEquivalent:event])
271 // HACK! KeyCode 50 represent the key which switches between windows
272 // within an application (like Cmd+Tab is used to switch between
273 // applications). Return NO here, else the window switching does not work.
275 // Will this hack work for all languages / keyboard layouts?
276 if ([event keyCode] == 50)
279 //NSLog(@"%s%@", _cmd, event);
281 NSString *chars = [event characters];
282 NSString *unmodchars = [event charactersIgnoringModifiers];
283 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
284 NSMutableData *data = [NSMutableData data];
289 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
290 // can clear the shift flag as it is already included in 'unmodchars'.
291 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
292 // an English keyboard).
293 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
294 flags &= ~NSShiftKeyMask;
296 if (0x3 == [unmodchars characterAtIndex:0]) {
297 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
298 // handle it separately (else Cmd-enter turns into Ctrl-C).
299 unmodchars = MMKeypadEnterString;
300 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
303 [data appendBytes:&flags length:sizeof(int)];
304 [data appendBytes:&len length:sizeof(int)];
305 [data appendBytes:[unmodchars UTF8String] length:len];
307 [[self vimController] sendMessage:CmdKeyMsgID data:data];
312 - (BOOL)hasMarkedText
314 //NSLog(@"%s", _cmd);
315 return markedTextField && [[markedTextField stringValue] length] > 0;
318 - (NSRange)markedRange
320 //NSLog(@"%s", _cmd);
321 // HACK! If a valid range is returned, then NSTextView changes the
322 // background color of the returned range. Since marked text is displayed
323 // in a separate popup window this behaviour is not wanted. By setting the
324 // location of the returned range to NSNotFound NSTextView does nothing.
325 // This hack is continued in 'firstRectForCharacterRange:'.
326 return NSMakeRange(NSNotFound, 0);
329 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
331 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
332 // NSStringFromRange(range));
334 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
337 if (!markedTextField) {
338 // Create a text field and put it inside a floating panel. This field
339 // is used to display marked text.
340 NSSize cellSize = [ts cellSize];
341 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
343 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
344 [markedTextField setEditable:NO];
345 [markedTextField setSelectable:NO];
346 [markedTextField setBezeled:NO];
347 [markedTextField setBordered:YES];
349 NSPanel *panel = [[NSPanel alloc]
350 initWithContentRect:cellRect
351 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
352 backing:NSBackingStoreBuffered
355 //[panel setHidesOnDeactivate:NO];
356 [panel setFloatingPanel:YES];
357 [panel setBecomesKeyOnlyIfNeeded:YES];
358 [panel setContentView:markedTextField];
361 if (text && [text length] > 0) {
362 [markedTextField setFont:[ts font]];
363 if ([text isKindOfClass:[NSAttributedString class]])
364 [markedTextField setAttributedStringValue:text];
366 [markedTextField setStringValue:text];
368 [markedTextField sizeToFit];
369 NSSize size = [markedTextField frame].size;
371 // Convert coordinates (row,col) -> view -> window base -> screen
373 if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
376 origin = [self convertPoint:origin toView:nil];
377 origin = [[self window] convertBaseToScreen:origin];
379 NSWindow *win = [markedTextField window];
380 [win setContentSize:size];
381 [win setFrameOrigin:origin];
382 [win orderFront:nil];
384 [self hideMarkedTextField];
390 //NSLog(@"%s", _cmd);
391 [self hideMarkedTextField];
394 - (NSRect)firstRectForCharacterRange:(NSRange)range
396 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
398 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
399 NSLayoutManager *lm = [self layoutManager];
400 NSTextContainer *tc = [self textContainer];
402 // HACK! Since we always return marked text to have location NSNotFound,
403 // this method will be called with 'range.location == NSNotFound' whenever
404 // the input manager tries to position a popup window near the insertion
405 // point. For this reason we compute where the insertion point is and
406 // return a rect which contains it.
407 if (!(ts && lm && tc) || NSNotFound != range.location)
408 return [super firstRectForCharacterRange:range];
410 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
411 column:insertionPointColumn];
413 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
414 actualCharacterRange:NULL];
415 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
417 ipRect.origin.x += [self textContainerOrigin].x;
418 ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
420 ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
421 ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
426 - (void)scrollWheel:(NSEvent *)event
428 if ([event deltaY] == 0)
432 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
433 if (![self convertPoint:pt toRow:&row column:&col])
436 int flags = [event modifierFlags];
437 float dy = [event deltaY];
438 NSMutableData *data = [NSMutableData data];
440 [data appendBytes:&row length:sizeof(int)];
441 [data appendBytes:&col length:sizeof(int)];
442 [data appendBytes:&flags length:sizeof(int)];
443 [data appendBytes:&dy length:sizeof(float)];
445 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
448 - (void)mouseDown:(NSEvent *)event
451 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
452 if (![self convertPoint:pt toRow:&row column:&col])
455 lastMouseDownEvent = [event copy];
457 int button = [event buttonNumber];
458 int flags = [event modifierFlags];
459 int count = [event clickCount];
460 NSMutableData *data = [NSMutableData data];
462 // If desired, intepret Ctrl-Click as a right mouse click.
463 if ([[NSUserDefaults standardUserDefaults]
464 boolForKey:MMTranslateCtrlClickKey]
465 && button == 0 && flags & NSControlKeyMask) {
467 flags &= ~NSControlKeyMask;
470 [data appendBytes:&row length:sizeof(int)];
471 [data appendBytes:&col length:sizeof(int)];
472 [data appendBytes:&button length:sizeof(int)];
473 [data appendBytes:&flags length:sizeof(int)];
474 [data appendBytes:&count length:sizeof(int)];
476 [[self vimController] sendMessage:MouseDownMsgID data:data];
479 - (void)rightMouseDown:(NSEvent *)event
481 [self mouseDown:event];
484 - (void)otherMouseDown:(NSEvent *)event
486 [self mouseDown:event];
489 - (void)mouseUp:(NSEvent *)event
492 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
493 if (![self convertPoint:pt toRow:&row column:&col])
496 int flags = [event modifierFlags];
497 NSMutableData *data = [NSMutableData data];
499 [data appendBytes:&row length:sizeof(int)];
500 [data appendBytes:&col length:sizeof(int)];
501 [data appendBytes:&flags length:sizeof(int)];
503 [[self vimController] sendMessage:MouseUpMsgID data:data];
508 - (void)rightMouseUp:(NSEvent *)event
510 [self mouseUp:event];
513 - (void)otherMouseUp:(NSEvent *)event
515 [self mouseUp:event];
518 - (void)mouseDragged:(NSEvent *)event
520 int flags = [event modifierFlags];
522 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
523 if (![self convertPoint:pt toRow:&row column:&col])
526 // Autoscrolling is done in dragTimerFired:
527 if (!isAutoscrolling) {
528 NSMutableData *data = [NSMutableData data];
530 [data appendBytes:&row length:sizeof(int)];
531 [data appendBytes:&col length:sizeof(int)];
532 [data appendBytes:&flags length:sizeof(int)];
534 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
538 dragRow = row; dragColumn = col; dragFlags = flags;
540 [self startDragTimerWithInterval:.5];
545 - (void)rightMouseDragged:(NSEvent *)event
547 [self mouseDragged:event];
550 - (void)otherMouseDragged:(NSEvent *)event
552 [self mouseDragged:event];
555 - (void)mouseMoved:(NSEvent *)event
557 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
560 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
562 if (![self convertPoint:pt toRow:&row column:&col])
565 // HACK! It seems impossible to get the tracking rects set up before the
566 // view is visible, which means that the first mouseEntered: or
567 // mouseExited: events are never received. This forces us to check if the
568 // mouseMoved: event really happened over the text.
570 [ts getMaxRows:&rows columns:&cols];
571 if (row >= 0 && row < rows && col >= 0 && col < cols) {
572 NSMutableData *data = [NSMutableData data];
574 [data appendBytes:&row length:sizeof(int)];
575 [data appendBytes:&col length:sizeof(int)];
577 [[self vimController] sendMessage:MouseMovedMsgID data:data];
581 - (void)mouseEntered:(NSEvent *)event
583 //NSLog(@"%s", _cmd);
585 // NOTE: This event is received even when the window is not key; thus we
586 // have to take care not to enable mouse moved events unless our window is
588 if ([[self window] isKeyWindow])
589 [[self window] setAcceptsMouseMovedEvents:YES];
592 - (void)mouseExited:(NSEvent *)event
594 //NSLog(@"%s", _cmd);
596 [[self window] setAcceptsMouseMovedEvents:NO];
598 // NOTE: This event is received even when the window is not key; if the
599 // mouse shape is set when our window is not key, the hollow (unfocused)
600 // cursor will become a block (focused) cursor.
601 if ([[self window] isKeyWindow]) {
603 NSMutableData *data = [NSMutableData data];
604 [data appendBytes:&shape length:sizeof(int)];
605 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
609 - (void)setFrame:(NSRect)frame
611 //NSLog(@"%s", _cmd);
613 // When the frame changes we also need to update the tracking rect.
614 [super setFrame:frame];
615 [self removeTrackingRect:trackingRectTag];
616 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
617 userData:NULL assumeInside:YES];
620 - (void)viewDidMoveToWindow
622 //NSLog(@"%s (window=%@)", _cmd, [self window]);
624 // Set a tracking rect which covers the text.
625 // NOTE: While the mouse cursor is in this rect the view will receive
626 // 'mouseMoved:' events so that Vim can take care of updating the mouse
629 [[self window] setAcceptsMouseMovedEvents:YES];
630 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
631 userData:NULL assumeInside:YES];
635 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
637 //NSLog(@"%s%@", _cmd, newWindow);
639 // Remove tracking rect if view moves or is removed.
640 if ([self window] && trackingRectTag) {
641 [self removeTrackingRect:trackingRectTag];
646 - (NSMenu*)menuForEvent:(NSEvent *)event
648 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
649 // own). Called when user Ctrl-clicks in the view (this is already handled
650 // in rightMouseDown:).
654 - (NSArray *)acceptableDragTypes
656 return [NSArray arrayWithObjects:NSFilenamesPboardType,
657 NSStringPboardType, nil];
660 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
662 NSPasteboard *pboard = [sender draggingPasteboard];
664 if ([[pboard types] containsObject:NSStringPboardType]) {
665 NSString *string = [pboard stringForType:NSStringPboardType];
666 [[self vimController] dropString:string];
668 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
669 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
670 [[self vimController] dropFiles:files];
677 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
679 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
680 NSPasteboard *pboard = [sender draggingPasteboard];
682 if ( [[pboard types] containsObject:NSFilenamesPboardType]
683 && (sourceDragMask & NSDragOperationCopy) )
684 return NSDragOperationCopy;
685 if ( [[pboard types] containsObject:NSStringPboardType]
686 && (sourceDragMask & NSDragOperationCopy) )
687 return NSDragOperationCopy;
689 return NSDragOperationNone;
692 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
694 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
695 NSPasteboard *pboard = [sender draggingPasteboard];
697 if ( [[pboard types] containsObject:NSFilenamesPboardType]
698 && (sourceDragMask & NSDragOperationCopy) )
699 return NSDragOperationCopy;
700 if ( [[pboard types] containsObject:NSStringPboardType]
701 && (sourceDragMask & NSDragOperationCopy) )
702 return NSDragOperationCopy;
704 return NSDragOperationNone;
707 - (void)changeFont:(id)sender
709 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
712 NSFont *oldFont = [ts font];
713 NSFont *newFont = [sender convertFont:oldFont];
716 NSString *name = [newFont displayName];
717 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
719 NSMutableData *data = [NSMutableData data];
720 float pointSize = [newFont pointSize];
722 [data appendBytes:&pointSize length:sizeof(float)];
724 ++len; // include NUL byte
725 [data appendBytes:&len length:sizeof(unsigned)];
726 [data appendBytes:[name UTF8String] length:len];
728 [[self vimController] sendMessage:SetFontMsgID data:data];
733 - (void)resetCursorRects
735 // No need to set up cursor rects since Vim handles cursor changes.
738 - (void)updateFontPanel
740 // The font panel is updated whenever the font is set.
743 - (void)viewDidEndLiveResize
745 // HACK! If a SetTextDimensionsMsgID message is lost while dragging to
746 // resize the window, then the text view and window sizes may become out of
747 // sync. To avoid this problem, resize the window when live resizes ends.
748 // This sometimes makes the window size 'jump' unpleasantly, but that is
749 // better than the alternative.
750 id windowController = [[self window] windowController];
751 [windowController resizeWindowToFit:self];
759 @implementation MMTextView (Private)
761 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
764 NSLayoutManager *lm = [self layoutManager];
765 NSTextContainer *tc = [self textContainer];
766 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
768 if (!(lm && tc && ts))
771 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
772 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
774 int mod = [ts maxColumns] + 1;
776 if (row) *row = (int)(charIdx / mod);
777 if (column) *column = (int)(charIdx % mod);
779 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
784 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
785 NSSize cellSize = [ts cellSize];
786 if (!(cellSize.width > 0 && cellSize.height > 0))
788 NSPoint origin = [self textContainerOrigin];
790 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
791 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
793 //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;
844 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
845 // _cmd, c, imc, chars, unmodchars);
847 if (' ' == imc && 0xa0 != c) {
848 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
849 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
850 // should be passed on as is.)
851 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
852 bytes = [unmodchars UTF8String];
853 } else if (imc == c && '2' == c) {
854 // HACK! Translate Ctrl+2 to <C-@>.
855 static char ctrl_at = 0;
856 len = 1; bytes = &ctrl_at;
857 } else if (imc == c && '6' == c) {
858 // HACK! Translate Ctrl+6 to <C-^>.
859 static char ctrl_hat = 0x1e;
860 len = 1; bytes = &ctrl_hat;
861 } else if (c == 0x19 && imc == 0x19) {
862 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
863 // separately (else Ctrl-Y doesn't work).
864 static char back_tab[2] = { 'k', 'B' };
865 len = 2; bytes = back_tab;
867 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
868 bytes = [chars UTF8String];
871 [self sendKeyDown:bytes length:len modifiers:[event modifierFlags]];
874 - (MMVimController *)vimController
876 id windowController = [[self window] windowController];
878 // TODO: Make sure 'windowController' is a MMWindowController before type
880 return [(MMWindowController*)windowController vimController];
883 - (void)startDragTimerWithInterval:(NSTimeInterval)t
885 [NSTimer scheduledTimerWithTimeInterval:t target:self
886 selector:@selector(dragTimerFired:)
887 userInfo:nil repeats:NO];
890 - (void)dragTimerFired:(NSTimer *)timer
892 // TODO: Autoscroll in horizontal direction?
893 static unsigned tick = 1;
894 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
896 isAutoscrolling = NO;
898 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
899 // HACK! If the mouse cursor is outside the text area, then send a
900 // dragged event. However, if row&col hasn't changed since the last
901 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
902 // Thus we fiddle with the column to make sure something happens.
903 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
904 NSMutableData *data = [NSMutableData data];
906 [data appendBytes:&dragRow length:sizeof(int)];
907 [data appendBytes:&col length:sizeof(int)];
908 [data appendBytes:&dragFlags length:sizeof(int)];
910 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
912 isAutoscrolling = YES;
916 // Compute timer interval depending on how far away the mouse cursor is
917 // from the text view.
918 NSRect rect = [self trackingRect];
920 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
921 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
922 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
924 NSTimeInterval t = MMDragTimerMaxInterval -
925 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
927 [self startDragTimerWithInterval:t];
933 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
935 if (chars && len > 0) {
936 NSMutableData *data = [NSMutableData data];
938 [data appendBytes:&flags length:sizeof(int)];
939 [data appendBytes:&len length:sizeof(int)];
940 [data appendBytes:chars length:len];
942 // TODO: Support 'mousehide' (check p_mh)
943 [NSCursor setHiddenUntilMouseMoves:YES];
945 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
946 [[self vimController] sendMessage:KeyDownMsgID data:data];
950 @end // MMTextView (Private)