File->Close sends performClose:
[MacVim.git] / src / MacVim / MMTextView.m
blob3d7df765c028a5f8fa63812f0794d78c94666cf5
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 "MMTextView.h"
21 #import "MMTextStorage.h"
22 #import "MMWindowController.h"
23 #import "MMVimController.h"
24 #import "MMTypesetter.h"
25 #import "MacVim.h"
29 // This is taken from gui.h
30 #define DRAW_CURSOR 0x20
32 // The max/min drag timer interval in seconds
33 static NSTimeInterval MMDragTimerMaxInterval = .3f;
34 static NSTimeInterval MMDragTimerMinInterval = .01f;
36 // The number of pixels in which the drag timer interval changes
37 static float MMDragAreaSize = 73.0f;
39 static char MMKeypadEnter[2] = { 'K', 'A' };
40 static NSString *MMKeypadEnterString = @"KA";
42 enum {
43     MMMinRows = 4,
44     MMMinColumns = 20
48 @interface MMTextView (Private)
49 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
50 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
51 - (NSRect)trackingRect;
52 - (void)dispatchKeyEvent:(NSEvent *)event;
53 - (MMVimController *)vimController;
54 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
55 - (void)dragTimerFired:(NSTimer *)timer;
56 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
57 @end
61 @implementation MMTextView
63 - (id)initWithFrame:(NSRect)frame
65     // Set up a Cocoa text system.  Note that the textStorage is released in
66     // -[MMVimView dealloc].
67     MMTextStorage *textStorage = [[MMTextStorage alloc] init];
68     NSLayoutManager *lm = [[NSLayoutManager alloc] init];
69     NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
70                     NSMakeSize(1.0e7,1.0e7)];
72     NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
73             stringForKey:MMTypesetterKey];
74     if ([typesetterString isEqual:@"MMTypesetter"]) {
75         NSTypesetter *typesetter = [[MMTypesetter alloc] init];
76         [lm setTypesetter:typesetter];
77         [typesetter release];
78     } else if ([typesetterString isEqual:@"MMTypesetter2"]) {
79         NSTypesetter *typesetter = [[MMTypesetter2 alloc] init];
80         [lm setTypesetter:typesetter];
81         [typesetter release];
82     } else {
83         // Only MMTypesetter supports different cell width multipliers.
84         [[NSUserDefaults standardUserDefaults]
85                 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
86     }
88     // The characters in the text storage are in display order, so disable
89     // bidirectional text processing (this call is 10.4 only).
90     [[lm typesetter] setBidiProcessingEnabled:NO];
92     [tc setWidthTracksTextView:NO];
93     [tc setHeightTracksTextView:NO];
94     [tc setLineFragmentPadding:0];
96     [textStorage addLayoutManager:lm];
97     [lm addTextContainer:tc];
99     // The text storage retains the layout manager which in turn retains
100     // the text container.
101     [tc release];
102     [lm release];
104     // NOTE: This will make the text storage the principal owner of the text
105     // system.  Releasing the text storage will in turn release the layout
106     // manager, the text container, and finally the text view (self).  This
107     // complicates deallocation somewhat, see -[MMVimView dealloc].
108     if (![super initWithFrame:frame textContainer:tc]) {
109         [textStorage release];
110         return nil;
111     }
113     // Allow control of text view inset via MMTextInset* user defaults.
114     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
115     int left = [ud integerForKey:MMTextInsetLeftKey];
116     int top = [ud integerForKey:MMTextInsetTopKey];
117     [self setTextContainerInset:NSMakeSize(left, top)];
119     return self;
122 - (void)dealloc
124     //NSLog(@"MMTextView dealloc");
126     if (markedTextField) {
127         [[markedTextField window] autorelease];
128         [markedTextField release];
129         markedTextField = nil;
130     }
132     [lastMouseDownEvent release];
133     [super dealloc];
136 - (NSEvent *)lastMouseDownEvent
138     return lastMouseDownEvent;
141 - (BOOL)shouldDrawInsertionPoint
143     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
144     // nice to be able to use the insertion point related methods of
145     // NSTextView, but it seems impossible to get them to work properly (search
146     // the cocoabuilder archives).
147     return NO;
150 - (void)setShouldDrawInsertionPoint:(BOOL)on
152     shouldDrawInsertionPoint = on;
155 - (void)setPreEditRow:(int)row column:(int)col
157     preEditRow = row;
158     preEditColumn = col;
161 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
162                        fraction:(int)percent color:(NSColor *)color
164     //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
165     //        row, col, shape, color);
167     // This only stores where to draw the insertion point, the actual drawing
168     // is done in drawRect:.
169     shouldDrawInsertionPoint = YES;
170     insertionPointRow = row;
171     insertionPointColumn = col;
172     insertionPointShape = shape;
173     insertionPointFraction = percent;
175     [self setInsertionPointColor:color];
178 - (void)hideMarkedTextField
180     if (markedTextField) {
181         NSWindow *win = [markedTextField window];
182         [win close];
183         [markedTextField setStringValue:@""];
184     }
188 #define MM_DEBUG_DRAWING 0
190 - (void)performBatchDrawWithData:(NSData *)data
192     MMTextStorage *textStorage = (MMTextStorage *)[self textStorage];
193     if (!textStorage)
194         return;
196     const void *bytes = [data bytes];
197     const void *end = bytes + [data length];
199 #if MM_DEBUG_DRAWING
200     NSLog(@"====> BEGIN %s", _cmd);
201 #endif
202     [textStorage beginEditing];
204     // TODO: Sanity check input
206     while (bytes < end) {
207         int type = *((int*)bytes);  bytes += sizeof(int);
209         if (ClearAllDrawType == type) {
210 #if MM_DEBUG_DRAWING
211             NSLog(@"   Clear all");
212 #endif
213             [textStorage clearAll];
214         } else if (ClearBlockDrawType == type) {
215             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
216             int row1 = *((int*)bytes);  bytes += sizeof(int);
217             int col1 = *((int*)bytes);  bytes += sizeof(int);
218             int row2 = *((int*)bytes);  bytes += sizeof(int);
219             int col2 = *((int*)bytes);  bytes += sizeof(int);
221 #if MM_DEBUG_DRAWING
222             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
223                     row2,col2);
224 #endif
225             [textStorage clearBlockFromRow:row1 column:col1
226                     toRow:row2 column:col2
227                     color:[NSColor colorWithArgbInt:color]];
228         } else if (DeleteLinesDrawType == type) {
229             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
230             int row = *((int*)bytes);  bytes += sizeof(int);
231             int count = *((int*)bytes);  bytes += sizeof(int);
232             int bot = *((int*)bytes);  bytes += sizeof(int);
233             int left = *((int*)bytes);  bytes += sizeof(int);
234             int right = *((int*)bytes);  bytes += sizeof(int);
236 #if MM_DEBUG_DRAWING
237             NSLog(@"   Delete %d line(s) from %d", count, row);
238 #endif
239             [textStorage deleteLinesFromRow:row lineCount:count
240                     scrollBottom:bot left:left right:right
241                            color:[NSColor colorWithArgbInt:color]];
242         } else if (DrawStringDrawType == type) {
243             int bg = *((int*)bytes);  bytes += sizeof(int);
244             int fg = *((int*)bytes);  bytes += sizeof(int);
245             int sp = *((int*)bytes);  bytes += sizeof(int);
246             int row = *((int*)bytes);  bytes += sizeof(int);
247             int col = *((int*)bytes);  bytes += sizeof(int);
248             int cells = *((int*)bytes);  bytes += sizeof(int);
249             int flags = *((int*)bytes);  bytes += sizeof(int);
250             int len = *((int*)bytes);  bytes += sizeof(int);
251             NSString *string = [[NSString alloc]
252                     initWithBytesNoCopy:(void*)bytes
253                                  length:len
254                                encoding:NSUTF8StringEncoding
255                            freeWhenDone:NO];
256             bytes += len;
258 #if MM_DEBUG_DRAWING
259             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
260                     "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
261                     len > 0 ? [string substringToIndex:1] : @"");
262 #endif
263             // NOTE: If this is a call to draw the (block) cursor, then cancel
264             // any previous request to draw the insertion point, or it might
265             // get drawn as well.
266             if (flags & DRAW_CURSOR) {
267                 [self setShouldDrawInsertionPoint:NO];
268                 //NSColor *color = [NSColor colorWithRgbInt:bg];
269                 //[self drawInsertionPointAtRow:row column:col
270                 //                            shape:MMInsertionPointBlock
271                 //                            color:color];
272             }
274             [textStorage drawString:string
275                               atRow:row column:col cells:cells
276                           withFlags:flags
277                     foregroundColor:[NSColor colorWithRgbInt:fg]
278                     backgroundColor:[NSColor colorWithArgbInt:bg]
279                        specialColor:[NSColor colorWithRgbInt:sp]];
281             [string release];
282         } else if (InsertLinesDrawType == type) {
283             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
284             int row = *((int*)bytes);  bytes += sizeof(int);
285             int count = *((int*)bytes);  bytes += sizeof(int);
286             int bot = *((int*)bytes);  bytes += sizeof(int);
287             int left = *((int*)bytes);  bytes += sizeof(int);
288             int right = *((int*)bytes);  bytes += sizeof(int);
290 #if MM_DEBUG_DRAWING
291             NSLog(@"   Insert %d line(s) at row %d", count, row);
292 #endif
293             [textStorage insertLinesAtRow:row lineCount:count
294                              scrollBottom:bot left:left right:right
295                                     color:[NSColor colorWithArgbInt:color]];
296         } else if (DrawCursorDrawType == type) {
297             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
298             int row = *((int*)bytes);  bytes += sizeof(int);
299             int col = *((int*)bytes);  bytes += sizeof(int);
300             int shape = *((int*)bytes);  bytes += sizeof(int);
301             int percent = *((int*)bytes);  bytes += sizeof(int);
303 #if MM_DEBUG_DRAWING
304             NSLog(@"   Draw cursor at (%d,%d)", row, col);
305 #endif
306             [self drawInsertionPointAtRow:row column:col shape:shape
307                                      fraction:percent
308                                         color:[NSColor colorWithRgbInt:color]];
309         } else {
310             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
311         }
312     }
314     [textStorage endEditing];
316     // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
317     // and columns are changed (due to ipc delays). Force a redraw here.
318     [self displayIfNeeded];
320 #if MM_DEBUG_DRAWING
321     NSLog(@"<==== END   %s", _cmd);
322 #endif
325 - (NSFont *)font
327     return [(MMTextStorage*)[self textStorage] font];
330 - (void)setFont:(NSFont *)newFont
332     [(MMTextStorage*)[self textStorage] setFont:newFont];
335 - (void)setWideFont:(NSFont *)newFont
337     [(MMTextStorage*)[self textStorage] setWideFont:newFont];
340 - (NSSize)cellSize
342     return [(MMTextStorage*)[self textStorage] cellSize];
345 - (void)setLinespace:(float)newLinespace
347     return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
350 - (void)getMaxRows:(int*)rows columns:(int*)cols
352     return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
355 - (void)setMaxRows:(int)rows columns:(int)cols
357     return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
360 - (NSRect)rectForRowsInRange:(NSRange)range
362     return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
365 - (NSRect)rectForColumnsInRange:(NSRange)range
367     return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
370 - (void)setDefaultColorsBackground:(NSColor *)bgColor
371                         foreground:(NSColor *)fgColor
373     [self setBackgroundColor:bgColor];
374     return [(MMTextStorage*)[self textStorage]
375             setDefaultColorsBackground:bgColor foreground:fgColor];
378 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
380     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
381     int right = [ud integerForKey:MMTextInsetRightKey];
382     int bot = [ud integerForKey:MMTextInsetBottomKey];
384     size.width -= [self textContainerOrigin].x + right;
385     size.height -= [self textContainerOrigin].y + bot;
387     NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
388                                                               rows:rows
389                                                            columns:cols];
391     newSize.width += [self textContainerOrigin].x + right;
392     newSize.height += [self textContainerOrigin].y + bot;
394     return newSize;
397 - (NSSize)desiredSize
399     NSSize size = [(MMTextStorage*)[self textStorage] size];
401     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
402     int right = [ud integerForKey:MMTextInsetRightKey];
403     int bot = [ud integerForKey:MMTextInsetBottomKey];
405     size.width += [self textContainerOrigin].x + right;
406     size.height += [self textContainerOrigin].y + bot;
408     return size;
411 - (NSSize)minSize
413     NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
414     NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
416     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
417     int right = [ud integerForKey:MMTextInsetRightKey];
418     int bot = [ud integerForKey:MMTextInsetBottomKey];
420     size.width += [self textContainerOrigin].x + right;
421     size.height += [self textContainerOrigin].y + bot;
423     return size;
426 - (BOOL)isOpaque
428     return NO;
431 - (void)drawRect:(NSRect)rect
433     [super drawRect:rect];
435     if (shouldDrawInsertionPoint) {
436         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
438         NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
439                                                    column:insertionPointColumn];
440         ipRect.origin.x += [self textContainerOrigin].x;
441         ipRect.origin.y += [self textContainerOrigin].y;
443         if (MMInsertionPointHorizontal == insertionPointShape) {
444             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
445             ipRect.origin.y += ipRect.size.height - frac;
446             ipRect.size.height = frac;
447         } else if (MMInsertionPointVertical == insertionPointShape) {
448             int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
449             ipRect.size.width = frac;
450         }
452         [[self insertionPointColor] set];
453         if (MMInsertionPointHollow == insertionPointShape) {
454             NSFrameRect(ipRect);
455         } else {
456             NSRectFill(ipRect);
457         }
459         // NOTE: We only draw the cursor once and rely on Vim to say when it
460         // should be drawn again.
461         shouldDrawInsertionPoint = NO;
463         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
464         //        NSStringFromRect(ipRect), insertionPointShape,
465         //        [self insertionPointColor]);
466     }
467 #if 0
468     // this code invalidates the shadow, so we don't 
469     // get shifting ghost text on scroll and resize
470     // but makes speed unusable
471     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
472     if ([ts defaultBackgroundAlpha] < 1.0f) {
473         if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
474         {
475             [[self window] setHasShadow:NO];
476             [[self window] setHasShadow:YES];
477         }
478         else
479             [[self window] invalidateShadow];
481     }
482 #endif
485 - (void)keyDown:(NSEvent *)event
487     //NSLog(@"%s %@", _cmd, event);
488     // HACK! If control modifier is held, don't pass the event along to
489     // interpretKeyEvents: since some keys are bound to multiple commands which
490     // means doCommandBySelector: is called several times.  Do the same for
491     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
492     // commands).  This hack may break input management, but unless we can
493     // figure out a way to disable key bindings there seems little else to do.
494     //
495     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
496     // affecting input management.
497     int flags = [event modifierFlags];
498     if ((flags & NSControlKeyMask) ||
499             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
500         NSString *unmod = [event charactersIgnoringModifiers];
501         if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
502                                 && [unmod characterAtIndex:0] >= 0x60) {
503             // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
504             // as normal text to be added to the Vim input buffer.  This must
505             // be done in order for the backend to be able to separate e.g.
506             // Ctrl-i and Ctrl-tab.
507             [self insertText:[event characters]];
508         } else {
509             [self dispatchKeyEvent:event];
510         }
511     } else {
512         [super keyDown:event];
513     }
516 - (void)insertText:(id)string
518     //NSLog(@"%s %@", _cmd, string);
519     // NOTE!  This method is called for normal key presses but also for
520     // Option-key presses --- even when Ctrl is held as well as Option.  When
521     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
522     // so 'string' need not be a printable character!  In this case it still
523     // works to pass 'string' on to Vim as a printable character (since
524     // modifiers are already included and should not be added to the input
525     // buffer using CSI, K_MODIFIER).
527     [self hideMarkedTextField];
529     NSEvent *event = [NSApp currentEvent];
531     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
532     // to watch for them here.
533     if ([event type] == NSKeyDown
534             && [[event charactersIgnoringModifiers] length] > 0
535             && [event modifierFlags]
536                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
537         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
539         // <S-M-Tab> translates to 0x19 
540         if (' ' == c || 0x19 == c) {
541             [self dispatchKeyEvent:event];
542             return;
543         }
544     }
546     // TODO: Support 'mousehide' (check p_mh)
547     [NSCursor setHiddenUntilMouseMoves:YES];
549     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
550     // do not support attributes, simply pass the corresponding NSString in the
551     // latter case.
552     if ([string isKindOfClass:[NSAttributedString class]])
553         string = [string string];
555     //NSLog(@"send InsertTextMsgID: %@", string);
557     [[self vimController] sendMessage:InsertTextMsgID
558                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
562 - (void)doCommandBySelector:(SEL)selector
564     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
565     // By ignoring the selector we effectively disable the key binding
566     // mechanism of Cocoa.  Hopefully this is what the user will expect
567     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
568     // match, etc.).
569     //
570     // We usually end up here if the user pressed Ctrl+key (but not
571     // Ctrl+Option+key).
573     NSEvent *event = [NSApp currentEvent];
575     if (selector == @selector(cancelOperation:)
576             || selector == @selector(insertNewline:)) {
577         // HACK! If there was marked text which got abandoned as a result of
578         // hitting escape or enter, then 'insertText:' is called with the
579         // abandoned text but '[event characters]' includes the abandoned text
580         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
581         // must intercept these keys here or the abandonded text gets inserted
582         // twice.
583         NSString *key = [event charactersIgnoringModifiers];
584         const char *chars = [key UTF8String];
585         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
587         if (0x3 == chars[0]) {
588             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
589             // handle it separately (else Ctrl-C doesn't work).
590             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
591             chars = MMKeypadEnter;
592         }
594         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
595     } else {
596         [self dispatchKeyEvent:event];
597     }
600 - (BOOL)performKeyEquivalent:(NSEvent *)event
602     //NSLog(@"%s %@", _cmd, event);
603     // Called for Cmd+key keystrokes, function keys, arrow keys, page
604     // up/down, home, end.
605     //
606     // NOTE: This message cannot be ignored since Cmd+letter keys never are
607     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
608     // strokes, unless the key is a function key.
610     // NOTE: If the event that triggered this method represents a function key
611     // down then we do nothing, otherwise the input method never gets the key
612     // stroke (some input methods use e.g. arrow keys).  The function key down
613     // event will still reach Vim though (via keyDown:).  The exceptions to
614     // this rule are: PageUp/PageDown (keycode 116/121).
615     int flags = [event modifierFlags];
616     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
617             && !(116 == [event keyCode] || 121 == [event keyCode]))
618         return NO;
620     // HACK!  Let the main menu try to handle any key down event, before
621     // passing it on to vim, otherwise key equivalents for menus will
622     // effectively be disabled.
623     if ([[NSApp mainMenu] performKeyEquivalent:event])
624         return YES;
626     // HACK!  KeyCode 50 represent the key which switches between windows
627     // within an application (like Cmd+Tab is used to switch between
628     // applications).  Return NO here, else the window switching does not work.
629     //
630     // Will this hack work for all languages / keyboard layouts?
631     if ([event keyCode] == 50)
632         return NO;
634     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
635     if (flags & NSControlKeyMask) {
636         [self keyDown:event];
637         return YES;
638     }
640     //NSLog(@"%s%@", _cmd, event);
642     NSString *chars = [event characters];
643     NSString *unmodchars = [event charactersIgnoringModifiers];
644     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
645     NSMutableData *data = [NSMutableData data];
647     if (len <= 0)
648         return NO;
650     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
651     // can clear the shift flag as it is already included in 'unmodchars'.
652     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
653     // an English keyboard).
654     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
655         flags &= ~NSShiftKeyMask;
657     if (0x3 == [unmodchars characterAtIndex:0]) {
658         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
659         // handle it separately (else Cmd-enter turns into Ctrl-C).
660         unmodchars = MMKeypadEnterString;
661         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
662     }
664     [data appendBytes:&flags length:sizeof(int)];
665     [data appendBytes:&len length:sizeof(int)];
666     [data appendBytes:[unmodchars UTF8String] length:len];
668     [[self vimController] sendMessage:CmdKeyMsgID data:data];
670     return YES;
673 - (BOOL)hasMarkedText
675     //NSLog(@"%s", _cmd);
676     return markedTextField && [[markedTextField stringValue] length] > 0;
679 - (NSRange)markedRange
681     //NSLog(@"%s", _cmd);
682     unsigned len = [[markedTextField stringValue] length];
683     return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
686 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
688     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
689     //        NSStringFromRange(range));
691     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
692     if (!ts) return;
694     if (!markedTextField) {
695         // Create a text field and put it inside a floating panel.  This field
696         // is used to display marked text.
697         NSSize cellSize = [ts cellSize];
698         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
700         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
701         [markedTextField setEditable:NO];
702         [markedTextField setSelectable:NO];
703         [markedTextField setBezeled:NO];
704         [markedTextField setBordered:YES];
706         NSPanel *panel = [[NSPanel alloc]
707             initWithContentRect:cellRect
708                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
709                         backing:NSBackingStoreBuffered
710                           defer:YES];
712         //[panel setHidesOnDeactivate:NO];
713         [panel setFloatingPanel:YES];
714         [panel setBecomesKeyOnlyIfNeeded:YES];
715         [panel setContentView:markedTextField];
716     }
718     if (text && [text length] > 0) {
719         [markedTextField setFont:[ts font]];
720         if ([text isKindOfClass:[NSAttributedString class]])
721             [markedTextField setAttributedStringValue:text];
722         else
723             [markedTextField setStringValue:text];
725         [markedTextField sizeToFit];
726         NSSize size = [markedTextField frame].size;
728         // Convert coordinates (row,col) -> view -> window base -> screen
729         NSPoint origin;
730         if (![self convertRow:preEditRow+1 column:preEditColumn
731                      toPoint:&origin])
732             return;
733         origin = [self convertPoint:origin toView:nil];
734         origin = [[self window] convertBaseToScreen:origin];
736         NSWindow *win = [markedTextField window];
737         [win setContentSize:size];
738         [win setFrameOrigin:origin];
739         [win orderFront:nil];
740     } else {
741         [self hideMarkedTextField];
742     }
745 - (void)unmarkText
747     //NSLog(@"%s", _cmd);
748     [self hideMarkedTextField];
751 - (NSRect)firstRectForCharacterRange:(NSRange)range
753     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
754     // HACK!  This method is called when the input manager wants to pop up an
755     // auxiliary window.  The position where this should be is controller by
756     // Vim by sending SetPreEditPositionMsgID so compute a position based on
757     // the pre-edit (row,column) pair.
758     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
760     NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
761                                              column:preEditColumn];
762     rect.origin.x += [self textContainerOrigin].x;
763     rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
765     rect.origin = [self convertPoint:rect.origin toView:nil];
766     rect.origin = [[self window] convertBaseToScreen:rect.origin];
768     return rect;
771 - (void)scrollWheel:(NSEvent *)event
773     if ([event deltaY] == 0)
774         return;
776     int row, col;
777     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
778     if (![self convertPoint:pt toRow:&row column:&col])
779         return;
781     int flags = [event modifierFlags];
782     float dy = [event deltaY];
783     NSMutableData *data = [NSMutableData data];
785     [data appendBytes:&row length:sizeof(int)];
786     [data appendBytes:&col length:sizeof(int)];
787     [data appendBytes:&flags length:sizeof(int)];
788     [data appendBytes:&dy length:sizeof(float)];
790     [[self vimController] sendMessage:ScrollWheelMsgID data:data];
793 - (void)mouseDown:(NSEvent *)event
795     int row, col;
796     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
797     if (![self convertPoint:pt toRow:&row column:&col])
798         return;
800     lastMouseDownEvent = [event copy];
802     int button = [event buttonNumber];
803     int flags = [event modifierFlags];
804     int count = [event clickCount];
805     NSMutableData *data = [NSMutableData data];
807     // If desired, intepret Ctrl-Click as a right mouse click.
808     if ([[NSUserDefaults standardUserDefaults]
809             boolForKey:MMTranslateCtrlClickKey]
810             && button == 0 && flags & NSControlKeyMask) {
811         button = 1;
812         flags &= ~NSControlKeyMask;
813     }
815     [data appendBytes:&row length:sizeof(int)];
816     [data appendBytes:&col length:sizeof(int)];
817     [data appendBytes:&button length:sizeof(int)];
818     [data appendBytes:&flags length:sizeof(int)];
819     [data appendBytes:&count length:sizeof(int)];
821     [[self vimController] sendMessage:MouseDownMsgID data:data];
824 - (void)rightMouseDown:(NSEvent *)event
826     [self mouseDown:event];
829 - (void)otherMouseDown:(NSEvent *)event
831     [self mouseDown:event];
834 - (void)mouseUp:(NSEvent *)event
836     int row, col;
837     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
838     if (![self convertPoint:pt toRow:&row column:&col])
839         return;
841     int flags = [event modifierFlags];
842     NSMutableData *data = [NSMutableData data];
844     [data appendBytes:&row length:sizeof(int)];
845     [data appendBytes:&col length:sizeof(int)];
846     [data appendBytes:&flags length:sizeof(int)];
848     [[self vimController] sendMessage:MouseUpMsgID data:data];
850     isDragging = NO;
853 - (void)rightMouseUp:(NSEvent *)event
855     [self mouseUp:event];
858 - (void)otherMouseUp:(NSEvent *)event
860     [self mouseUp:event];
863 - (void)mouseDragged:(NSEvent *)event
865     int flags = [event modifierFlags];
866     int row, col;
867     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
868     if (![self convertPoint:pt toRow:&row column:&col])
869         return;
871     // Autoscrolling is done in dragTimerFired:
872     if (!isAutoscrolling) {
873         NSMutableData *data = [NSMutableData data];
875         [data appendBytes:&row length:sizeof(int)];
876         [data appendBytes:&col length:sizeof(int)];
877         [data appendBytes:&flags length:sizeof(int)];
879         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
880     }
882     dragPoint = pt;
883     dragRow = row; dragColumn = col; dragFlags = flags;
884     if (!isDragging) {
885         [self startDragTimerWithInterval:.5];
886         isDragging = YES;
887     }
890 - (void)rightMouseDragged:(NSEvent *)event
892     [self mouseDragged:event];
895 - (void)otherMouseDragged:(NSEvent *)event
897     [self mouseDragged:event];
900 - (void)mouseMoved:(NSEvent *)event
902     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
903     if (!ts) return;
905     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
906     int row, col;
907     if (![self convertPoint:pt toRow:&row column:&col])
908         return;
910     // HACK! It seems impossible to get the tracking rects set up before the
911     // view is visible, which means that the first mouseEntered: or
912     // mouseExited: events are never received.  This forces us to check if the
913     // mouseMoved: event really happened over the text.
914     int rows, cols;
915     [ts getMaxRows:&rows columns:&cols];
916     if (row >= 0 && row < rows && col >= 0 && col < cols) {
917         NSMutableData *data = [NSMutableData data];
919         [data appendBytes:&row length:sizeof(int)];
920         [data appendBytes:&col length:sizeof(int)];
922         [[self vimController] sendMessage:MouseMovedMsgID data:data];
923     }
926 - (void)mouseEntered:(NSEvent *)event
928     //NSLog(@"%s", _cmd);
930     // NOTE: This event is received even when the window is not key; thus we
931     // have to take care not to enable mouse moved events unless our window is
932     // key.
933     if ([[self window] isKeyWindow])
934         [[self window] setAcceptsMouseMovedEvents:YES];
937 - (void)mouseExited:(NSEvent *)event
939     //NSLog(@"%s", _cmd);
941     [[self window] setAcceptsMouseMovedEvents:NO];
943     // NOTE: This event is received even when the window is not key; if the
944     // mouse shape is set when our window is not key, the hollow (unfocused)
945     // cursor will become a block (focused) cursor.
946     if ([[self window] isKeyWindow]) {
947         int shape = 0;
948         NSMutableData *data = [NSMutableData data];
949         [data appendBytes:&shape length:sizeof(int)];
950         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
951     }
954 - (void)setFrame:(NSRect)frame
956     //NSLog(@"%s", _cmd);
958     // When the frame changes we also need to update the tracking rect.
959     [super setFrame:frame];
960     [self removeTrackingRect:trackingRectTag];
961     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
962                                    userData:NULL assumeInside:YES];
965 - (void)viewDidMoveToWindow
967     //NSLog(@"%s (window=%@)", _cmd, [self window]);
969     // Set a tracking rect which covers the text.
970     // NOTE: While the mouse cursor is in this rect the view will receive
971     // 'mouseMoved:' events so that Vim can take care of updating the mouse
972     // cursor.
973     if ([self window]) {
974         [[self window] setAcceptsMouseMovedEvents:YES];
975         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
976                                        userData:NULL assumeInside:YES];
977     }
980 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
982     //NSLog(@"%s%@", _cmd, newWindow);
984     // Remove tracking rect if view moves or is removed.
985     if ([self window] && trackingRectTag) {
986         [self removeTrackingRect:trackingRectTag];
987         trackingRectTag = 0;
988     }
991 - (NSMenu*)menuForEvent:(NSEvent *)event
993     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
994     // own).  Called when user Ctrl-clicks in the view (this is already handled
995     // in rightMouseDown:).
996     return nil;
999 - (NSArray *)acceptableDragTypes
1001     return [NSArray arrayWithObjects:NSFilenamesPboardType,
1002            NSStringPboardType, nil];
1005 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1007     NSPasteboard *pboard = [sender draggingPasteboard];
1009     if ([[pboard types] containsObject:NSStringPboardType]) {
1010         NSString *string = [pboard stringForType:NSStringPboardType];
1011         [[self vimController] dropString:string];
1012         return YES;
1013     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1014         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1015         [[self vimController] dropFiles:files forceOpen:NO];
1016         return YES;
1017     }
1019     return NO;
1022 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1024     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1025     NSPasteboard *pboard = [sender draggingPasteboard];
1027     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1028             && (sourceDragMask & NSDragOperationCopy) )
1029         return NSDragOperationCopy;
1030     if ( [[pboard types] containsObject:NSStringPboardType]
1031             && (sourceDragMask & NSDragOperationCopy) )
1032         return NSDragOperationCopy;
1034     return NSDragOperationNone;
1037 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1039     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1040     NSPasteboard *pboard = [sender draggingPasteboard];
1042     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1043             && (sourceDragMask & NSDragOperationCopy) )
1044         return NSDragOperationCopy;
1045     if ( [[pboard types] containsObject:NSStringPboardType]
1046             && (sourceDragMask & NSDragOperationCopy) )
1047         return NSDragOperationCopy;
1049     return NSDragOperationNone;
1052 - (void)changeFont:(id)sender
1054     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1055     if (!ts) return;
1057     NSFont *oldFont = [ts font];
1058     NSFont *newFont = [sender convertFont:oldFont];
1060     if (newFont) {
1061         NSString *name = [newFont displayName];
1062         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1063         if (len > 0) {
1064             NSMutableData *data = [NSMutableData data];
1065             float pointSize = [newFont pointSize];
1067             [data appendBytes:&pointSize length:sizeof(float)];
1069             ++len;  // include NUL byte
1070             [data appendBytes:&len length:sizeof(unsigned)];
1071             [data appendBytes:[name UTF8String] length:len];
1073             [[self vimController] sendMessage:SetFontMsgID data:data];
1074         }
1075     }
1078 - (void)resetCursorRects
1080     // No need to set up cursor rects since Vim handles cursor changes.
1083 - (void)updateFontPanel
1085     // The font panel is updated whenever the font is set.
1088 @end // MMTextView
1093 @implementation MMTextView (Private)
1095 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1097     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1098     NSSize cellSize = [ts cellSize];
1099     if (!(cellSize.width > 0 && cellSize.height > 0))
1100         return NO;
1101     NSPoint origin = [self textContainerOrigin];
1103     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1104     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1106     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1107     //        *row, *column);
1109     return YES;
1112 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1114     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1115     NSSize cellSize = [ts cellSize];
1116     if (!(point && cellSize.width > 0 && cellSize.height > 0))
1117         return NO;
1119     *point = [self textContainerOrigin];
1120     point->x += column * cellSize.width;
1121     point->y += row * cellSize.height;
1123     return YES;
1126 - (NSRect)trackingRect
1128     NSRect rect = [self frame];
1129     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1130     int left = [ud integerForKey:MMTextInsetLeftKey];
1131     int top = [ud integerForKey:MMTextInsetTopKey];
1132     int right = [ud integerForKey:MMTextInsetRightKey];
1133     int bot = [ud integerForKey:MMTextInsetBottomKey];
1135     rect.origin.x = left;
1136     rect.origin.y = top;
1137     rect.size.width -= left + right - 1;
1138     rect.size.height -= top + bot - 1;
1140     return rect;
1143 - (void)dispatchKeyEvent:(NSEvent *)event
1145     // Only handle the command if it came from a keyDown event
1146     if ([event type] != NSKeyDown)
1147         return;
1149     NSString *chars = [event characters];
1150     NSString *unmodchars = [event charactersIgnoringModifiers];
1151     unichar c = [chars characterAtIndex:0];
1152     unichar imc = [unmodchars characterAtIndex:0];
1153     int len = 0;
1154     const char *bytes = 0;
1155     int mods = [event modifierFlags];
1157     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1158     //        _cmd, c, imc, chars, unmodchars);
1160     if (' ' == imc && 0xa0 != c) {
1161         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
1162         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
1163         // should be passed on as is.)
1164         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1165         bytes = [unmodchars UTF8String];
1166     } else if (imc == c && '2' == c) {
1167         // HACK!  Translate Ctrl+2 to <C-@>.
1168         static char ctrl_at = 0;
1169         len = 1;  bytes = &ctrl_at;
1170     } else if (imc == c && '6' == c) {
1171         // HACK!  Translate Ctrl+6 to <C-^>.
1172         static char ctrl_hat = 0x1e;
1173         len = 1;  bytes = &ctrl_hat;
1174     } else if (c == 0x19 && imc == 0x19) {
1175         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1176         // separately (else Ctrl-Y doesn't work).
1177         static char tab = 0x9;
1178         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
1179     } else {
1180         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1181         bytes = [chars UTF8String];
1182     }
1184     [self sendKeyDown:bytes length:len modifiers:mods];
1187 - (MMVimController *)vimController
1189     id windowController = [[self window] windowController];
1191     // TODO: Make sure 'windowController' is a MMWindowController before type
1192     // casting.
1193     return [(MMWindowController*)windowController vimController];
1196 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1198     [NSTimer scheduledTimerWithTimeInterval:t target:self
1199                                    selector:@selector(dragTimerFired:)
1200                                    userInfo:nil repeats:NO];
1203 - (void)dragTimerFired:(NSTimer *)timer
1205     // TODO: Autoscroll in horizontal direction?
1206     static unsigned tick = 1;
1207     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1209     isAutoscrolling = NO;
1211     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1212         // HACK! If the mouse cursor is outside the text area, then send a
1213         // dragged event.  However, if row&col hasn't changed since the last
1214         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1215         // Thus we fiddle with the column to make sure something happens.
1216         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1217         NSMutableData *data = [NSMutableData data];
1219         [data appendBytes:&dragRow length:sizeof(int)];
1220         [data appendBytes:&col length:sizeof(int)];
1221         [data appendBytes:&dragFlags length:sizeof(int)];
1223         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1225         isAutoscrolling = YES;
1226     }
1228     if (isDragging) {
1229         // Compute timer interval depending on how far away the mouse cursor is
1230         // from the text view.
1231         NSRect rect = [self trackingRect];
1232         float dy = 0;
1233         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1234         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1235         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1237         NSTimeInterval t = MMDragTimerMaxInterval -
1238             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1240         [self startDragTimerWithInterval:t];
1241     }
1243     ++tick;
1246 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1248     if (chars && len > 0) {
1249         NSMutableData *data = [NSMutableData data];
1251         [data appendBytes:&flags length:sizeof(int)];
1252         [data appendBytes:&len length:sizeof(int)];
1253         [data appendBytes:chars length:len];
1255         // TODO: Support 'mousehide' (check p_mh)
1256         [NSCursor setHiddenUntilMouseMoves:YES];
1258         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1259         [[self vimController] sendMessage:KeyDownMsgID data:data];
1260     }
1263 @end // MMTextView (Private)