Removed stray debug log message.
[MacVim/jjgod.git] / src / MacVim / MMTextView.m
blob0e2399d72e5baafaa804181745e2a28320161ad6
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;
26 static char MMKeypadEnter[2] = { 'K', 'A' };
27 static NSString *MMKeypadEnterString = @"KA";
31 @interface MMTextView (Private)
32 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
33 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point;
34 - (NSRect)trackingRect;
35 - (void)dispatchKeyEvent:(NSEvent *)event;
36 - (MMVimController *)vimController;
37 - (void)startDragTimerWithInterval:(NSTimeInterval)t;
38 - (void)dragTimerFired:(NSTimer *)timer;
39 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
40 @end
44 @implementation MMTextView
46 - (void)dealloc
48     if (markedTextField) {
49         [[markedTextField window] autorelease];
50         [markedTextField release];
51         markedTextField = nil;
52     }
54     [lastMouseDownEvent release];
55     [super dealloc];
58 - (NSEvent *)lastMouseDownEvent
60     return lastMouseDownEvent;
63 - (BOOL)shouldDrawInsertionPoint
65     // NOTE: The insertion point is drawn manually in drawRect:.  It would be
66     // nice to be able to use the insertion point related methods of
67     // NSTextView, but it seems impossible to get them to work properly (search
68     // the cocoabuilder archives).
69     return NO;
72 - (void)setShouldDrawInsertionPoint:(BOOL)on
74     shouldDrawInsertionPoint = on;
77 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
78                        fraction:(int)percent color:(NSColor *)color
80     //NSLog(@"drawInsertionPointAtRow:%d column:%d shape:%d color:%@",
81     //        row, col, shape, color);
83     // This only stores where to draw the insertion point, the actual drawing
84     // is done in drawRect:.
85     shouldDrawInsertionPoint = YES;
86     insertionPointRow = row;
87     insertionPointColumn = col;
88     insertionPointShape = shape;
89     insertionPointFraction = percent;
91     [self setInsertionPointColor:color];
94 - (void)hideMarkedTextField
96     if (markedTextField) {
97         NSWindow *win = [markedTextField window];
98         [win close];
99         [markedTextField setStringValue:@""];
100     }
103 - (BOOL)isOpaque
105     return NO;
108 - (void)drawRect:(NSRect)rect
110     [super drawRect:rect];
112     if (shouldDrawInsertionPoint) {
113         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
114         NSLayoutManager *lm = [self layoutManager];
115         NSTextContainer *tc = [self textContainer];
117         // Given (row,column), calculate the bounds of the glyph at that spot.
118         // We use the layout manager because this gives us exactly the size and
119         // location of the glyph so that we can match the insertion point to
120         // it.
121         unsigned charIdx = [ts characterIndexForRow:insertionPointRow
122                                              column:insertionPointColumn];
123         NSRange glyphRange =
124             [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
125                        actualCharacterRange:NULL];
126         NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
127                                       inTextContainer:tc];
128         ipRect.origin.x += [self textContainerOrigin].x;
129         ipRect.origin.y += [self textContainerOrigin].y;
131         if (MMInsertionPointHorizontal == insertionPointShape) {
132             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
133             ipRect.origin.y += ipRect.size.height - frac;
134             ipRect.size.height = frac;
135         } else if (MMInsertionPointVertical == insertionPointShape) {
136             int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
137             ipRect.size.width = frac;
138         }
140         [[self insertionPointColor] set];
141         if (MMInsertionPointHollow == insertionPointShape) {
142             NSFrameRect(ipRect);
143         } else {
144             NSRectFill(ipRect);
145         }
147         // NOTE: We only draw the cursor once and rely on Vim to say when it
148         // should be drawn again.
149         shouldDrawInsertionPoint = NO;
151         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
152         //        NSStringFromRect(ipRect), insertionPointShape,
153         //        [self insertionPointColor]);
154     }
155 #if 0
156     // this code invalidates the shadow, so we don't 
157     // get shifting ghost text on scroll and resize
158     // but makes speed unusable
159     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
160     if ([ts defaultBackgroundAlpha] < 1.0f) {
161         if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_1)
162         {
163             [[self window] setHasShadow:NO];
164             [[self window] setHasShadow:YES];
165         }
166         else
167             [[self window] invalidateShadow];
169     }
170 #endif
173 - (void)keyDown:(NSEvent *)event
175     //NSLog(@"%s %@", _cmd, event);
176     // HACK! If a modifier is held, don't pass the event along to
177     // interpretKeyEvents: since some keys are bound to multiple commands which
178     // means doCommandBySelector: is called several times.
179     //
180     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
181     // affecting input management.
183     if ([event modifierFlags] & NSControlKeyMask)
184         [self dispatchKeyEvent:event];
185     else
186         [super keyDown:event];
189 - (void)insertText:(id)string
191     //NSLog(@"%s %@", _cmd, string);
192     // NOTE!  This method is called for normal key presses but also for
193     // Option-key presses --- even when Ctrl is held as well as Option.  When
194     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
195     // so 'string' need not be a printable character!  In this case it still
196     // works to pass 'string' on to Vim as a printable character (since
197     // modifiers are already included and should not be added to the input
198     // buffer using CSI, K_MODIFIER).
200     [self hideMarkedTextField];
202     NSEvent *event = [NSApp currentEvent];
204     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
205     // to watch for them here.
206     if ([event type] == NSKeyDown
207             && [[event charactersIgnoringModifiers] length] > 0
208             && [event modifierFlags]
209                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
210         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
212         // <S-M-Tab> translates to 0x19 
213         if (' ' == c || 0x19 == c) {
214             [self dispatchKeyEvent:event];
215             return;
216         }
217     }
219     // TODO: Support 'mousehide' (check p_mh)
220     [NSCursor setHiddenUntilMouseMoves:YES];
222     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
223     // do not support attributes, simply pass the corresponding NSString in the
224     // latter case.
225     if ([string isKindOfClass:[NSAttributedString class]])
226         string = [string string];
228     [[self vimController] sendMessage:InsertTextMsgID
229                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
233 - (void)doCommandBySelector:(SEL)selector
235     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
236     // By ignoring the selector we effectively disable the key binding
237     // mechanism of Cocoa.  Hopefully this is what the user will expect
238     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
239     // match, etc.).
240     //
241     // We usually end up here if the user pressed Ctrl+key (but not
242     // Ctrl+Option+key).
244     NSEvent *event = [NSApp currentEvent];
246     if (selector == @selector(cancelOperation:)
247             || selector == @selector(insertNewline:)) {
248         // HACK! If there was marked text which got abandoned as a result of
249         // hitting escape or enter, then 'insertText:' is called with the
250         // abandoned text but '[event characters]' includes the abandoned text
251         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
252         // must intercept these keys here or the abandonded text gets inserted
253         // twice.
254         NSString *key = [event charactersIgnoringModifiers];
255         const char *chars = [key UTF8String];
256         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
258         if (0x3 == chars[0]) {
259             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
260             // handle it separately (else Ctrl-C doesn't work).
261             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
262             chars = MMKeypadEnter;
263         }
265         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
266     } else {
267         [self dispatchKeyEvent:event];
268     }
271 - (BOOL)performKeyEquivalent:(NSEvent *)event
273     //NSLog(@"%s %@", _cmd, event);
274     // Called for Cmd+key keystrokes, function keys, arrow keys, page
275     // up/down, home, end.
276     //
277     // NOTE: This message cannot be ignored since Cmd+letter keys never are
278     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
279     // strokes, unless the key is a function key.
281     // NOTE: If the event that triggered this method represents a function key
282     // down then we do nothing, otherwise the input method never gets the key
283     // stroke (some input methods use e.g. arrow keys).  The function key down
284     // event will still reach Vim though (via keyDown:).  The exceptions to
285     // this rule are: PageUp/PageDown (keycode 116/121).
286     int flags = [event modifierFlags];
287     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
288             && !(116 == [event keyCode] || 121 == [event keyCode]))
289         return NO;
291     // HACK!  Let the main menu try to handle any key down event, before
292     // passing it on to vim, otherwise key equivalents for menus will
293     // effectively be disabled.
294     if ([[NSApp mainMenu] performKeyEquivalent:event])
295         return YES;
297     // HACK!  KeyCode 50 represent the key which switches between windows
298     // within an application (like Cmd+Tab is used to switch between
299     // applications).  Return NO here, else the window switching does not work.
300     //
301     // Will this hack work for all languages / keyboard layouts?
302     if ([event keyCode] == 50)
303         return NO;
305     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
306     if (flags & NSControlKeyMask) {
307         [self dispatchKeyEvent:event];
308         return YES;
309     }
311     //NSLog(@"%s%@", _cmd, event);
313     NSString *chars = [event characters];
314     NSString *unmodchars = [event charactersIgnoringModifiers];
315     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
316     NSMutableData *data = [NSMutableData data];
318     if (len <= 0)
319         return NO;
321     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
322     // can clear the shift flag as it is already included in 'unmodchars'.
323     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
324     // an English keyboard).
325     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
326         flags &= ~NSShiftKeyMask;
328     if (0x3 == [unmodchars characterAtIndex:0]) {
329         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
330         // handle it separately (else Cmd-enter turns into Ctrl-C).
331         unmodchars = MMKeypadEnterString;
332         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
333     }
335     [data appendBytes:&flags length:sizeof(int)];
336     [data appendBytes:&len length:sizeof(int)];
337     [data appendBytes:[unmodchars UTF8String] length:len];
339     [[self vimController] sendMessage:CmdKeyMsgID data:data];
341     return YES;
344 - (BOOL)hasMarkedText
346     //NSLog(@"%s", _cmd);
347     return markedTextField && [[markedTextField stringValue] length] > 0;
350 - (NSRange)markedRange
352     //NSLog(@"%s", _cmd);
353     // HACK! If a valid range is returned, then NSTextView changes the
354     // background color of the returned range.  Since marked text is displayed
355     // in a separate popup window this behaviour is not wanted.  By setting the
356     // location of the returned range to NSNotFound NSTextView does nothing.
357     // This hack is continued in 'firstRectForCharacterRange:'.
358     return NSMakeRange(NSNotFound, 0);
361 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
363     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
364     //        NSStringFromRange(range));
366     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
367     if (!ts) return;
369     if (!markedTextField) {
370         // Create a text field and put it inside a floating panel.  This field
371         // is used to display marked text.
372         NSSize cellSize = [ts cellSize];
373         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
375         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
376         [markedTextField setEditable:NO];
377         [markedTextField setSelectable:NO];
378         [markedTextField setBezeled:NO];
379         [markedTextField setBordered:YES];
381         NSPanel *panel = [[NSPanel alloc]
382             initWithContentRect:cellRect
383                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
384                         backing:NSBackingStoreBuffered
385                           defer:YES];
387         //[panel setHidesOnDeactivate:NO];
388         [panel setFloatingPanel:YES];
389         [panel setBecomesKeyOnlyIfNeeded:YES];
390         [panel setContentView:markedTextField];
391     }
393     if (text && [text length] > 0) {
394         [markedTextField setFont:[ts font]];
395         if ([text isKindOfClass:[NSAttributedString class]])
396             [markedTextField setAttributedStringValue:text];
397         else
398             [markedTextField setStringValue:text];
400         [markedTextField sizeToFit];
401         NSSize size = [markedTextField frame].size;
403         // Convert coordinates (row,col) -> view -> window base -> screen
404         NSPoint origin;
405         if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
406                      toPoint:&origin])
407             return;
408         origin = [self convertPoint:origin toView:nil];
409         origin = [[self window] convertBaseToScreen:origin];
411         NSWindow *win = [markedTextField window];
412         [win setContentSize:size];
413         [win setFrameOrigin:origin];
414         [win orderFront:nil];
415     } else {
416         [self hideMarkedTextField];
417     }
420 - (void)unmarkText
422     //NSLog(@"%s", _cmd);
423     [self hideMarkedTextField];
426 - (NSRect)firstRectForCharacterRange:(NSRange)range
428     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
430     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
431     NSLayoutManager *lm = [self layoutManager];
432     NSTextContainer *tc = [self textContainer];
434     // HACK! Since we always return marked text to have location NSNotFound,
435     // this method will be called with 'range.location == NSNotFound' whenever
436     // the input manager tries to position a popup window near the insertion
437     // point.  For this reason we compute where the insertion point is and
438     // return a rect which contains it.
439     if (!(ts && lm && tc) || NSNotFound != range.location)
440         return [super firstRectForCharacterRange:range];
442     unsigned charIdx = [ts characterIndexForRow:insertionPointRow
443                                          column:insertionPointColumn];
444     NSRange glyphRange =
445         [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
446                    actualCharacterRange:NULL];
447     NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
448                                   inTextContainer:tc];
449     ipRect.origin.x += [self textContainerOrigin].x;
450     ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
452     ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
453     ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
455     return ipRect;
458 - (void)scrollWheel:(NSEvent *)event
460     if ([event deltaY] == 0)
461         return;
463     int row, col;
464     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
465     if (![self convertPoint:pt toRow:&row column:&col])
466         return;
468     int flags = [event modifierFlags];
469     float dy = [event deltaY];
470     NSMutableData *data = [NSMutableData data];
472     [data appendBytes:&row length:sizeof(int)];
473     [data appendBytes:&col length:sizeof(int)];
474     [data appendBytes:&flags length:sizeof(int)];
475     [data appendBytes:&dy length:sizeof(float)];
477     [[self vimController] sendMessage:ScrollWheelMsgID data:data];
480 - (void)mouseDown:(NSEvent *)event
482     int row, col;
483     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
484     if (![self convertPoint:pt toRow:&row column:&col])
485         return;
487     lastMouseDownEvent = [event copy];
489     int button = [event buttonNumber];
490     int flags = [event modifierFlags];
491     int count = [event clickCount];
492     NSMutableData *data = [NSMutableData data];
494     // If desired, intepret Ctrl-Click as a right mouse click.
495     if ([[NSUserDefaults standardUserDefaults]
496             boolForKey:MMTranslateCtrlClickKey]
497             && button == 0 && flags & NSControlKeyMask) {
498         button = 1;
499         flags &= ~NSControlKeyMask;
500     }
502     [data appendBytes:&row length:sizeof(int)];
503     [data appendBytes:&col length:sizeof(int)];
504     [data appendBytes:&button length:sizeof(int)];
505     [data appendBytes:&flags length:sizeof(int)];
506     [data appendBytes:&count length:sizeof(int)];
508     [[self vimController] sendMessage:MouseDownMsgID data:data];
511 - (void)rightMouseDown:(NSEvent *)event
513     [self mouseDown:event];
516 - (void)otherMouseDown:(NSEvent *)event
518     [self mouseDown:event];
521 - (void)mouseUp:(NSEvent *)event
523     int row, col;
524     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
525     if (![self convertPoint:pt toRow:&row column:&col])
526         return;
528     int flags = [event modifierFlags];
529     NSMutableData *data = [NSMutableData data];
531     [data appendBytes:&row length:sizeof(int)];
532     [data appendBytes:&col length:sizeof(int)];
533     [data appendBytes:&flags length:sizeof(int)];
535     [[self vimController] sendMessage:MouseUpMsgID data:data];
537     isDragging = NO;
540 - (void)rightMouseUp:(NSEvent *)event
542     [self mouseUp:event];
545 - (void)otherMouseUp:(NSEvent *)event
547     [self mouseUp:event];
550 - (void)mouseDragged:(NSEvent *)event
552     int flags = [event modifierFlags];
553     int row, col;
554     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
555     if (![self convertPoint:pt toRow:&row column:&col])
556         return;
558     // Autoscrolling is done in dragTimerFired:
559     if (!isAutoscrolling) {
560         NSMutableData *data = [NSMutableData data];
562         [data appendBytes:&row length:sizeof(int)];
563         [data appendBytes:&col length:sizeof(int)];
564         [data appendBytes:&flags length:sizeof(int)];
566         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
567     }
569     dragPoint = pt;
570     dragRow = row; dragColumn = col; dragFlags = flags;
571     if (!isDragging) {
572         [self startDragTimerWithInterval:.5];
573         isDragging = YES;
574     }
577 - (void)rightMouseDragged:(NSEvent *)event
579     [self mouseDragged:event];
582 - (void)otherMouseDragged:(NSEvent *)event
584     [self mouseDragged:event];
587 - (void)mouseMoved:(NSEvent *)event
589     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
590     if (!ts) return;
592     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
593     int row, col;
594     if (![self convertPoint:pt toRow:&row column:&col])
595         return;
597     // HACK! It seems impossible to get the tracking rects set up before the
598     // view is visible, which means that the first mouseEntered: or
599     // mouseExited: events are never received.  This forces us to check if the
600     // mouseMoved: event really happened over the text.
601     int rows, cols;
602     [ts getMaxRows:&rows columns:&cols];
603     if (row >= 0 && row < rows && col >= 0 && col < cols) {
604         NSMutableData *data = [NSMutableData data];
606         [data appendBytes:&row length:sizeof(int)];
607         [data appendBytes:&col length:sizeof(int)];
609         [[self vimController] sendMessage:MouseMovedMsgID data:data];
610     }
613 - (void)mouseEntered:(NSEvent *)event
615     //NSLog(@"%s", _cmd);
617     // NOTE: This event is received even when the window is not key; thus we
618     // have to take care not to enable mouse moved events unless our window is
619     // key.
620     if ([[self window] isKeyWindow])
621         [[self window] setAcceptsMouseMovedEvents:YES];
624 - (void)mouseExited:(NSEvent *)event
626     //NSLog(@"%s", _cmd);
628     [[self window] setAcceptsMouseMovedEvents:NO];
630     // NOTE: This event is received even when the window is not key; if the
631     // mouse shape is set when our window is not key, the hollow (unfocused)
632     // cursor will become a block (focused) cursor.
633     if ([[self window] isKeyWindow]) {
634         int shape = 0;
635         NSMutableData *data = [NSMutableData data];
636         [data appendBytes:&shape length:sizeof(int)];
637         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
638     }
641 - (void)setFrame:(NSRect)frame
643     //NSLog(@"%s", _cmd);
645     // When the frame changes we also need to update the tracking rect.
646     [super setFrame:frame];
647     [self removeTrackingRect:trackingRectTag];
648     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
649                                    userData:NULL assumeInside:YES];
652 - (void)viewDidMoveToWindow
654     //NSLog(@"%s (window=%@)", _cmd, [self window]);
656     // Set a tracking rect which covers the text.
657     // NOTE: While the mouse cursor is in this rect the view will receive
658     // 'mouseMoved:' events so that Vim can take care of updating the mouse
659     // cursor.
660     if ([self window]) {
661         [[self window] setAcceptsMouseMovedEvents:YES];
662         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
663                                        userData:NULL assumeInside:YES];
664     }
667 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
669     //NSLog(@"%s%@", _cmd, newWindow);
671     // Remove tracking rect if view moves or is removed.
672     if ([self window] && trackingRectTag) {
673         [self removeTrackingRect:trackingRectTag];
674         trackingRectTag = 0;
675     }
678 - (NSMenu*)menuForEvent:(NSEvent *)event
680     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
681     // own).  Called when user Ctrl-clicks in the view (this is already handled
682     // in rightMouseDown:).
683     return nil;
686 - (NSArray *)acceptableDragTypes
688     return [NSArray arrayWithObjects:NSFilenamesPboardType,
689            NSStringPboardType, nil];
692 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
694     NSPasteboard *pboard = [sender draggingPasteboard];
696     if ([[pboard types] containsObject:NSStringPboardType]) {
697         NSString *string = [pboard stringForType:NSStringPboardType];
698         [[self vimController] dropString:string];
699         return YES;
700     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
701         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
702         [[self vimController] dropFiles:files];
703         return YES;
704     }
706     return NO;
709 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
711     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
712     NSPasteboard *pboard = [sender draggingPasteboard];
714     if ( [[pboard types] containsObject:NSFilenamesPboardType]
715             && (sourceDragMask & NSDragOperationCopy) )
716         return NSDragOperationCopy;
717     if ( [[pboard types] containsObject:NSStringPboardType]
718             && (sourceDragMask & NSDragOperationCopy) )
719         return NSDragOperationCopy;
721     return NSDragOperationNone;
724 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
726     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
727     NSPasteboard *pboard = [sender draggingPasteboard];
729     if ( [[pboard types] containsObject:NSFilenamesPboardType]
730             && (sourceDragMask & NSDragOperationCopy) )
731         return NSDragOperationCopy;
732     if ( [[pboard types] containsObject:NSStringPboardType]
733             && (sourceDragMask & NSDragOperationCopy) )
734         return NSDragOperationCopy;
736     return NSDragOperationNone;
739 - (void)changeFont:(id)sender
741     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
742     if (!ts) return;
744     NSFont *oldFont = [ts font];
745     NSFont *newFont = [sender convertFont:oldFont];
747     if (newFont) {
748         NSString *name = [newFont displayName];
749         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
750         if (len > 0) {
751             NSMutableData *data = [NSMutableData data];
752             float pointSize = [newFont pointSize];
754             [data appendBytes:&pointSize length:sizeof(float)];
756             ++len;  // include NUL byte
757             [data appendBytes:&len length:sizeof(unsigned)];
758             [data appendBytes:[name UTF8String] length:len];
760             [[self vimController] sendMessage:SetFontMsgID data:data];
761         }
762     }
765 - (void)resetCursorRects
767     // No need to set up cursor rects since Vim handles cursor changes.
770 - (void)updateFontPanel
772     // The font panel is updated whenever the font is set.
775 - (void)viewWillStartLiveResize
777     id windowController = [[self window] windowController];
778     [windowController liveResizeWillStart];
780     [super viewWillStartLiveResize];
783 - (void)viewDidEndLiveResize
785     id windowController = [[self window] windowController];
786     [windowController liveResizeDidEnd];
788     [super viewDidEndLiveResize];
791 @end // MMTextView
796 @implementation MMTextView (Private)
798 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
800 #if 0
801     NSLayoutManager *lm = [self layoutManager];
802     NSTextContainer *tc = [self textContainer];
803     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
805     if (!(lm && tc && ts))
806         return NO;
808     unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
809     unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
811     int mod = [ts maxColumns] + 1;
813     if (row) *row = (int)(charIdx / mod);
814     if (column) *column = (int)(charIdx % mod);
816     NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
817             *row, *column);
819     return YES;
820 #else
821     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
822     NSSize cellSize = [ts cellSize];
823     if (!(cellSize.width > 0 && cellSize.height > 0))
824         return NO;
825     NSPoint origin = [self textContainerOrigin];
827     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
828     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
830     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
831     //        *row, *column);
833     return YES;
834 #endif
837 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
839     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
840     NSSize cellSize = [ts cellSize];
841     if (!(point && cellSize.width > 0 && cellSize.height > 0))
842         return NO;
844     *point = [self textContainerOrigin];
845     point->x += column * cellSize.width;
846     point->y += row * cellSize.height;
848     return YES;
851 - (NSRect)trackingRect
853     NSRect rect = [self frame];
854     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
855     int left = [ud integerForKey:MMTextInsetLeftKey];
856     int top = [ud integerForKey:MMTextInsetTopKey];
857     int right = [ud integerForKey:MMTextInsetRightKey];
858     int bot = [ud integerForKey:MMTextInsetBottomKey];
860     rect.origin.x = left;
861     rect.origin.y = top;
862     rect.size.width -= left + right - 1;
863     rect.size.height -= top + bot - 1;
865     return rect;
868 - (void)dispatchKeyEvent:(NSEvent *)event
870     // Only handle the command if it came from a keyDown event
871     if ([event type] != NSKeyDown)
872         return;
874     NSString *chars = [event characters];
875     NSString *unmodchars = [event charactersIgnoringModifiers];
876     unichar c = [chars characterAtIndex:0];
877     unichar imc = [unmodchars characterAtIndex:0];
878     int len = 0;
879     const char *bytes = 0;
880     int mods = [event modifierFlags];
882     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
883     //        _cmd, c, imc, chars, unmodchars);
885     if (' ' == imc && 0xa0 != c) {
886         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
887         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
888         // should be passed on as is.)
889         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
890         bytes = [unmodchars UTF8String];
891     } else if (imc == c && '2' == c) {
892         // HACK!  Translate Ctrl+2 to <C-@>.
893         static char ctrl_at = 0;
894         len = 1;  bytes = &ctrl_at;
895     } else if (imc == c && '6' == c) {
896         // HACK!  Translate Ctrl+6 to <C-^>.
897         static char ctrl_hat = 0x1e;
898         len = 1;  bytes = &ctrl_hat;
899     } else if (c == 0x19 && imc == 0x19) {
900         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
901         // separately (else Ctrl-Y doesn't work).
902         static char tab = 0x9;
903         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
904     } else {
905         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
906         bytes = [chars UTF8String];
907     }
909     [self sendKeyDown:bytes length:len modifiers:mods];
912 - (MMVimController *)vimController
914     id windowController = [[self window] windowController];
916     // TODO: Make sure 'windowController' is a MMWindowController before type
917     // casting.
918     return [(MMWindowController*)windowController vimController];
921 - (void)startDragTimerWithInterval:(NSTimeInterval)t
923     [NSTimer scheduledTimerWithTimeInterval:t target:self
924                                    selector:@selector(dragTimerFired:)
925                                    userInfo:nil repeats:NO];
928 - (void)dragTimerFired:(NSTimer *)timer
930     // TODO: Autoscroll in horizontal direction?
931     static unsigned tick = 1;
932     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
934     isAutoscrolling = NO;
936     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
937         // HACK! If the mouse cursor is outside the text area, then send a
938         // dragged event.  However, if row&col hasn't changed since the last
939         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
940         // Thus we fiddle with the column to make sure something happens.
941         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
942         NSMutableData *data = [NSMutableData data];
944         [data appendBytes:&dragRow length:sizeof(int)];
945         [data appendBytes:&col length:sizeof(int)];
946         [data appendBytes:&dragFlags length:sizeof(int)];
948         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
950         isAutoscrolling = YES;
951     }
953     if (isDragging) {
954         // Compute timer interval depending on how far away the mouse cursor is
955         // from the text view.
956         NSRect rect = [self trackingRect];
957         float dy = 0;
958         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
959         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
960         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
962         NSTimeInterval t = MMDragTimerMaxInterval -
963             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
965         [self startDragTimerWithInterval:t];
966     }
968     ++tick;
971 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
973     if (chars && len > 0) {
974         NSMutableData *data = [NSMutableData data];
976         [data appendBytes:&flags length:sizeof(int)];
977         [data appendBytes:&len length:sizeof(int)];
978         [data appendBytes:chars length:len];
980         // TODO: Support 'mousehide' (check p_mh)
981         [NSCursor setHiddenUntilMouseMoves:YES];
983         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
984         [[self vimController] sendMessage:KeyDownMsgID data:data];
985     }
988 @end // MMTextView (Private)