Improved method to start Vim processes in a login shell
[MacVim.git] / src / MacVim / MMTextView.m
blob2e0b978840de80f7de44c428586ed63ff4d93a7e
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 autorelease];
102     [lm autorelease];
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     return self;
116 - (void)dealloc
118     //NSLog(@"MMTextView dealloc");
120     if (markedTextField) {
121         [[markedTextField window] autorelease];
122         [markedTextField release];
123         markedTextField = nil;
124     }
126     [lastMouseDownEvent release];  lastMouseDownEvent = nil;
127     [super dealloc];
130 - (NSEvent *)lastMouseDownEvent
132     return lastMouseDownEvent;
135 - (BOOL)shouldDrawInsertionPoint
137     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
138     // nice to be able to use the insertion point related methods of
139     // NSTextView, but it seems impossible to get them to work properly (search
140     // the cocoabuilder archives).
141     return NO;
144 - (void)setShouldDrawInsertionPoint:(BOOL)on
146     shouldDrawInsertionPoint = on;
149 - (void)setPreEditRow:(int)row column:(int)col
151     preEditRow = row;
152     preEditColumn = col;
155 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
156                        fraction:(int)percent color:(NSColor *)color
158     //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
159     //        row, col, shape, color);
161     // This only stores where to draw the insertion point, the actual drawing
162     // is done in drawRect:.
163     shouldDrawInsertionPoint = YES;
164     insertionPointRow = row;
165     insertionPointColumn = col;
166     insertionPointShape = shape;
167     insertionPointFraction = percent;
169     [self setInsertionPointColor:color];
172 - (void)hideMarkedTextField
174     if (markedTextField) {
175         NSWindow *win = [markedTextField window];
176         [win close];
177         [markedTextField setStringValue:@""];
178     }
182 #define MM_DEBUG_DRAWING 0
184 - (void)performBatchDrawWithData:(NSData *)data
186     MMTextStorage *textStorage = (MMTextStorage *)[self textStorage];
187     if (!textStorage)
188         return;
190     const void *bytes = [data bytes];
191     const void *end = bytes + [data length];
192     int cursorRow = -1, cursorCol = 0;
194 #if MM_DEBUG_DRAWING
195     NSLog(@"====> BEGIN %s", _cmd);
196 #endif
197     [textStorage beginEditing];
199     // TODO: Sanity check input
201     while (bytes < end) {
202         int type = *((int*)bytes);  bytes += sizeof(int);
204         if (ClearAllDrawType == type) {
205 #if MM_DEBUG_DRAWING
206             NSLog(@"   Clear all");
207 #endif
208             [textStorage clearAll];
209         } else if (ClearBlockDrawType == type) {
210             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
211             int row1 = *((int*)bytes);  bytes += sizeof(int);
212             int col1 = *((int*)bytes);  bytes += sizeof(int);
213             int row2 = *((int*)bytes);  bytes += sizeof(int);
214             int col2 = *((int*)bytes);  bytes += sizeof(int);
216 #if MM_DEBUG_DRAWING
217             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
218                     row2,col2);
219 #endif
220             [textStorage clearBlockFromRow:row1 column:col1
221                     toRow:row2 column:col2
222                     color:[NSColor colorWithArgbInt:color]];
223         } else if (DeleteLinesDrawType == type) {
224             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
225             int row = *((int*)bytes);  bytes += sizeof(int);
226             int count = *((int*)bytes);  bytes += sizeof(int);
227             int bot = *((int*)bytes);  bytes += sizeof(int);
228             int left = *((int*)bytes);  bytes += sizeof(int);
229             int right = *((int*)bytes);  bytes += sizeof(int);
231 #if MM_DEBUG_DRAWING
232             NSLog(@"   Delete %d line(s) from %d", count, row);
233 #endif
234             [textStorage deleteLinesFromRow:row lineCount:count
235                     scrollBottom:bot left:left right:right
236                            color:[NSColor colorWithArgbInt:color]];
237         } else if (DrawStringDrawType == type) {
238             int bg = *((int*)bytes);  bytes += sizeof(int);
239             int fg = *((int*)bytes);  bytes += sizeof(int);
240             int sp = *((int*)bytes);  bytes += sizeof(int);
241             int row = *((int*)bytes);  bytes += sizeof(int);
242             int col = *((int*)bytes);  bytes += sizeof(int);
243             int cells = *((int*)bytes);  bytes += sizeof(int);
244             int flags = *((int*)bytes);  bytes += sizeof(int);
245             int len = *((int*)bytes);  bytes += sizeof(int);
246             NSString *string = [[NSString alloc]
247                     initWithBytes:(void*)bytes length:len
248                          encoding:NSUTF8StringEncoding];
249             bytes += len;
251 #if MM_DEBUG_DRAWING
252             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
253                     "bg=0x%x sp=0x%x (%@)", row, col, len, flags, fg, bg, sp,
254                     len > 0 ? [string substringToIndex:1] : @"");
255 #endif
256             // NOTE: If this is a call to draw the (block) cursor, then cancel
257             // any previous request to draw the insertion point, or it might
258             // get drawn as well.
259             if (flags & DRAW_CURSOR) {
260                 [self setShouldDrawInsertionPoint:NO];
261                 //NSColor *color = [NSColor colorWithRgbInt:bg];
262                 //[self drawInsertionPointAtRow:row column:col
263                 //                            shape:MMInsertionPointBlock
264                 //                            color:color];
265             }
267             [textStorage drawString:string
268                               atRow:row column:col cells:cells
269                           withFlags:flags
270                     foregroundColor:[NSColor colorWithRgbInt:fg]
271                     backgroundColor:[NSColor colorWithArgbInt:bg]
272                        specialColor:[NSColor colorWithRgbInt:sp]];
274             [string release];
275         } else if (InsertLinesDrawType == type) {
276             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
277             int row = *((int*)bytes);  bytes += sizeof(int);
278             int count = *((int*)bytes);  bytes += sizeof(int);
279             int bot = *((int*)bytes);  bytes += sizeof(int);
280             int left = *((int*)bytes);  bytes += sizeof(int);
281             int right = *((int*)bytes);  bytes += sizeof(int);
283 #if MM_DEBUG_DRAWING
284             NSLog(@"   Insert %d line(s) at row %d", count, row);
285 #endif
286             [textStorage insertLinesAtRow:row lineCount:count
287                              scrollBottom:bot left:left right:right
288                                     color:[NSColor colorWithArgbInt:color]];
289         } else if (DrawCursorDrawType == type) {
290             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
291             int row = *((int*)bytes);  bytes += sizeof(int);
292             int col = *((int*)bytes);  bytes += sizeof(int);
293             int shape = *((int*)bytes);  bytes += sizeof(int);
294             int percent = *((int*)bytes);  bytes += sizeof(int);
296 #if MM_DEBUG_DRAWING
297             NSLog(@"   Draw cursor at (%d,%d)", row, col);
298 #endif
299             [self drawInsertionPointAtRow:row column:col shape:shape
300                                      fraction:percent
301                                         color:[NSColor colorWithRgbInt:color]];
302         } else if (SetCursorPosDrawType == type) {
303             cursorRow = *((int*)bytes);  bytes += sizeof(int);
304             cursorCol = *((int*)bytes);  bytes += sizeof(int);
305         } else {
306             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
307         }
308     }
310     [textStorage endEditing];
312     if (cursorRow >= 0) {
313         unsigned off = [textStorage characterIndexForRow:cursorRow
314                                                   column:cursorCol];
315         unsigned maxoff = [[textStorage string] length];
316         if (off > maxoff) off = maxoff;
318         [self setSelectedRange:NSMakeRange(off, 0)];
319     }
321     // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
322     // and columns are changed (due to ipc delays). Force a redraw here.
323     [self displayIfNeeded];
325 #if MM_DEBUG_DRAWING
326     NSLog(@"<==== END   %s", _cmd);
327 #endif
330 - (NSFont *)font
332     return [(MMTextStorage*)[self textStorage] font];
335 - (void)setFont:(NSFont *)newFont
337     [(MMTextStorage*)[self textStorage] setFont:newFont];
340 - (void)setWideFont:(NSFont *)newFont
342     [(MMTextStorage*)[self textStorage] setWideFont:newFont];
345 - (NSSize)cellSize
347     return [(MMTextStorage*)[self textStorage] cellSize];
350 - (void)setLinespace:(float)newLinespace
352     return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace];
355 - (void)getMaxRows:(int*)rows columns:(int*)cols
357     return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols];
360 - (void)setMaxRows:(int)rows columns:(int)cols
362     return [(MMTextStorage*)[self textStorage] setMaxRows:rows columns:cols];
365 - (NSRect)rectForRowsInRange:(NSRange)range
367     return [(MMTextStorage*)[self textStorage] rectForRowsInRange:range];
370 - (NSRect)rectForColumnsInRange:(NSRange)range
372     return [(MMTextStorage*)[self textStorage] rectForColumnsInRange:range];
375 - (void)setDefaultColorsBackground:(NSColor *)bgColor
376                         foreground:(NSColor *)fgColor
378     [self setBackgroundColor:bgColor];
379     return [(MMTextStorage*)[self textStorage]
380             setDefaultColorsBackground:bgColor foreground:fgColor];
383 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
385     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
386     int right = [ud integerForKey:MMTextInsetRightKey];
387     int bot = [ud integerForKey:MMTextInsetBottomKey];
389     size.width -= [self textContainerOrigin].x + right;
390     size.height -= [self textContainerOrigin].y + bot;
392     NSSize newSize = [(MMTextStorage*)[self textStorage] fitToSize:size
393                                                               rows:rows
394                                                            columns:cols];
396     newSize.width += [self textContainerOrigin].x + right;
397     newSize.height += [self textContainerOrigin].y + bot;
399     return newSize;
402 - (NSSize)desiredSize
404     NSSize size = [(MMTextStorage*)[self textStorage] size];
406     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
407     int right = [ud integerForKey:MMTextInsetRightKey];
408     int bot = [ud integerForKey:MMTextInsetBottomKey];
410     size.width += [self textContainerOrigin].x + right;
411     size.height += [self textContainerOrigin].y + bot;
413     return size;
416 - (NSSize)minSize
418     NSSize cellSize = [(MMTextStorage*)[self textStorage] cellSize];
419     NSSize size = { MMMinColumns*cellSize.width, MMMinRows*cellSize.height };
421     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
422     int right = [ud integerForKey:MMTextInsetRightKey];
423     int bot = [ud integerForKey:MMTextInsetBottomKey];
425     size.width += [self textContainerOrigin].x + right;
426     size.height += [self textContainerOrigin].y + bot;
428     return size;
431 - (BOOL)isOpaque
433     return NO;
436 - (void)drawRect:(NSRect)rect
438     [super drawRect:rect];
440     if (shouldDrawInsertionPoint) {
441         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
443         NSRect ipRect = [ts boundingRectForCharacterAtRow:insertionPointRow
444                                                    column:insertionPointColumn];
445         ipRect.origin.x += [self textContainerOrigin].x;
446         ipRect.origin.y += [self textContainerOrigin].y;
448         if (MMInsertionPointHorizontal == insertionPointShape) {
449             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
450             ipRect.origin.y += ipRect.size.height - frac;
451             ipRect.size.height = frac;
452         } else if (MMInsertionPointVertical == insertionPointShape) {
453             int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
454             ipRect.size.width = frac;
455         }
457         [[self insertionPointColor] set];
458         if (MMInsertionPointHollow == insertionPointShape) {
459             NSFrameRect(ipRect);
460         } else {
461             NSRectFill(ipRect);
462         }
464         // NOTE: We only draw the cursor once and rely on Vim to say when it
465         // should be drawn again.
466         shouldDrawInsertionPoint = NO;
468         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
469         //        NSStringFromRect(ipRect), insertionPointShape,
470         //        [self insertionPointColor]);
471     }
472 #if 0
473     // this code invalidates the shadow, so we don't 
474     // get shifting ghost text on scroll and resize
475     // but makes speed unusable
476     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
477     if ([ts defaultBackgroundAlpha] < 1.0f) {
478         if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
479         {
480             [[self window] setHasShadow:NO];
481             [[self window] setHasShadow:YES];
482         }
483         else
484             [[self window] invalidateShadow];
486     }
487 #endif
490 - (void)keyDown:(NSEvent *)event
492     //NSLog(@"%s %@", _cmd, event);
493     // HACK! If control modifier is held, don't pass the event along to
494     // interpretKeyEvents: since some keys are bound to multiple commands which
495     // means doCommandBySelector: is called several times.  Do the same for
496     // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
497     // commands).  This hack may break input management, but unless we can
498     // figure out a way to disable key bindings there seems little else to do.
499     //
500     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
501     // affecting input management.
502     int flags = [event modifierFlags];
503     if ((flags & NSControlKeyMask) ||
504             ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
505         NSString *unmod = [event charactersIgnoringModifiers];
506         if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
507                                 && [unmod characterAtIndex:0] >= 0x60) {
508             // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
509             // as normal text to be added to the Vim input buffer.  This must
510             // be done in order for the backend to be able to separate e.g.
511             // Ctrl-i and Ctrl-tab.
512             [self insertText:[event characters]];
513         } else {
514             [self dispatchKeyEvent:event];
515         }
516     } else {
517         [super keyDown:event];
518     }
521 - (void)insertText:(id)string
523     //NSLog(@"%s %@", _cmd, string);
524     // NOTE!  This method is called for normal key presses but also for
525     // Option-key presses --- even when Ctrl is held as well as Option.  When
526     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
527     // so 'string' need not be a printable character!  In this case it still
528     // works to pass 'string' on to Vim as a printable character (since
529     // modifiers are already included and should not be added to the input
530     // buffer using CSI, K_MODIFIER).
532     [self hideMarkedTextField];
534     NSEvent *event = [NSApp currentEvent];
536     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
537     // to watch for them here.
538     if ([event type] == NSKeyDown
539             && [[event charactersIgnoringModifiers] length] > 0
540             && [event modifierFlags]
541                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
542         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
544         // <S-M-Tab> translates to 0x19 
545         if (' ' == c || 0x19 == c) {
546             [self dispatchKeyEvent:event];
547             return;
548         }
549     }
551     // TODO: Support 'mousehide' (check p_mh)
552     [NSCursor setHiddenUntilMouseMoves:YES];
554     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
555     // do not support attributes, simply pass the corresponding NSString in the
556     // latter case.
557     if ([string isKindOfClass:[NSAttributedString class]])
558         string = [string string];
560     //NSLog(@"send InsertTextMsgID: %@", string);
562     [[self vimController] sendMessage:InsertTextMsgID
563                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
567 - (void)doCommandBySelector:(SEL)selector
569     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
570     // By ignoring the selector we effectively disable the key binding
571     // mechanism of Cocoa.  Hopefully this is what the user will expect
572     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
573     // match, etc.).
574     //
575     // We usually end up here if the user pressed Ctrl+key (but not
576     // Ctrl+Option+key).
578     NSEvent *event = [NSApp currentEvent];
580     if (selector == @selector(cancelOperation:)
581             || selector == @selector(insertNewline:)) {
582         // HACK! If there was marked text which got abandoned as a result of
583         // hitting escape or enter, then 'insertText:' is called with the
584         // abandoned text but '[event characters]' includes the abandoned text
585         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
586         // must intercept these keys here or the abandonded text gets inserted
587         // twice.
588         NSString *key = [event charactersIgnoringModifiers];
589         const char *chars = [key UTF8String];
590         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
592         if (0x3 == chars[0]) {
593             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
594             // handle it separately (else Ctrl-C doesn't work).
595             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
596             chars = MMKeypadEnter;
597         }
599         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
600     } else {
601         [self dispatchKeyEvent:event];
602     }
605 - (BOOL)performKeyEquivalent:(NSEvent *)event
607     //NSLog(@"%s %@", _cmd, event);
608     // Called for Cmd+key keystrokes, function keys, arrow keys, page
609     // up/down, home, end.
610     //
611     // NOTE: This message cannot be ignored since Cmd+letter keys never are
612     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
613     // strokes, unless the key is a function key.
615     // NOTE: If the event that triggered this method represents a function key
616     // down then we do nothing, otherwise the input method never gets the key
617     // stroke (some input methods use e.g. arrow keys).  The function key down
618     // event will still reach Vim though (via keyDown:).  The exceptions to
619     // this rule are: PageUp/PageDown (keycode 116/121).
620     int flags = [event modifierFlags];
621     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
622             && !(116 == [event keyCode] || 121 == [event keyCode]))
623         return NO;
625     // HACK!  Let the main menu try to handle any key down event, before
626     // passing it on to vim, otherwise key equivalents for menus will
627     // effectively be disabled.
628     if ([[NSApp mainMenu] performKeyEquivalent:event])
629         return YES;
631     // HACK!  KeyCode 50 represent the key which switches between windows
632     // within an application (like Cmd+Tab is used to switch between
633     // applications).  Return NO here, else the window switching does not work.
634     //
635     // Will this hack work for all languages / keyboard layouts?
636     if ([event keyCode] == 50)
637         return NO;
639     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
640     if (flags & NSControlKeyMask) {
641         [self keyDown:event];
642         return YES;
643     }
645     //NSLog(@"%s%@", _cmd, event);
647     NSString *chars = [event characters];
648     NSString *unmodchars = [event charactersIgnoringModifiers];
649     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
650     NSMutableData *data = [NSMutableData data];
652     if (len <= 0)
653         return NO;
655     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
656     // can clear the shift flag as it is already included in 'unmodchars'.
657     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
658     // an English keyboard).
659     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
660         flags &= ~NSShiftKeyMask;
662     if (0x3 == [unmodchars characterAtIndex:0]) {
663         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
664         // handle it separately (else Cmd-enter turns into Ctrl-C).
665         unmodchars = MMKeypadEnterString;
666         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
667     }
669     [data appendBytes:&flags length:sizeof(int)];
670     [data appendBytes:&len length:sizeof(int)];
671     [data appendBytes:[unmodchars UTF8String] length:len];
673     [[self vimController] sendMessage:CmdKeyMsgID data:data];
675     return YES;
678 - (BOOL)hasMarkedText
680     //NSLog(@"%s", _cmd);
681     return markedTextField && [[markedTextField stringValue] length] > 0;
684 - (NSRange)markedRange
686     //NSLog(@"%s", _cmd);
687     unsigned len = [[markedTextField stringValue] length];
688     return NSMakeRange(len > 0 ? 0 : NSNotFound, len);
691 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
693     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
694     //        NSStringFromRange(range));
696     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
697     if (!ts) return;
699     if (!markedTextField) {
700         // Create a text field and put it inside a floating panel.  This field
701         // is used to display marked text.
702         NSSize cellSize = [ts cellSize];
703         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
705         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
706         [markedTextField setEditable:NO];
707         [markedTextField setSelectable:NO];
708         [markedTextField setBezeled:NO];
709         [markedTextField setBordered:YES];
711         // NOTE: The panel that holds the marked text field is allocated here
712         // and released in dealloc.  No pointer to the panel is kept, instead
713         // [markedTextField window] is used to access the panel.
714         NSPanel *panel = [[NSPanel alloc]
715             initWithContentRect:cellRect
716                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
717                         backing:NSBackingStoreBuffered
718                           defer:YES];
720         //[panel setHidesOnDeactivate:NO];
721         [panel setFloatingPanel:YES];
722         [panel setBecomesKeyOnlyIfNeeded:YES];
723         [panel setContentView:markedTextField];
724     }
726     if (text && [text length] > 0) {
727         [markedTextField setFont:[ts font]];
728         if ([text isKindOfClass:[NSAttributedString class]])
729             [markedTextField setAttributedStringValue:text];
730         else
731             [markedTextField setStringValue:text];
733         [markedTextField sizeToFit];
734         NSSize size = [markedTextField frame].size;
736         // Convert coordinates (row,col) -> view -> window base -> screen
737         NSPoint origin;
738         if (![self convertRow:preEditRow+1 column:preEditColumn
739                      toPoint:&origin])
740             return;
741         origin = [self convertPoint:origin toView:nil];
742         origin = [[self window] convertBaseToScreen:origin];
744         NSWindow *win = [markedTextField window];
745         [win setContentSize:size];
746         [win setFrameOrigin:origin];
747         [win orderFront:nil];
748     } else {
749         [self hideMarkedTextField];
750     }
753 - (void)unmarkText
755     //NSLog(@"%s", _cmd);
756     [self hideMarkedTextField];
759 - (NSRect)firstRectForCharacterRange:(NSRange)range
761     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
762     // HACK!  This method is called when the input manager wants to pop up an
763     // auxiliary window.  The position where this should be is controller by
764     // Vim by sending SetPreEditPositionMsgID so compute a position based on
765     // the pre-edit (row,column) pair.
766     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
768     NSRect rect = [ts boundingRectForCharacterAtRow:preEditRow
769                                              column:preEditColumn];
770     rect.origin.x += [self textContainerOrigin].x;
771     rect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
773     rect.origin = [self convertPoint:rect.origin toView:nil];
774     rect.origin = [[self window] convertBaseToScreen:rect.origin];
776     return rect;
779 - (void)scrollWheel:(NSEvent *)event
781     if ([event deltaY] == 0)
782         return;
784     int row, col;
785     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
786     if (![self convertPoint:pt toRow:&row column:&col])
787         return;
789     int flags = [event modifierFlags];
790     float dy = [event deltaY];
791     NSMutableData *data = [NSMutableData data];
793     [data appendBytes:&row length:sizeof(int)];
794     [data appendBytes:&col length:sizeof(int)];
795     [data appendBytes:&flags length:sizeof(int)];
796     [data appendBytes:&dy length:sizeof(float)];
798     [[self vimController] sendMessage:ScrollWheelMsgID data:data];
801 - (void)mouseDown:(NSEvent *)event
803     int row, col;
804     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
805     if (![self convertPoint:pt toRow:&row column:&col])
806         return;
808     lastMouseDownEvent = [event copy];
810     int button = [event buttonNumber];
811     int flags = [event modifierFlags];
812     int count = [event clickCount];
813     NSMutableData *data = [NSMutableData data];
815     // If desired, intepret Ctrl-Click as a right mouse click.
816     if ([[NSUserDefaults standardUserDefaults]
817             boolForKey:MMTranslateCtrlClickKey]
818             && button == 0 && flags & NSControlKeyMask) {
819         button = 1;
820         flags &= ~NSControlKeyMask;
821     }
823     [data appendBytes:&row length:sizeof(int)];
824     [data appendBytes:&col length:sizeof(int)];
825     [data appendBytes:&button length:sizeof(int)];
826     [data appendBytes:&flags length:sizeof(int)];
827     [data appendBytes:&count length:sizeof(int)];
829     [[self vimController] sendMessage:MouseDownMsgID data:data];
832 - (void)rightMouseDown:(NSEvent *)event
834     [self mouseDown:event];
837 - (void)otherMouseDown:(NSEvent *)event
839     [self mouseDown:event];
842 - (void)mouseUp:(NSEvent *)event
844     int row, col;
845     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
846     if (![self convertPoint:pt toRow:&row column:&col])
847         return;
849     int flags = [event modifierFlags];
850     NSMutableData *data = [NSMutableData data];
852     [data appendBytes:&row length:sizeof(int)];
853     [data appendBytes:&col length:sizeof(int)];
854     [data appendBytes:&flags length:sizeof(int)];
856     [[self vimController] sendMessage:MouseUpMsgID data:data];
858     isDragging = NO;
861 - (void)rightMouseUp:(NSEvent *)event
863     [self mouseUp:event];
866 - (void)otherMouseUp:(NSEvent *)event
868     [self mouseUp:event];
871 - (void)mouseDragged:(NSEvent *)event
873     int flags = [event modifierFlags];
874     int row, col;
875     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
876     if (![self convertPoint:pt toRow:&row column:&col])
877         return;
879     // Autoscrolling is done in dragTimerFired:
880     if (!isAutoscrolling) {
881         NSMutableData *data = [NSMutableData data];
883         [data appendBytes:&row length:sizeof(int)];
884         [data appendBytes:&col length:sizeof(int)];
885         [data appendBytes:&flags length:sizeof(int)];
887         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
888     }
890     dragPoint = pt;
891     dragRow = row; dragColumn = col; dragFlags = flags;
892     if (!isDragging) {
893         [self startDragTimerWithInterval:.5];
894         isDragging = YES;
895     }
898 - (void)rightMouseDragged:(NSEvent *)event
900     [self mouseDragged:event];
903 - (void)otherMouseDragged:(NSEvent *)event
905     [self mouseDragged:event];
908 - (void)mouseMoved:(NSEvent *)event
910     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
911     if (!ts) return;
913     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
914     int row, col;
915     if (![self convertPoint:pt toRow:&row column:&col])
916         return;
918     // HACK! It seems impossible to get the tracking rects set up before the
919     // view is visible, which means that the first mouseEntered: or
920     // mouseExited: events are never received.  This forces us to check if the
921     // mouseMoved: event really happened over the text.
922     int rows, cols;
923     [ts getMaxRows:&rows columns:&cols];
924     if (row >= 0 && row < rows && col >= 0 && col < cols) {
925         NSMutableData *data = [NSMutableData data];
927         [data appendBytes:&row length:sizeof(int)];
928         [data appendBytes:&col length:sizeof(int)];
930         [[self vimController] sendMessage:MouseMovedMsgID data:data];
931     }
934 - (void)mouseEntered:(NSEvent *)event
936     //NSLog(@"%s", _cmd);
938     // NOTE: This event is received even when the window is not key; thus we
939     // have to take care not to enable mouse moved events unless our window is
940     // key.
941     if ([[self window] isKeyWindow])
942         [[self window] setAcceptsMouseMovedEvents:YES];
945 - (void)mouseExited:(NSEvent *)event
947     //NSLog(@"%s", _cmd);
949     [[self window] setAcceptsMouseMovedEvents:NO];
951     // NOTE: This event is received even when the window is not key; if the
952     // mouse shape is set when our window is not key, the hollow (unfocused)
953     // cursor will become a block (focused) cursor.
954     if ([[self window] isKeyWindow]) {
955         int shape = 0;
956         NSMutableData *data = [NSMutableData data];
957         [data appendBytes:&shape length:sizeof(int)];
958         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
959     }
962 - (void)setFrame:(NSRect)frame
964     //NSLog(@"%s", _cmd);
966     // When the frame changes we also need to update the tracking rect.
967     [super setFrame:frame];
968     [self removeTrackingRect:trackingRectTag];
969     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
970                                    userData:NULL assumeInside:YES];
973 - (void)viewDidMoveToWindow
975     //NSLog(@"%s (window=%@)", _cmd, [self window]);
977     // Set a tracking rect which covers the text.
978     // NOTE: While the mouse cursor is in this rect the view will receive
979     // 'mouseMoved:' events so that Vim can take care of updating the mouse
980     // cursor.
981     if ([self window]) {
982         [[self window] setAcceptsMouseMovedEvents:YES];
983         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
984                                        userData:NULL assumeInside:YES];
985     }
988 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
990     //NSLog(@"%s%@", _cmd, newWindow);
992     // Remove tracking rect if view moves or is removed.
993     if ([self window] && trackingRectTag) {
994         [self removeTrackingRect:trackingRectTag];
995         trackingRectTag = 0;
996     }
999 - (NSMenu*)menuForEvent:(NSEvent *)event
1001     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
1002     // own).  Called when user Ctrl-clicks in the view (this is already handled
1003     // in rightMouseDown:).
1004     return nil;
1007 - (NSArray *)acceptableDragTypes
1009     return [NSArray arrayWithObjects:NSFilenamesPboardType,
1010            NSStringPboardType, nil];
1013 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
1015     NSPasteboard *pboard = [sender draggingPasteboard];
1017     if ([[pboard types] containsObject:NSStringPboardType]) {
1018         NSString *string = [pboard stringForType:NSStringPboardType];
1019         [[self vimController] dropString:string];
1020         return YES;
1021     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
1022         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
1023         [[self vimController] dropFiles:files forceOpen:NO];
1024         return YES;
1025     }
1027     return NO;
1030 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
1032     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1033     NSPasteboard *pboard = [sender draggingPasteboard];
1035     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1036             && (sourceDragMask & NSDragOperationCopy) )
1037         return NSDragOperationCopy;
1038     if ( [[pboard types] containsObject:NSStringPboardType]
1039             && (sourceDragMask & NSDragOperationCopy) )
1040         return NSDragOperationCopy;
1042     return NSDragOperationNone;
1045 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
1047     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
1048     NSPasteboard *pboard = [sender draggingPasteboard];
1050     if ( [[pboard types] containsObject:NSFilenamesPboardType]
1051             && (sourceDragMask & NSDragOperationCopy) )
1052         return NSDragOperationCopy;
1053     if ( [[pboard types] containsObject:NSStringPboardType]
1054             && (sourceDragMask & NSDragOperationCopy) )
1055         return NSDragOperationCopy;
1057     return NSDragOperationNone;
1060 - (void)changeFont:(id)sender
1062     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1063     if (!ts) return;
1065     NSFont *oldFont = [ts font];
1066     NSFont *newFont = [sender convertFont:oldFont];
1068     if (newFont) {
1069         NSString *name = [newFont displayName];
1070         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1071         if (len > 0) {
1072             NSMutableData *data = [NSMutableData data];
1073             float pointSize = [newFont pointSize];
1075             [data appendBytes:&pointSize length:sizeof(float)];
1077             ++len;  // include NUL byte
1078             [data appendBytes:&len length:sizeof(unsigned)];
1079             [data appendBytes:[name UTF8String] length:len];
1081             [[self vimController] sendMessage:SetFontMsgID data:data];
1082         }
1083     }
1086 - (void)resetCursorRects
1088     // No need to set up cursor rects since Vim handles cursor changes.
1091 - (void)updateFontPanel
1093     // The font panel is updated whenever the font is set.
1096 @end // MMTextView
1101 @implementation MMTextView (Private)
1103 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
1105     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1106     NSSize cellSize = [ts cellSize];
1107     if (!(cellSize.width > 0 && cellSize.height > 0))
1108         return NO;
1109     NSPoint origin = [self textContainerOrigin];
1111     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
1112     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
1114     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
1115     //        *row, *column);
1117     return YES;
1120 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
1122     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
1123     NSSize cellSize = [ts cellSize];
1124     if (!(point && cellSize.width > 0 && cellSize.height > 0))
1125         return NO;
1127     *point = [self textContainerOrigin];
1128     point->x += column * cellSize.width;
1129     point->y += row * cellSize.height;
1131     return YES;
1134 - (NSRect)trackingRect
1136     NSRect rect = [self frame];
1137     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
1138     int left = [ud integerForKey:MMTextInsetLeftKey];
1139     int top = [ud integerForKey:MMTextInsetTopKey];
1140     int right = [ud integerForKey:MMTextInsetRightKey];
1141     int bot = [ud integerForKey:MMTextInsetBottomKey];
1143     rect.origin.x = left;
1144     rect.origin.y = top;
1145     rect.size.width -= left + right - 1;
1146     rect.size.height -= top + bot - 1;
1148     return rect;
1151 - (void)dispatchKeyEvent:(NSEvent *)event
1153     // Only handle the command if it came from a keyDown event
1154     if ([event type] != NSKeyDown)
1155         return;
1157     NSString *chars = [event characters];
1158     NSString *unmodchars = [event charactersIgnoringModifiers];
1159     unichar c = [chars characterAtIndex:0];
1160     unichar imc = [unmodchars characterAtIndex:0];
1161     int len = 0;
1162     const char *bytes = 0;
1163     int mods = [event modifierFlags];
1165     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
1166     //        _cmd, c, imc, chars, unmodchars);
1168     if (' ' == imc && 0xa0 != c) {
1169         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
1170         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
1171         // should be passed on as is.)
1172         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1173         bytes = [unmodchars UTF8String];
1174     } else if (imc == c && '2' == c) {
1175         // HACK!  Translate Ctrl+2 to <C-@>.
1176         static char ctrl_at = 0;
1177         len = 1;  bytes = &ctrl_at;
1178     } else if (imc == c && '6' == c) {
1179         // HACK!  Translate Ctrl+6 to <C-^>.
1180         static char ctrl_hat = 0x1e;
1181         len = 1;  bytes = &ctrl_hat;
1182     } else if (c == 0x19 && imc == 0x19) {
1183         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
1184         // separately (else Ctrl-Y doesn't work).
1185         static char tab = 0x9;
1186         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
1187     } else {
1188         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
1189         bytes = [chars UTF8String];
1190     }
1192     [self sendKeyDown:bytes length:len modifiers:mods];
1195 - (MMVimController *)vimController
1197     id windowController = [[self window] windowController];
1199     // TODO: Make sure 'windowController' is a MMWindowController before type
1200     // casting.
1201     return [(MMWindowController*)windowController vimController];
1204 - (void)startDragTimerWithInterval:(NSTimeInterval)t
1206     [NSTimer scheduledTimerWithTimeInterval:t target:self
1207                                    selector:@selector(dragTimerFired:)
1208                                    userInfo:nil repeats:NO];
1211 - (void)dragTimerFired:(NSTimer *)timer
1213     // TODO: Autoscroll in horizontal direction?
1214     static unsigned tick = 1;
1215     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
1217     isAutoscrolling = NO;
1219     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
1220         // HACK! If the mouse cursor is outside the text area, then send a
1221         // dragged event.  However, if row&col hasn't changed since the last
1222         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
1223         // Thus we fiddle with the column to make sure something happens.
1224         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
1225         NSMutableData *data = [NSMutableData data];
1227         [data appendBytes:&dragRow length:sizeof(int)];
1228         [data appendBytes:&col length:sizeof(int)];
1229         [data appendBytes:&dragFlags length:sizeof(int)];
1231         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
1233         isAutoscrolling = YES;
1234     }
1236     if (isDragging) {
1237         // Compute timer interval depending on how far away the mouse cursor is
1238         // from the text view.
1239         NSRect rect = [self trackingRect];
1240         float dy = 0;
1241         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
1242         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
1243         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
1245         NSTimeInterval t = MMDragTimerMaxInterval -
1246             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
1248         [self startDragTimerWithInterval:t];
1249     }
1251     ++tick;
1254 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
1256     if (chars && len > 0) {
1257         NSMutableData *data = [NSMutableData data];
1259         [data appendBytes:&flags length:sizeof(int)];
1260         [data appendBytes:&len length:sizeof(int)];
1261         [data appendBytes:chars length:len];
1263         // TODO: Support 'mousehide' (check p_mh)
1264         [NSCursor setHiddenUntilMouseMoves:YES];
1266         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
1267         [[self vimController] sendMessage:KeyDownMsgID data:data];
1268     }
1271 @end // MMTextView (Private)