Window and view refactoring
[MacVim.git] / src / MacVim / MMTextView.m
blobb1e7148c9500992c8d6f211bd7df0ae8f9f832bf
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.
491     //
492     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
493     // affecting input management.
494     if ([event modifierFlags] & NSControlKeyMask) {
495         NSString *unmod = [event charactersIgnoringModifiers];
496         if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
497                                 && [unmod characterAtIndex:0] >= 0x60) {
498             // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
499             // as normal text to be added to the Vim input buffer.  This must
500             // be done in order for the backend to be able to separate e.g.
501             // Ctrl-i and Ctrl-tab.
502             [self insertText:[event characters]];
503         } else {
504             [self dispatchKeyEvent:event];
505         }
506     } else {
507         [super keyDown:event];
508     }
511 - (void)insertText:(id)string
513     //NSLog(@"%s %@", _cmd, string);
514     // NOTE!  This method is called for normal key presses but also for
515     // Option-key presses --- even when Ctrl is held as well as Option.  When
516     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
517     // so 'string' need not be a printable character!  In this case it still
518     // works to pass 'string' on to Vim as a printable character (since
519     // modifiers are already included and should not be added to the input
520     // buffer using CSI, K_MODIFIER).
522     [self hideMarkedTextField];
524     NSEvent *event = [NSApp currentEvent];
526     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
527     // to watch for them here.
528     if ([event type] == NSKeyDown
529             && [[event charactersIgnoringModifiers] length] > 0
530             && [event modifierFlags]
531                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
532         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
534         // <S-M-Tab> translates to 0x19 
535         if (' ' == c || 0x19 == c) {
536             [self dispatchKeyEvent:event];
537             return;
538         }
539     }
541     // TODO: Support 'mousehide' (check p_mh)
542     [NSCursor setHiddenUntilMouseMoves:YES];
544     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
545     // do not support attributes, simply pass the corresponding NSString in the
546     // latter case.
547     if ([string isKindOfClass:[NSAttributedString class]])
548         string = [string string];
550     //NSLog(@"send InsertTextMsgID: %@", string);
552     [[self vimController] sendMessage:InsertTextMsgID
553                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
557 - (void)doCommandBySelector:(SEL)selector
559     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
560     // By ignoring the selector we effectively disable the key binding
561     // mechanism of Cocoa.  Hopefully this is what the user will expect
562     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
563     // match, etc.).
564     //
565     // We usually end up here if the user pressed Ctrl+key (but not
566     // Ctrl+Option+key).
568     NSEvent *event = [NSApp currentEvent];
570     if (selector == @selector(cancelOperation:)
571             || selector == @selector(insertNewline:)) {
572         // HACK! If there was marked text which got abandoned as a result of
573         // hitting escape or enter, then 'insertText:' is called with the
574         // abandoned text but '[event characters]' includes the abandoned text
575         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
576         // must intercept these keys here or the abandonded text gets inserted
577         // twice.
578         NSString *key = [event charactersIgnoringModifiers];
579         const char *chars = [key UTF8String];
580         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
582         if (0x3 == chars[0]) {
583             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
584             // handle it separately (else Ctrl-C doesn't work).
585             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
586             chars = MMKeypadEnter;
587         }
589         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
590     } else {
591         [self dispatchKeyEvent:event];
592     }
595 - (BOOL)performKeyEquivalent:(NSEvent *)event
597     //NSLog(@"%s %@", _cmd, event);
598     // Called for Cmd+key keystrokes, function keys, arrow keys, page
599     // up/down, home, end.
600     //
601     // NOTE: This message cannot be ignored since Cmd+letter keys never are
602     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
603     // strokes, unless the key is a function key.
605     // NOTE: If the event that triggered this method represents a function key
606     // down then we do nothing, otherwise the input method never gets the key
607     // stroke (some input methods use e.g. arrow keys).  The function key down
608     // event will still reach Vim though (via keyDown:).  The exceptions to
609     // this rule are: PageUp/PageDown (keycode 116/121).
610     int flags = [event modifierFlags];
611     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
612             && !(116 == [event keyCode] || 121 == [event keyCode]))
613         return NO;
615     // HACK!  Let the main menu try to handle any key down event, before
616     // passing it on to vim, otherwise key equivalents for menus will
617     // effectively be disabled.
618     if ([[NSApp mainMenu] performKeyEquivalent:event])
619         return YES;
621     // HACK!  KeyCode 50 represent the key which switches between windows
622     // within an application (like Cmd+Tab is used to switch between
623     // applications).  Return NO here, else the window switching does not work.
624     //
625     // Will this hack work for all languages / keyboard layouts?
626     if ([event keyCode] == 50)
627         return NO;
629     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
630     if (flags & NSControlKeyMask) {
631         [self keyDown:event];
632         return YES;
633     }
635     //NSLog(@"%s%@", _cmd, event);
637     NSString *chars = [event characters];
638     NSString *unmodchars = [event charactersIgnoringModifiers];
639     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
640     NSMutableData *data = [NSMutableData data];
642     if (len <= 0)
643         return NO;
645     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
646     // can clear the shift flag as it is already included in 'unmodchars'.
647     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
648     // an English keyboard).
649     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
650         flags &= ~NSShiftKeyMask;
652     if (0x3 == [unmodchars characterAtIndex:0]) {
653         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
654         // handle it separately (else Cmd-enter turns into Ctrl-C).
655         unmodchars = MMKeypadEnterString;
656         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
657     }
659     [data appendBytes:&flags length:sizeof(int)];
660     [data appendBytes:&len length:sizeof(int)];
661     [data appendBytes:[unmodchars UTF8String] length:len];
663     [[self vimController] sendMessage:CmdKeyMsgID data:data];
665     return YES;
668 - (BOOL)hasMarkedText
670     //NSLog(@"%s", _cmd);
671     return markedTextField && [[markedTextField stringValue] length] > 0;
674 - (NSRange)markedRange
676     //NSLog(@"%s", _cmd);
677     unsigned len = [[markedTextField stringValue] length];
678     return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
681 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
683     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
684     //        NSStringFromRange(range));
686     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
687     if (!ts) return;
689     if (!markedTextField) {
690         // Create a text field and put it inside a floating panel.  This field
691         // is used to display marked text.
692         NSSize cellSize = [ts cellSize];
693         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
695         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
696         [markedTextField setEditable:NO];
697         [markedTextField setSelectable:NO];
698         [markedTextField setBezeled:NO];
699         [markedTextField setBordered:YES];
701         NSPanel *panel = [[NSPanel alloc]
702             initWithContentRect:cellRect
703                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
704                         backing:NSBackingStoreBuffered
705                           defer:YES];
707         //[panel setHidesOnDeactivate:NO];
708         [panel setFloatingPanel:YES];
709         [panel setBecomesKeyOnlyIfNeeded:YES];
710         [panel setContentView:markedTextField];
711     }
713     if (text && [text length] > 0) {
714         [markedTextField setFont:[ts font]];
715         if ([text isKindOfClass:[NSAttributedString class]])
716             [markedTextField setAttributedStringValue:text];
717         else
718             [markedTextField setStringValue:text];
720         [markedTextField sizeToFit];
721         NSSize size = [markedTextField frame].size;
723         // Convert coordinates (row,col) -> view -> window base -> screen
724         NSPoint origin;
725         if (![self convertRow:preEditRow+1 column:preEditColumn
726                      toPoint:&origin])
727             return;
728         origin = [self convertPoint:origin toView:nil];
729         origin = [[self window] convertBaseToScreen:origin];
731         NSWindow *win = [markedTextField window];
732         [win setContentSize:size];
733         [win setFrameOrigin:origin];
734         [win orderFront:nil];
735     } else {
736         [self hideMarkedTextField];
737     }
740 - (void)unmarkText
742     //NSLog(@"%s", _cmd);
743     [self hideMarkedTextField];
746 - (NSRect)firstRectForCharacterRange:(NSRange)range
748     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
749     // HACK!  This method is called when the input manager wants to pop up an
750     // auxiliary window.  The position where this should be is controller by
751     // Vim by sending SetPreEditPositionMsgID so compute a position based on
752     // the pre-edit (row,column) pair.
753     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
755     NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
756                                              column:preEditColumn];
757     rect.origin.x += [self textContainerOrigin].x;
758     rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
760     rect.origin = [self convertPoint:rect.origin toView:nil];
761     rect.origin = [[self window] convertBaseToScreen:rect.origin];
763     return rect;
766 - (void)scrollWheel:(NSEvent *)event
768     if ([event deltaY] == 0)
769         return;
771     int row, col;
772     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
773     if (![self convertPoint:pt toRow:&row column:&col])
774         return;
776     int flags = [event modifierFlags];
777     float dy = [event deltaY];
778     NSMutableData *data = [NSMutableData data];
780     [data appendBytes:&row length:sizeof(int)];
781     [data appendBytes:&col length:sizeof(int)];
782     [data appendBytes:&flags length:sizeof(int)];
783     [data appendBytes:&dy length:sizeof(float)];
785     [[self vimController] sendMessage:ScrollWheelMsgID data:data];
788 - (void)mouseDown:(NSEvent *)event
790     int row, col;
791     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
792     if (![self convertPoint:pt toRow:&row column:&col])
793         return;
795     lastMouseDownEvent = [event copy];
797     int button = [event buttonNumber];
798     int flags = [event modifierFlags];
799     int count = [event clickCount];
800     NSMutableData *data = [NSMutableData data];
802     // If desired, intepret Ctrl-Click as a right mouse click.
803     if ([[NSUserDefaults standardUserDefaults]
804             boolForKey:MMTranslateCtrlClickKey]
805             && button == 0 && flags & NSControlKeyMask) {
806         button = 1;
807         flags &= ~NSControlKeyMask;
808     }
810     [data appendBytes:&row length:sizeof(int)];
811     [data appendBytes:&col length:sizeof(int)];
812     [data appendBytes:&button length:sizeof(int)];
813     [data appendBytes:&flags length:sizeof(int)];
814     [data appendBytes:&count length:sizeof(int)];
816     [[self vimController] sendMessage:MouseDownMsgID data:data];
819 - (void)rightMouseDown:(NSEvent *)event
821     [self mouseDown:event];
824 - (void)otherMouseDown:(NSEvent *)event
826     [self mouseDown:event];
829 - (void)mouseUp:(NSEvent *)event
831     int row, col;
832     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
833     if (![self convertPoint:pt toRow:&row column:&col])
834         return;
836     int flags = [event modifierFlags];
837     NSMutableData *data = [NSMutableData data];
839     [data appendBytes:&row length:sizeof(int)];
840     [data appendBytes:&col length:sizeof(int)];
841     [data appendBytes:&flags length:sizeof(int)];
843     [[self vimController] sendMessage:MouseUpMsgID data:data];
845     isDragging = NO;
848 - (void)rightMouseUp:(NSEvent *)event
850     [self mouseUp:event];
853 - (void)otherMouseUp:(NSEvent *)event
855     [self mouseUp:event];
858 - (void)mouseDragged:(NSEvent *)event
860     int flags = [event modifierFlags];
861     int row, col;
862     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
863     if (![self convertPoint:pt toRow:&row column:&col])
864         return;
866     // Autoscrolling is done in dragTimerFired:
867     if (!isAutoscrolling) {
868         NSMutableData *data = [NSMutableData data];
870         [data appendBytes:&row length:sizeof(int)];
871         [data appendBytes:&col length:sizeof(int)];
872         [data appendBytes:&flags length:sizeof(int)];
874         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
875     }
877     dragPoint = pt;
878     dragRow = row; dragColumn = col; dragFlags = flags;
879     if (!isDragging) {
880         [self startDragTimerWithInterval:.5];
881         isDragging = YES;
882     }
885 - (void)rightMouseDragged:(NSEvent *)event
887     [self mouseDragged:event];
890 - (void)otherMouseDragged:(NSEvent *)event
892     [self mouseDragged:event];
895 - (void)mouseMoved:(NSEvent *)event
897     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
898     if (!ts) return;
900     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
901     int row, col;
902     if (![self convertPoint:pt toRow:&row column:&col])
903         return;
905     // HACK! It seems impossible to get the tracking rects set up before the
906     // view is visible, which means that the first mouseEntered: or
907     // mouseExited: events are never received.  This forces us to check if the
908     // mouseMoved: event really happened over the text.
909     int rows, cols;
910     [ts getMaxRows:&rows columns:&cols];
911     if (row >= 0 && row < rows && col >= 0 && col < cols) {
912         NSMutableData *data = [NSMutableData data];
914         [data appendBytes:&row length:sizeof(int)];
915         [data appendBytes:&col length:sizeof(int)];
917         [[self vimController] sendMessage:MouseMovedMsgID data:data];
918     }
921 - (void)mouseEntered:(NSEvent *)event
923     //NSLog(@"%s", _cmd);
925     // NOTE: This event is received even when the window is not key; thus we
926     // have to take care not to enable mouse moved events unless our window is
927     // key.
928     if ([[self window] isKeyWindow])
929         [[self window] setAcceptsMouseMovedEvents:YES];
932 - (void)mouseExited:(NSEvent *)event
934     //NSLog(@"%s", _cmd);
936     [[self window] setAcceptsMouseMovedEvents:NO];
938     // NOTE: This event is received even when the window is not key; if the
939     // mouse shape is set when our window is not key, the hollow (unfocused)
940     // cursor will become a block (focused) cursor.
941     if ([[self window] isKeyWindow]) {
942         int shape = 0;
943         NSMutableData *data = [NSMutableData data];
944         [data appendBytes:&shape length:sizeof(int)];
945         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
946     }
949 - (void)setFrame:(NSRect)frame
951     //NSLog(@"%s", _cmd);
953     // When the frame changes we also need to update the tracking rect.
954     [super setFrame:frame];
955     [self removeTrackingRect:trackingRectTag];
956     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
957                                    userData:NULL assumeInside:YES];
960 - (void)viewDidMoveToWindow
962     //NSLog(@"%s (window=%@)", _cmd, [self window]);
964     // Set a tracking rect which covers the text.
965     // NOTE: While the mouse cursor is in this rect the view will receive
966     // 'mouseMoved:' events so that Vim can take care of updating the mouse
967     // cursor.
968     if ([self window]) {
969         [[self window] setAcceptsMouseMovedEvents:YES];
970         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
971                                        userData:NULL assumeInside:YES];
972     }
975 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
977     //NSLog(@"%s%@", _cmd, newWindow);
979     // Remove tracking rect if view moves or is removed.
980     if ([self window] && trackingRectTag) {
981         [self removeTrackingRect:trackingRectTag];
982         trackingRectTag = 0;
983     }
986 - (NSMenu*)menuForEvent:(NSEvent *)event
988     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
989     // own).  Called when user Ctrl-clicks in the view (this is already handled
990     // in rightMouseDown:).
991     return nil;
994 - (NSArray *)acceptableDragTypes
996     return [NSArray arrayWithObjects:NSFilenamesPboardType,
997            NSStringPboardType, nil];
1000 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1002     NSPasteboard *pboard = [sender draggingPasteboard];
1004     if ([[pboard types] containsObject:NSStringPboardType]) {
1005         NSString *string = [pboard stringForType:NSStringPboardType];
1006         [[self vimController] dropString:string];
1007         return YES;
1008     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1009         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1010         [[self vimController] dropFiles:files forceOpen:NO];
1011         return YES;
1012     }
1014     return NO;
1017 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1019     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1020     NSPasteboard *pboard = [sender draggingPasteboard];
1022     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1023             && (sourceDragMask & NSDragOperationCopy) )
1024         return NSDragOperationCopy;
1025     if ( [[pboard types] containsObject:NSStringPboardType]
1026             && (sourceDragMask & NSDragOperationCopy) )
1027         return NSDragOperationCopy;
1029     return NSDragOperationNone;
1032 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1034     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1035     NSPasteboard *pboard = [sender draggingPasteboard];
1037     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1038             && (sourceDragMask & NSDragOperationCopy) )
1039         return NSDragOperationCopy;
1040     if ( [[pboard types] containsObject:NSStringPboardType]
1041             && (sourceDragMask & NSDragOperationCopy) )
1042         return NSDragOperationCopy;
1044     return NSDragOperationNone;
1047 - (void)changeFont:(id)sender
1049     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1050     if (!ts) return;
1052     NSFont *oldFont = [ts font];
1053     NSFont *newFont = [sender convertFont:oldFont];
1055     if (newFont) {
1056         NSString *name = [newFont displayName];
1057         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1058         if (len > 0) {
1059             NSMutableData *data = [NSMutableData data];
1060             float pointSize = [newFont pointSize];
1062             [data appendBytes:&pointSize length:sizeof(float)];
1064             ++len;  // include NUL byte
1065             [data appendBytes:&len length:sizeof(unsigned)];
1066             [data appendBytes:[name UTF8String] length:len];
1068             [[self vimController] sendMessage:SetFontMsgID data:data];
1069         }
1070     }
1073 - (void)resetCursorRects
1075     // No need to set up cursor rects since Vim handles cursor changes.
1078 - (void)updateFontPanel
1080     // The font panel is updated whenever the font is set.
1083 @end // MMTextView
1088 @implementation MMTextView (Private)
1090 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1092     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1093     NSSize cellSize = [ts cellSize];
1094     if (!(cellSize.width > 0 && cellSize.height > 0))
1095         return NO;
1096     NSPoint origin = [self textContainerOrigin];
1098     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1099     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1101     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1102     //        *row, *column);
1104     return YES;
1107 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1109     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1110     NSSize cellSize = [ts cellSize];
1111     if (!(point && cellSize.width > 0 && cellSize.height > 0))
1112         return NO;
1114     *point = [self textContainerOrigin];
1115     point->x += column * cellSize.width;
1116     point->y += row * cellSize.height;
1118     return YES;
1121 - (NSRect)trackingRect
1123     NSRect rect = [self frame];
1124     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1125     int left = [ud integerForKey:MMTextInsetLeftKey];
1126     int top = [ud integerForKey:MMTextInsetTopKey];
1127     int right = [ud integerForKey:MMTextInsetRightKey];
1128     int bot = [ud integerForKey:MMTextInsetBottomKey];
1130     rect.origin.x = left;
1131     rect.origin.y = top;
1132     rect.size.width -= left + right - 1;
1133     rect.size.height -= top + bot - 1;
1135     return rect;
1138 - (void)dispatchKeyEvent:(NSEvent *)event
1140     // Only handle the command if it came from a keyDown event
1141     if ([event type] != NSKeyDown)
1142         return;
1144     NSString *chars = [event characters];
1145     NSString *unmodchars = [event charactersIgnoringModifiers];
1146     unichar c = [chars characterAtIndex:0];
1147     unichar imc = [unmodchars characterAtIndex:0];
1148     int len = 0;
1149     const char *bytes = 0;
1150     int mods = [event modifierFlags];
1152     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1153     //        _cmd, c, imc, chars, unmodchars);
1155     if (' ' == imc && 0xa0 != c) {
1156         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
1157         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
1158         // should be passed on as is.)
1159         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1160         bytes = [unmodchars UTF8String];
1161     } else if (imc == c && '2' == c) {
1162         // HACK!  Translate Ctrl+2 to <C-@>.
1163         static char ctrl_at = 0;
1164         len = 1;  bytes = &ctrl_at;
1165     } else if (imc == c && '6' == c) {
1166         // HACK!  Translate Ctrl+6 to <C-^>.
1167         static char ctrl_hat = 0x1e;
1168         len = 1;  bytes = &ctrl_hat;
1169     } else if (c == 0x19 && imc == 0x19) {
1170         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1171         // separately (else Ctrl-Y doesn't work).
1172         static char tab = 0x9;
1173         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
1174     } else {
1175         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1176         bytes = [chars UTF8String];
1177     }
1179     [self sendKeyDown:bytes length:len modifiers:mods];
1182 - (MMVimController *)vimController
1184     id windowController = [[self window] windowController];
1186     // TODO: Make sure 'windowController' is a MMWindowController before type
1187     // casting.
1188     return [(MMWindowController*)windowController vimController];
1191 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1193     [NSTimer scheduledTimerWithTimeInterval:t target:self
1194                                    selector:@selector(dragTimerFired:)
1195                                    userInfo:nil repeats:NO];
1198 - (void)dragTimerFired:(NSTimer *)timer
1200     // TODO: Autoscroll in horizontal direction?
1201     static unsigned tick = 1;
1202     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1204     isAutoscrolling = NO;
1206     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1207         // HACK! If the mouse cursor is outside the text area, then send a
1208         // dragged event.  However, if row&col hasn't changed since the last
1209         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1210         // Thus we fiddle with the column to make sure something happens.
1211         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1212         NSMutableData *data = [NSMutableData data];
1214         [data appendBytes:&dragRow length:sizeof(int)];
1215         [data appendBytes:&col length:sizeof(int)];
1216         [data appendBytes:&dragFlags length:sizeof(int)];
1218         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1220         isAutoscrolling = YES;
1221     }
1223     if (isDragging) {
1224         // Compute timer interval depending on how far away the mouse cursor is
1225         // from the text view.
1226         NSRect rect = [self trackingRect];
1227         float dy = 0;
1228         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1229         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1230         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1232         NSTimeInterval t = MMDragTimerMaxInterval -
1233             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1235         [self startDragTimerWithInterval:t];
1236     }
1238     ++tick;
1241 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1243     if (chars && len > 0) {
1244         NSMutableData *data = [NSMutableData data];
1246         [data appendBytes:&flags length:sizeof(int)];
1247         [data appendBytes:&len length:sizeof(int)];
1248         [data appendBytes:chars length:len];
1250         // TODO: Support 'mousehide' (check p_mh)
1251         [NSCursor setHiddenUntilMouseMoves:YES];
1253         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1254         [[self vimController] sendMessage:KeyDownMsgID data:data];
1255     }
1258 @end // MMTextView (Private)