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:@""];
108 - (void)drawRect:(NSRect)rect
110 [super drawRect:rect];
112 if (shouldDrawInsertionPoint) {
113 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
114 NSLayoutManager *lm = [self layoutManager];
115 NSTextContainer *tc = [self textContainer];
117 // Given (row,column), calculate the bounds of the glyph at that spot.
118 // We use the layout manager because this gives us exactly the size and
119 // location of the glyph so that we can match the insertion point to
121 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
122 column:insertionPointColumn];
124 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
125 actualCharacterRange:NULL];
126 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
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 //NSLog(@"%s%@", _cmd, event);
307 NSString *chars = [event characters];
308 NSString *unmodchars = [event charactersIgnoringModifiers];
309 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
310 NSMutableData *data = [NSMutableData data];
315 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
316 // can clear the shift flag as it is already included in 'unmodchars'.
317 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
318 // an English keyboard).
319 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
320 flags &= ~NSShiftKeyMask;
322 if (0x3 == [unmodchars characterAtIndex:0]) {
323 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
324 // handle it separately (else Cmd-enter turns into Ctrl-C).
325 unmodchars = MMKeypadEnterString;
326 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
329 [data appendBytes:&flags length:sizeof(int)];
330 [data appendBytes:&len length:sizeof(int)];
331 [data appendBytes:[unmodchars UTF8String] length:len];
333 [[self vimController] sendMessage:CmdKeyMsgID data:data];
338 - (BOOL)hasMarkedText
340 //NSLog(@"%s", _cmd);
341 return markedTextField && [[markedTextField stringValue] length] > 0;
344 - (NSRange)markedRange
346 //NSLog(@"%s", _cmd);
347 // HACK! If a valid range is returned, then NSTextView changes the
348 // background color of the returned range. Since marked text is displayed
349 // in a separate popup window this behaviour is not wanted. By setting the
350 // location of the returned range to NSNotFound NSTextView does nothing.
351 // This hack is continued in 'firstRectForCharacterRange:'.
352 return NSMakeRange(NSNotFound, 0);
355 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
357 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
358 // NSStringFromRange(range));
360 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
363 if (!markedTextField) {
364 // Create a text field and put it inside a floating panel. This field
365 // is used to display marked text.
366 NSSize cellSize = [ts cellSize];
367 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
369 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
370 [markedTextField setEditable:NO];
371 [markedTextField setSelectable:NO];
372 [markedTextField setBezeled:NO];
373 [markedTextField setBordered:YES];
375 NSPanel *panel = [[NSPanel alloc]
376 initWithContentRect:cellRect
377 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
378 backing:NSBackingStoreBuffered
381 //[panel setHidesOnDeactivate:NO];
382 [panel setFloatingPanel:YES];
383 [panel setBecomesKeyOnlyIfNeeded:YES];
384 [panel setContentView:markedTextField];
387 if (text && [text length] > 0) {
388 [markedTextField setFont:[ts font]];
389 if ([text isKindOfClass:[NSAttributedString class]])
390 [markedTextField setAttributedStringValue:text];
392 [markedTextField setStringValue:text];
394 [markedTextField sizeToFit];
395 NSSize size = [markedTextField frame].size;
397 // Convert coordinates (row,col) -> view -> window base -> screen
399 if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
402 origin = [self convertPoint:origin toView:nil];
403 origin = [[self window] convertBaseToScreen:origin];
405 NSWindow *win = [markedTextField window];
406 [win setContentSize:size];
407 [win setFrameOrigin:origin];
408 [win orderFront:nil];
410 [self hideMarkedTextField];
416 //NSLog(@"%s", _cmd);
417 [self hideMarkedTextField];
420 - (NSRect)firstRectForCharacterRange:(NSRange)range
422 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
424 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
425 NSLayoutManager *lm = [self layoutManager];
426 NSTextContainer *tc = [self textContainer];
428 // HACK! Since we always return marked text to have location NSNotFound,
429 // this method will be called with 'range.location == NSNotFound' whenever
430 // the input manager tries to position a popup window near the insertion
431 // point. For this reason we compute where the insertion point is and
432 // return a rect which contains it.
433 if (!(ts && lm && tc) || NSNotFound != range.location)
434 return [super firstRectForCharacterRange:range];
436 unsigned charIdx = [ts characterIndexForRow:insertionPointRow
437 column:insertionPointColumn];
439 [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
440 actualCharacterRange:NULL];
441 NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
443 ipRect.origin.x += [self textContainerOrigin].x;
444 ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
446 ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
447 ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
452 - (void)scrollWheel:(NSEvent *)event
454 if ([event deltaY] == 0)
458 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
459 if (![self convertPoint:pt toRow:&row column:&col])
462 int flags = [event modifierFlags];
463 float dy = [event deltaY];
464 NSMutableData *data = [NSMutableData data];
466 [data appendBytes:&row length:sizeof(int)];
467 [data appendBytes:&col length:sizeof(int)];
468 [data appendBytes:&flags length:sizeof(int)];
469 [data appendBytes:&dy length:sizeof(float)];
471 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
474 - (void)mouseDown:(NSEvent *)event
477 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
478 if (![self convertPoint:pt toRow:&row column:&col])
481 lastMouseDownEvent = [event copy];
483 int button = [event buttonNumber];
484 int flags = [event modifierFlags];
485 int count = [event clickCount];
486 NSMutableData *data = [NSMutableData data];
488 // If desired, intepret Ctrl-Click as a right mouse click.
489 if ([[NSUserDefaults standardUserDefaults]
490 boolForKey:MMTranslateCtrlClickKey]
491 && button == 0 && flags & NSControlKeyMask) {
493 flags &= ~NSControlKeyMask;
496 [data appendBytes:&row length:sizeof(int)];
497 [data appendBytes:&col length:sizeof(int)];
498 [data appendBytes:&button length:sizeof(int)];
499 [data appendBytes:&flags length:sizeof(int)];
500 [data appendBytes:&count length:sizeof(int)];
502 [[self vimController] sendMessage:MouseDownMsgID data:data];
505 - (void)rightMouseDown:(NSEvent *)event
507 [self mouseDown:event];
510 - (void)otherMouseDown:(NSEvent *)event
512 [self mouseDown:event];
515 - (void)mouseUp:(NSEvent *)event
518 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
519 if (![self convertPoint:pt toRow:&row column:&col])
522 int flags = [event modifierFlags];
523 NSMutableData *data = [NSMutableData data];
525 [data appendBytes:&row length:sizeof(int)];
526 [data appendBytes:&col length:sizeof(int)];
527 [data appendBytes:&flags length:sizeof(int)];
529 [[self vimController] sendMessage:MouseUpMsgID data:data];
534 - (void)rightMouseUp:(NSEvent *)event
536 [self mouseUp:event];
539 - (void)otherMouseUp:(NSEvent *)event
541 [self mouseUp:event];
544 - (void)mouseDragged:(NSEvent *)event
546 int flags = [event modifierFlags];
548 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
549 if (![self convertPoint:pt toRow:&row column:&col])
552 // Autoscrolling is done in dragTimerFired:
553 if (!isAutoscrolling) {
554 NSMutableData *data = [NSMutableData data];
556 [data appendBytes:&row length:sizeof(int)];
557 [data appendBytes:&col length:sizeof(int)];
558 [data appendBytes:&flags length:sizeof(int)];
560 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
564 dragRow = row; dragColumn = col; dragFlags = flags;
566 [self startDragTimerWithInterval:.5];
571 - (void)rightMouseDragged:(NSEvent *)event
573 [self mouseDragged:event];
576 - (void)otherMouseDragged:(NSEvent *)event
578 [self mouseDragged:event];
581 - (void)mouseMoved:(NSEvent *)event
583 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
586 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
588 if (![self convertPoint:pt toRow:&row column:&col])
591 // HACK! It seems impossible to get the tracking rects set up before the
592 // view is visible, which means that the first mouseEntered: or
593 // mouseExited: events are never received. This forces us to check if the
594 // mouseMoved: event really happened over the text.
596 [ts getMaxRows:&rows columns:&cols];
597 if (row >= 0 && row < rows && col >= 0 && col < cols) {
598 NSMutableData *data = [NSMutableData data];
600 [data appendBytes:&row length:sizeof(int)];
601 [data appendBytes:&col length:sizeof(int)];
603 [[self vimController] sendMessage:MouseMovedMsgID data:data];
607 - (void)mouseEntered:(NSEvent *)event
609 //NSLog(@"%s", _cmd);
611 // NOTE: This event is received even when the window is not key; thus we
612 // have to take care not to enable mouse moved events unless our window is
614 if ([[self window] isKeyWindow])
615 [[self window] setAcceptsMouseMovedEvents:YES];
618 - (void)mouseExited:(NSEvent *)event
620 //NSLog(@"%s", _cmd);
622 [[self window] setAcceptsMouseMovedEvents:NO];
624 // NOTE: This event is received even when the window is not key; if the
625 // mouse shape is set when our window is not key, the hollow (unfocused)
626 // cursor will become a block (focused) cursor.
627 if ([[self window] isKeyWindow]) {
629 NSMutableData *data = [NSMutableData data];
630 [data appendBytes:&shape length:sizeof(int)];
631 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
635 - (void)setFrame:(NSRect)frame
637 //NSLog(@"%s", _cmd);
639 // When the frame changes we also need to update the tracking rect.
640 [super setFrame:frame];
641 [self removeTrackingRect:trackingRectTag];
642 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
643 userData:NULL assumeInside:YES];
646 - (void)viewDidMoveToWindow
648 //NSLog(@"%s (window=%@)", _cmd, [self window]);
650 // Set a tracking rect which covers the text.
651 // NOTE: While the mouse cursor is in this rect the view will receive
652 // 'mouseMoved:' events so that Vim can take care of updating the mouse
655 [[self window] setAcceptsMouseMovedEvents:YES];
656 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
657 userData:NULL assumeInside:YES];
661 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
663 //NSLog(@"%s%@", _cmd, newWindow);
665 // Remove tracking rect if view moves or is removed.
666 if ([self window] && trackingRectTag) {
667 [self removeTrackingRect:trackingRectTag];
672 - (NSMenu*)menuForEvent:(NSEvent *)event
674 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
675 // own). Called when user Ctrl-clicks in the view (this is already handled
676 // in rightMouseDown:).
680 - (NSArray *)acceptableDragTypes
682 return [NSArray arrayWithObjects:NSFilenamesPboardType,
683 NSStringPboardType, nil];
686 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
688 NSPasteboard *pboard = [sender draggingPasteboard];
690 if ([[pboard types] containsObject:NSStringPboardType]) {
691 NSString *string = [pboard stringForType:NSStringPboardType];
692 [[self vimController] dropString:string];
694 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
695 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
696 [[self vimController] dropFiles:files];
703 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
705 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
706 NSPasteboard *pboard = [sender draggingPasteboard];
708 if ( [[pboard types] containsObject:NSFilenamesPboardType]
709 && (sourceDragMask & NSDragOperationCopy) )
710 return NSDragOperationCopy;
711 if ( [[pboard types] containsObject:NSStringPboardType]
712 && (sourceDragMask & NSDragOperationCopy) )
713 return NSDragOperationCopy;
715 return NSDragOperationNone;
718 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
720 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
721 NSPasteboard *pboard = [sender draggingPasteboard];
723 if ( [[pboard types] containsObject:NSFilenamesPboardType]
724 && (sourceDragMask & NSDragOperationCopy) )
725 return NSDragOperationCopy;
726 if ( [[pboard types] containsObject:NSStringPboardType]
727 && (sourceDragMask & NSDragOperationCopy) )
728 return NSDragOperationCopy;
730 return NSDragOperationNone;
733 - (void)changeFont:(id)sender
735 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
738 NSFont *oldFont = [ts font];
739 NSFont *newFont = [sender convertFont:oldFont];
742 NSString *name = [newFont displayName];
743 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
745 NSMutableData *data = [NSMutableData data];
746 float pointSize = [newFont pointSize];
748 [data appendBytes:&pointSize length:sizeof(float)];
750 ++len; // include NUL byte
751 [data appendBytes:&len length:sizeof(unsigned)];
752 [data appendBytes:[name UTF8String] length:len];
754 [[self vimController] sendMessage:SetFontMsgID data:data];
759 - (void)resetCursorRects
761 // No need to set up cursor rects since Vim handles cursor changes.
764 - (void)updateFontPanel
766 // The font panel is updated whenever the font is set.
769 - (void)viewDidEndLiveResize
771 id windowController = [[self window] windowController];
772 [windowController liveResizeDidEnd];
780 @implementation MMTextView (Private)
782 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
785 NSLayoutManager *lm = [self layoutManager];
786 NSTextContainer *tc = [self textContainer];
787 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
789 if (!(lm && tc && ts))
792 unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
793 unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
795 int mod = [ts maxColumns] + 1;
797 if (row) *row = (int)(charIdx / mod);
798 if (column) *column = (int)(charIdx % mod);
800 NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
805 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
806 NSSize cellSize = [ts cellSize];
807 if (!(cellSize.width > 0 && cellSize.height > 0))
809 NSPoint origin = [self textContainerOrigin];
811 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
812 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
814 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
821 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
823 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
824 NSSize cellSize = [ts cellSize];
825 if (!(point && cellSize.width > 0 && cellSize.height > 0))
828 *point = [self textContainerOrigin];
829 point->x += column * cellSize.width;
830 point->y += row * cellSize.height;
835 - (NSRect)trackingRect
837 NSRect rect = [self frame];
838 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
839 int left = [ud integerForKey:MMTextInsetLeftKey];
840 int top = [ud integerForKey:MMTextInsetTopKey];
841 int right = [ud integerForKey:MMTextInsetRightKey];
842 int bot = [ud integerForKey:MMTextInsetBottomKey];
844 rect.origin.x = left;
846 rect.size.width -= left + right - 1;
847 rect.size.height -= top + bot - 1;
852 - (void)dispatchKeyEvent:(NSEvent *)event
854 // Only handle the command if it came from a keyDown event
855 if ([event type] != NSKeyDown)
858 NSString *chars = [event characters];
859 NSString *unmodchars = [event charactersIgnoringModifiers];
860 unichar c = [chars characterAtIndex:0];
861 unichar imc = [unmodchars characterAtIndex:0];
863 const char *bytes = 0;
864 int mods = [event modifierFlags];
866 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
867 // _cmd, c, imc, chars, unmodchars);
869 if (' ' == imc && 0xa0 != c) {
870 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
871 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
872 // should be passed on as is.)
873 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
874 bytes = [unmodchars UTF8String];
875 } else if (imc == c && '2' == c) {
876 // HACK! Translate Ctrl+2 to <C-@>.
877 static char ctrl_at = 0;
878 len = 1; bytes = &ctrl_at;
879 } else if (imc == c && '6' == c) {
880 // HACK! Translate Ctrl+6 to <C-^>.
881 static char ctrl_hat = 0x1e;
882 len = 1; bytes = &ctrl_hat;
883 } else if (c == 0x19 && imc == 0x19) {
884 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
885 // separately (else Ctrl-Y doesn't work).
886 static char tab = 0x9;
887 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
889 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
890 bytes = [chars UTF8String];
893 [self sendKeyDown:bytes length:len modifiers:mods];
896 - (MMVimController *)vimController
898 id windowController = [[self window] windowController];
900 // TODO: Make sure 'windowController' is a MMWindowController before type
902 return [(MMWindowController*)windowController vimController];
905 - (void)startDragTimerWithInterval:(NSTimeInterval)t
907 [NSTimer scheduledTimerWithTimeInterval:t target:self
908 selector:@selector(dragTimerFired:)
909 userInfo:nil repeats:NO];
912 - (void)dragTimerFired:(NSTimer *)timer
914 // TODO: Autoscroll in horizontal direction?
915 static unsigned tick = 1;
916 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
918 isAutoscrolling = NO;
920 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
921 // HACK! If the mouse cursor is outside the text area, then send a
922 // dragged event. However, if row&col hasn't changed since the last
923 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
924 // Thus we fiddle with the column to make sure something happens.
925 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
926 NSMutableData *data = [NSMutableData data];
928 [data appendBytes:&dragRow length:sizeof(int)];
929 [data appendBytes:&col length:sizeof(int)];
930 [data appendBytes:&dragFlags length:sizeof(int)];
932 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
934 isAutoscrolling = YES;
938 // Compute timer interval depending on how far away the mouse cursor is
939 // from the text view.
940 NSRect rect = [self trackingRect];
942 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
943 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
944 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
946 NSTimeInterval t = MMDragTimerMaxInterval -
947 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
949 [self startDragTimerWithInterval:t];
955 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
957 if (chars && len > 0) {
958 NSMutableData *data = [NSMutableData data];
960 [data appendBytes:&flags length:sizeof(int)];
961 [data appendBytes:&len length:sizeof(int)];
962 [data appendBytes:chars length:len];
964 // TODO: Support 'mousehide' (check p_mh)
965 [NSCursor setHiddenUntilMouseMoves:YES];
967 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
968 [[self vimController] sendMessage:KeyDownMsgID data:data];
972 @end // MMTextView (Private)