Don't set Visual group in gui_mch_def_colors()
[MacVim/jjgod.git] / MMTextView.m
blob57cfc91294f7d15c8b1c9d6d5a7fb79dcc8da3d7
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 - (void)drawRect:(NSRect)rect
105     [super drawRect:rect];
107     if (shouldDrawInsertionPoint) {
108         MMTextStorage *ts = (MMTextStorage*)[self textStorage];
109         NSLayoutManager *lm = [self layoutManager];
110         NSTextContainer *tc = [self textContainer];
112         // Given (row,column), calculate the bounds of the glyph at that spot.
113         // We use the layout manager because this gives us exactly the size and
114         // location of the glyph so that we can match the insertion point to
115         // it.
116         unsigned charIdx = [ts characterIndexForRow:insertionPointRow
117                                              column:insertionPointColumn];
118         NSRange glyphRange =
119             [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
120                        actualCharacterRange:NULL];
121         NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
122                                       inTextContainer:tc];
123         ipRect.origin.x += [self textContainerOrigin].x;
124         ipRect.origin.y += [self textContainerOrigin].y;
126         if (MMInsertionPointHorizontal == insertionPointShape) {
127             int frac = ([ts cellSize].height * insertionPointFraction + 99)/100;
128             ipRect.origin.y += ipRect.size.height - frac;
129             ipRect.size.height = frac;
130         } else if (MMInsertionPointVertical == insertionPointShape) {
131             int frac = ([ts cellSize].width* insertionPointFraction + 99)/100;
132             ipRect.size.width = frac;
133         }
135         [[self insertionPointColor] set];
136         if (MMInsertionPointHollow == insertionPointShape) {
137             NSFrameRect(ipRect);
138         } else {
139             NSRectFill(ipRect);
140         }
142         // NOTE: We only draw the cursor once and rely on Vim to say when it
143         // should be drawn again.
144         shouldDrawInsertionPoint = NO;
146         //NSLog(@"%s draw insertion point %@ shape=%d color=%@", _cmd,
147         //        NSStringFromRect(ipRect), insertionPointShape,
148         //        [self insertionPointColor]);
149     }
152 - (void)keyDown:(NSEvent *)event
154     //NSLog(@"%s %@", _cmd, event);
155     // HACK! If a modifier is held, don't pass the event along to
156     // interpretKeyEvents: since some keys are bound to multiple commands which
157     // means doCommandBySelector: is called several times.
158     //
159     // TODO: Figure out a way to disable Cocoa key bindings entirely, without
160     // affecting input management.
162     if ([event modifierFlags] & NSControlKeyMask)
163         [self dispatchKeyEvent:event];
164     else
165         [super keyDown:event];
168 - (void)insertText:(id)string
170     //NSLog(@"%s %@", _cmd, string);
171     // NOTE!  This method is called for normal key presses but also for
172     // Option-key presses --- even when Ctrl is held as well as Option.  When
173     // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
174     // so 'string' need not be a printable character!  In this case it still
175     // works to pass 'string' on to Vim as a printable character (since
176     // modifiers are already included and should not be added to the input
177     // buffer using CSI, K_MODIFIER).
179     [self hideMarkedTextField];
181     NSEvent *event = [NSApp currentEvent];
183     // HACK!  In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
184     // to watch for them here.
185     if ([event type] == NSKeyDown
186             && [[event charactersIgnoringModifiers] length] > 0
187             && [event modifierFlags]
188                 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
189         unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
191         // <S-M-Tab> translates to 0x19 
192         if (' ' == c || 0x19 == c) {
193             [self dispatchKeyEvent:event];
194             return;
195         }
196     }
198     // TODO: Support 'mousehide' (check p_mh)
199     [NSCursor setHiddenUntilMouseMoves:YES];
201     // NOTE: 'string' is either an NSString or an NSAttributedString.  Since we
202     // do not support attributes, simply pass the corresponding NSString in the
203     // latter case.
204     if ([string isKindOfClass:[NSAttributedString class]])
205         string = [string string];
207     [[self vimController] sendMessage:InsertTextMsgID
208                  data:[string dataUsingEncoding:NSUTF8StringEncoding]];
212 - (void)doCommandBySelector:(SEL)selector
214     //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
215     // By ignoring the selector we effectively disable the key binding
216     // mechanism of Cocoa.  Hopefully this is what the user will expect
217     // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
218     // match, etc.).
219     //
220     // We usually end up here if the user pressed Ctrl+key (but not
221     // Ctrl+Option+key).
223     NSEvent *event = [NSApp currentEvent];
225     if (selector == @selector(cancelOperation:)
226             || selector == @selector(insertNewline:)) {
227         // HACK! If there was marked text which got abandoned as a result of
228         // hitting escape or enter, then 'insertText:' is called with the
229         // abandoned text but '[event characters]' includes the abandoned text
230         // as well.  Since 'dispatchKeyEvent:' looks at '[event characters]' we
231         // must intercept these keys here or the abandonded text gets inserted
232         // twice.
233         NSString *key = [event charactersIgnoringModifiers];
234         const char *chars = [key UTF8String];
235         int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
237         if (0x3 == chars[0]) {
238             // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
239             // handle it separately (else Ctrl-C doesn't work).
240             len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
241             chars = MMKeypadEnter;
242         }
244         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
245     } else {
246         [self dispatchKeyEvent:event];
247     }
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.
255     //
256     // NOTE: This message cannot be ignored since Cmd+letter keys never are
257     // passed to keyDown:.  It seems as if the main menu consumes Cmd-key
258     // strokes, unless the key is a function key.
260     // NOTE: If the event that triggered this method represents a function key
261     // down then we do nothing, otherwise the input method never gets the key
262     // stroke (some input methods use e.g.  arrow keys).  The function key down
263     // event will still reach Vim though (via keyDown:).
264     int flags = [event modifierFlags];
265     if ([event type] != NSKeyDown || flags & NSFunctionKeyMask)
266         return NO;
268     // HACK!  Let the main menu try to handle any key down event, before
269     // passing it on to vim, otherwise key equivalents for menus will
270     // effectively be disabled.
271     if ([[NSApp mainMenu] performKeyEquivalent:event])
272         return YES;
274     // HACK!  KeyCode 50 represent the key which switches between windows
275     // within an application (like Cmd+Tab is used to switch between
276     // applications).  Return NO here, else the window switching does not work.
277     //
278     // Will this hack work for all languages / keyboard layouts?
279     if ([event keyCode] == 50)
280         return NO;
282     //NSLog(@"%s%@", _cmd, event);
284     NSString *chars = [event characters];
285     NSString *unmodchars = [event charactersIgnoringModifiers];
286     int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
287     NSMutableData *data = [NSMutableData data];
289     if (len <= 0)
290         return NO;
292     // If 'chars' and 'unmodchars' differs when shift flag is present, then we
293     // can clear the shift flag as it is already included in 'unmodchars'.
294     // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
295     // an English keyboard).
296     if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
297         flags &= ~NSShiftKeyMask;
299     if (0x3 == [unmodchars characterAtIndex:0]) {
300         // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
301         // handle it separately (else Cmd-enter turns into Ctrl-C).
302         unmodchars = MMKeypadEnterString;
303         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
304     }
306     [data appendBytes:&flags length:sizeof(int)];
307     [data appendBytes:&len length:sizeof(int)];
308     [data appendBytes:[unmodchars UTF8String] length:len];
310     [[self vimController] sendMessage:CmdKeyMsgID data:data];
312     return YES;
315 - (BOOL)hasMarkedText
317     //NSLog(@"%s", _cmd);
318     return markedTextField && [[markedTextField stringValue] length] > 0;
321 - (NSRange)markedRange
323     //NSLog(@"%s", _cmd);
324     // HACK! If a valid range is returned, then NSTextView changes the
325     // background color of the returned range.  Since marked text is displayed
326     // in a separate popup window this behaviour is not wanted.  By setting the
327     // location of the returned range to NSNotFound NSTextView does nothing.
328     // This hack is continued in 'firstRectForCharacterRange:'.
329     return NSMakeRange(NSNotFound, 0);
332 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
334     //NSLog(@"setMarkedText:'%@' selectedRange:%@", text,
335     //        NSStringFromRange(range));
337     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
338     if (!ts) return;
340     if (!markedTextField) {
341         // Create a text field and put it inside a floating panel.  This field
342         // is used to display marked text.
343         NSSize cellSize = [ts cellSize];
344         NSRect cellRect = { 0, 0, cellSize.width, cellSize.height };
346         markedTextField = [[NSTextField alloc] initWithFrame:cellRect];
347         [markedTextField setEditable:NO];
348         [markedTextField setSelectable:NO];
349         [markedTextField setBezeled:NO];
350         [markedTextField setBordered:YES];
352         NSPanel *panel = [[NSPanel alloc]
353             initWithContentRect:cellRect
354                       styleMask:NSBorderlessWindowMask|NSUtilityWindowMask
355                         backing:NSBackingStoreBuffered
356                           defer:YES];
358         //[panel setHidesOnDeactivate:NO];
359         [panel setFloatingPanel:YES];
360         [panel setBecomesKeyOnlyIfNeeded:YES];
361         [panel setContentView:markedTextField];
362     }
364     if (text && [text length] > 0) {
365         [markedTextField setFont:[ts font]];
366         if ([text isKindOfClass:[NSAttributedString class]])
367             [markedTextField setAttributedStringValue:text];
368         else
369             [markedTextField setStringValue:text];
371         [markedTextField sizeToFit];
372         NSSize size = [markedTextField frame].size;
374         // Convert coordinates (row,col) -> view -> window base -> screen
375         NSPoint origin;
376         if (![self convertRow:insertionPointRow+1 column:insertionPointColumn
377                      toPoint:&origin])
378             return;
379         origin = [self convertPoint:origin toView:nil];
380         origin = [[self window] convertBaseToScreen:origin];
382         NSWindow *win = [markedTextField window];
383         [win setContentSize:size];
384         [win setFrameOrigin:origin];
385         [win orderFront:nil];
386     } else {
387         [self hideMarkedTextField];
388     }
391 - (void)unmarkText
393     //NSLog(@"%s", _cmd);
394     [self hideMarkedTextField];
397 - (NSRect)firstRectForCharacterRange:(NSRange)range
399     //NSLog(@"%s%@", _cmd, NSStringFromRange(range));
401     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
402     NSLayoutManager *lm = [self layoutManager];
403     NSTextContainer *tc = [self textContainer];
405     // HACK! Since we always return marked text to have location NSNotFound,
406     // this method will be called with 'range.location == NSNotFound' whenever
407     // the input manager tries to position a popup window near the insertion
408     // point.  For this reason we compute where the insertion point is and
409     // return a rect which contains it.
410     if (!(ts && lm && tc) || NSNotFound != range.location)
411         return [super firstRectForCharacterRange:range];
413     unsigned charIdx = [ts characterIndexForRow:insertionPointRow
414                                          column:insertionPointColumn];
415     NSRange glyphRange =
416         [lm glyphRangeForCharacterRange:NSMakeRange(charIdx,1)
417                    actualCharacterRange:NULL];
418     NSRect ipRect = [lm boundingRectForGlyphRange:glyphRange
419                                   inTextContainer:tc];
420     ipRect.origin.x += [self textContainerOrigin].x;
421     ipRect.origin.y += [self textContainerOrigin].y + [ts cellSize].height;
423     ipRect.origin = [self convertPoint:ipRect.origin toView:nil];
424     ipRect.origin = [[self window] convertBaseToScreen:ipRect.origin];
426     return ipRect;
429 - (void)scrollWheel:(NSEvent *)event
431     if ([event deltaY] == 0)
432         return;
434     int row, col;
435     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
436     if (![self convertPoint:pt toRow:&row column:&col])
437         return;
439     int flags = [event modifierFlags];
440     float dy = [event deltaY];
441     NSMutableData *data = [NSMutableData data];
443     [data appendBytes:&row length:sizeof(int)];
444     [data appendBytes:&col length:sizeof(int)];
445     [data appendBytes:&flags length:sizeof(int)];
446     [data appendBytes:&dy length:sizeof(float)];
448     [[self vimController] sendMessage:ScrollWheelMsgID data:data];
451 - (void)mouseDown:(NSEvent *)event
453     int row, col;
454     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
455     if (![self convertPoint:pt toRow:&row column:&col])
456         return;
458     lastMouseDownEvent = [event copy];
460     int button = [event buttonNumber];
461     int flags = [event modifierFlags];
462     int count = [event clickCount];
463     NSMutableData *data = [NSMutableData data];
465     // If desired, intepret Ctrl-Click as a right mouse click.
466     if ([[NSUserDefaults standardUserDefaults]
467             boolForKey:MMTranslateCtrlClickKey]
468             && button == 0 && flags & NSControlKeyMask) {
469         button = 1;
470         flags &= ~NSControlKeyMask;
471     }
473     [data appendBytes:&row length:sizeof(int)];
474     [data appendBytes:&col length:sizeof(int)];
475     [data appendBytes:&button length:sizeof(int)];
476     [data appendBytes:&flags length:sizeof(int)];
477     [data appendBytes:&count length:sizeof(int)];
479     [[self vimController] sendMessage:MouseDownMsgID data:data];
482 - (void)rightMouseDown:(NSEvent *)event
484     [self mouseDown:event];
487 - (void)otherMouseDown:(NSEvent *)event
489     [self mouseDown:event];
492 - (void)mouseUp:(NSEvent *)event
494     int row, col;
495     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
496     if (![self convertPoint:pt toRow:&row column:&col])
497         return;
499     int flags = [event modifierFlags];
500     NSMutableData *data = [NSMutableData data];
502     [data appendBytes:&row length:sizeof(int)];
503     [data appendBytes:&col length:sizeof(int)];
504     [data appendBytes:&flags length:sizeof(int)];
506     [[self vimController] sendMessage:MouseUpMsgID data:data];
508     isDragging = NO;
511 - (void)rightMouseUp:(NSEvent *)event
513     [self mouseUp:event];
516 - (void)otherMouseUp:(NSEvent *)event
518     [self mouseUp:event];
521 - (void)mouseDragged:(NSEvent *)event
523     int flags = [event modifierFlags];
524     int row, col;
525     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
526     if (![self convertPoint:pt toRow:&row column:&col])
527         return;
529     // Autoscrolling is done in dragTimerFired:
530     if (!isAutoscrolling) {
531         NSMutableData *data = [NSMutableData data];
533         [data appendBytes:&row length:sizeof(int)];
534         [data appendBytes:&col length:sizeof(int)];
535         [data appendBytes:&flags length:sizeof(int)];
537         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
538     }
540     dragPoint = pt;
541     dragRow = row; dragColumn = col; dragFlags = flags;
542     if (!isDragging) {
543         [self startDragTimerWithInterval:.5];
544         isDragging = YES;
545     }
548 - (void)rightMouseDragged:(NSEvent *)event
550     [self mouseDragged:event];
553 - (void)otherMouseDragged:(NSEvent *)event
555     [self mouseDragged:event];
558 - (void)mouseMoved:(NSEvent *)event
560     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
561     if (!ts) return;
563     NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
564     int row, col;
565     if (![self convertPoint:pt toRow:&row column:&col])
566         return;
568     // HACK! It seems impossible to get the tracking rects set up before the
569     // view is visible, which means that the first mouseEntered: or
570     // mouseExited: events are never received.  This forces us to check if the
571     // mouseMoved: event really happened over the text.
572     int rows, cols;
573     [ts getMaxRows:&rows columns:&cols];
574     if (row >= 0 && row < rows && col >= 0 && col < cols) {
575         NSMutableData *data = [NSMutableData data];
577         [data appendBytes:&row length:sizeof(int)];
578         [data appendBytes:&col length:sizeof(int)];
580         [[self vimController] sendMessage:MouseMovedMsgID data:data];
581     }
584 - (void)mouseEntered:(NSEvent *)event
586     //NSLog(@"%s", _cmd);
588     // NOTE: This event is received even when the window is not key; thus we
589     // have to take care not to enable mouse moved events unless our window is
590     // key.
591     if ([[self window] isKeyWindow])
592         [[self window] setAcceptsMouseMovedEvents:YES];
595 - (void)mouseExited:(NSEvent *)event
597     //NSLog(@"%s", _cmd);
599     [[self window] setAcceptsMouseMovedEvents:NO];
601     // NOTE: This event is received even when the window is not key; if the
602     // mouse shape is set when our window is not key, the hollow (unfocused)
603     // cursor will become a block (focused) cursor.
604     if ([[self window] isKeyWindow]) {
605         int shape = 0;
606         NSMutableData *data = [NSMutableData data];
607         [data appendBytes:&shape length:sizeof(int)];
608         [[self vimController] sendMessage:SetMouseShapeMsgID data:data];
609     }
612 - (void)setFrame:(NSRect)frame
614     //NSLog(@"%s", _cmd);
616     // When the frame changes we also need to update the tracking rect.
617     [super setFrame:frame];
618     [self removeTrackingRect:trackingRectTag];
619     trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
620                                    userData:NULL assumeInside:YES];
623 - (void)viewDidMoveToWindow
625     //NSLog(@"%s (window=%@)", _cmd, [self window]);
627     // Set a tracking rect which covers the text.
628     // NOTE: While the mouse cursor is in this rect the view will receive
629     // 'mouseMoved:' events so that Vim can take care of updating the mouse
630     // cursor.
631     if ([self window]) {
632         [[self window] setAcceptsMouseMovedEvents:YES];
633         trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self
634                                        userData:NULL assumeInside:YES];
635     }
638 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
640     //NSLog(@"%s%@", _cmd, newWindow);
642     // Remove tracking rect if view moves or is removed.
643     if ([self window] && trackingRectTag) {
644         [self removeTrackingRect:trackingRectTag];
645         trackingRectTag = 0;
646     }
649 - (NSMenu*)menuForEvent:(NSEvent *)event
651     // HACK! Return nil to disable NSTextView's popup menus (Vim provides its
652     // own).  Called when user Ctrl-clicks in the view (this is already handled
653     // in rightMouseDown:).
654     return nil;
657 - (NSArray *)acceptableDragTypes
659     return [NSArray arrayWithObjects:NSFilenamesPboardType,
660            NSStringPboardType, nil];
663 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
665     NSPasteboard *pboard = [sender draggingPasteboard];
667     if ([[pboard types] containsObject:NSStringPboardType]) {
668         NSString *string = [pboard stringForType:NSStringPboardType];
669         [[self vimController] dropString:string];
670         return YES;
671     } else if ([[pboard types] containsObject:NSFilenamesPboardType]) {
672         NSArray *files = [pboard propertyListForType:NSFilenamesPboardType];
673         [[self vimController] dropFiles:files];
674         return YES;
675     }
677     return NO;
680 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
682     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
683     NSPasteboard *pboard = [sender draggingPasteboard];
685     if ( [[pboard types] containsObject:NSFilenamesPboardType]
686             && (sourceDragMask & NSDragOperationCopy) )
687         return NSDragOperationCopy;
688     if ( [[pboard types] containsObject:NSStringPboardType]
689             && (sourceDragMask & NSDragOperationCopy) )
690         return NSDragOperationCopy;
692     return NSDragOperationNone;
695 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
697     NSDragOperation sourceDragMask = [sender draggingSourceOperationMask];
698     NSPasteboard *pboard = [sender draggingPasteboard];
700     if ( [[pboard types] containsObject:NSFilenamesPboardType]
701             && (sourceDragMask & NSDragOperationCopy) )
702         return NSDragOperationCopy;
703     if ( [[pboard types] containsObject:NSStringPboardType]
704             && (sourceDragMask & NSDragOperationCopy) )
705         return NSDragOperationCopy;
707     return NSDragOperationNone;
710 - (void)changeFont:(id)sender
712     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
713     if (!ts) return;
715     NSFont *oldFont = [ts font];
716     NSFont *newFont = [sender convertFont:oldFont];
718     if (newFont) {
719         NSString *name = [newFont displayName];
720         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
721         if (len > 0) {
722             NSMutableData *data = [NSMutableData data];
723             float pointSize = [newFont pointSize];
725             [data appendBytes:&pointSize length:sizeof(float)];
727             ++len;  // include NUL byte
728             [data appendBytes:&len length:sizeof(unsigned)];
729             [data appendBytes:[name UTF8String] length:len];
731             [[self vimController] sendMessage:SetFontMsgID data:data];
732         }
733     }
736 - (void)resetCursorRects
738     // No need to set up cursor rects since Vim handles cursor changes.
741 - (void)updateFontPanel
743     // The font panel is updated whenever the font is set.
746 - (void)viewDidEndLiveResize
748     id windowController = [[self window] windowController];
749     [windowController liveResizeDidEnd];
752 @end // MMTextView
757 @implementation MMTextView (Private)
759 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
761 #if 0
762     NSLayoutManager *lm = [self layoutManager];
763     NSTextContainer *tc = [self textContainer];
764     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
766     if (!(lm && tc && ts))
767         return NO;
769     unsigned glyphIdx = [lm glyphIndexForPoint:point inTextContainer:tc];
770     unsigned charIdx = [lm characterIndexForGlyphAtIndex:glyphIdx];
772     int mod = [ts maxColumns] + 1;
774     if (row) *row = (int)(charIdx / mod);
775     if (column) *column = (int)(charIdx % mod);
777     NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
778             *row, *column);
780     return YES;
781 #else
782     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
783     NSSize cellSize = [ts cellSize];
784     if (!(cellSize.width > 0 && cellSize.height > 0))
785         return NO;
786     NSPoint origin = [self textContainerOrigin];
788     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
789     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
791     //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
792     //        *row, *column);
794     return YES;
795 #endif
798 - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point
800     MMTextStorage *ts = (MMTextStorage*)[self textStorage];
801     NSSize cellSize = [ts cellSize];
802     if (!(point && cellSize.width > 0 && cellSize.height > 0))
803         return NO;
805     *point = [self textContainerOrigin];
806     point->x += column * cellSize.width;
807     point->y += row * cellSize.height;
809     return YES;
812 - (NSRect)trackingRect
814     NSRect rect = [self frame];
815     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
816     int left = [ud integerForKey:MMTextInsetLeftKey];
817     int top = [ud integerForKey:MMTextInsetTopKey];
818     int right = [ud integerForKey:MMTextInsetRightKey];
819     int bot = [ud integerForKey:MMTextInsetBottomKey];
821     rect.origin.x = left;
822     rect.origin.y = top;
823     rect.size.width -= left + right - 1;
824     rect.size.height -= top + bot - 1;
826     return rect;
829 - (void)dispatchKeyEvent:(NSEvent *)event
831     // Only handle the command if it came from a keyDown event
832     if ([event type] != NSKeyDown)
833         return;
835     NSString *chars = [event characters];
836     NSString *unmodchars = [event charactersIgnoringModifiers];
837     unichar c = [chars characterAtIndex:0];
838     unichar imc = [unmodchars characterAtIndex:0];
839     int len = 0;
840     const char *bytes = 0;
841     int mods = [event modifierFlags];
843     //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
844     //        _cmd, c, imc, chars, unmodchars);
846     if (' ' == imc && 0xa0 != c) {
847         // HACK!  The AppKit turns <C-Space> into <C-@> which is not standard
848         // Vim behaviour, so bypass this problem.  (0xa0 is <M-Space>, which
849         // should be passed on as is.)
850         len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
851         bytes = [unmodchars UTF8String];
852     } else if (imc == c && '2' == c) {
853         // HACK!  Translate Ctrl+2 to <C-@>.
854         static char ctrl_at = 0;
855         len = 1;  bytes = &ctrl_at;
856     } else if (imc == c && '6' == c) {
857         // HACK!  Translate Ctrl+6 to <C-^>.
858         static char ctrl_hat = 0x1e;
859         len = 1;  bytes = &ctrl_hat;
860     } else if (c == 0x19 && imc == 0x19) {
861         // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
862         // separately (else Ctrl-Y doesn't work).
863         static char tab = 0x9;
864         len = 1;  bytes = &tab;  mods |= NSShiftKeyMask;
865     } else {
866         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
867         bytes = [chars UTF8String];
868     }
870     [self sendKeyDown:bytes length:len modifiers:mods];
873 - (MMVimController *)vimController
875     id windowController = [[self window] windowController];
877     // TODO: Make sure 'windowController' is a MMWindowController before type
878     // casting.
879     return [(MMWindowController*)windowController vimController];
882 - (void)startDragTimerWithInterval:(NSTimeInterval)t
884     [NSTimer scheduledTimerWithTimeInterval:t target:self
885                                    selector:@selector(dragTimerFired:)
886                                    userInfo:nil repeats:NO];
889 - (void)dragTimerFired:(NSTimer *)timer
891     // TODO: Autoscroll in horizontal direction?
892     static unsigned tick = 1;
893     MMTextStorage *ts = (MMTextStorage *)[self textStorage];
895     isAutoscrolling = NO;
897     if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) {
898         // HACK! If the mouse cursor is outside the text area, then send a
899         // dragged event.  However, if row&col hasn't changed since the last
900         // dragged event, Vim won't do anything (see gui_send_mouse_event()).
901         // Thus we fiddle with the column to make sure something happens.
902         int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2));
903         NSMutableData *data = [NSMutableData data];
905         [data appendBytes:&dragRow length:sizeof(int)];
906         [data appendBytes:&col length:sizeof(int)];
907         [data appendBytes:&dragFlags length:sizeof(int)];
909         [[self vimController] sendMessage:MouseDraggedMsgID data:data];
911         isAutoscrolling = YES;
912     }
914     if (isDragging) {
915         // Compute timer interval depending on how far away the mouse cursor is
916         // from the text view.
917         NSRect rect = [self trackingRect];
918         float dy = 0;
919         if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y;
920         else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect);
921         if (dy > MMDragAreaSize) dy = MMDragAreaSize;
923         NSTimeInterval t = MMDragTimerMaxInterval -
924             dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize;
926         [self startDragTimerWithInterval:t];
927     }
929     ++tick;
932 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
934     if (chars && len > 0) {
935         NSMutableData *data = [NSMutableData data];
937         [data appendBytes:&flags length:sizeof(int)];
938         [data appendBytes:&len length:sizeof(int)];
939         [data appendBytes:chars length:len];
941         // TODO: Support 'mousehide' (check p_mh)
942         [NSCursor setHiddenUntilMouseMoves:YES];
944         //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
945         [[self vimController] sendMessage:KeyDownMsgID data:data];
946     }
949 @end // MMTextView (Private)