Add file for misc code in frontend
[MacVim.git] / src / MacVim / MMTextView.m
blob965443efb8ae4d9a1c666aac7b5444c012315a9a
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
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.
9  */
11  * MMTextView
12  *
13  * Dispatches keyboard and mouse input to the backend.  Handles drag-n-drop of
14  * files onto window.
15  *
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).
18  */
20 #import "MMAppController.h"
21 #import "MMTextStorage.h"
22 #import "MMTextView.h"
23 #import "MMTypesetter.h"
24 #import "MMVimController.h"
25 #import "MMWindowController.h"
26 #import "Miscellaneous.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";
43 enum {
44     MMMinRows = 4,
45     MMMinColumns = 20
49 @interface MMTextView (Private)
50 - (void)setCursor;
51 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
52 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
53 - (BOOL)convertRow:(int)row column:(int)column numRows:(int)nr
54         numColumns:(int)nc toRect:(NSRect *)rect;
55 - (NSRect)trackingRect;
56 - (void)dispatchKeyEvent:(NSEvent *)event;
57 - (MMWindowController *)windowController;
58 - (MMVimController *)vimController;
59 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
60 - (void)dragTimerFired:(NSTimer *)timer;
61 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
62 - (void)hideMouseCursor;
63 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
64                        fraction:(int)percent color:(NSColor *)color;
65 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
66                    numColumns:(int)ncols invert:(int)invert;
67 @end
71 @implementation MMTextView
73 - (id)initWithFrame:(NSRect)frame
75     // Set up a Cocoa text system.  Note that the textStorage is released in
76     // -[MMVimView dealloc].
77     MMTextStorage *textStorage = [[MMTextStorage alloc] init];
78     NSLayoutManager *lm = [[NSLayoutManager alloc] init];
79     NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
80                     NSMakeSize(1.0e7,1.0e7)];
82     NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
83             stringForKey:MMTypesetterKey];
84     if ([typesetterString isEqual:@"MMTypesetter"]) {
85         NSTypesetter *typesetter = [[MMTypesetter alloc] init];
86         [lm setTypesetter:typesetter];
87         [typesetter release];
88     } else if ([typesetterString isEqual:@"MMTypesetter2"]) {
89         NSTypesetter *typesetter = [[MMTypesetter2 alloc] init];
90         [lm setTypesetter:typesetter];
91         [typesetter release];
92     } else {
93         // Only MMTypesetter supports different cell width multipliers.
94         [[NSUserDefaults standardUserDefaults]
95                 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
96     }
98     // The characters in the text storage are in display order, so disable
99     // bidirectional text processing (this call is 10.4 only).
100     [[lm typesetter] setBidiProcessingEnabled:NO];
102     [tc setWidthTracksTextView:NO];
103     [tc setHeightTracksTextView:NO];
104     [tc setLineFragmentPadding:0];
106     [textStorage addLayoutManager:lm];
107     [lm addTextContainer:tc];
109     // The text storage retains the layout manager which in turn retains
110     // the text container.
111     [tc autorelease];
112     [lm autorelease];
114     // NOTE: This will make the text storage the principal owner of the text
115     // system.  Releasing the text storage will in turn release the layout
116     // manager, the text container, and finally the text view (self).  This
117     // complicates deallocation somewhat, see -[MMVimView dealloc].
118     if (![super initWithFrame:frame textContainer:tc]) {
119         [textStorage release];
120         return nil;
121     }
123     // NOTE: If the default changes to 'NO' then the intialization of
124     // p_antialias in option.c must change as well.
125     antialias = YES;
126     return self;
129 - (void)dealloc
131     //NSLog(@"MMTextView dealloc");
133     if (markedTextField) {
134         [[markedTextField window] autorelease];
135         [markedTextField release];
136         markedTextField = nil;
137     }
139     if (invertRects) {
140         free(invertRects);
141         invertRects = NULL;
142         numInvertRects = 0;
143     }
145     [super dealloc];
148 - (BOOL)shouldDrawInsertionPoint
150     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
151     // nice to be able to use the insertion point related methods of
152     // NSTextView, but it seems impossible to get them to work properly (search
153     // the cocoabuilder archives).
154     return NO;
157 - (void)setShouldDrawInsertionPoint:(BOOL)on
159     shouldDrawInsertionPoint = on;
162 - (void)setPreEditRow:(int)row column:(int)col
164     preEditRow = row;
165     preEditColumn = col;
168 - (void)hideMarkedTextField
170     if (markedTextField) {
171         NSWindow *win = [markedTextField window];
172         [win close];
173         [markedTextField setStringValue:@""];
174     }
178 #define MM_DEBUG_DRAWING 0
180 - (void)performBatchDrawWithData:(NSData *)data
182     MMTextStorage *textStorage = (MMTextStorage *)[self textStorage];
183     if (!textStorage)
184         return;
186     const void *bytes = [data bytes];
187     const void *end = bytes + [data length];
188     int cursorRow = -1, cursorCol = 0;
190 #if MM_DEBUG_DRAWING
191     NSLog(@"====> BEGIN %s", _cmd);
192 #endif
193     [textStorage beginEditing];
195     // TODO: Sanity check input
197     while (bytes < end) {
198         int type = *((int*)bytes);  bytes += sizeof(int);
200         if (ClearAllDrawType == type) {
201 #if MM_DEBUG_DRAWING
202             NSLog(@"   Clear all");
203 #endif
204             [textStorage clearAll];
205         } else if (ClearBlockDrawType == type) {
206             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
207             int row1 = *((int*)bytes);  bytes += sizeof(int);
208             int col1 = *((int*)bytes);  bytes += sizeof(int);
209             int row2 = *((int*)bytes);  bytes += sizeof(int);
210             int col2 = *((int*)bytes);  bytes += sizeof(int);
212 #if MM_DEBUG_DRAWING
213             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
214                     row2,col2);
215 #endif
216             [textStorage clearBlockFromRow:row1 column:col1
217                     toRow:row2 column:col2
218                     color:[NSColor colorWithArgbInt:color]];
219         } else if (DeleteLinesDrawType == type) {
220             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
221             int row = *((int*)bytes);  bytes += sizeof(int);
222             int count = *((int*)bytes);  bytes += sizeof(int);
223             int bot = *((int*)bytes);  bytes += sizeof(int);
224             int left = *((int*)bytes);  bytes += sizeof(int);
225             int right = *((int*)bytes);  bytes += sizeof(int);
227 #if MM_DEBUG_DRAWING
228             NSLog(@"   Delete %d line(s) from %d", count, row);
229 #endif
230             [textStorage deleteLinesFromRow:row lineCount:count
231                     scrollBottom:bot left:left right:right
232                            color:[NSColor colorWithArgbInt:color]];
233         } else if (DrawStringDrawType == type) {
234             int bg = *((int*)bytes);  bytes += sizeof(int);
235             int fg = *((int*)bytes);  bytes += sizeof(int);
236             int sp = *((int*)bytes);  bytes += sizeof(int);
237             int row = *((int*)bytes);  bytes += sizeof(int);
238             int col = *((int*)bytes);  bytes += sizeof(int);
239             int cells = *((int*)bytes);  bytes += sizeof(int);
240             int flags = *((int*)bytes);  bytes += sizeof(int);
241             int len = *((int*)bytes);  bytes += sizeof(int);
242             NSString *string = [[NSString alloc]
243                     initWithBytes:(void*)bytes length:len
244                          encoding:NSUTF8StringEncoding];
245             bytes += len;
247 #if MM_DEBUG_DRAWING
248             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
249                     "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
250                     len > 0 ? [string substringToIndex:1] : @"");
251 #endif
252             // NOTE: If this is a call to draw the (block) cursor, then cancel
253             // any previous request to draw the insertion point, or it might
254             // get drawn as well.
255             if (flags & DRAW_CURSOR) {
256                 [self setShouldDrawInsertionPoint:NO];
257                 //NSColor *color = [NSColor colorWithRgbInt:bg];
258                 //[self drawInsertionPointAtRow:row column:col
259                 //                            shape:MMInsertionPointBlock
260                 //                            color:color];
261             }
263             [textStorage drawString:string
264                               atRow:row column:col cells:cells
265                           withFlags:flags
266                     foregroundColor:[NSColor colorWithRgbInt:fg]
267                     backgroundColor:[NSColor colorWithArgbInt:bg]
268                        specialColor:[NSColor colorWithRgbInt:sp]];
270             [string release];
271         } else if (InsertLinesDrawType == type) {
272             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
273             int row = *((int*)bytes);  bytes += sizeof(int);
274             int count = *((int*)bytes);  bytes += sizeof(int);
275             int bot = *((int*)bytes);  bytes += sizeof(int);
276             int left = *((int*)bytes);  bytes += sizeof(int);
277             int right = *((int*)bytes);  bytes += sizeof(int);
279 #if MM_DEBUG_DRAWING
280             NSLog(@"   Insert %d line(s) at row %d", count, row);
281 #endif
282             [textStorage insertLinesAtRow:row lineCount:count
283                              scrollBottom:bot left:left right:right
284                                     color:[NSColor colorWithArgbInt:color]];
285         } else if (DrawCursorDrawType == type) {
286             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
287             int row = *((int*)bytes);  bytes += sizeof(int);
288             int col = *((int*)bytes);  bytes += sizeof(int);
289             int shape = *((int*)bytes);  bytes += sizeof(int);
290             int percent = *((int*)bytes);  bytes += sizeof(int);
292 #if MM_DEBUG_DRAWING
293             NSLog(@"   Draw cursor at (%d,%d)", row, col);
294 #endif
295             [self drawInsertionPointAtRow:row column:col shape:shape
296                                      fraction:percent
297                                         color:[NSColor colorWithRgbInt:color]];
298         } else if (DrawInvertedRectDrawType == type) {
299             int row = *((int*)bytes);  bytes += sizeof(int);
300             int col = *((int*)bytes);  bytes += sizeof(int);
301             int nr = *((int*)bytes);  bytes += sizeof(int);
302             int nc = *((int*)bytes);  bytes += sizeof(int);
303             int invert = *((int*)bytes);  bytes += sizeof(int);
305 #if MM_DEBUG_DRAWING
306             NSLog(@"   Draw inverted rect: row=%d col=%d nrows=%d ncols=%d",
307                     row, col, nr, nc);
308 #endif
309             [self drawInvertedRectAtRow:row column:col numRows:nr numColumns:nc
310                                  invert:invert];
311         } else if (SetCursorPosDrawType == type) {
312             cursorRow = *((int*)bytes);  bytes += sizeof(int);
313             cursorCol = *((int*)bytes);  bytes += sizeof(int);
314         } else {
315             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
316         }
317     }
319     [textStorage endEditing];
321     if (cursorRow >= 0) {
322         unsigned off = [textStorage characterIndexForRow:cursorRow
323                                                   column:cursorCol];
324         unsigned maxoff = [[textStorage string] length];
325         if (off > maxoff) off = maxoff;
327         [self setSelectedRange:NSMakeRange(off, 0)];
328     }
330     // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
331     // and columns are changed (due to ipc delays). Force a redraw here.
332     [self displayIfNeeded];
334 #if MM_DEBUG_DRAWING
335     NSLog(@"<==== END   %s", _cmd);
336 #endif
339 - (void)setMouseShape:(int)shape
341     mouseShape = shape;
342     [self setCursor];
345 - (void)setAntialias:(BOOL)state
347     antialias = state;
350 - (NSFont *)font
352     return [(MMTextStorage*)[self textStorage] font];
355 - (void)setFont:(NSFont *)newFont
357     [(MMTextStorage*)[self textStorage] setFont:newFont];
360 - (void)setWideFont:(NSFont *)newFont
362     [(MMTextStorage*)[self textStorage] setWideFont:newFont];
365 - (NSSize)cellSize
367     return [(MMTextStorage*)[self textStorage] cellSize];
370 - (void)setLinespace:(float)newLinespace
372     return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
375 - (void)getMaxRows:(int*)rows columns:(int*)cols
377     return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
380 - (void)setMaxRows:(int)rows columns:(int)cols
382     return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
385 - (NSRect)rectForRowsInRange:(NSRange)range
387     return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
390 - (NSRect)rectForColumnsInRange:(NSRange)range
392     return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
395 - (void)setDefaultColorsBackground:(NSColor *)bgColor
396                         foreground:(NSColor *)fgColor
398     [self setBackgroundColor:bgColor];
399     return [(MMTextStorage*)[self textStorage]
400             setDefaultColorsBackground:bgColor foreground:fgColor];
403 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
405     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
406     int right = [ud integerForKey:MMTextInsetRightKey];
407     int bot = [ud integerForKey:MMTextInsetBottomKey];
409     size.width -= [self textContainerOrigin].x + right;
410     size.height -= [self textContainerOrigin].y + bot;
412     NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
413                                                               rows:rows
414                                                            columns:cols];
416     newSize.width += [self textContainerOrigin].x + right;
417     newSize.height += [self textContainerOrigin].y + bot;
419     return newSize;
422 - (NSSize)desiredSize
424     NSSize size = [(MMTextStorage*)[self textStorage] size];
426     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
427     int right = [ud integerForKey:MMTextInsetRightKey];
428     int bot = [ud integerForKey:MMTextInsetBottomKey];
430     size.width += [self textContainerOrigin].x + right;
431     size.height += [self textContainerOrigin].y + bot;
433     return size;
436 - (NSSize)minSize
438     NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
439     NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
441     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
442     int right = [ud integerForKey:MMTextInsetRightKey];
443     int bot = [ud integerForKey:MMTextInsetBottomKey];
445     size.width += [self textContainerOrigin].x + right;
446     size.height += [self textContainerOrigin].y + bot;
448     return size;
451 - (BOOL)isOpaque
453     return NO;
456 - (void)drawRect:(NSRect)rect
458     NSGraphicsContext *context = [NSGraphicsContext currentContext];
459     [context setShouldAntialias:antialias];
461     [super drawRect:rect];
463     if (invertRects) {
464         CGContextRef cgctx = (CGContextRef)[context graphicsPort];
465         CGContextSaveGState(cgctx);
466         CGContextSetBlendMode(cgctx, kCGBlendModeDifference);
467         CGContextSetRGBFillColor(cgctx, 1.0, 1.0, 1.0, 1.0);
469         int i;
470         CGRect *rect = (CGRect*)invertRects;
471         for (i = 0; i < numInvertRects; ++i)
472             CGContextFillRect(cgctx, rect[i]);
474         CGContextRestoreGState(cgctx);
476         free(invertRects);
477         invertRects = NULL;
478         numInvertRects = 0;
479     }
481     if (shouldDrawInsertionPoint) {
482         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
484         NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
485                                                    column:insertionPointColumn];
486         ipRect.origin.x += [self textContainerOrigin].x;
487         ipRect.origin.y += [self textContainerOrigin].y;
489         if (MMInsertionPointHorizontal == insertionPointShape) {
490             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
491             ipRect.origin.y += ipRect.size.height - frac;
492             ipRect.size.height = frac;
493         } else if (MMInsertionPointVertical == insertionPointShape) {
494             int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
495             ipRect.size.width = frac;
496         } else if (MMInsertionPointVerticalRight == insertionPointShape) {
497             int frac = ([ts cellSize].width * insertionPointFraction + 99)/100;
498             ipRect.origin.x += ipRect.size.width - frac;
499             ipRect.size.width = frac;
500         }
502         [[self insertionPointColor] set];
503         if (MMInsertionPointHollow == insertionPointShape) {
504             NSFrameRect(ipRect);
505         } else {
506             NSRectFill(ipRect);
507         }
509         // NOTE: We only draw the cursor once and rely on Vim to say when it
510         // should be drawn again.
511         shouldDrawInsertionPoint = NO;
513         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
514         //        NSStringFromRect(ipRect), insertionPointShape,
515         //        [self insertionPointColor]);
516     }
517 #if 0
518     // this code invalidates the shadow, so we don't 
519     // get shifting ghost text on scroll and resize
520     // but makes speed unusable
521     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
522     if ([ts defaultBackgroundAlpha] < 1.0f) {
523         if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
524         {
525             [[self window] setHasShadow:NO];
526             [[self window] setHasShadow:YES];
527         }
528         else
529             [[self window] invalidateShadow];
531     }
532 #endif
535 - (void)keyDown:(NSEvent *)event
537     //NSLog(@"%s %@", _cmd, event);
538     // HACK! If control modifier is held, don't pass the event along to
539     // interpretKeyEvents: since some keys are bound to multiple commands which
540     // means doCommandBySelector: is called several times.  Do the same for
541     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
542     // commands).  This hack may break input management, but unless we can
543     // figure out a way to disable key bindings there seems little else to do.
544     //
545     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
546     // affecting input management.
547     int flags = [event modifierFlags];
548     if ((flags & NSControlKeyMask) ||
549             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
550         NSString *unmod = [event charactersIgnoringModifiers];
551         if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
552                                 && [unmod characterAtIndex:0] >= 0x60) {
553             // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
554             // as normal text to be added to the Vim input buffer.  This must
555             // be done in order for the backend to be able to separate e.g.
556             // Ctrl-i and Ctrl-tab.
557             [self insertText:[event characters]];
558         } else {
559             [self dispatchKeyEvent:event];
560         }
561     } else {
562         [super keyDown:event];
563     }
566 - (void)insertText:(id)string
568     //NSLog(@"%s %@", _cmd, string);
569     // NOTE!  This method is called for normal key presses but also for
570     // Option-key presses --- even when Ctrl is held as well as Option.  When
571     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
572     // so 'string' need not be a printable character!  In this case it still
573     // works to pass 'string' on to Vim as a printable character (since
574     // modifiers are already included and should not be added to the input
575     // buffer using CSI, K_MODIFIER).
577     [self hideMarkedTextField];
579     NSEvent *event = [NSApp currentEvent];
581     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
582     // to watch for them here.
583     if ([event type] == NSKeyDown
584             && [[event charactersIgnoringModifiers] length] > 0
585             && [event modifierFlags]
586                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
587         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
589         // <S-M-Tab> translates to 0x19 
590         if (' ' == c || 0x19 == c) {
591             [self dispatchKeyEvent:event];
592             return;
593         }
594     }
596     [self hideMouseCursor];
598     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
599     // do not support attributes, simply pass the corresponding NSString in the
600     // latter case.
601     if ([string isKindOfClass:[NSAttributedString class]])
602         string = [string string];
604     //NSLog(@"send InsertTextMsgID: %@", string);
606     [[self vimController] sendMessage:InsertTextMsgID
607                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
611 - (void)doCommandBySelector:(SEL)selector
613     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
614     // By ignoring the selector we effectively disable the key binding
615     // mechanism of Cocoa.  Hopefully this is what the user will expect
616     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
617     // match, etc.).
618     //
619     // We usually end up here if the user pressed Ctrl+key (but not
620     // Ctrl+Option+key).
622     NSEvent *event = [NSApp currentEvent];
624     if (selector == @selector(cancelOperation:)
625             || selector == @selector(insertNewline:)) {
626         // HACK! If there was marked text which got abandoned as a result of
627         // hitting escape or enter, then 'insertText:' is called with the
628         // abandoned text but '[event characters]' includes the abandoned text
629         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
630         // must intercept these keys here or the abandonded text gets inserted
631         // twice.
632         NSString *key = [event charactersIgnoringModifiers];
633         const char *chars = [key UTF8String];
634         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
636         if (0x3 == chars[0]) {
637             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
638             // handle it separately (else Ctrl-C doesn't work).
639             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
640             chars = MMKeypadEnter;
641         }
643         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
644     } else {
645         [self dispatchKeyEvent:event];
646     }
649 - (BOOL)performKeyEquivalent:(NSEvent *)event
651     //NSLog(@"%s %@", _cmd, event);
652     // Called for Cmd+key keystrokes, function keys, arrow keys, page
653     // up/down, home, end.
654     //
655     // NOTE: This message cannot be ignored since Cmd+letter keys never are
656     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
657     // strokes, unless the key is a function key.
659     // NOTE: If the event that triggered this method represents a function key
660     // down then we do nothing, otherwise the input method never gets the key
661     // stroke (some input methods use e.g. arrow keys).  The function key down
662     // event will still reach Vim though (via keyDown:).  The exceptions to
663     // this rule are: PageUp/PageDown (keycode 116/121).
664     int flags = [event modifierFlags];
665     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
666             && !(116 == [event keyCode] || 121 == [event keyCode]))
667         return NO;
669     // HACK!  KeyCode 50 represent the key which switches between windows
670     // within an application (like Cmd+Tab is used to switch between
671     // applications).  Return NO here, else the window switching does not work.
672     if ([event keyCode] == 50)
673         return NO;
675     // HACK!  Let the main menu try to handle any key down event, before
676     // passing it on to vim, otherwise key equivalents for menus will
677     // effectively be disabled.
678     if ([[NSApp mainMenu] performKeyEquivalent:event])
679         return YES;
681     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
682     if (flags & NSControlKeyMask) {
683         [self keyDown:event];
684         return YES;
685     }
687     //NSLog(@"%s%@", _cmd, event);
689     NSString *chars = [event characters];
690     NSString *unmodchars = [event charactersIgnoringModifiers];
691     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
692     NSMutableData *data = [NSMutableData data];
694     if (len <= 0)
695         return NO;
697     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
698     // can clear the shift flag as it is already included in 'unmodchars'.
699     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
700     // an English keyboard).
701     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
702         flags &= ~NSShiftKeyMask;
704     if (0x3 == [unmodchars characterAtIndex:0]) {
705         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
706         // handle it separately (else Cmd-enter turns into Ctrl-C).
707         unmodchars = MMKeypadEnterString;
708         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
709     }
711     [data appendBytes:&flags length:sizeof(int)];
712     [data appendBytes:&len length:sizeof(int)];
713     [data appendBytes:[unmodchars UTF8String] length:len];
715     [[self vimController] sendMessage:CmdKeyMsgID data:data];
717     return YES;
720 - (BOOL)hasMarkedText
722     //NSLog(@"%s", _cmd);
723     return markedTextField && [[markedTextField stringValue] length] > 0;
726 - (NSRange)markedRange
728     //NSLog(@"%s", _cmd);
729     unsigned len = [[markedTextField stringValue] length];
730     return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
733 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
735     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
736     //        NSStringFromRange(range));
738     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
739     if (!ts) return;
741     if (!markedTextField) {
742         // Create a text field and put it inside a floating panel.  This field
743         // is used to display marked text.
744         NSSize cellSize = [ts cellSize];
745         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
747         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
748         [markedTextField setEditable:NO];
749         [markedTextField setSelectable:NO];
750         [markedTextField setBezeled:NO];
751         [markedTextField setBordered:YES];
753         // NOTE: The panel that holds the marked text field is allocated here
754         // and released in dealloc.  No pointer to the panel is kept, instead
755         // [markedTextField window] is used to access the panel.
756         NSPanel *panel = [[NSPanel alloc]
757             initWithContentRect:cellRect
758                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
759                         backing:NSBackingStoreBuffered
760                           defer:YES];
762         //[panel setHidesOnDeactivate:NO];
763         [panel setFloatingPanel:YES];
764         [panel setBecomesKeyOnlyIfNeeded:YES];
765         [panel setContentView:markedTextField];
766     }
768     if (text && [text length] > 0) {
769         [markedTextField setFont:[ts font]];
770         if ([text isKindOfClass:[NSAttributedString class]])
771             [markedTextField setAttributedStringValue:text];
772         else
773             [markedTextField setStringValue:text];
775         [markedTextField sizeToFit];
776         NSSize size = [markedTextField frame].size;
778         // Convert coordinates (row,col) -> view -> window base -> screen
779         NSPoint origin;
780         if (![self convertRow:preEditRow+1 column:preEditColumn
781                      toPoint:&origin])
782             return;
783         origin = [self convertPoint:origin toView:nil];
784         origin = [[self window] convertBaseToScreen:origin];
786         NSWindow *win = [markedTextField window];
787         [win setContentSize:size];
788         [win setFrameOrigin:origin];
789         [win orderFront:nil];
790     } else {
791         [self hideMarkedTextField];
792     }
795 - (void)unmarkText
797     //NSLog(@"%s", _cmd);
798     [self hideMarkedTextField];
801 - (NSRect)firstRectForCharacterRange:(NSRange)range
803     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
804     // HACK!  This method is called when the input manager wants to pop up an
805     // auxiliary window.  The position where this should be is controller by
806     // Vim by sending SetPreEditPositionMsgID so compute a position based on
807     // the pre-edit (row,column) pair.
808     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
810     NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
811                                              column:preEditColumn];
812     rect.origin.x += [self textContainerOrigin].x;
813     rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
815     rect.origin = [self convertPoint:rect.origin toView:nil];
816     rect.origin = [[self window] convertBaseToScreen:rect.origin];
818     return rect;
821 - (void)scrollWheel:(NSEvent *)event
823     if ([event deltaY] == 0)
824         return;
826     int row, col;
827     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
828     if (![self convertPoint:pt toRow:&row column:&col])
829         return;
831     int flags = [event modifierFlags];
832     float dy = [event deltaY];
833     NSMutableData *data = [NSMutableData data];
835     [data appendBytes:&row length:sizeof(int)];
836     [data appendBytes:&col length:sizeof(int)];
837     [data appendBytes:&flags length:sizeof(int)];
838     [data appendBytes:&dy length:sizeof(float)];
840     [[self vimController] sendMessage:ScrollWheelMsgID data:data];
843 - (void)mouseDown:(NSEvent *)event
845     int row, col;
846     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
847     if (![self convertPoint:pt toRow:&row column:&col])
848         return;
850     int button = [event buttonNumber];
851     int flags = [event modifierFlags];
852     int count = [event clickCount];
853     NSMutableData *data = [NSMutableData data];
855     // If desired, intepret Ctrl-Click as a right mouse click.
856     BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults]
857             boolForKey:MMTranslateCtrlClickKey];
858     flags = flags & NSDeviceIndependentModifierFlagsMask;
859     if (translateCtrlClick && button == 0 &&
860             (flags == NSControlKeyMask ||
861              flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) {
862         button = 1;
863         flags &= ~NSControlKeyMask;
864     }
866     [data appendBytes:&row length:sizeof(int)];
867     [data appendBytes:&col length:sizeof(int)];
868     [data appendBytes:&button length:sizeof(int)];
869     [data appendBytes:&flags length:sizeof(int)];
870     [data appendBytes:&count length:sizeof(int)];
872     [[self vimController] sendMessage:MouseDownMsgID data:data];
875 - (void)rightMouseDown:(NSEvent *)event
877     [self mouseDown:event];
880 - (void)otherMouseDown:(NSEvent *)event
882     [self mouseDown:event];
885 - (void)mouseUp:(NSEvent *)event
887     int row, col;
888     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
889     if (![self convertPoint:pt toRow:&row column:&col])
890         return;
892     int flags = [event modifierFlags];
893     NSMutableData *data = [NSMutableData data];
895     [data appendBytes:&row length:sizeof(int)];
896     [data appendBytes:&col length:sizeof(int)];
897     [data appendBytes:&flags length:sizeof(int)];
899     [[self vimController] sendMessage:MouseUpMsgID data:data];
901     isDragging = NO;
904 - (void)rightMouseUp:(NSEvent *)event
906     [self mouseUp:event];
909 - (void)otherMouseUp:(NSEvent *)event
911     [self mouseUp:event];
914 - (void)mouseDragged:(NSEvent *)event
916     int flags = [event modifierFlags];
917     int row, col;
918     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
919     if (![self convertPoint:pt toRow:&row column:&col])
920         return;
922     // Autoscrolling is done in dragTimerFired:
923     if (!isAutoscrolling) {
924         NSMutableData *data = [NSMutableData data];
926         [data appendBytes:&row length:sizeof(int)];
927         [data appendBytes:&col length:sizeof(int)];
928         [data appendBytes:&flags length:sizeof(int)];
930         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
931     }
933     dragPoint = pt;
934     dragRow = row; dragColumn = col; dragFlags = flags;
935     if (!isDragging) {
936         [self startDragTimerWithInterval:.5];
937         isDragging = YES;
938     }
941 - (void)rightMouseDragged:(NSEvent *)event
943     [self mouseDragged:event];
946 - (void)otherMouseDragged:(NSEvent *)event
948     [self mouseDragged:event];
951 - (void)mouseMoved:(NSEvent *)event
953     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
954     if (!ts) return;
956     // HACK! NSTextView has a nasty habit of resetting the cursor to the
957     // default I-beam cursor at random moments.  The only reliable way we know
958     // of to work around this is to set the cursor each time the mouse moves.
959     [self setCursor];
961     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
962     int row, col;
963     if (![self convertPoint:pt toRow:&row column:&col])
964         return;
966     // HACK! It seems impossible to get the tracking rects set up before the
967     // view is visible, which means that the first mouseEntered: or
968     // mouseExited: events are never received.  This forces us to check if the
969     // mouseMoved: event really happened over the text.
970     int rows, cols;
971     [ts getMaxRows:&rows columns:&cols];
972     if (row >= 0 && row < rows && col >= 0 && col < cols) {
973         NSMutableData *data = [NSMutableData data];
975         [data appendBytes:&row length:sizeof(int)];
976         [data appendBytes:&col length:sizeof(int)];
978         [[self vimController] sendMessage:MouseMovedMsgID data:data];
980         //NSLog(@"Moved %d %d\n", col, row);
981     }
984 - (void)mouseEntered:(NSEvent *)event
986     //NSLog(@"%s", _cmd);
988     // NOTE: This event is received even when the window is not key; thus we
989     // have to take care not to enable mouse moved events unless our window is
990     // key.
991     if ([[self window] isKeyWindow]) {
992         [[self window] setAcceptsMouseMovedEvents:YES];
993     }
996 - (void)mouseExited:(NSEvent *)event
998     //NSLog(@"%s", _cmd);
1000     [[self window] setAcceptsMouseMovedEvents:NO];
1002     // NOTE: This event is received even when the window is not key; if the
1003     // mouse shape is set when our window is not key, the hollow (unfocused)
1004     // cursor will become a block (focused) cursor.
1005     if ([[self window] isKeyWindow]) {
1006         int shape = 0;
1007         NSMutableData *data = [NSMutableData data];
1008         [data appendBytes:&shape length:sizeof(int)];
1009         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
1010     }
1013 - (void)setFrame:(NSRect)frame
1015     //NSLog(@"%s", _cmd);
1017     // When the frame changes we also need to update the tracking rect.
1018     [super setFrame:frame];
1019     [self removeTrackingRect:trackingRectTag];
1020     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
1021                                    userData:NULL assumeInside:YES];
1024 - (void)viewDidMoveToWindow
1026     //NSLog(@"%s (window=%@)", _cmd, [self window]);
1028     // Set a tracking rect which covers the text.
1029     // NOTE: While the mouse cursor is in this rect the view will receive
1030     // 'mouseMoved:' events so that Vim can take care of updating the mouse
1031     // cursor.
1032     if ([self window]) {
1033         [[self window] setAcceptsMouseMovedEvents:YES];
1034         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
1035                                        userData:NULL assumeInside:YES];
1036     }
1039 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
1041     //NSLog(@"%s%@", _cmd, newWindow);
1043     // Remove tracking rect if view moves or is removed.
1044     if ([self window] && trackingRectTag) {
1045         [self removeTrackingRect:trackingRectTag];
1046         trackingRectTag = 0;
1047     }
1050 - (NSMenu*)menuForEvent:(NSEvent *)event
1052     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
1053     // own).  Called when user Ctrl-clicks in the view (this is already handled
1054     // in rightMouseDown:).
1055     return nil;
1058 - (NSArray *)acceptableDragTypes
1060     return [NSArray arrayWithObjects:NSFilenamesPboardType,
1061            NSStringPboardType, nil];
1064 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1066     NSPasteboard *pboard = [sender draggingPasteboard];
1068     if ([[pboard types] containsObject:NSStringPboardType]) {
1069         NSString *string = [pboard stringForType:NSStringPboardType];
1070         [[self vimController] dropString:string];
1071         return YES;
1072     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1073         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1074         [[self vimController] dropFiles:files forceOpen:NO];
1075         return YES;
1076     }
1078     return NO;
1081 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1083     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1084     NSPasteboard *pboard = [sender draggingPasteboard];
1086     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1087             && (sourceDragMask & NSDragOperationCopy) )
1088         return NSDragOperationCopy;
1089     if ( [[pboard types] containsObject:NSStringPboardType]
1090             && (sourceDragMask & NSDragOperationCopy) )
1091         return NSDragOperationCopy;
1093     return NSDragOperationNone;
1096 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1098     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1099     NSPasteboard *pboard = [sender draggingPasteboard];
1101     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1102             && (sourceDragMask & NSDragOperationCopy) )
1103         return NSDragOperationCopy;
1104     if ( [[pboard types] containsObject:NSStringPboardType]
1105             && (sourceDragMask & NSDragOperationCopy) )
1106         return NSDragOperationCopy;
1108     return NSDragOperationNone;
1111 - (void)changeFont:(id)sender
1113     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1114     if (!ts) return;
1116     NSFont *oldFont = [ts font];
1117     NSFont *newFont = [sender convertFont:oldFont];
1119     if (newFont) {
1120         NSString *name = [newFont displayName];
1121         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1122         if (len > 0) {
1123             NSMutableData *data = [NSMutableData data];
1124             float pointSize = [newFont pointSize];
1126             [data appendBytes:&pointSize length:sizeof(float)];
1128             ++len;  // include NUL byte
1129             [data appendBytes:&len length:sizeof(unsigned)];
1130             [data appendBytes:[name UTF8String] length:len];
1132             [[self vimController] sendMessage:SetFontMsgID data:data];
1133         }
1134     }
1137 - (void)resetCursorRects
1139     // No need to set up cursor rects since Vim handles cursor changes.
1142 - (void)updateFontPanel
1144     // The font panel is updated whenever the font is set.
1149 // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
1150 // to the same actions as in IB otherwise they will not work with dialogs.  All
1151 // we do here is forward these actions to the Vim process.
1153 - (IBAction)cut:(id)sender
1155     [[self windowController] vimMenuItemAction:sender];
1158 - (IBAction)copy:(id)sender
1160     [[self windowController] vimMenuItemAction:sender];
1163 - (IBAction)paste:(id)sender
1165     [[self windowController] vimMenuItemAction:sender];
1168 - (IBAction)undo:(id)sender
1170     [[self windowController] vimMenuItemAction:sender];
1173 - (IBAction)redo:(id)sender
1175     [[self windowController] vimMenuItemAction:sender];
1178 - (IBAction)selectAll:(id)sender
1180     [[self windowController] vimMenuItemAction:sender];
1183 - (BOOL)validateMenuItem:(NSMenuItem *)item
1185     if ([item action] == @selector(cut:)
1186             || [item action] == @selector(copy:)
1187             || [item action] == @selector(paste:)
1188             || [item action] == @selector(undo:)
1189             || [item action] == @selector(redo:)
1190             || [item action] == @selector(selectAll:))
1191         return [item tag];
1193     return YES;
1195 @end // MMTextView
1200 @implementation MMTextView (Private)
1202 - (void)setCursor
1204     static NSCursor *customIbeamCursor = nil;
1206     if (!customIbeamCursor) {
1207         // Use a custom Ibeam cursor that has better contrast against dark
1208         // backgrounds.
1209         // TODO: Is the hotspot ok?
1210         NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"];
1211         if (ibeamImage) {
1212             NSSize size = [ibeamImage size];
1213             NSPoint hotSpot = { size.width*.5f, size.height*.5f };
1215             customIbeamCursor = [[NSCursor alloc]
1216                     initWithImage:ibeamImage hotSpot:hotSpot];
1217         }
1218         if (!customIbeamCursor) {
1219             NSLog(@"WARNING: Failed to load custom Ibeam cursor");
1220             customIbeamCursor = [NSCursor IBeamCursor];
1221         }
1222     }
1224     // This switch should match mshape_names[] in misc2.c.
1225     //
1226     // TODO: Add missing cursor shapes.
1227     switch (mouseShape) {
1228         case 2: [customIbeamCursor set]; break;
1229         case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break;
1230         case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break;
1231         case 9: [[NSCursor crosshairCursor] set]; break;
1232         case 10: [[NSCursor pointingHandCursor] set]; break;
1233         case 11: [[NSCursor openHandCursor] set]; break;
1234         default:
1235             [[NSCursor arrowCursor] set]; break;
1236     }
1238     // Shape 1 indicates that the mouse cursor should be hidden.
1239     if (1 == mouseShape)
1240         [NSCursor setHiddenUntilMouseMoves:YES];
1243 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1245     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1246     NSSize cellSize = [ts cellSize];
1247     if (!(cellSize.width > 0 && cellSize.height > 0))
1248         return NO;
1249     NSPoint origin = [self textContainerOrigin];
1251     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1252     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1254     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1255     //        *row, *column);
1257     return YES;
1260 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1262     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1263     NSSize cellSize = [ts cellSize];
1264     if (!(point && cellSize.width > 0 && cellSize.height > 0))
1265         return NO;
1267     *point = [self textContainerOrigin];
1268     point->x += column * cellSize.width;
1269     point->y += row * cellSize.height;
1271     return YES;
1274 - (BOOL)convertRow:(int)row column:(int)column numRows:(int)nr
1275         numColumns:(int)nc toRect:(NSRect *)rect
1277     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1278     NSSize cellSize = [ts cellSize];
1279     if (!(rect && cellSize.width > 0 && cellSize.height > 0))
1280         return NO;
1282     rect->origin = [self textContainerOrigin];
1283     rect->origin.x += column * cellSize.width;
1284     rect->origin.y += row * cellSize.height;
1285     rect->size.width = cellSize.width * nc;
1286     rect->size.height = cellSize.height * nr;
1288     return YES;
1291 - (NSRect)trackingRect
1293     NSRect rect = [self frame];
1294     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1295     int left = [ud integerForKey:MMTextInsetLeftKey];
1296     int top = [ud integerForKey:MMTextInsetTopKey];
1297     int right = [ud integerForKey:MMTextInsetRightKey];
1298     int bot = [ud integerForKey:MMTextInsetBottomKey];
1300     rect.origin.x = left;
1301     rect.origin.y = top;
1302     rect.size.width -= left + right - 1;
1303     rect.size.height -= top + bot - 1;
1305     return rect;
1308 - (void)dispatchKeyEvent:(NSEvent *)event
1310     // Only handle the command if it came from a keyDown event
1311     if ([event type] != NSKeyDown)
1312         return;
1314     NSString *chars = [event characters];
1315     NSString *unmodchars = [event charactersIgnoringModifiers];
1316     unichar c = [chars characterAtIndex:0];
1317     unichar imc = [unmodchars characterAtIndex:0];
1318     int len = 0;
1319     const char *bytes = 0;
1320     int mods = [event modifierFlags];
1322     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1323     //        _cmd, c, imc, chars, unmodchars);
1325     if (' ' == imc && 0xa0 != c) {
1326         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
1327         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
1328         // should be passed on as is.)
1329         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1330         bytes = [unmodchars UTF8String];
1331     } else if (imc == c && '2' == c) {
1332         // HACK!  Translate Ctrl+2 to <C-@>.
1333         static char ctrl_at = 0;
1334         len = 1;  bytes = &ctrl_at;
1335     } else if (imc == c && '6' == c) {
1336         // HACK!  Translate Ctrl+6 to <C-^>.
1337         static char ctrl_hat = 0x1e;
1338         len = 1;  bytes = &ctrl_hat;
1339     } else if (c == 0x19 && imc == 0x19) {
1340         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1341         // separately (else Ctrl-Y doesn't work).
1342         static char tab = 0x9;
1343         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
1344     } else {
1345         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1346         bytes = [chars UTF8String];
1347     }
1349     [self sendKeyDown:bytes length:len modifiers:mods];
1352 - (MMWindowController *)windowController
1354     id windowController = [[self window] windowController];
1355     if ([windowController isKindOfClass:[MMWindowController class]])
1356         return (MMWindowController*)windowController;
1357     return nil;
1360 - (MMVimController *)vimController
1362     return [[self windowController] vimController];
1365 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1367     [NSTimer scheduledTimerWithTimeInterval:t target:self
1368                                    selector:@selector(dragTimerFired:)
1369                                    userInfo:nil repeats:NO];
1372 - (void)dragTimerFired:(NSTimer *)timer
1374     // TODO: Autoscroll in horizontal direction?
1375     static unsigned tick = 1;
1376     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1378     isAutoscrolling = NO;
1380     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1381         // HACK! If the mouse cursor is outside the text area, then send a
1382         // dragged event.  However, if row&col hasn't changed since the last
1383         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1384         // Thus we fiddle with the column to make sure something happens.
1385         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1386         NSMutableData *data = [NSMutableData data];
1388         [data appendBytes:&dragRow length:sizeof(int)];
1389         [data appendBytes:&col length:sizeof(int)];
1390         [data appendBytes:&dragFlags length:sizeof(int)];
1392         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1394         isAutoscrolling = YES;
1395     }
1397     if (isDragging) {
1398         // Compute timer interval depending on how far away the mouse cursor is
1399         // from the text view.
1400         NSRect rect = [self trackingRect];
1401         float dy = 0;
1402         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1403         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1404         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1406         NSTimeInterval t = MMDragTimerMaxInterval -
1407             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1409         [self startDragTimerWithInterval:t];
1410     }
1412     ++tick;
1415 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1417     if (chars && len > 0) {
1418         NSMutableData *data = [NSMutableData data];
1420         [data appendBytes:&flags length:sizeof(int)];
1421         [data appendBytes:&len length:sizeof(int)];
1422         [data appendBytes:chars length:len];
1424         [self hideMouseCursor];
1426         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1427         [[self vimController] sendMessage:KeyDownMsgID data:data];
1428     }
1431 - (void)hideMouseCursor
1433     // Check 'mousehide' option
1434     id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
1435     if (mh && ![mh boolValue])
1436         [NSCursor setHiddenUntilMouseMoves:NO];
1437     else
1438         [NSCursor setHiddenUntilMouseMoves:YES];
1441 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
1442                        fraction:(int)percent color:(NSColor *)color
1444     //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
1445     //        row, col, shape, color);
1447     // This only stores where to draw the insertion point, the actual drawing
1448     // is done in drawRect:.
1449     shouldDrawInsertionPoint = YES;
1450     insertionPointRow = row;
1451     insertionPointColumn = col;
1452     insertionPointShape = shape;
1453     insertionPointFraction = percent;
1455     [self setInsertionPointColor:color];
1458 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
1459                    numColumns:(int)ncols invert:(int)invert
1461     if (invert) {
1462         // The result should be inverted.
1463         int n = numInvertRects++;
1464         invertRects = reallocf(invertRects,
1465                                numInvertRects*sizeof(NSRect));
1466         if (NULL != invertRects) {
1467             [self convertRow:row column:col numRows:nrows numColumns:ncols
1468                       toRect:&invertRects[n]];
1469             [self setNeedsDisplayInRect:invertRects[n]];
1470         } else {
1471             n = numInvertRects = 0;
1472         }
1473     } else {
1474         // The result should look normal; all we need to do is to mark
1475         // the rect for redrawing and Cocoa will redraw the text.
1476         NSRect rect;
1477         [self convertRow:row column:col numRows:nrows numColumns:ncols
1478                   toRect:&rect];
1479         [self setNeedsDisplayInRect:rect];
1480     }
1483 @end // MMTextView (Private)