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"
24 #import "MMTypesetter.h"
29 // This is taken from gui.h
30 #define DRAW_CURSOR 0x20
32 // The max/min drag timer interval in seconds
33 static NSTimeInterval MMDragTimerMaxInterval = .3f;
34 static NSTimeInterval MMDragTimerMinInterval = .01f;
36 // The number of pixels in which the drag timer interval changes
37 static float MMDragAreaSize = 73.0f;
39 static char MMKeypadEnter[2] = { 'K', 'A' };
40 static NSString *MMKeypadEnterString = @"KA";
48 @interface MMTextView (Private)
50 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
51 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
52 - (NSRect)trackingRect;
53 - (void)dispatchKeyEvent:(NSEvent *)event;
54 - (MMVimController *)vimController;
55 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
56 - (void)dragTimerFired:(NSTimer *)timer;
57 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
62 @implementation MMTextView
64 - (id)initWithFrame:(NSRect)frame
66 // Set up a Cocoa text system. Note that the textStorage is released in
67 // -[MMVimView dealloc].
68 MMTextStorage *textStorage = [[MMTextStorage alloc] init];
69 NSLayoutManager *lm = [[NSLayoutManager alloc] init];
70 NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
71 NSMakeSize(1.0e7,1.0e7)];
73 NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
74 stringForKey:MMTypesetterKey];
75 if ([typesetterString isEqual:@"MMTypesetter"]) {
76 NSTypesetter *typesetter = [[MMTypesetter alloc] init];
77 [lm setTypesetter:typesetter];
79 } else if ([typesetterString isEqual:@"MMTypesetter2"]) {
80 NSTypesetter *typesetter = [[MMTypesetter2 alloc] init];
81 [lm setTypesetter:typesetter];
84 // Only MMTypesetter supports different cell width multipliers.
85 [[NSUserDefaults standardUserDefaults]
86 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
89 // The characters in the text storage are in display order, so disable
90 // bidirectional text processing (this call is 10.4 only).
91 [[lm typesetter] setBidiProcessingEnabled:NO];
93 [tc setWidthTracksTextView:NO];
94 [tc setHeightTracksTextView:NO];
95 [tc setLineFragmentPadding:0];
97 [textStorage addLayoutManager:lm];
98 [lm addTextContainer:tc];
100 // The text storage retains the layout manager which in turn retains
101 // the text container.
105 // NOTE: This will make the text storage the principal owner of the text
106 // system. Releasing the text storage will in turn release the layout
107 // manager, the text container, and finally the text view (self). This
108 // complicates deallocation somewhat, see -[MMVimView dealloc].
109 if (![super initWithFrame:frame textContainer:tc]) {
110 [textStorage release];
119 //NSLog(@"MMTextView dealloc");
121 if (markedTextField) {
122 [[markedTextField window] autorelease];
123 [markedTextField release];
124 markedTextField = nil;
127 [lastMouseDownEvent release]; lastMouseDownEvent = nil;
131 - (NSEvent *)lastMouseDownEvent
133 return lastMouseDownEvent;
136 - (BOOL)shouldDrawInsertionPoint
138 // NOTE: The insertion point is drawn manually in drawRect:. It would be
139 // nice to be able to use the insertion point related methods of
140 // NSTextView, but it seems impossible to get them to work properly (search
141 // the cocoabuilder archives).
145 - (void)setShouldDrawInsertionPoint:(BOOL)on
147 shouldDrawInsertionPoint = on;
150 - (void)setPreEditRow:(int)row column:(int)col
156 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
157 fraction:(int)percent color:(NSColor *)color
159 //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
160 // row, col, shape, color);
162 // This only stores where to draw the insertion point, the actual drawing
163 // is done in drawRect:.
164 shouldDrawInsertionPoint = YES;
165 insertionPointRow = row;
166 insertionPointColumn = col;
167 insertionPointShape = shape;
168 insertionPointFraction = percent;
170 [self setInsertionPointColor:color];
173 - (void)hideMarkedTextField
175 if (markedTextField) {
176 NSWindow *win = [markedTextField window];
178 [markedTextField setStringValue:@""];
183 #define MM_DEBUG_DRAWING 0
185 - (void)performBatchDrawWithData:(NSData *)data
187 MMTextStorage *textStorage = (MMTextStorage *)[self textStorage];
191 const void *bytes = [data bytes];
192 const void *end = bytes + [data length];
193 int cursorRow = -1, cursorCol = 0;
196 NSLog(@"====> BEGIN %s", _cmd);
198 [textStorage beginEditing];
200 // TODO: Sanity check input
202 while (bytes < end) {
203 int type = *((int*)bytes); bytes += sizeof(int);
205 if (ClearAllDrawType == type) {
207 NSLog(@" Clear all");
209 [textStorage clearAll];
210 } else if (ClearBlockDrawType == type) {
211 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
212 int row1 = *((int*)bytes); bytes += sizeof(int);
213 int col1 = *((int*)bytes); bytes += sizeof(int);
214 int row2 = *((int*)bytes); bytes += sizeof(int);
215 int col2 = *((int*)bytes); bytes += sizeof(int);
218 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
221 [textStorage clearBlockFromRow:row1 column:col1
222 toRow:row2 column:col2
223 color:[NSColor colorWithArgbInt:color]];
224 } else if (DeleteLinesDrawType == type) {
225 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
226 int row = *((int*)bytes); bytes += sizeof(int);
227 int count = *((int*)bytes); bytes += sizeof(int);
228 int bot = *((int*)bytes); bytes += sizeof(int);
229 int left = *((int*)bytes); bytes += sizeof(int);
230 int right = *((int*)bytes); bytes += sizeof(int);
233 NSLog(@" Delete %d line(s) from %d", count, row);
235 [textStorage deleteLinesFromRow:row lineCount:count
236 scrollBottom:bot left:left right:right
237 color:[NSColor colorWithArgbInt:color]];
238 } else if (DrawStringDrawType == type) {
239 int bg = *((int*)bytes); bytes += sizeof(int);
240 int fg = *((int*)bytes); bytes += sizeof(int);
241 int sp = *((int*)bytes); bytes += sizeof(int);
242 int row = *((int*)bytes); bytes += sizeof(int);
243 int col = *((int*)bytes); bytes += sizeof(int);
244 int cells = *((int*)bytes); bytes += sizeof(int);
245 int flags = *((int*)bytes); bytes += sizeof(int);
246 int len = *((int*)bytes); bytes += sizeof(int);
247 NSString *string = [[NSString alloc]
248 initWithBytes:(void*)bytes length:len
249 encoding:NSUTF8StringEncoding];
253 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
254 "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
255 len > 0 ? [string substringToIndex:1] : @"");
257 // NOTE: If this is a call to draw the (block) cursor, then cancel
258 // any previous request to draw the insertion point, or it might
259 // get drawn as well.
260 if (flags & DRAW_CURSOR) {
261 [self setShouldDrawInsertionPoint:NO];
262 //NSColor *color = [NSColor colorWithRgbInt:bg];
263 //[self drawInsertionPointAtRow:row column:col
264 // shape:MMInsertionPointBlock
268 [textStorage drawString:string
269 atRow:row column:col cells:cells
271 foregroundColor:[NSColor colorWithRgbInt:fg]
272 backgroundColor:[NSColor colorWithArgbInt:bg]
273 specialColor:[NSColor colorWithRgbInt:sp]];
276 } else if (InsertLinesDrawType == type) {
277 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
278 int row = *((int*)bytes); bytes += sizeof(int);
279 int count = *((int*)bytes); bytes += sizeof(int);
280 int bot = *((int*)bytes); bytes += sizeof(int);
281 int left = *((int*)bytes); bytes += sizeof(int);
282 int right = *((int*)bytes); bytes += sizeof(int);
285 NSLog(@" Insert %d line(s) at row %d", count, row);
287 [textStorage insertLinesAtRow:row lineCount:count
288 scrollBottom:bot left:left right:right
289 color:[NSColor colorWithArgbInt:color]];
290 } else if (DrawCursorDrawType == type) {
291 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
292 int row = *((int*)bytes); bytes += sizeof(int);
293 int col = *((int*)bytes); bytes += sizeof(int);
294 int shape = *((int*)bytes); bytes += sizeof(int);
295 int percent = *((int*)bytes); bytes += sizeof(int);
298 NSLog(@" Draw cursor at (%d,%d)", row, col);
300 [self drawInsertionPointAtRow:row column:col shape:shape
302 color:[NSColor colorWithRgbInt:color]];
303 } else if (SetCursorPosDrawType == type) {
304 cursorRow = *((int*)bytes); bytes += sizeof(int);
305 cursorCol = *((int*)bytes); bytes += sizeof(int);
307 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
311 [textStorage endEditing];
313 if (cursorRow >= 0) {
314 unsigned off = [textStorage characterIndexForRow:cursorRow
316 unsigned maxoff = [[textStorage string] length];
317 if (off > maxoff) off = maxoff;
319 [self setSelectedRange:NSMakeRange(off, 0)];
322 // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
323 // and columns are changed (due to ipc delays). Force a redraw here.
324 [self displayIfNeeded];
327 NSLog(@"<==== END %s", _cmd);
333 return [(MMTextStorage*)[self textStorage] font];
336 - (void)setFont:(NSFont *)newFont
338 [(MMTextStorage*)[self textStorage] setFont:newFont];
341 - (void)setWideFont:(NSFont *)newFont
343 [(MMTextStorage*)[self textStorage] setWideFont:newFont];
348 return [(MMTextStorage*)[self textStorage] cellSize];
351 - (void)setLinespace:(float)newLinespace
353 return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
356 - (void)getMaxRows:(int*)rows columns:(int*)cols
358 return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
361 - (void)setMaxRows:(int)rows columns:(int)cols
363 return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
366 - (NSRect)rectForRowsInRange:(NSRange)range
368 return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
371 - (NSRect)rectForColumnsInRange:(NSRange)range
373 return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
376 - (void)setDefaultColorsBackground:(NSColor *)bgColor
377 foreground:(NSColor *)fgColor
379 [self setBackgroundColor:bgColor];
380 return [(MMTextStorage*)[self textStorage]
381 setDefaultColorsBackground:bgColor foreground:fgColor];
384 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
386 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
387 int right = [ud integerForKey:MMTextInsetRightKey];
388 int bot = [ud integerForKey:MMTextInsetBottomKey];
390 size.width -= [self textContainerOrigin].x + right;
391 size.height -= [self textContainerOrigin].y + bot;
393 NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
397 newSize.width += [self textContainerOrigin].x + right;
398 newSize.height += [self textContainerOrigin].y + bot;
403 - (NSSize)desiredSize
405 NSSize size = [(MMTextStorage*)[self textStorage] size];
407 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
408 int right = [ud integerForKey:MMTextInsetRightKey];
409 int bot = [ud integerForKey:MMTextInsetBottomKey];
411 size.width += [self textContainerOrigin].x + right;
412 size.height += [self textContainerOrigin].y + bot;
419 NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
420 NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
422 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
423 int right = [ud integerForKey:MMTextInsetRightKey];
424 int bot = [ud integerForKey:MMTextInsetBottomKey];
426 size.width += [self textContainerOrigin].x + right;
427 size.height += [self textContainerOrigin].y + bot;
437 - (void)drawRect:(NSRect)rect
439 [super drawRect:rect];
441 if (shouldDrawInsertionPoint) {
442 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
444 NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
445 column:insertionPointColumn];
446 ipRect.origin.x += [self textContainerOrigin].x;
447 ipRect.origin.y += [self textContainerOrigin].y;
449 if (MMInsertionPointHorizontal == insertionPointShape) {
450 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
451 ipRect.origin.y += ipRect.size.height - frac;
452 ipRect.size.height = frac;
453 } else if (MMInsertionPointVertical == insertionPointShape) {
454 int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
455 ipRect.size.width = frac;
458 [[self insertionPointColor] set];
459 if (MMInsertionPointHollow == insertionPointShape) {
465 // NOTE: We only draw the cursor once and rely on Vim to say when it
466 // should be drawn again.
467 shouldDrawInsertionPoint = NO;
469 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
470 // NSStringFromRect(ipRect), insertionPointShape,
471 // [self insertionPointColor]);
474 // this code invalidates the shadow, so we don't
475 // get shifting ghost text on scroll and resize
476 // but makes speed unusable
477 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
478 if ([ts defaultBackgroundAlpha] < 1.0f) {
479 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
481 [[self window] setHasShadow:NO];
482 [[self window] setHasShadow:YES];
485 [[self window] invalidateShadow];
491 - (void)keyDown:(NSEvent *)event
493 //NSLog(@"%s %@", _cmd, event);
494 // HACK! If control modifier is held, don't pass the event along to
495 // interpretKeyEvents: since some keys are bound to multiple commands which
496 // means doCommandBySelector: is called several times. Do the same for
497 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
498 // commands). This hack may break input management, but unless we can
499 // figure out a way to disable key bindings there seems little else to do.
501 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
502 // affecting input management.
503 int flags = [event modifierFlags];
504 if ((flags & NSControlKeyMask) ||
505 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
506 NSString *unmod = [event charactersIgnoringModifiers];
507 if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
508 && [unmod characterAtIndex:0] >= 0x60) {
509 // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
510 // as normal text to be added to the Vim input buffer. This must
511 // be done in order for the backend to be able to separate e.g.
512 // Ctrl-i and Ctrl-tab.
513 [self insertText:[event characters]];
515 [self dispatchKeyEvent:event];
518 [super keyDown:event];
522 - (void)insertText:(id)string
524 //NSLog(@"%s %@", _cmd, string);
525 // NOTE! This method is called for normal key presses but also for
526 // Option-key presses --- even when Ctrl is held as well as Option. When
527 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
528 // so 'string' need not be a printable character! In this case it still
529 // works to pass 'string' on to Vim as a printable character (since
530 // modifiers are already included and should not be added to the input
531 // buffer using CSI, K_MODIFIER).
533 [self hideMarkedTextField];
535 NSEvent *event = [NSApp currentEvent];
537 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
538 // to watch for them here.
539 if ([event type] == NSKeyDown
540 && [[event charactersIgnoringModifiers] length] > 0
541 && [event modifierFlags]
542 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
543 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
545 // <S-M-Tab> translates to 0x19
546 if (' ' == c || 0x19 == c) {
547 [self dispatchKeyEvent:event];
552 // TODO: Support 'mousehide' (check p_mh)
553 [NSCursor setHiddenUntilMouseMoves:YES];
555 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
556 // do not support attributes, simply pass the corresponding NSString in the
558 if ([string isKindOfClass:[NSAttributedString class]])
559 string = [string string];
561 //NSLog(@"send InsertTextMsgID: %@", string);
563 [[self vimController] sendMessage:InsertTextMsgID
564 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
568 - (void)doCommandBySelector:(SEL)selector
570 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
571 // By ignoring the selector we effectively disable the key binding
572 // mechanism of Cocoa. Hopefully this is what the user will expect
573 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
576 // We usually end up here if the user pressed Ctrl+key (but not
579 NSEvent *event = [NSApp currentEvent];
581 if (selector == @selector(cancelOperation:)
582 || selector == @selector(insertNewline:)) {
583 // HACK! If there was marked text which got abandoned as a result of
584 // hitting escape or enter, then 'insertText:' is called with the
585 // abandoned text but '[event characters]' includes the abandoned text
586 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
587 // must intercept these keys here or the abandonded text gets inserted
589 NSString *key = [event charactersIgnoringModifiers];
590 const char *chars = [key UTF8String];
591 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
593 if (0x3 == chars[0]) {
594 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
595 // handle it separately (else Ctrl-C doesn't work).
596 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
597 chars = MMKeypadEnter;
600 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
602 [self dispatchKeyEvent:event];
606 - (BOOL)performKeyEquivalent:(NSEvent *)event
608 //NSLog(@"%s %@", _cmd, event);
609 // Called for Cmd+key keystrokes, function keys, arrow keys, page
610 // up/down, home, end.
612 // NOTE: This message cannot be ignored since Cmd+letter keys never are
613 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
614 // strokes, unless the key is a function key.
616 // NOTE: If the event that triggered this method represents a function key
617 // down then we do nothing, otherwise the input method never gets the key
618 // stroke (some input methods use e.g. arrow keys). The function key down
619 // event will still reach Vim though (via keyDown:). The exceptions to
620 // this rule are: PageUp/PageDown (keycode 116/121).
621 int flags = [event modifierFlags];
622 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
623 && !(116 == [event keyCode] || 121 == [event keyCode]))
626 // HACK! Let the main menu try to handle any key down event, before
627 // passing it on to vim, otherwise key equivalents for menus will
628 // effectively be disabled.
629 if ([[NSApp mainMenu] performKeyEquivalent:event])
632 // HACK! KeyCode 50 represent the key which switches between windows
633 // within an application (like Cmd+Tab is used to switch between
634 // applications). Return NO here, else the window switching does not work.
636 // Will this hack work for all languages / keyboard layouts?
637 if ([event keyCode] == 50)
640 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
641 if (flags & NSControlKeyMask) {
642 [self keyDown:event];
646 //NSLog(@"%s%@", _cmd, event);
648 NSString *chars = [event characters];
649 NSString *unmodchars = [event charactersIgnoringModifiers];
650 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
651 NSMutableData *data = [NSMutableData data];
656 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
657 // can clear the shift flag as it is already included in 'unmodchars'.
658 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
659 // an English keyboard).
660 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
661 flags &= ~NSShiftKeyMask;
663 if (0x3 == [unmodchars characterAtIndex:0]) {
664 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
665 // handle it separately (else Cmd-enter turns into Ctrl-C).
666 unmodchars = MMKeypadEnterString;
667 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
670 [data appendBytes:&flags length:sizeof(int)];
671 [data appendBytes:&len length:sizeof(int)];
672 [data appendBytes:[unmodchars UTF8String] length:len];
674 [[self vimController] sendMessage:CmdKeyMsgID data:data];
679 - (BOOL)hasMarkedText
681 //NSLog(@"%s", _cmd);
682 return markedTextField && [[markedTextField stringValue] length] > 0;
685 - (NSRange)markedRange
687 //NSLog(@"%s", _cmd);
688 unsigned len = [[markedTextField stringValue] length];
689 return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
692 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
694 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
695 // NSStringFromRange(range));
697 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
700 if (!markedTextField) {
701 // Create a text field and put it inside a floating panel. This field
702 // is used to display marked text.
703 NSSize cellSize = [ts cellSize];
704 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
706 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
707 [markedTextField setEditable:NO];
708 [markedTextField setSelectable:NO];
709 [markedTextField setBezeled:NO];
710 [markedTextField setBordered:YES];
712 // NOTE: The panel that holds the marked text field is allocated here
713 // and released in dealloc. No pointer to the panel is kept, instead
714 // [markedTextField window] is used to access the panel.
715 NSPanel *panel = [[NSPanel alloc]
716 initWithContentRect:cellRect
717 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
718 backing:NSBackingStoreBuffered
721 //[panel setHidesOnDeactivate:NO];
722 [panel setFloatingPanel:YES];
723 [panel setBecomesKeyOnlyIfNeeded:YES];
724 [panel setContentView:markedTextField];
727 if (text && [text length] > 0) {
728 [markedTextField setFont:[ts font]];
729 if ([text isKindOfClass:[NSAttributedString class]])
730 [markedTextField setAttributedStringValue:text];
732 [markedTextField setStringValue:text];
734 [markedTextField sizeToFit];
735 NSSize size = [markedTextField frame].size;
737 // Convert coordinates (row,col) -> view -> window base -> screen
739 if (![self convertRow:preEditRow+1 column:preEditColumn
742 origin = [self convertPoint:origin toView:nil];
743 origin = [[self window] convertBaseToScreen:origin];
745 NSWindow *win = [markedTextField window];
746 [win setContentSize:size];
747 [win setFrameOrigin:origin];
748 [win orderFront:nil];
750 [self hideMarkedTextField];
756 //NSLog(@"%s", _cmd);
757 [self hideMarkedTextField];
760 - (NSRect)firstRectForCharacterRange:(NSRange)range
762 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
763 // HACK! This method is called when the input manager wants to pop up an
764 // auxiliary window. The position where this should be is controller by
765 // Vim by sending SetPreEditPositionMsgID so compute a position based on
766 // the pre-edit (row,column) pair.
767 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
769 NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
770 column:preEditColumn];
771 rect.origin.x += [self textContainerOrigin].x;
772 rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
774 rect.origin = [self convertPoint:rect.origin toView:nil];
775 rect.origin = [[self window] convertBaseToScreen:rect.origin];
780 - (void)scrollWheel:(NSEvent *)event
782 if ([event deltaY] == 0)
786 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
787 if (![self convertPoint:pt toRow:&row column:&col])
790 int flags = [event modifierFlags];
791 float dy = [event deltaY];
792 NSMutableData *data = [NSMutableData data];
794 [data appendBytes:&row length:sizeof(int)];
795 [data appendBytes:&col length:sizeof(int)];
796 [data appendBytes:&flags length:sizeof(int)];
797 [data appendBytes:&dy length:sizeof(float)];
799 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
802 - (void)mouseDown:(NSEvent *)event
805 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
806 if (![self convertPoint:pt toRow:&row column:&col])
809 lastMouseDownEvent = [event copy];
811 int button = [event buttonNumber];
812 int flags = [event modifierFlags];
813 int count = [event clickCount];
814 NSMutableData *data = [NSMutableData data];
816 // If desired, intepret Ctrl-Click as a right mouse click.
817 if ([[NSUserDefaults standardUserDefaults]
818 boolForKey:MMTranslateCtrlClickKey]
819 && button == 0 && flags & NSControlKeyMask) {
821 flags &= ~NSControlKeyMask;
824 [data appendBytes:&row length:sizeof(int)];
825 [data appendBytes:&col length:sizeof(int)];
826 [data appendBytes:&button length:sizeof(int)];
827 [data appendBytes:&flags length:sizeof(int)];
828 [data appendBytes:&count length:sizeof(int)];
830 [[self vimController] sendMessage:MouseDownMsgID data:data];
833 - (void)rightMouseDown:(NSEvent *)event
835 [self mouseDown:event];
838 - (void)otherMouseDown:(NSEvent *)event
840 [self mouseDown:event];
843 - (void)mouseUp:(NSEvent *)event
846 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
847 if (![self convertPoint:pt toRow:&row column:&col])
850 int flags = [event modifierFlags];
851 NSMutableData *data = [NSMutableData data];
853 [data appendBytes:&row length:sizeof(int)];
854 [data appendBytes:&col length:sizeof(int)];
855 [data appendBytes:&flags length:sizeof(int)];
857 [[self vimController] sendMessage:MouseUpMsgID data:data];
862 - (void)rightMouseUp:(NSEvent *)event
864 [self mouseUp:event];
867 - (void)otherMouseUp:(NSEvent *)event
869 [self mouseUp:event];
872 - (void)mouseDragged:(NSEvent *)event
874 int flags = [event modifierFlags];
876 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
877 if (![self convertPoint:pt toRow:&row column:&col])
880 // Autoscrolling is done in dragTimerFired:
881 if (!isAutoscrolling) {
882 NSMutableData *data = [NSMutableData data];
884 [data appendBytes:&row length:sizeof(int)];
885 [data appendBytes:&col length:sizeof(int)];
886 [data appendBytes:&flags length:sizeof(int)];
888 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
892 dragRow = row; dragColumn = col; dragFlags = flags;
894 [self startDragTimerWithInterval:.5];
899 - (void)rightMouseDragged:(NSEvent *)event
901 [self mouseDragged:event];
904 - (void)otherMouseDragged:(NSEvent *)event
906 [self mouseDragged:event];
909 - (void)mouseMoved:(NSEvent *)event
911 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
914 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
916 if (![self convertPoint:pt toRow:&row column:&col])
919 // HACK! It seems impossible to get the tracking rects set up before the
920 // view is visible, which means that the first mouseEntered: or
921 // mouseExited: events are never received. This forces us to check if the
922 // mouseMoved: event really happened over the text.
924 [ts getMaxRows:&rows columns:&cols];
925 if (row >= 0 && row < rows && col >= 0 && col < cols) {
926 NSMutableData *data = [NSMutableData data];
928 [data appendBytes:&row length:sizeof(int)];
929 [data appendBytes:&col length:sizeof(int)];
931 // NSTextView wants to set the cursor to an IBeam every now and then.
932 // Not even Apple's TextLinks example application works, so we set
933 // "our" cursor on every mouse move.
936 [[self vimController] sendMessage:MouseMovedMsgID data:data];
938 //NSLog(@"Moved %d %d\n", col, row);
942 - (void)mouseEntered:(NSEvent *)event
944 //NSLog(@"%s", _cmd);
946 // NOTE: This event is received even when the window is not key; thus we
947 // have to take care not to enable mouse moved events unless our window is
949 if ([[self window] isKeyWindow])
950 [[self window] setAcceptsMouseMovedEvents:YES];
953 - (void)mouseExited:(NSEvent *)event
955 //NSLog(@"%s", _cmd);
957 [[self window] setAcceptsMouseMovedEvents:NO];
959 // NOTE: This event is received even when the window is not key; if the
960 // mouse shape is set when our window is not key, the hollow (unfocused)
961 // cursor will become a block (focused) cursor.
962 if ([[self window] isKeyWindow]) {
964 NSMutableData *data = [NSMutableData data];
965 [data appendBytes:&shape length:sizeof(int)];
966 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
970 - (void)setFrame:(NSRect)frame
972 //NSLog(@"%s", _cmd);
974 // When the frame changes we also need to update the tracking rect.
975 [super setFrame:frame];
976 [self removeTrackingRect:trackingRectTag];
977 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
978 userData:NULL assumeInside:YES];
981 - (void)viewDidMoveToWindow
983 //NSLog(@"%s (window=%@)", _cmd, [self window]);
985 // Set a tracking rect which covers the text.
986 // NOTE: While the mouse cursor is in this rect the view will receive
987 // 'mouseMoved:' events so that Vim can take care of updating the mouse
990 [[self window] setAcceptsMouseMovedEvents:YES];
991 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
992 userData:NULL assumeInside:YES];
996 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
998 //NSLog(@"%s%@", _cmd, newWindow);
1000 // Remove tracking rect if view moves or is removed.
1001 if ([self window] && trackingRectTag) {
1002 [self removeTrackingRect:trackingRectTag];
1003 trackingRectTag = 0;
1007 - (NSMenu*)menuForEvent:(NSEvent *)event
1009 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
1010 // own). Called when user Ctrl-clicks in the view (this is already handled
1011 // in rightMouseDown:).
1015 - (NSArray *)acceptableDragTypes
1017 return [NSArray arrayWithObjects:NSFilenamesPboardType,
1018 NSStringPboardType, nil];
1021 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1023 NSPasteboard *pboard = [sender draggingPasteboard];
1025 if ([[pboard types] containsObject:NSStringPboardType]) {
1026 NSString *string = [pboard stringForType:NSStringPboardType];
1027 [[self vimController] dropString:string];
1029 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1030 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1031 [[self vimController] dropFiles:files forceOpen:NO];
1038 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1040 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1041 NSPasteboard *pboard = [sender draggingPasteboard];
1043 if ( [[pboard types] containsObject:NSFilenamesPboardType]
1044 && (sourceDragMask & NSDragOperationCopy) )
1045 return NSDragOperationCopy;
1046 if ( [[pboard types] containsObject:NSStringPboardType]
1047 && (sourceDragMask & NSDragOperationCopy) )
1048 return NSDragOperationCopy;
1050 return NSDragOperationNone;
1053 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1055 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1056 NSPasteboard *pboard = [sender draggingPasteboard];
1058 if ( [[pboard types] containsObject:NSFilenamesPboardType]
1059 && (sourceDragMask & NSDragOperationCopy) )
1060 return NSDragOperationCopy;
1061 if ( [[pboard types] containsObject:NSStringPboardType]
1062 && (sourceDragMask & NSDragOperationCopy) )
1063 return NSDragOperationCopy;
1065 return NSDragOperationNone;
1068 - (void)changeFont:(id)sender
1070 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1073 NSFont *oldFont = [ts font];
1074 NSFont *newFont = [sender convertFont:oldFont];
1077 NSString *name = [newFont displayName];
1078 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1080 NSMutableData *data = [NSMutableData data];
1081 float pointSize = [newFont pointSize];
1083 [data appendBytes:&pointSize length:sizeof(float)];
1085 ++len; // include NUL byte
1086 [data appendBytes:&len length:sizeof(unsigned)];
1087 [data appendBytes:[name UTF8String] length:len];
1089 [[self vimController] sendMessage:SetFontMsgID data:data];
1094 - (void)resetCursorRects
1096 // No need to set up cursor rects since Vim handles cursor changes.
1099 - (void)updateFontPanel
1101 // The font panel is updated whenever the font is set.
1104 - (void)setMouseShape:(int)shape
1115 @implementation MMTextView (Private)
1119 static NSCursor *customIbeamCursor = nil;
1121 if (!customIbeamCursor) {
1122 // Use a custom Ibeam cursor that has better contrast against dark
1124 // TODO: Is the hotspot ok?
1125 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1127 NSSize size = [ibeamImage size];
1128 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1130 customIbeamCursor = [[NSCursor alloc]
1131 initWithImage:ibeamImage hotSpot:hotSpot];
1133 if (!customIbeamCursor) {
1134 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
1135 customIbeamCursor = [NSCursor IBeamCursor];
1139 // This switch should match mshape_names[] in misc2.c.
1141 // TODO: Add missing cursor shapes.
1142 switch (mouseShape) {
1143 case 2: [customIbeamCursor set]; break;
1144 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1145 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1146 case 9: [[NSCursor crosshairCursor] set]; break;
1147 case 10: [[NSCursor pointingHandCursor] set]; break;
1148 case 11: [[NSCursor openHandCursor] set]; break;
1150 [[NSCursor arrowCursor] set]; break;
1153 // Shape 1 indicates that the mouse cursor should be hidden.
1154 if (1 == mouseShape)
1155 [NSCursor setHiddenUntilMouseMoves:YES];
1158 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1160 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1161 NSSize cellSize = [ts cellSize];
1162 if (!(cellSize.width > 0 && cellSize.height > 0))
1164 NSPoint origin = [self textContainerOrigin];
1166 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1167 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1169 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1175 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1177 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1178 NSSize cellSize = [ts cellSize];
1179 if (!(point && cellSize.width > 0 && cellSize.height > 0))
1182 *point = [self textContainerOrigin];
1183 point->x += column * cellSize.width;
1184 point->y += row * cellSize.height;
1189 - (NSRect)trackingRect
1191 NSRect rect = [self frame];
1192 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1193 int left = [ud integerForKey:MMTextInsetLeftKey];
1194 int top = [ud integerForKey:MMTextInsetTopKey];
1195 int right = [ud integerForKey:MMTextInsetRightKey];
1196 int bot = [ud integerForKey:MMTextInsetBottomKey];
1198 rect.origin.x = left;
1199 rect.origin.y = top;
1200 rect.size.width -= left + right - 1;
1201 rect.size.height -= top + bot - 1;
1206 - (void)dispatchKeyEvent:(NSEvent *)event
1208 // Only handle the command if it came from a keyDown event
1209 if ([event type] != NSKeyDown)
1212 NSString *chars = [event characters];
1213 NSString *unmodchars = [event charactersIgnoringModifiers];
1214 unichar c = [chars characterAtIndex:0];
1215 unichar imc = [unmodchars characterAtIndex:0];
1217 const char *bytes = 0;
1218 int mods = [event modifierFlags];
1220 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1221 // _cmd, c, imc, chars, unmodchars);
1223 if (' ' == imc && 0xa0 != c) {
1224 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
1225 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
1226 // should be passed on as is.)
1227 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1228 bytes = [unmodchars UTF8String];
1229 } else if (imc == c && '2' == c) {
1230 // HACK! Translate Ctrl+2 to <C-@>.
1231 static char ctrl_at = 0;
1232 len = 1; bytes = &ctrl_at;
1233 } else if (imc == c && '6' == c) {
1234 // HACK! Translate Ctrl+6 to <C-^>.
1235 static char ctrl_hat = 0x1e;
1236 len = 1; bytes = &ctrl_hat;
1237 } else if (c == 0x19 && imc == 0x19) {
1238 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1239 // separately (else Ctrl-Y doesn't work).
1240 static char tab = 0x9;
1241 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
1243 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1244 bytes = [chars UTF8String];
1247 [self sendKeyDown:bytes length:len modifiers:mods];
1250 - (MMVimController *)vimController
1252 id windowController = [[self window] windowController];
1254 // TODO: Make sure 'windowController' is a MMWindowController before type
1256 return [(MMWindowController*)windowController vimController];
1259 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1261 [NSTimer scheduledTimerWithTimeInterval:t target:self
1262 selector:@selector(dragTimerFired:)
1263 userInfo:nil repeats:NO];
1266 - (void)dragTimerFired:(NSTimer *)timer
1268 // TODO: Autoscroll in horizontal direction?
1269 static unsigned tick = 1;
1270 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1272 isAutoscrolling = NO;
1274 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1275 // HACK! If the mouse cursor is outside the text area, then send a
1276 // dragged event. However, if row&col hasn't changed since the last
1277 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1278 // Thus we fiddle with the column to make sure something happens.
1279 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1280 NSMutableData *data = [NSMutableData data];
1282 [data appendBytes:&dragRow length:sizeof(int)];
1283 [data appendBytes:&col length:sizeof(int)];
1284 [data appendBytes:&dragFlags length:sizeof(int)];
1286 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1288 isAutoscrolling = YES;
1292 // Compute timer interval depending on how far away the mouse cursor is
1293 // from the text view.
1294 NSRect rect = [self trackingRect];
1296 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1297 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1298 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1300 NSTimeInterval t = MMDragTimerMaxInterval -
1301 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1303 [self startDragTimerWithInterval:t];
1309 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1311 if (chars && len > 0) {
1312 NSMutableData *data = [NSMutableData data];
1314 [data appendBytes:&flags length:sizeof(int)];
1315 [data appendBytes:&len length:sizeof(int)];
1316 [data appendBytes:chars length:len];
1318 // TODO: Support 'mousehide' (check p_mh)
1319 [NSCursor setHiddenUntilMouseMoves:YES];
1321 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1322 [[self vimController] sendMessage:KeyDownMsgID data:data];
1326 @end // MMTextView (Private)