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"
25 #import "MMAppController.h"
30 // This is taken from gui.h
31 #define DRAW_CURSOR 0x20
33 // The max/min drag timer interval in seconds
34 static NSTimeInterval MMDragTimerMaxInterval = .3f;
35 static NSTimeInterval MMDragTimerMinInterval = .01f;
37 // The number of pixels in which the drag timer interval changes
38 static float MMDragAreaSize = 73.0f;
40 static char MMKeypadEnter[2] = { 'K', 'A' };
41 static NSString *MMKeypadEnterString = @"KA";
49 @interface MMTextView (Private)
51 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
52 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
53 - (NSRect)trackingRect;
54 - (void)dispatchKeyEvent:(NSEvent *)event;
55 - (MMWindowController *)windowController;
56 - (MMVimController *)vimController;
57 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
58 - (void)dragTimerFired:(NSTimer *)timer;
59 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
60 - (void)hideMouseCursor;
65 @implementation MMTextView
67 - (id)initWithFrame:(NSRect)frame
69 // Set up a Cocoa text system. Note that the textStorage is released in
70 // -[MMVimView dealloc].
71 MMTextStorage *textStorage = [[MMTextStorage alloc] init];
72 NSLayoutManager *lm = [[NSLayoutManager alloc] init];
73 NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
74 NSMakeSize(1.0e7,1.0e7)];
76 NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
77 stringForKey:MMTypesetterKey];
78 if ([typesetterString isEqual:@"MMTypesetter"]) {
79 NSTypesetter *typesetter = [[MMTypesetter alloc] init];
80 [lm setTypesetter:typesetter];
82 } else if ([typesetterString isEqual:@"MMTypesetter2"]) {
83 NSTypesetter *typesetter = [[MMTypesetter2 alloc] init];
84 [lm setTypesetter:typesetter];
87 // Only MMTypesetter supports different cell width multipliers.
88 [[NSUserDefaults standardUserDefaults]
89 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
92 // The characters in the text storage are in display order, so disable
93 // bidirectional text processing (this call is 10.4 only).
94 [[lm typesetter] setBidiProcessingEnabled:NO];
96 [tc setWidthTracksTextView:NO];
97 [tc setHeightTracksTextView:NO];
98 [tc setLineFragmentPadding:0];
100 [textStorage addLayoutManager:lm];
101 [lm addTextContainer:tc];
103 // The text storage retains the layout manager which in turn retains
104 // the text container.
108 // NOTE: This will make the text storage the principal owner of the text
109 // system. Releasing the text storage will in turn release the layout
110 // manager, the text container, and finally the text view (self). This
111 // complicates deallocation somewhat, see -[MMVimView dealloc].
112 if (![super initWithFrame:frame textContainer:tc]) {
113 [textStorage release];
117 // NOTE: If the default changes to 'NO' then the intialization of
118 // p_antialias in option.c must change as well.
125 //NSLog(@"MMTextView dealloc");
127 if (markedTextField) {
128 [[markedTextField window] autorelease];
129 [markedTextField release];
130 markedTextField = nil;
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);
331 - (void)setMouseShape:(int)shape
337 - (void)setAntialias:(BOOL)state
344 return [(MMTextStorage*)[self textStorage] font];
347 - (void)setFont:(NSFont *)newFont
349 [(MMTextStorage*)[self textStorage] setFont:newFont];
352 - (void)setWideFont:(NSFont *)newFont
354 [(MMTextStorage*)[self textStorage] setWideFont:newFont];
359 return [(MMTextStorage*)[self textStorage] cellSize];
362 - (void)setLinespace:(float)newLinespace
364 return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
367 - (void)getMaxRows:(int*)rows columns:(int*)cols
369 return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
372 - (void)setMaxRows:(int)rows columns:(int)cols
374 return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
377 - (NSRect)rectForRowsInRange:(NSRange)range
379 return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
382 - (NSRect)rectForColumnsInRange:(NSRange)range
384 return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
387 - (void)setDefaultColorsBackground:(NSColor *)bgColor
388 foreground:(NSColor *)fgColor
390 [self setBackgroundColor:bgColor];
391 return [(MMTextStorage*)[self textStorage]
392 setDefaultColorsBackground:bgColor foreground:fgColor];
395 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
397 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
398 int right = [ud integerForKey:MMTextInsetRightKey];
399 int bot = [ud integerForKey:MMTextInsetBottomKey];
401 size.width -= [self textContainerOrigin].x + right;
402 size.height -= [self textContainerOrigin].y + bot;
404 NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
408 newSize.width += [self textContainerOrigin].x + right;
409 newSize.height += [self textContainerOrigin].y + bot;
414 - (NSSize)desiredSize
416 NSSize size = [(MMTextStorage*)[self textStorage] size];
418 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
419 int right = [ud integerForKey:MMTextInsetRightKey];
420 int bot = [ud integerForKey:MMTextInsetBottomKey];
422 size.width += [self textContainerOrigin].x + right;
423 size.height += [self textContainerOrigin].y + bot;
430 NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
431 NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
433 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
434 int right = [ud integerForKey:MMTextInsetRightKey];
435 int bot = [ud integerForKey:MMTextInsetBottomKey];
437 size.width += [self textContainerOrigin].x + right;
438 size.height += [self textContainerOrigin].y + bot;
448 - (void)drawRect:(NSRect)rect
450 NSGraphicsContext *context = [NSGraphicsContext currentContext];
451 [context setShouldAntialias:antialias];
453 [super drawRect:rect];
455 if (shouldDrawInsertionPoint) {
456 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
458 NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
459 column:insertionPointColumn];
460 ipRect.origin.x += [self textContainerOrigin].x;
461 ipRect.origin.y += [self textContainerOrigin].y;
463 if (MMInsertionPointHorizontal == insertionPointShape) {
464 int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
465 ipRect.origin.y += ipRect.size.height - frac;
466 ipRect.size.height = frac;
467 } else if (MMInsertionPointVertical == insertionPointShape) {
468 int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
469 ipRect.size.width = frac;
470 } else if (MMInsertionPointVerticalRight == insertionPointShape) {
471 int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
472 ipRect.origin.x += ipRect.size.width - frac;
473 ipRect.size.width = frac;
476 [[self insertionPointColor] set];
477 if (MMInsertionPointHollow == insertionPointShape) {
483 // NOTE: We only draw the cursor once and rely on Vim to say when it
484 // should be drawn again.
485 shouldDrawInsertionPoint = NO;
487 //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
488 // NSStringFromRect(ipRect), insertionPointShape,
489 // [self insertionPointColor]);
492 // this code invalidates the shadow, so we don't
493 // get shifting ghost text on scroll and resize
494 // but makes speed unusable
495 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
496 if ([ts defaultBackgroundAlpha] < 1.0f) {
497 if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
499 [[self window] setHasShadow:NO];
500 [[self window] setHasShadow:YES];
503 [[self window] invalidateShadow];
509 - (void)keyDown:(NSEvent *)event
511 //NSLog(@"%s %@", _cmd, event);
512 // HACK! If control modifier is held, don't pass the event along to
513 // interpretKeyEvents: since some keys are bound to multiple commands which
514 // means doCommandBySelector: is called several times. Do the same for
515 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
516 // commands). This hack may break input management, but unless we can
517 // figure out a way to disable key bindings there seems little else to do.
519 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
520 // affecting input management.
521 int flags = [event modifierFlags];
522 if ((flags & NSControlKeyMask) ||
523 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
524 NSString *unmod = [event charactersIgnoringModifiers];
525 if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
526 && [unmod characterAtIndex:0] >= 0x60) {
527 // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
528 // as normal text to be added to the Vim input buffer. This must
529 // be done in order for the backend to be able to separate e.g.
530 // Ctrl-i and Ctrl-tab.
531 [self insertText:[event characters]];
533 [self dispatchKeyEvent:event];
536 [super keyDown:event];
540 - (void)insertText:(id)string
542 //NSLog(@"%s %@", _cmd, string);
543 // NOTE! This method is called for normal key presses but also for
544 // Option-key presses --- even when Ctrl is held as well as Option. When
545 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
546 // so 'string' need not be a printable character! In this case it still
547 // works to pass 'string' on to Vim as a printable character (since
548 // modifiers are already included and should not be added to the input
549 // buffer using CSI, K_MODIFIER).
551 [self hideMarkedTextField];
553 NSEvent *event = [NSApp currentEvent];
555 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
556 // to watch for them here.
557 if ([event type] == NSKeyDown
558 && [[event charactersIgnoringModifiers] length] > 0
559 && [event modifierFlags]
560 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
561 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
563 // <S-M-Tab> translates to 0x19
564 if (' ' == c || 0x19 == c) {
565 [self dispatchKeyEvent:event];
570 [self hideMouseCursor];
572 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
573 // do not support attributes, simply pass the corresponding NSString in the
575 if ([string isKindOfClass:[NSAttributedString class]])
576 string = [string string];
578 //NSLog(@"send InsertTextMsgID: %@", string);
580 [[self vimController] sendMessage:InsertTextMsgID
581 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
585 - (void)doCommandBySelector:(SEL)selector
587 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
588 // By ignoring the selector we effectively disable the key binding
589 // mechanism of Cocoa. Hopefully this is what the user will expect
590 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
593 // We usually end up here if the user pressed Ctrl+key (but not
596 NSEvent *event = [NSApp currentEvent];
598 if (selector == @selector(cancelOperation:)
599 || selector == @selector(insertNewline:)) {
600 // HACK! If there was marked text which got abandoned as a result of
601 // hitting escape or enter, then 'insertText:' is called with the
602 // abandoned text but '[event characters]' includes the abandoned text
603 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
604 // must intercept these keys here or the abandonded text gets inserted
606 NSString *key = [event charactersIgnoringModifiers];
607 const char *chars = [key UTF8String];
608 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
610 if (0x3 == chars[0]) {
611 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
612 // handle it separately (else Ctrl-C doesn't work).
613 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
614 chars = MMKeypadEnter;
617 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
619 [self dispatchKeyEvent:event];
623 - (BOOL)performKeyEquivalent:(NSEvent *)event
625 //NSLog(@"%s %@", _cmd, event);
626 // Called for Cmd+key keystrokes, function keys, arrow keys, page
627 // up/down, home, end.
629 // NOTE: This message cannot be ignored since Cmd+letter keys never are
630 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
631 // strokes, unless the key is a function key.
633 // NOTE: If the event that triggered this method represents a function key
634 // down then we do nothing, otherwise the input method never gets the key
635 // stroke (some input methods use e.g. arrow keys). The function key down
636 // event will still reach Vim though (via keyDown:). The exceptions to
637 // this rule are: PageUp/PageDown (keycode 116/121).
638 int flags = [event modifierFlags];
639 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
640 && !(116 == [event keyCode] || 121 == [event keyCode]))
643 // HACK! KeyCode 50 represent the key which switches between windows
644 // within an application (like Cmd+Tab is used to switch between
645 // applications). Return NO here, else the window switching does not work.
646 if ([event keyCode] == 50)
649 // HACK! Let the main menu try to handle any key down event, before
650 // passing it on to vim, otherwise key equivalents for menus will
651 // effectively be disabled.
652 if ([[NSApp mainMenu] performKeyEquivalent:event])
655 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
656 if (flags & NSControlKeyMask) {
657 [self keyDown:event];
661 //NSLog(@"%s%@", _cmd, event);
663 NSString *chars = [event characters];
664 NSString *unmodchars = [event charactersIgnoringModifiers];
665 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
666 NSMutableData *data = [NSMutableData data];
671 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
672 // can clear the shift flag as it is already included in 'unmodchars'.
673 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
674 // an English keyboard).
675 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
676 flags &= ~NSShiftKeyMask;
678 if (0x3 == [unmodchars characterAtIndex:0]) {
679 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
680 // handle it separately (else Cmd-enter turns into Ctrl-C).
681 unmodchars = MMKeypadEnterString;
682 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
685 [data appendBytes:&flags length:sizeof(int)];
686 [data appendBytes:&len length:sizeof(int)];
687 [data appendBytes:[unmodchars UTF8String] length:len];
689 [[self vimController] sendMessage:CmdKeyMsgID data:data];
694 - (BOOL)hasMarkedText
696 //NSLog(@"%s", _cmd);
697 return markedTextField && [[markedTextField stringValue] length] > 0;
700 - (NSRange)markedRange
702 //NSLog(@"%s", _cmd);
703 unsigned len = [[markedTextField stringValue] length];
704 return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
707 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
709 //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
710 // NSStringFromRange(range));
712 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
715 if (!markedTextField) {
716 // Create a text field and put it inside a floating panel. This field
717 // is used to display marked text.
718 NSSize cellSize = [ts cellSize];
719 NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
721 markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
722 [markedTextField setEditable:NO];
723 [markedTextField setSelectable:NO];
724 [markedTextField setBezeled:NO];
725 [markedTextField setBordered:YES];
727 // NOTE: The panel that holds the marked text field is allocated here
728 // and released in dealloc. No pointer to the panel is kept, instead
729 // [markedTextField window] is used to access the panel.
730 NSPanel *panel = [[NSPanel alloc]
731 initWithContentRect:cellRect
732 styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
733 backing:NSBackingStoreBuffered
736 //[panel setHidesOnDeactivate:NO];
737 [panel setFloatingPanel:YES];
738 [panel setBecomesKeyOnlyIfNeeded:YES];
739 [panel setContentView:markedTextField];
742 if (text && [text length] > 0) {
743 [markedTextField setFont:[ts font]];
744 if ([text isKindOfClass:[NSAttributedString class]])
745 [markedTextField setAttributedStringValue:text];
747 [markedTextField setStringValue:text];
749 [markedTextField sizeToFit];
750 NSSize size = [markedTextField frame].size;
752 // Convert coordinates (row,col) -> view -> window base -> screen
754 if (![self convertRow:preEditRow+1 column:preEditColumn
757 origin = [self convertPoint:origin toView:nil];
758 origin = [[self window] convertBaseToScreen:origin];
760 NSWindow *win = [markedTextField window];
761 [win setContentSize:size];
762 [win setFrameOrigin:origin];
763 [win orderFront:nil];
765 [self hideMarkedTextField];
771 //NSLog(@"%s", _cmd);
772 [self hideMarkedTextField];
775 - (NSRect)firstRectForCharacterRange:(NSRange)range
777 //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
778 // HACK! This method is called when the input manager wants to pop up an
779 // auxiliary window. The position where this should be is controller by
780 // Vim by sending SetPreEditPositionMsgID so compute a position based on
781 // the pre-edit (row,column) pair.
782 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
784 NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
785 column:preEditColumn];
786 rect.origin.x += [self textContainerOrigin].x;
787 rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
789 rect.origin = [self convertPoint:rect.origin toView:nil];
790 rect.origin = [[self window] convertBaseToScreen:rect.origin];
795 - (void)scrollWheel:(NSEvent *)event
797 if ([event deltaY] == 0)
801 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
802 if (![self convertPoint:pt toRow:&row column:&col])
805 int flags = [event modifierFlags];
806 float dy = [event deltaY];
807 NSMutableData *data = [NSMutableData data];
809 [data appendBytes:&row length:sizeof(int)];
810 [data appendBytes:&col length:sizeof(int)];
811 [data appendBytes:&flags length:sizeof(int)];
812 [data appendBytes:&dy length:sizeof(float)];
814 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
817 - (void)mouseDown:(NSEvent *)event
820 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
821 if (![self convertPoint:pt toRow:&row column:&col])
824 int button = [event buttonNumber];
825 int flags = [event modifierFlags];
826 int count = [event clickCount];
827 NSMutableData *data = [NSMutableData data];
829 // If desired, intepret Ctrl-Click as a right mouse click.
830 if ([[NSUserDefaults standardUserDefaults]
831 boolForKey:MMTranslateCtrlClickKey]
832 && button == 0 && flags & NSControlKeyMask) {
834 flags &= ~NSControlKeyMask;
837 [data appendBytes:&row length:sizeof(int)];
838 [data appendBytes:&col length:sizeof(int)];
839 [data appendBytes:&button length:sizeof(int)];
840 [data appendBytes:&flags length:sizeof(int)];
841 [data appendBytes:&count length:sizeof(int)];
843 [[self vimController] sendMessage:MouseDownMsgID data:data];
846 - (void)rightMouseDown:(NSEvent *)event
848 [self mouseDown:event];
851 - (void)otherMouseDown:(NSEvent *)event
853 [self mouseDown:event];
856 - (void)mouseUp:(NSEvent *)event
859 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
860 if (![self convertPoint:pt toRow:&row column:&col])
863 int flags = [event modifierFlags];
864 NSMutableData *data = [NSMutableData data];
866 [data appendBytes:&row length:sizeof(int)];
867 [data appendBytes:&col length:sizeof(int)];
868 [data appendBytes:&flags length:sizeof(int)];
870 [[self vimController] sendMessage:MouseUpMsgID data:data];
875 - (void)rightMouseUp:(NSEvent *)event
877 [self mouseUp:event];
880 - (void)otherMouseUp:(NSEvent *)event
882 [self mouseUp:event];
885 - (void)mouseDragged:(NSEvent *)event
887 int flags = [event modifierFlags];
889 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
890 if (![self convertPoint:pt toRow:&row column:&col])
893 // Autoscrolling is done in dragTimerFired:
894 if (!isAutoscrolling) {
895 NSMutableData *data = [NSMutableData data];
897 [data appendBytes:&row length:sizeof(int)];
898 [data appendBytes:&col length:sizeof(int)];
899 [data appendBytes:&flags length:sizeof(int)];
901 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
905 dragRow = row; dragColumn = col; dragFlags = flags;
907 [self startDragTimerWithInterval:.5];
912 - (void)rightMouseDragged:(NSEvent *)event
914 [self mouseDragged:event];
917 - (void)otherMouseDragged:(NSEvent *)event
919 [self mouseDragged:event];
922 - (void)mouseMoved:(NSEvent *)event
924 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
927 // HACK! NSTextView has a nasty habit of resetting the cursor to the
928 // default I-beam cursor at random moments. The only reliable way we know
929 // of to work around this is to set the cursor each time the mouse moves.
932 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
934 if (![self convertPoint:pt toRow:&row column:&col])
937 // HACK! It seems impossible to get the tracking rects set up before the
938 // view is visible, which means that the first mouseEntered: or
939 // mouseExited: events are never received. This forces us to check if the
940 // mouseMoved: event really happened over the text.
942 [ts getMaxRows:&rows columns:&cols];
943 if (row >= 0 && row < rows && col >= 0 && col < cols) {
944 NSMutableData *data = [NSMutableData data];
946 [data appendBytes:&row length:sizeof(int)];
947 [data appendBytes:&col length:sizeof(int)];
949 [[self vimController] sendMessage:MouseMovedMsgID data:data];
951 //NSLog(@"Moved %d %d\n", col, row);
955 - (void)mouseEntered:(NSEvent *)event
957 //NSLog(@"%s", _cmd);
959 // NOTE: This event is received even when the window is not key; thus we
960 // have to take care not to enable mouse moved events unless our window is
962 if ([[self window] isKeyWindow]) {
963 [[self window] setAcceptsMouseMovedEvents:YES];
967 - (void)mouseExited:(NSEvent *)event
969 //NSLog(@"%s", _cmd);
971 [[self window] setAcceptsMouseMovedEvents:NO];
973 // NOTE: This event is received even when the window is not key; if the
974 // mouse shape is set when our window is not key, the hollow (unfocused)
975 // cursor will become a block (focused) cursor.
976 if ([[self window] isKeyWindow]) {
978 NSMutableData *data = [NSMutableData data];
979 [data appendBytes:&shape length:sizeof(int)];
980 [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
984 - (void)setFrame:(NSRect)frame
986 //NSLog(@"%s", _cmd);
988 // When the frame changes we also need to update the tracking rect.
989 [super setFrame:frame];
990 [self removeTrackingRect:trackingRectTag];
991 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
992 userData:NULL assumeInside:YES];
995 - (void)viewDidMoveToWindow
997 //NSLog(@"%s (window=%@)", _cmd, [self window]);
999 // Set a tracking rect which covers the text.
1000 // NOTE: While the mouse cursor is in this rect the view will receive
1001 // 'mouseMoved:' events so that Vim can take care of updating the mouse
1003 if ([self window]) {
1004 [[self window] setAcceptsMouseMovedEvents:YES];
1005 trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
1006 userData:NULL assumeInside:YES];
1010 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
1012 //NSLog(@"%s%@", _cmd, newWindow);
1014 // Remove tracking rect if view moves or is removed.
1015 if ([self window] && trackingRectTag) {
1016 [self removeTrackingRect:trackingRectTag];
1017 trackingRectTag = 0;
1021 - (NSMenu*)menuForEvent:(NSEvent *)event
1023 // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
1024 // own). Called when user Ctrl-clicks in the view (this is already handled
1025 // in rightMouseDown:).
1029 - (NSArray *)acceptableDragTypes
1031 return [NSArray arrayWithObjects:NSFilenamesPboardType,
1032 NSStringPboardType, nil];
1035 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1037 NSPasteboard *pboard = [sender draggingPasteboard];
1039 if ([[pboard types] containsObject:NSStringPboardType]) {
1040 NSString *string = [pboard stringForType:NSStringPboardType];
1041 [[self vimController] dropString:string];
1043 } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1044 NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1045 [[self vimController] dropFiles:files forceOpen:NO];
1052 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1054 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1055 NSPasteboard *pboard = [sender draggingPasteboard];
1057 if ( [[pboard types] containsObject:NSFilenamesPboardType]
1058 && (sourceDragMask & NSDragOperationCopy) )
1059 return NSDragOperationCopy;
1060 if ( [[pboard types] containsObject:NSStringPboardType]
1061 && (sourceDragMask & NSDragOperationCopy) )
1062 return NSDragOperationCopy;
1064 return NSDragOperationNone;
1067 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1069 NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1070 NSPasteboard *pboard = [sender draggingPasteboard];
1072 if ( [[pboard types] containsObject:NSFilenamesPboardType]
1073 && (sourceDragMask & NSDragOperationCopy) )
1074 return NSDragOperationCopy;
1075 if ( [[pboard types] containsObject:NSStringPboardType]
1076 && (sourceDragMask & NSDragOperationCopy) )
1077 return NSDragOperationCopy;
1079 return NSDragOperationNone;
1082 - (void)changeFont:(id)sender
1084 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1087 NSFont *oldFont = [ts font];
1088 NSFont *newFont = [sender convertFont:oldFont];
1091 NSString *name = [newFont displayName];
1092 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1094 NSMutableData *data = [NSMutableData data];
1095 float pointSize = [newFont pointSize];
1097 [data appendBytes:&pointSize length:sizeof(float)];
1099 ++len; // include NUL byte
1100 [data appendBytes:&len length:sizeof(unsigned)];
1101 [data appendBytes:[name UTF8String] length:len];
1103 [[self vimController] sendMessage:SetFontMsgID data:data];
1108 - (void)resetCursorRects
1110 // No need to set up cursor rects since Vim handles cursor changes.
1113 - (void)updateFontPanel
1115 // The font panel is updated whenever the font is set.
1120 // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
1121 // to the same actions as in IB otherwise they will not work with dialogs. All
1122 // we do here is forward these actions to the Vim process.
1124 - (IBAction)cut:(id)sender
1126 [[self windowController] vimMenuItemAction:sender];
1129 - (IBAction)copy:(id)sender
1131 [[self windowController] vimMenuItemAction:sender];
1134 - (IBAction)paste:(id)sender
1136 [[self windowController] vimMenuItemAction:sender];
1139 - (IBAction)undo:(id)sender
1141 [[self windowController] vimMenuItemAction:sender];
1144 - (IBAction)redo:(id)sender
1146 [[self windowController] vimMenuItemAction:sender];
1149 - (IBAction)selectAll:(id)sender
1151 [[self windowController] vimMenuItemAction:sender];
1154 - (BOOL)validateMenuItem:(NSMenuItem *)item
1156 if ([item action] == @selector(cut:)
1157 || [item action] == @selector(copy:)
1158 || [item action] == @selector(paste:)
1159 || [item action] == @selector(undo:)
1160 || [item action] == @selector(redo:)
1161 || [item action] == @selector(selectAll:))
1171 @implementation MMTextView (Private)
1175 static NSCursor *customIbeamCursor = nil;
1177 if (!customIbeamCursor) {
1178 // Use a custom Ibeam cursor that has better contrast against dark
1180 // TODO: Is the hotspot ok?
1181 NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1183 NSSize size = [ibeamImage size];
1184 NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1186 customIbeamCursor = [[NSCursor alloc]
1187 initWithImage:ibeamImage hotSpot:hotSpot];
1189 if (!customIbeamCursor) {
1190 NSLog(@"WARNING: Failed to load custom Ibeam cursor");
1191 customIbeamCursor = [NSCursor IBeamCursor];
1195 // This switch should match mshape_names[] in misc2.c.
1197 // TODO: Add missing cursor shapes.
1198 switch (mouseShape) {
1199 case 2: [customIbeamCursor set]; break;
1200 case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1201 case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1202 case 9: [[NSCursor crosshairCursor] set]; break;
1203 case 10: [[NSCursor pointingHandCursor] set]; break;
1204 case 11: [[NSCursor openHandCursor] set]; break;
1206 [[NSCursor arrowCursor] set]; break;
1209 // Shape 1 indicates that the mouse cursor should be hidden.
1210 if (1 == mouseShape)
1211 [NSCursor setHiddenUntilMouseMoves:YES];
1214 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1216 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1217 NSSize cellSize = [ts cellSize];
1218 if (!(cellSize.width > 0 && cellSize.height > 0))
1220 NSPoint origin = [self textContainerOrigin];
1222 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1223 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1225 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1231 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1233 MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1234 NSSize cellSize = [ts cellSize];
1235 if (!(point && cellSize.width > 0 && cellSize.height > 0))
1238 *point = [self textContainerOrigin];
1239 point->x += column * cellSize.width;
1240 point->y += row * cellSize.height;
1245 - (NSRect)trackingRect
1247 NSRect rect = [self frame];
1248 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1249 int left = [ud integerForKey:MMTextInsetLeftKey];
1250 int top = [ud integerForKey:MMTextInsetTopKey];
1251 int right = [ud integerForKey:MMTextInsetRightKey];
1252 int bot = [ud integerForKey:MMTextInsetBottomKey];
1254 rect.origin.x = left;
1255 rect.origin.y = top;
1256 rect.size.width -= left + right - 1;
1257 rect.size.height -= top + bot - 1;
1262 - (void)dispatchKeyEvent:(NSEvent *)event
1264 // Only handle the command if it came from a keyDown event
1265 if ([event type] != NSKeyDown)
1268 NSString *chars = [event characters];
1269 NSString *unmodchars = [event charactersIgnoringModifiers];
1270 unichar c = [chars characterAtIndex:0];
1271 unichar imc = [unmodchars characterAtIndex:0];
1273 const char *bytes = 0;
1274 int mods = [event modifierFlags];
1276 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1277 // _cmd, c, imc, chars, unmodchars);
1279 if (' ' == imc && 0xa0 != c) {
1280 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
1281 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
1282 // should be passed on as is.)
1283 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1284 bytes = [unmodchars UTF8String];
1285 } else if (imc == c && '2' == c) {
1286 // HACK! Translate Ctrl+2 to <C-@>.
1287 static char ctrl_at = 0;
1288 len = 1; bytes = &ctrl_at;
1289 } else if (imc == c && '6' == c) {
1290 // HACK! Translate Ctrl+6 to <C-^>.
1291 static char ctrl_hat = 0x1e;
1292 len = 1; bytes = &ctrl_hat;
1293 } else if (c == 0x19 && imc == 0x19) {
1294 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1295 // separately (else Ctrl-Y doesn't work).
1296 static char tab = 0x9;
1297 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
1299 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1300 bytes = [chars UTF8String];
1303 [self sendKeyDown:bytes length:len modifiers:mods];
1306 - (MMWindowController *)windowController
1308 id windowController = [[self window] windowController];
1309 if ([windowController isKindOfClass:[MMWindowController class]])
1310 return (MMWindowController*)windowController;
1314 - (MMVimController *)vimController
1316 return [[self windowController] vimController];
1319 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1321 [NSTimer scheduledTimerWithTimeInterval:t target:self
1322 selector:@selector(dragTimerFired:)
1323 userInfo:nil repeats:NO];
1326 - (void)dragTimerFired:(NSTimer *)timer
1328 // TODO: Autoscroll in horizontal direction?
1329 static unsigned tick = 1;
1330 MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1332 isAutoscrolling = NO;
1334 if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1335 // HACK! If the mouse cursor is outside the text area, then send a
1336 // dragged event. However, if row&col hasn't changed since the last
1337 // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1338 // Thus we fiddle with the column to make sure something happens.
1339 int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1340 NSMutableData *data = [NSMutableData data];
1342 [data appendBytes:&dragRow length:sizeof(int)];
1343 [data appendBytes:&col length:sizeof(int)];
1344 [data appendBytes:&dragFlags length:sizeof(int)];
1346 [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1348 isAutoscrolling = YES;
1352 // Compute timer interval depending on how far away the mouse cursor is
1353 // from the text view.
1354 NSRect rect = [self trackingRect];
1356 if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1357 else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1358 if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1360 NSTimeInterval t = MMDragTimerMaxInterval -
1361 dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1363 [self startDragTimerWithInterval:t];
1369 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1371 if (chars && len > 0) {
1372 NSMutableData *data = [NSMutableData data];
1374 [data appendBytes:&flags length:sizeof(int)];
1375 [data appendBytes:&len length:sizeof(int)];
1376 [data appendBytes:chars length:len];
1378 [self hideMouseCursor];
1380 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1381 [[self vimController] sendMessage:KeyDownMsgID data:data];
1385 - (void)hideMouseCursor
1387 // Check 'mousehide' option
1388 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
1389 if (mh && ![mh boolValue])
1390 [NSCursor setHiddenUntilMouseMoves:NO];
1392 [NSCursor setHiddenUntilMouseMoves:YES];
1395 @end // MMTextView (Private)