Fixed rounding problem when looking up system colors.
[MacVim/jjgod.git] / MMTextView.m
blob27afcd2b1375257bc807ffc0f50032a7f22d7cfb
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 #import "MMTextView.h"
12 #import "MMTextStorage.h"
13 #import "MMWindowController.h"
14 #import "MMVimController.h"
15 #import "MacVim.h"
19 // The max/min drag timer interval in seconds
20 static NSTimeInterval MMDragTimerMaxInterval = .3f;
21 static NSTimeInterval MMDragTimerMinInterval = .01f;
23 // The number of pixels in which the drag timer interval changes
24 static float MMDragAreaSize = 73.0f;
29 @interface MMTextView (Private)
30 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
31 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
32 - (NSRect)trackingRect;
33 - (void)dispatchKeyEvent:(NSEvent *)event;
34 - (MMVimController *)vimController;
35 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
36 - (void)dragTimerFired:(NSTimer *)timer;
37 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
38 @end
42 @implementation MMTextView
44 - (void)dealloc
46     if (markedTextField) {
47         [[markedTextField window] autorelease];
48         [markedTextField release];
49         markedTextField = nil;
50     }
52     [lastMouseDownEvent release];
53     [super dealloc];
56 - (NSEvent *)lastMouseDownEvent
58     return lastMouseDownEvent;
61 - (BOOL)shouldDrawInsertionPoint
63     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
64     // nice to be able to use the insertion point related methods of
65     // NSTextView, but it seems impossible to get them to work properly (search
66     // the cocoabuilder archives).
67     return NO;
70 - (void)setShouldDrawInsertionPoint:(BOOL)on
72     shouldDrawInsertionPoint = on;
75 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
76                        fraction:(int)percent color:(NSColor *)color
78     //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
79     //        row, col, shape, color);
81     // This only stores where to draw the insertion point, the actual drawing
82     // is done in drawRect:.
83     shouldDrawInsertionPoint = YES;
84     insertionPointRow = row;
85     insertionPointColumn = col;
86     insertionPointShape = shape;
87     insertionPointFraction = percent;
89     [self setInsertionPointColor:color];
92 - (void)hideMarkedTextField
94     if (markedTextField) {
95         NSWindow *win = [markedTextField window];
96         [win close];
97         [markedTextField setStringValue:@""];
98     }
101 - (void)drawRect:(NSRect)rect
103     [super drawRect:rect];
105     if (shouldDrawInsertionPoint) {
106         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
107         NSLayoutManager *lm = [self layoutManager];
108         NSTextContainer *tc = [self textContainer];
110         // Given (row,column), calculate the bounds of the glyph at that spot.
111         // We use the layout manager because this gives us exactly the size and
112         // location of the glyph so that we can match the insertion point to
113         // it.
114         unsigned charIdx = [ts characterIndexForRow:insertionPointRow
115                                              column:insertionPointColumn];
116         NSRange glyphRange =
117             [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
118                        actualCharacterRange:NULL];
119         NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
120                                       inTextContainer:tc];
121         ipRect.origin.x += [self textContainerOrigin].x;
122         ipRect.origin.y += [self textContainerOrigin].y;
124         if (MMInsertionPointHorizontal == insertionPointShape) {
125             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
126             ipRect.origin.y += ipRect.size.height - frac;
127             ipRect.size.height = frac;
128         } else if (MMInsertionPointVertical == insertionPointShape) {
129             int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
130             ipRect.size.width = frac;
131         }
133         [[self insertionPointColor] set];
134         if (MMInsertionPointHollow == insertionPointShape) {
135             NSFrameRect(ipRect);
136         } else {
137             NSRectFill(ipRect);
138         }
140         // NOTE: We only draw the cursor once and rely on Vim to say when it
141         // should be drawn again.
142         shouldDrawInsertionPoint = NO;
144         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
145         //        NSStringFromRect(ipRect), insertionPointShape,
146         //        [self insertionPointColor]);
147     }
150 - (void)keyDown:(NSEvent *)event
152     //NSLog(@"%s %@", _cmd, event);
153     // HACK! If a modifier is held, don't pass the event along to
154     // interpretKeyEvents: since some keys are bound to multiple commands which
155     // means doCommandBySelector: is called several times.
156     //
157     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
158     // affecting input management.
160     if ([event modifierFlags] & NSControlKeyMask)
161         [self dispatchKeyEvent:event];
162     else
163         [super keyDown:event];
166 - (void)insertText:(id)string
168     //NSLog(@"%s %@", _cmd, string);
169     // NOTE!  This method is called for normal key presses but also for
170     // Option-key presses --- even when Ctrl is held as well as Option.  When
171     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
172     // so 'string' need not be a printable character!  In this case it still
173     // works to pass 'string' on to Vim as a printable character (since
174     // modifiers are already included and should not be added to the input
175     // buffer using CSI, K_MODIFIER).
177     [self hideMarkedTextField];
179     NSEvent *event = [NSApp currentEvent];
181     // HACK!  In order to be able to bind to <S-Space> etc. we have to watch
182     // for when space was pressed.
183     if ([event type] == NSKeyDown
184             && [[event charactersIgnoringModifiers] length] > 0
185             && [[event charactersIgnoringModifiers] characterAtIndex:0] == ' '
186             && [event modifierFlags]
187                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask))
188     {
189         [self dispatchKeyEvent:event];
190         return;
191     }
193     // TODO: Support 'mousehide' (check p_mh)
194     [NSCursor setHiddenUntilMouseMoves:YES];
196     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
197     // do not support attributes, simply pass the corresponding NSString in the
198     // latter case.
199     if ([string isKindOfClass:[NSAttributedString class]])
200         string = [string string];
202     [[self vimController] sendMessage:InsertTextMsgID
203                  data:[string dataUsingEncoding:NSUTF8StringEncoding]
204                  wait:NO];
208 - (void)doCommandBySelector:(SEL)selector
210     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
211     // By ignoring the selector we effectively disable the key binding
212     // mechanism of Cocoa.  Hopefully this is what the user will expect
213     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
214     // match, etc.).
215     //
216     // We usually end up here if the user pressed Ctrl+key (but not
217     // Ctrl+Option+key).
219     NSEvent *event = [NSApp currentEvent];
221     if (selector == @selector(cancelOperation:)
222             || selector == @selector(insertNewline:)) {
223         // HACK! If there was marked text which got abandoned as a result of
224         // hitting escape or enter, then 'insertText:' is called with the
225         // abandoned text but '[event characters]' includes the abandoned text
226         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
227         // must intercept these keys here or the abandonded text gets inserted
228         // twice.
229         NSString *key = [event charactersIgnoringModifiers];
230         const char *chars = [key UTF8String];
231         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
233         if (0x3 == chars[0]) {
234             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
235             // handle it separately (else Ctrl-C doesn't work).
236             static char keypadEnter[2] = { 'K', 'A' };
237             len = 2; chars = keypadEnter;
238         }
240         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
241     } else {
242         [self dispatchKeyEvent:event];
243     }
246 #if 0
247 // Confused note to self: Why did I implement this in the first place?  Will
248 // something break if I don't?  Input methods that use arrow keys do not work
249 // properly with this implementation, so it is disabled for now.
250 - (BOOL)performKeyEquivalent:(NSEvent *)event
252     NSLog(@"%s %@", _cmd, event);
253     // Called for Cmd+key keystrokes, function keys, arrow keys, page
254     // up/down, home, end.
256     if ([event type] != NSKeyDown)
257         return NO;
259     // HACK!  Let the main menu try to handle any key down event, before
260     // passing it on to vim, otherwise key equivalents for menus will
261     // effectively be disabled.
262     if ([[NSApp mainMenu] performKeyEquivalent:event])
263         return YES;
265     // HACK!  KeyCode 50 represent the key which switches between windows
266     // within an application (like Cmd+Tab is used to switch between
267     // applications).  Return NO here, else the window switching does not work.
268     //
269     // Will this hack work for all languages / keyboard layouts?
270     if ([event keyCode] == 50)
271         return NO;
273     //NSLog(@"%s%@", _cmd, event);
275     NSString *string = [event charactersIgnoringModifiers];
276     int flags = [event modifierFlags];
277     int len = [string lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
278     NSMutableData *data = [NSMutableData data];
280     [data appendBytes:&flags length:sizeof(int)];
281     [data appendBytes:&len length:sizeof(int)];
282     [data appendBytes:[string UTF8String] length:len];
284     [[self vimController] sendMessage:CmdKeyMsgID data:data wait:NO];
286     return YES;
288 #endif
290 - (BOOL)hasMarkedText
292     //NSLog(@"%s", _cmd);
293     return markedTextField && [[markedTextField stringValue] length] > 0;
296 - (NSRange)markedRange
298     //NSLog(@"%s", _cmd);
299     // HACK! If a valid range is returned, then NSTextView changes the
300     // background color of the returned range.  Since marked text is displayed
301     // in a separate popup window this behaviour is not wanted.  By setting the
302     // location of the returned range to NSNotFound NSTextView does nothing.
303     // This hack is continued in 'firstRectForCharacterRange:'.
304     return NSMakeRange(NSNotFound, 0);
307 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
309     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
310     //        NSStringFromRange(range));
312     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
313     if (!ts) return;
315     if (!markedTextField) {
316         // Create a text field and put it inside a floating panel.  This field
317         // is used to display marked text.
318         NSSize cellSize = [ts cellSize];
319         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
321         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
322         [markedTextField setEditable:NO];
323         [markedTextField setSelectable:NO];
324         [markedTextField setBezeled:NO];
325         [markedTextField setBordered:YES];
327         NSPanel *panel = [[NSPanel alloc]
328             initWithContentRect:cellRect
329                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
330                         backing:NSBackingStoreBuffered
331                           defer:YES];
333         //[panel setHidesOnDeactivate:NO];
334         [panel setFloatingPanel:YES];
335         [panel setBecomesKeyOnlyIfNeeded:YES];
336         [panel setContentView:markedTextField];
337     }
339     if (text && [text length] > 0) {
340         [markedTextField setFont:[ts font]];
341         if ([text isKindOfClass:[NSAttributedString class]])
342             [markedTextField setAttributedStringValue:text];
343         else
344             [markedTextField setStringValue:text];
346         [markedTextField sizeToFit];
347         NSSize size = [markedTextField frame].size;
349         // Convert coordinates (row,col) -> view -> window base -> screen
350         NSPoint origin;
351         if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
352                      toPoint:&origin])
353             return;
354         origin = [self convertPoint:origin toView:nil];
355         origin = [[self window] convertBaseToScreen:origin];
357         NSWindow *win = [markedTextField window];
358         [win setContentSize:size];
359         [win setFrameOrigin:origin];
360         [win orderFront:nil];
361     } else {
362         [self hideMarkedTextField];
363     }
366 - (void)unmarkText
368     //NSLog(@"%s", _cmd);
369     [self hideMarkedTextField];
372 - (NSRect)firstRectForCharacterRange:(NSRange)range
374     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
376     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
377     NSLayoutManager *lm = [self layoutManager];
378     NSTextContainer *tc = [self textContainer];
380     // HACK! Since we always return marked text to have location NSNotFound,
381     // this method will be called with 'range.location == NSNotFound' whenever
382     // the input manager tries to position a popup window near the insertion
383     // point.  For this reason we compute where the insertion point is and
384     // return a rect which contains it.
385     if (!(ts && lm && tc) || NSNotFound != range.location)
386         return [super firstRectForCharacterRange:range];
388     unsigned charIdx = [ts characterIndexForRow:insertionPointRow
389                                          column:insertionPointColumn];
390     NSRange glyphRange =
391         [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
392                    actualCharacterRange:NULL];
393     NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
394                                   inTextContainer:tc];
395     ipRect.origin.x += [self textContainerOrigin].x;
396     ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
398     ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
399     ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
401     return ipRect;
404 - (void)scrollWheel:(NSEvent *)event
406     if ([event deltaY] == 0)
407         return;
409     int row, col;
410     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
411     if (![self convertPoint:pt toRow:&row column:&col])
412         return;
414     int flags = [event modifierFlags];
415     float dy = [event deltaY];
416     NSMutableData *data = [NSMutableData data];
418     [data appendBytes:&row length:sizeof(int)];
419     [data appendBytes:&col length:sizeof(int)];
420     [data appendBytes:&flags length:sizeof(int)];
421     [data appendBytes:&dy length:sizeof(float)];
423     [[self vimController] sendMessage:ScrollWheelMsgID data:data wait:NO];
426 - (void)mouseDown:(NSEvent *)event
428     int row, col;
429     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
430     if (![self convertPoint:pt toRow:&row column:&col])
431         return;
433     lastMouseDownEvent = [event copy];
435     int button = [event buttonNumber];
436     int flags = [event modifierFlags];
437     int count = [event clickCount];
438     NSMutableData *data = [NSMutableData data];
440     // If desired, intepret Ctrl-Click as a right mouse click.
441     if ([[NSUserDefaults standardUserDefaults]
442             boolForKey:MMTranslateCtrlClickKey]
443             && button == 0 && flags & NSControlKeyMask) {
444         button = 1;
445         flags &= ~NSControlKeyMask;
446     }
448     [data appendBytes:&row length:sizeof(int)];
449     [data appendBytes:&col length:sizeof(int)];
450     [data appendBytes:&button length:sizeof(int)];
451     [data appendBytes:&flags length:sizeof(int)];
452     [data appendBytes:&count length:sizeof(int)];
454     [[self vimController] sendMessage:MouseDownMsgID data:data wait:NO];
457 - (void)rightMouseDown:(NSEvent *)event
459     [self mouseDown:event];
462 - (void)otherMouseDown:(NSEvent *)event
464     [self mouseDown:event];
467 - (void)mouseUp:(NSEvent *)event
469     int row, col;
470     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
471     if (![self convertPoint:pt toRow:&row column:&col])
472         return;
474     int flags = [event modifierFlags];
475     NSMutableData *data = [NSMutableData data];
477     [data appendBytes:&row length:sizeof(int)];
478     [data appendBytes:&col length:sizeof(int)];
479     [data appendBytes:&flags length:sizeof(int)];
481     [[self vimController] sendMessage:MouseUpMsgID data:data wait:NO];
483     isDragging = NO;
486 - (void)rightMouseUp:(NSEvent *)event
488     [self mouseUp:event];
491 - (void)otherMouseUp:(NSEvent *)event
493     [self mouseUp:event];
496 - (void)mouseDragged:(NSEvent *)event
498     int flags = [event modifierFlags];
499     int row, col;
500     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
501     if (![self convertPoint:pt toRow:&row column:&col])
502         return;
504     // Autoscrolling is done in dragTimerFired:
505     if (!isAutoscrolling) {
506         NSMutableData *data = [NSMutableData data];
508         [data appendBytes:&row length:sizeof(int)];
509         [data appendBytes:&col length:sizeof(int)];
510         [data appendBytes:&flags length:sizeof(int)];
512         [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
513     }
515     dragPoint = pt;
516     dragRow = row; dragColumn = col; dragFlags = flags;
517     if (!isDragging) {
518         [self startDragTimerWithInterval:.5];
519         isDragging = YES;
520     }
523 - (void)rightMouseDragged:(NSEvent *)event
525     [self mouseDragged:event];
528 - (void)otherMouseDragged:(NSEvent *)event
530     [self mouseDragged:event];
533 - (void)mouseMoved:(NSEvent *)event
535     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
536     if (!ts) return;
538     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
539     int row, col;
540     if (![self convertPoint:pt toRow:&row column:&col])
541         return;
543     // HACK! It seems impossible to get the tracking rects set up before the
544     // view is visible, which means that the first mouseEntered: or
545     // mouseExited: events are never received.  This forces us to check if the
546     // mouseMoved: event really happened over the text.
547     int rows, cols;
548     [ts getMaxRows:&rows columns:&cols];
549     if (row >= 0 && row < rows && col >= 0 && col < cols) {
550         NSMutableData *data = [NSMutableData data];
552         [data appendBytes:&row length:sizeof(int)];
553         [data appendBytes:&col length:sizeof(int)];
555         [[self vimController] sendMessage:MouseMovedMsgID data:data wait:NO];
556     }
559 - (void)mouseEntered:(NSEvent *)event
561     //NSLog(@"%s", _cmd);
563     // NOTE: This event is received even when the window is not key; thus we
564     // have to take care not to enable mouse moved events unless our window is
565     // key.
566     if ([[self window] isKeyWindow])
567         [[self window] setAcceptsMouseMovedEvents:YES];
570 - (void)mouseExited:(NSEvent *)event
572     //NSLog(@"%s", _cmd);
574     [[self window] setAcceptsMouseMovedEvents:NO];
576     // NOTE: This event is received even when the window is not key; if the
577     // mouse shape is set when our window is not key, the hollow (unfocused)
578     // cursor will become a block (focused) cursor.
579     if ([[self window] isKeyWindow]) {
580         int shape = 0;
581         NSMutableData *data = [NSMutableData data];
582         [data appendBytes:&shape length:sizeof(int)];
583         [[self vimController] sendMessage:SetMouseShapeMsgID data:data wait:NO];
584     }
587 - (void)setFrame:(NSRect)frame
589     //NSLog(@"%s", _cmd);
591     // When the frame changes we also need to update the tracking rect.
592     [super setFrame:frame];
593     [self removeTrackingRect:trackingRectTag];
594     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
595                                    userData:NULL assumeInside:YES];
598 - (void)viewDidMoveToWindow
600     //NSLog(@"%s (window=%@)", _cmd, [self window]);
602     // Set a tracking rect which covers the text.
603     // NOTE: While the mouse cursor is in this rect the view will receive
604     // 'mouseMoved:' events so that Vim can take care of updating the mouse
605     // cursor.
606     if ([self window]) {
607         [[self window] setAcceptsMouseMovedEvents:YES];
608         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
609                                        userData:NULL assumeInside:YES];
610     }
613 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
615     //NSLog(@"%s%@", _cmd, newWindow);
617     // Remove tracking rect if view moves or is removed.
618     if ([self window] && trackingRectTag) {
619         [self removeTrackingRect:trackingRectTag];
620         trackingRectTag = 0;
621     }
624 - (NSMenu*)menuForEvent:(NSEvent *)event
626     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
627     // own).  Called when user Ctrl-clicks in the view (this is already handled
628     // in rightMouseDown:).
629     return nil;
632 - (NSArray *)acceptableDragTypes
634     return [NSArray arrayWithObjects:NSFilenamesPboardType,
635            NSStringPboardType, nil];
638 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
640     NSPasteboard *pboard = [sender draggingPasteboard];
642     if ([[pboard types] containsObject:NSStringPboardType]) {
643         NSString *string = [pboard stringForType:NSStringPboardType];
644         [[self vimController] dropString:string];
645         return YES;
646     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
647         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
648         [[self vimController] dropFiles:files];
649         return YES;
650     }
652     return NO;
655 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
657     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
658     NSPasteboard *pboard = [sender draggingPasteboard];
660     if ( [[pboard types] containsObject:NSFilenamesPboardType]
661             && (sourceDragMask & NSDragOperationCopy) )
662         return NSDragOperationCopy;
663     if ( [[pboard types] containsObject:NSStringPboardType]
664             && (sourceDragMask & NSDragOperationCopy) )
665         return NSDragOperationCopy;
667     return NSDragOperationNone;
670 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
672     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
673     NSPasteboard *pboard = [sender draggingPasteboard];
675     if ( [[pboard types] containsObject:NSFilenamesPboardType]
676             && (sourceDragMask & NSDragOperationCopy) )
677         return NSDragOperationCopy;
678     if ( [[pboard types] containsObject:NSStringPboardType]
679             && (sourceDragMask & NSDragOperationCopy) )
680         return NSDragOperationCopy;
682     return NSDragOperationNone;
685 - (void)changeFont:(id)sender
687     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
688     if (!ts) return;
690     NSFont *oldFont = [ts font];
691     NSFont *newFont = [sender convertFont:oldFont];
693     if (newFont) {
694         NSString *name = [newFont displayName];
695         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
696         if (len > 0) {
697             NSMutableData *data = [NSMutableData data];
698             float pointSize = [newFont pointSize];
700             [data appendBytes:&pointSize length:sizeof(float)];
702             ++len;  // include NUL byte
703             [data appendBytes:&len length:sizeof(unsigned)];
704             [data appendBytes:[name UTF8String] length:len];
706             [[self vimController] sendMessage:SetFontMsgID data:data wait:NO];
707         }
708     }
711 - (void)resetCursorRects
713     // No need to set up cursor rects since Vim handles cursor changes.
716 - (void)updateFontPanel
718     // The font panel is updated whenever the font is set.
721 @end // MMTextView
726 @implementation MMTextView (Private)
728 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
730 #if 0
731     NSLayoutManager *lm = [self layoutManager];
732     NSTextContainer *tc = [self textContainer];
733     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
735     if (!(lm && tc && ts))
736         return NO;
738     unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
739     unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
741     int mod = [ts maxColumns] + 1;
743     if (row) *row = (int)(charIdx / mod);
744     if (column) *column = (int)(charIdx % mod);
746     NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
747             *row, *column);
749     return YES;
750 #else
751     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
752     NSSize cellSize = [ts cellSize];
753     if (!(cellSize.width > 0 && cellSize.height > 0))
754         return NO;
755     NSPoint origin = [self textContainerOrigin];
757     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
758     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
760     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
761     //        *row, *column);
763     return YES;
764 #endif
767 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
769     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
770     NSSize cellSize = [ts cellSize];
771     if (!(point && cellSize.width > 0 && cellSize.height > 0))
772         return NO;
774     *point = [self textContainerOrigin];
775     point->x += column * cellSize.width;
776     point->y += row * cellSize.height;
778     return YES;
781 - (NSRect)trackingRect
783     NSRect rect = [self frame];
784     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
785     int left = [ud integerForKey:MMTextInsetLeftKey];
786     int top = [ud integerForKey:MMTextInsetTopKey];
787     int right = [ud integerForKey:MMTextInsetRightKey];
788     int bot = [ud integerForKey:MMTextInsetBottomKey];
790     rect.origin.x = left;
791     rect.origin.y = top;
792     rect.size.width -= left + right - 1;
793     rect.size.height -= top + bot - 1;
795     return rect;
798 - (void)dispatchKeyEvent:(NSEvent *)event
800     // Only handle the command if it came from a keyDown event
801     if ([event type] != NSKeyDown)
802         return;
804     NSString *chars = [event characters];
805     NSString *unmodchars = [event charactersIgnoringModifiers];
806     unichar c = [chars characterAtIndex:0];
807     unichar imc = [unmodchars characterAtIndex:0];
808     int len = 0;
809     const char *bytes = 0;
811     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
812     //        _cmd, c, imc, chars, unmodchars);
814     if (' ' == imc && 0xa0 != c) {
815         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
816         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
817         // should be passed on as is.)
818         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
819         bytes = [unmodchars UTF8String];
820     } else if (imc == c && '2' == c) {
821         // HACK!  Translate Ctrl+2 to <C-@>.
822         static char ctrl_at = 0;
823         len = 1;  bytes = &ctrl_at;
824     } else if (imc == c && '6' == c) {
825         // HACK!  Translate Ctrl+6 to <C-^>.
826         static char ctrl_hat = 0x1e;
827         len = 1;  bytes = &ctrl_hat;
828     } else if (c == 0x19 && imc == 0x19) {
829         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
830         // separately (else Ctrl-Y doesn't work).
831         static char back_tab[2] = { 'k', 'B' };
832         len = 2; bytes = back_tab;
833     } else {
834         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
835         bytes = [chars UTF8String];
836     }
838     [self sendKeyDown:bytes length:len modifiers:[event modifierFlags]];
841 - (MMVimController *)vimController
843     id windowController = [[self window] windowController];
845     // TODO: Make sure 'windowController' is a MMWindowController before type
846     // casting.
847     return [(MMWindowController*)windowController vimController];
850 - (void)startDragTimerWithInterval:(NSTimeInterval)t
852     [NSTimer scheduledTimerWithTimeInterval:t target:self
853                                    selector:@selector(dragTimerFired:)
854                                    userInfo:nil repeats:NO];
857 - (void)dragTimerFired:(NSTimer *)timer
859     // TODO: Autoscroll in horizontal direction?
860     static unsigned tick = 1;
861     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
863     isAutoscrolling = NO;
865     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
866         // HACK! If the mouse cursor is outside the text area, then send a
867         // dragged event.  However, if row&col hasn't changed since the last
868         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
869         // Thus we fiddle with the column to make sure something happens.
870         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
871         NSMutableData *data = [NSMutableData data];
873         [data appendBytes:&dragRow length:sizeof(int)];
874         [data appendBytes:&col length:sizeof(int)];
875         [data appendBytes:&dragFlags length:sizeof(int)];
877         [[self vimController] sendMessage:MouseDraggedMsgID data:data wait:NO];
879         isAutoscrolling = YES;
880     }
882     if (isDragging) {
883         // Compute timer interval depending on how far away the mouse cursor is
884         // from the text view.
885         NSRect rect = [self trackingRect];
886         float dy = 0;
887         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
888         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
889         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
891         NSTimeInterval t = MMDragTimerMaxInterval -
892             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
894         [self startDragTimerWithInterval:t];
895     }
897     ++tick;
900 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
902     if (chars && len > 0) {
903         NSMutableData *data = [NSMutableData data];
905         [data appendBytes:&flags length:sizeof(int)];
906         [data appendBytes:&len length:sizeof(int)];
907         [data appendBytes:chars length:len];
909         // TODO: Support 'mousehide' (check p_mh)
910         [NSCursor setHiddenUntilMouseMoves:YES];
912         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
913         [[self vimController] sendMessage:KeyDownMsgID data:data wait:NO];
914     }
917 @end // MMTextView (Private)