From 8e360a39b9b4b66a758dfd73208bd8a8dce52cbc Mon Sep 17 00:00:00 2001 From: Bjorn Winckler Date: Tue, 12 Aug 2008 23:54:06 +0200 Subject: [PATCH] Remove duplicate code in text renderers Most of the code shared between the text renderers now resides in a "helper" object. This way it will be a lot easier to maintain several renderers at once. As an added bonus, the ATSUI renderer now has mouse support as well as drag-n-drop support. --- src/MacVim/MMAtsuiTextView.h | 6 + src/MacVim/MMAtsuiTextView.m | 445 ++++++----------- src/MacVim/MMTextView.h | 16 +- src/MacVim/MMTextView.m | 657 +++----------------------- src/MacVim/MMTextViewHelper.h | 56 +++ src/MacVim/MMTextViewHelper.m | 709 ++++++++++++++++++++++++++++ src/MacVim/MacVim.xcodeproj/project.pbxproj | 6 + 7 files changed, 994 insertions(+), 901 deletions(-) create mode 100644 src/MacVim/MMTextViewHelper.h create mode 100644 src/MacVim/MMTextViewHelper.m diff --git a/src/MacVim/MMAtsuiTextView.h b/src/MacVim/MMAtsuiTextView.h index 48c976a1..1e1cdfc9 100644 --- a/src/MacVim/MMAtsuiTextView.h +++ b/src/MacVim/MMAtsuiTextView.h @@ -13,6 +13,8 @@ enum { MMMaxCellsPerChar = 2 }; +@class MMTextViewHelper; + @interface MMAtsuiTextView : NSView { // From MMTextStorage @@ -31,6 +33,8 @@ enum { MMMaxCellsPerChar = 2 }; NSSize imageSize; ATSUStyle atsuStyles[MMMaxCellsPerChar]; BOOL antialias; + + MMTextViewHelper *helper; } - (id)initWithFrame:(NSRect)frame; @@ -38,6 +42,7 @@ enum { MMMaxCellsPerChar = 2 }; // // MMTextStorage methods // +- (int)maxRows; - (void)getMaxRows:(int*)rows columns:(int*)cols; - (void)setMaxRows:(int)rows columns:(int)cols; - (void)setDefaultColorsBackground:(NSColor *)bgColor @@ -59,6 +64,7 @@ enum { MMMaxCellsPerChar = 2 }; - (void)hideMarkedTextField; - (void)setMouseShape:(int)shape; - (void)setAntialias:(BOOL)state; +- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column; // // NSTextView methods diff --git a/src/MacVim/MMAtsuiTextView.m b/src/MacVim/MMAtsuiTextView.m index 4ddcba0e..bce017f0 100644 --- a/src/MacVim/MMAtsuiTextView.m +++ b/src/MacVim/MMAtsuiTextView.m @@ -27,6 +27,7 @@ #import "MMAppController.h" #import "MMAtsuiTextView.h" +#import "MMTextViewHelper.h" #import "MMVimController.h" #import "MMWindowController.h" #import "Miscellaneous.h" @@ -49,17 +50,6 @@ #define kUndercurlDotWidth 2 #define kUndercurlDotDistance 2 -static char MMKeypadEnter[2] = { 'K', 'A' }; -static NSString *MMKeypadEnterString = @"KA"; - -enum { - // These values are chosen so that the min size is not too small with the - // default font (they only affect resizing with the mouse, you can still - // use e.g. ":set lines=2" to go below these values). - MMMinRows = 4, - MMMinColumns = 30 -}; - @interface NSFont (AppKitPrivate) - (ATSUFontID) _atsFontID; @@ -67,13 +57,9 @@ enum { @interface MMAtsuiTextView (Private) -- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column; - (void)initAtsuStyles; - (void)disposeAtsuStyles; - (void)updateAtsuStyles; -- (void)dispatchKeyEvent:(NSEvent *)event; -- (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags; -- (void)hideMouseCursor; - (MMWindowController *)windowController; - (MMVimController *)vimController; @end @@ -124,21 +110,28 @@ defaultLineHeightForFont(NSFont *font) - (id)initWithFrame:(NSRect)frame { - if ((self = [super initWithFrame:frame])) { - // NOTE! It does not matter which font is set here, Vim will set its - // own font on startup anyway. Just set some bogus values. - font = [[NSFont userFixedPitchFontOfSize:0] retain]; - cellSize.width = cellSize.height = 1; - contentImage = nil; - imageSize = NSZeroSize; - insetSize = NSZeroSize; + if (!(self = [super initWithFrame:frame])) + return nil; - // NOTE: If the default changes to 'NO' then the intialization of - // p_antialias in option.c must change as well. - antialias = YES; + // NOTE! It does not matter which font is set here, Vim will set its + // own font on startup anyway. Just set some bogus values. + font = [[NSFont userFixedPitchFontOfSize:0] retain]; + cellSize.width = cellSize.height = 1; + contentImage = nil; + imageSize = NSZeroSize; + insetSize = NSZeroSize; - [self initAtsuStyles]; - } + // NOTE: If the default changes to 'NO' then the intialization of + // p_antialias in option.c must change as well. + antialias = YES; + + helper = [[MMTextViewHelper alloc] init]; + [helper setTextView:self]; + + [self initAtsuStyles]; + + [self registerForDraggedTypes:[NSArray arrayWithObjects: + NSFilenamesPboardType, NSStringPboardType, nil]]; return self; } @@ -150,9 +143,17 @@ defaultLineHeightForFont(NSFont *font) [defaultBackgroundColor release]; defaultBackgroundColor = nil; [defaultForegroundColor release]; defaultForegroundColor = nil; + [helper setTextView:nil]; + [helper dealloc]; helper = nil; + [super dealloc]; } +- (int)maxRows +{ + return maxRows; +} + - (void)getMaxRows:(int*)rows columns:(int*)cols { if (rows) *rows = maxRows; @@ -286,6 +287,7 @@ defaultLineHeightForFont(NSFont *font) - (void)setMouseShape:(int)shape { + [helper setMouseShape:shape]; } - (void)setAntialias:(BOOL)state @@ -298,194 +300,148 @@ defaultLineHeightForFont(NSFont *font) - (void)keyDown:(NSEvent *)event { - //NSLog(@"%s %@", _cmd, event); - // HACK! If control modifier is held, don't pass the event along to - // interpretKeyEvents: since some keys are bound to multiple commands which - // means doCommandBySelector: is called several times. Do the same for - // Alt+Function key presses (Alt+Up and Alt+Down are bound to two - // commands). This hack may break input management, but unless we can - // figure out a way to disable key bindings there seems little else to do. - // - // TODO: Figure out a way to disable Cocoa key bindings entirely, without - // affecting input management. - int flags = [event modifierFlags]; - if ((flags & NSControlKeyMask) || - ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) { - NSString *unmod = [event charactersIgnoringModifiers]; - if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f - && [unmod characterAtIndex:0] >= 0x60) { - // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_) - // as normal text to be added to the Vim input buffer. This must - // be done in order for the backend to be able to separate e.g. - // Ctrl-i and Ctrl-tab. - [self insertText:[event characters]]; - } else { - [self dispatchKeyEvent:event]; - } - } else { - [self interpretKeyEvents:[NSArray arrayWithObject:event]]; - } + [helper keyDown:event]; } - (void)insertText:(id)string { - //NSLog(@"%s %@", _cmd, string); - // NOTE! This method is called for normal key presses but also for - // Option-key presses --- even when Ctrl is held as well as Option. When - // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke, - // so 'string' need not be a printable character! In this case it still - // works to pass 'string' on to Vim as a printable character (since - // modifiers are already included and should not be added to the input - // buffer using CSI, K_MODIFIER). - - [self hideMarkedTextField]; - - NSEvent *event = [NSApp currentEvent]; - - // HACK! In order to be able to bind to , , etc. we have - // to watch for them here. - if ([event type] == NSKeyDown - && [[event charactersIgnoringModifiers] length] > 0 - && [event modifierFlags] - & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) { - unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0]; - - // translates to 0x19 - if (' ' == c || 0x19 == c) { - [self dispatchKeyEvent:event]; - return; - } - } + [helper insertText:string]; +} - [self hideMouseCursor]; +- (void)doCommandBySelector:(SEL)selector +{ + [helper doCommandBySelector:selector]; +} - // NOTE: 'string' is either an NSString or an NSAttributedString. Since we - // do not support attributes, simply pass the corresponding NSString in the - // latter case. - if ([string isKindOfClass:[NSAttributedString class]]) - string = [string string]; +- (BOOL)performKeyEquivalent:(NSEvent *)event +{ + return [helper performKeyEquivalent:event]; +} - //NSLog(@"send InsertTextMsgID: %@", string); +- (BOOL)hasMarkedText +{ + return NO; +} - [[self vimController] sendMessage:InsertTextMsgID - data:[string dataUsingEncoding:NSUTF8StringEncoding]]; +- (void)unmarkText +{ } -- (void)doCommandBySelector:(SEL)selector +- (void)scrollWheel:(NSEvent *)event { - //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector)); - // By ignoring the selector we effectively disable the key binding - // mechanism of Cocoa. Hopefully this is what the user will expect - // (pressing Ctrl+P would otherwise result in moveUp: instead of previous - // match, etc.). - // - // We usually end up here if the user pressed Ctrl+key (but not - // Ctrl+Option+key). - - NSEvent *event = [NSApp currentEvent]; - - if (selector == @selector(cancelOperation:) - || selector == @selector(insertNewline:)) { - // HACK! If there was marked text which got abandoned as a result of - // hitting escape or enter, then 'insertText:' is called with the - // abandoned text but '[event characters]' includes the abandoned text - // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we - // must intercept these keys here or the abandonded text gets inserted - // twice. - NSString *key = [event charactersIgnoringModifiers]; - const char *chars = [key UTF8String]; - int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - - if (0x3 == chars[0]) { - // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to - // handle it separately (else Ctrl-C doesn't work). - len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]); - chars = MMKeypadEnter; - } + [helper scrollWheel:event]; +} - [self sendKeyDown:chars length:len modifiers:[event modifierFlags]]; - } else { - [self dispatchKeyEvent:event]; - } +- (void)mouseDown:(NSEvent *)event +{ + [helper mouseDown:event]; } -- (BOOL)performKeyEquivalent:(NSEvent *)event +- (void)rightMouseDown:(NSEvent *)event { - //NSLog(@"%s %@", _cmd, event); - // Called for Cmd+key keystrokes, function keys, arrow keys, page - // up/down, home, end. - // - // NOTE: This message cannot be ignored since Cmd+letter keys never are - // passed to keyDown:. It seems as if the main menu consumes Cmd-key - // strokes, unless the key is a function key. - - // NOTE: If the event that triggered this method represents a function key - // down then we do nothing, otherwise the input method never gets the key - // stroke (some input methods use e.g. arrow keys). The function key down - // event will still reach Vim though (via keyDown:). The exceptions to - // this rule are: PageUp/PageDown (keycode 116/121). - int flags = [event modifierFlags]; - if ([event type] != NSKeyDown || flags & NSFunctionKeyMask - && !(116 == [event keyCode] || 121 == [event keyCode])) - return NO; + [helper mouseDown:event]; +} - // HACK! KeyCode 50 represent the key which switches between windows - // within an application (like Cmd+Tab is used to switch between - // applications). Return NO here, else the window switching does not work. - if ([event keyCode] == 50) - return NO; +- (void)otherMouseDown:(NSEvent *)event +{ + [helper mouseDown:event]; +} - // HACK! Let the main menu try to handle any key down event, before - // passing it on to vim, otherwise key equivalents for menus will - // effectively be disabled. - if ([[NSApp mainMenu] performKeyEquivalent:event]) - return YES; +- (void)mouseUp:(NSEvent *)event +{ + [helper mouseUp:event]; +} - // HACK! On Leopard Ctrl-key events end up here instead of keyDown:. - if (flags & NSControlKeyMask) { - [self keyDown:event]; - return YES; - } +- (void)rightMouseUp:(NSEvent *)event +{ + [helper mouseUp:event]; +} - // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard. - NSString *unmodchars = [event charactersIgnoringModifiers]; - if ([unmodchars isEqual:@"?"]) - return NO; +- (void)otherMouseUp:(NSEvent *)event +{ + [helper mouseUp:event]; +} + +- (void)mouseDragged:(NSEvent *)event +{ + [helper mouseDragged:event]; +} - //NSLog(@"%s%@", _cmd, event); +- (void)rightMouseDragged:(NSEvent *)event +{ + [helper mouseDragged:event]; +} - NSString *chars = [event characters]; - int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - NSMutableData *data = [NSMutableData data]; +- (void)otherMouseDragged:(NSEvent *)event +{ + [helper mouseDragged:event]; +} - if (len <= 0) - return NO; +- (void)mouseMoved:(NSEvent *)event +{ + [helper mouseMoved:event]; +} - // If 'chars' and 'unmodchars' differs when shift flag is present, then we - // can clear the shift flag as it is already included in 'unmodchars'. - // Failing to clear the shift flag means turns into (on - // an English keyboard). - if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars]) - flags &= ~NSShiftKeyMask; - - if (0x3 == [unmodchars characterAtIndex:0]) { - // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to - // handle it separately (else Cmd-enter turns into Ctrl-C). - unmodchars = MMKeypadEnterString; - len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - } +- (void)mouseEntered:(NSEvent *)event +{ + [helper mouseEntered:event]; +} - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&len length:sizeof(int)]; - [data appendBytes:[unmodchars UTF8String] length:len]; +- (void)mouseExited:(NSEvent *)event +{ + [helper mouseExited:event]; +} - [[self vimController] sendMessage:CmdKeyMsgID data:data]; +- (void)setFrame:(NSRect)frame +{ + [super setFrame:frame]; + [helper setFrame:frame]; +} - return YES; +- (void)viewDidMoveToWindow +{ + [helper viewDidMoveToWindow]; +} + +- (void)viewWillMoveToWindow:(NSWindow *)newWindow +{ + [helper viewWillMoveToWindow:newWindow]; } +- (NSMenu*)menuForEvent:(NSEvent *)event +{ + // HACK! Return nil to disable default popup menus (Vim provides its own). + // Called when user Ctrl-clicks in the view (this is already handled in + // rightMouseDown:). + return nil; +} +- (BOOL)performDragOperation:(id )sender +{ + return [helper performDragOperation:sender]; +} + +- (NSDragOperation)draggingEntered:(id )sender +{ + return [helper draggingEntered:sender]; +} + +- (NSDragOperation)draggingUpdated:(id )sender +{ + return [helper draggingUpdated:sender]; +} + + + +- (BOOL)mouseDownCanMoveWindow +{ + return NO; +} +- (BOOL)isOpaque +{ + return YES; +} - (BOOL)acceptsFirstResponder { @@ -741,34 +697,6 @@ defaultLineHeightForFont(NSFont *font) } } -- (void)scrollWheel:(NSEvent *)event -{ - if ([event deltaY] == 0) - return; - - int row, col; - NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil]; - - // View is not flipped, instead the atsui code draws to a flipped image; - // thus we need to 'flip' the coordinate here since the column number - // increases in an up-to-down order. - pt.y = [self frame].size.height - pt.y; - - if (![self convertPoint:pt toRow:&row column:&col]) - return; - - int flags = [event modifierFlags]; - float dy = [event deltaY]; - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&row length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&dy length:sizeof(float)]; - - [[self vimController] sendMessage:ScrollWheelMsgID data:data]; -} - // // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound @@ -805,15 +733,13 @@ defaultLineHeightForFont(NSFont *font) [[self windowController] vimMenuItemAction:sender]; } -@end // MMAtsuiTextView - - - - -@implementation MMAtsuiTextView (Private) - - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column { + // View is not flipped, instead the atsui code draws to a flipped image; + // thus we need to 'flip' the coordinate here since the column number + // increases in an up-to-down order. + point.y = [self frame].size.height - point.y; + NSPoint origin = { insetSize.width, insetSize.height }; if (!(cellSize.width > 0 && cellSize.height > 0)) @@ -828,6 +754,13 @@ defaultLineHeightForFont(NSFont *font) return YES; } +@end // MMAtsuiTextView + + + + +@implementation MMAtsuiTextView (Private) + - (void)initAtsuStyles { int i; @@ -906,76 +839,6 @@ defaultLineHeightForFont(NSFont *font) } } -- (void)dispatchKeyEvent:(NSEvent *)event -{ - // Only handle the command if it came from a keyDown event - if ([event type] != NSKeyDown) - return; - - NSString *chars = [event characters]; - NSString *unmodchars = [event charactersIgnoringModifiers]; - unichar c = [chars characterAtIndex:0]; - unichar imc = [unmodchars characterAtIndex:0]; - int len = 0; - const char *bytes = 0; - int mods = [event modifierFlags]; - - //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)", - // _cmd, c, imc, chars, unmodchars); - - if (' ' == imc && 0xa0 != c) { - // HACK! The AppKit turns into which is not standard - // Vim behaviour, so bypass this problem. (0xa0 is , which - // should be passed on as is.) - len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - bytes = [unmodchars UTF8String]; - } else if (imc == c && '2' == c) { - // HACK! Translate Ctrl+2 to . - static char ctrl_at = 0; - len = 1; bytes = &ctrl_at; - } else if (imc == c && '6' == c) { - // HACK! Translate Ctrl+6 to . - static char ctrl_hat = 0x1e; - len = 1; bytes = &ctrl_hat; - } else if (c == 0x19 && imc == 0x19) { - // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it - // separately (else Ctrl-Y doesn't work). - static char tab = 0x9; - len = 1; bytes = &tab; mods |= NSShiftKeyMask; - } else { - len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - bytes = [chars UTF8String]; - } - - [self sendKeyDown:bytes length:len modifiers:mods]; -} - -- (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags -{ - if (chars && len > 0) { - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&len length:sizeof(int)]; - [data appendBytes:chars length:len]; - - [self hideMouseCursor]; - - //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]); - [[self vimController] sendMessage:KeyDownMsgID data:data]; - } -} - -- (void)hideMouseCursor -{ - // Check 'mousehide' option - id mh = [[[self vimController] vimState] objectForKey:@"p_mh"]; - if (mh && ![mh boolValue]) - [NSCursor setHiddenUntilMouseMoves:NO]; - else - [NSCursor setHiddenUntilMouseMoves:YES]; -} - - (MMWindowController *)windowController { id windowController = [[self window] windowController]; diff --git a/src/MacVim/MMTextView.h b/src/MacVim/MMTextView.h index 63dea584..250f1f9e 100644 --- a/src/MacVim/MMTextView.h +++ b/src/MacVim/MMTextView.h @@ -10,16 +10,11 @@ #import +@class MMTextViewHelper; + @interface MMTextView : NSTextView { BOOL shouldDrawInsertionPoint; - NSTrackingRectTag trackingRectTag; - BOOL isDragging; - BOOL isAutoscrolling; - int dragRow; - int dragColumn; - int dragFlags; - NSPoint dragPoint; int insertionPointRow; int insertionPointColumn; int insertionPointShape; @@ -30,10 +25,11 @@ NSMutableAttributedString *markedText; int preEditRow; int preEditColumn; - int mouseShape; BOOL antialias; NSRect *invertRects; int numInvertRects; + + MMTextViewHelper *helper; } - (id)initWithFrame:(NSRect)frame; @@ -52,6 +48,7 @@ - (void)setWideFont:(NSFont *)newFont; - (NSSize)cellSize; - (void)setLinespace:(float)newLinespace; +- (int)maxRows; - (void)getMaxRows:(int*)rows columns:(int*)cols; - (void)setMaxRows:(int)rows columns:(int)cols; - (NSRect)rectForRowsInRange:(NSRange)range; @@ -63,4 +60,7 @@ - (NSSize)desiredSize; - (NSSize)minSize; + +- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column; + @end diff --git a/src/MacVim/MMTextView.m b/src/MacVim/MMTextView.m index 13905664..6308bba3 100644 --- a/src/MacVim/MMTextView.m +++ b/src/MacVim/MMTextView.m @@ -21,6 +21,7 @@ #import "MMAppController.h" #import "MMTextStorage.h" #import "MMTextView.h" +#import "MMTextViewHelper.h" #import "MMTypesetter.h" #import "MMVimController.h" #import "MMWindowController.h" @@ -31,36 +32,14 @@ // This is taken from gui.h #define DRAW_CURSOR 0x20 -// The max/min drag timer interval in seconds -static NSTimeInterval MMDragTimerMaxInterval = .3f; -static NSTimeInterval MMDragTimerMinInterval = .01f; - -// The number of pixels in which the drag timer interval changes -static float MMDragAreaSize = 73.0f; - -static char MMKeypadEnter[2] = { 'K', 'A' }; -static NSString *MMKeypadEnterString = @"KA"; - -enum { - MMMinRows = 4, - MMMinColumns = 20 -}; @interface MMTextView (Private) -- (void)setCursor; -- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column; - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point; - (BOOL)convertRow:(int)row column:(int)column numRows:(int)nr numColumns:(int)nc toRect:(NSRect *)rect; -- (NSRect)trackingRect; -- (void)dispatchKeyEvent:(NSEvent *)event; - (MMWindowController *)windowController; - (MMVimController *)vimController; -- (void)startDragTimerWithInterval:(NSTimeInterval)t; -- (void)dragTimerFired:(NSTimer *)timer; -- (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags; -- (void)hideMouseCursor; - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape fraction:(int)percent color:(NSColor *)color; - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows @@ -121,11 +100,15 @@ enum { return nil; } + helper = [[MMTextViewHelper alloc] init]; + [helper setTextView:self]; + imRange = NSMakeRange(0, 0); markedRange = NSMakeRange(0, 0); // NOTE: If the default changes to 'NO' then the intialization of // p_antialias in option.c must change as well. antialias = YES; + return self; } @@ -145,6 +128,9 @@ enum { numInvertRects = 0; } + [helper setTextView:nil]; + [helper dealloc]; helper = nil; + [super dealloc]; } @@ -331,8 +317,7 @@ enum { - (void)setMouseShape:(int)shape { - mouseShape = shape; - [self setCursor]; + [helper setMouseShape:shape]; } - (void)setAntialias:(BOOL)state @@ -365,6 +350,12 @@ enum { return [(MMTextStorage*)[self textStorage] setLinespace:newLinespace]; } +- (int)maxRows +{ + MMTextStorage *ts = (MMTextStorage *)[self textStorage]; + return [ts maxRows]; +} + - (void)getMaxRows:(int*)rows columns:(int*)cols { return [(MMTextStorage*)[self textStorage] getMaxRows:rows columns:cols]; @@ -441,6 +432,23 @@ enum { return size; } +- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column +{ + MMTextStorage *ts = (MMTextStorage*)[self textStorage]; + NSSize cellSize = [ts cellSize]; + if (!(cellSize.width > 0 && cellSize.height > 0)) + return NO; + NSPoint origin = [self textContainerOrigin]; + + if (row) *row = floor((point.y-origin.y-1) / cellSize.height); + if (column) *column = floor((point.x-origin.x-1) / cellSize.width); + + //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point), + // *row, *column); + + return YES; +} + - (BOOL)isOpaque { return NO; @@ -599,202 +607,22 @@ enum { - (void)keyDown:(NSEvent *)event { - //NSLog(@"%s %@", _cmd, event); - // HACK! If control modifier is held, don't pass the event along to - // interpretKeyEvents: since some keys are bound to multiple commands which - // means doCommandBySelector: is called several times. Do the same for - // Alt+Function key presses (Alt+Up and Alt+Down are bound to two - // commands). This hack may break input management, but unless we can - // figure out a way to disable key bindings there seems little else to do. - // - // TODO: Figure out a way to disable Cocoa key bindings entirely, without - // affecting input management. - - // When the Input Method is activated, some special key inputs - // should be treated as key inputs for Input Method. - if ([self hasMarkedText]) { - [self interpretKeyEvents:[NSArray arrayWithObject:event]]; - [self setNeedsDisplay:YES]; - return; - } - - int flags = [event modifierFlags]; - if ((flags & NSControlKeyMask) || - ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) { - NSString *unmod = [event charactersIgnoringModifiers]; - if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f - && [unmod characterAtIndex:0] >= 0x60) { - // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_) - // as normal text to be added to the Vim input buffer. This must - // be done in order for the backend to be able to separate e.g. - // Ctrl-i and Ctrl-tab. - [self insertText:[event characters]]; - } else { - [self dispatchKeyEvent:event]; - } - } else { - [super keyDown:event]; - } + [helper keyDown:event]; } - (void)insertText:(id)string { - //NSLog(@"%s %@", _cmd, string); - // NOTE! This method is called for normal key presses but also for - // Option-key presses --- even when Ctrl is held as well as Option. When - // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke, - // so 'string' need not be a printable character! In this case it still - // works to pass 'string' on to Vim as a printable character (since - // modifiers are already included and should not be added to the input - // buffer using CSI, K_MODIFIER). - - if ([self hasMarkedText]) { - [self unmarkText]; - } - - NSEvent *event = [NSApp currentEvent]; - - // HACK! In order to be able to bind to , , etc. we have - // to watch for them here. - if ([event type] == NSKeyDown - && [[event charactersIgnoringModifiers] length] > 0 - && [event modifierFlags] - & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) { - unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0]; - - // translates to 0x19 - if (' ' == c || 0x19 == c) { - [self dispatchKeyEvent:event]; - return; - } - } - - [self hideMouseCursor]; - - // NOTE: 'string' is either an NSString or an NSAttributedString. Since we - // do not support attributes, simply pass the corresponding NSString in the - // latter case. - if ([string isKindOfClass:[NSAttributedString class]]) - string = [string string]; - - //NSLog(@"send InsertTextMsgID: %@", string); - - [[self vimController] sendMessage:InsertTextMsgID - data:[string dataUsingEncoding:NSUTF8StringEncoding]]; + [helper insertText:string]; } - - (void)doCommandBySelector:(SEL)selector { - //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector)); - // By ignoring the selector we effectively disable the key binding - // mechanism of Cocoa. Hopefully this is what the user will expect - // (pressing Ctrl+P would otherwise result in moveUp: instead of previous - // match, etc.). - // - // We usually end up here if the user pressed Ctrl+key (but not - // Ctrl+Option+key). - - NSEvent *event = [NSApp currentEvent]; - - if (selector == @selector(cancelOperation:) - || selector == @selector(insertNewline:)) { - // HACK! If there was marked text which got abandoned as a result of - // hitting escape or enter, then 'insertText:' is called with the - // abandoned text but '[event characters]' includes the abandoned text - // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we - // must intercept these keys here or the abandonded text gets inserted - // twice. - NSString *key = [event charactersIgnoringModifiers]; - const char *chars = [key UTF8String]; - int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - - if (0x3 == chars[0]) { - // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to - // handle it separately (else Ctrl-C doesn't work). - len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]); - chars = MMKeypadEnter; - } - - [self sendKeyDown:chars length:len modifiers:[event modifierFlags]]; - } else { - [self dispatchKeyEvent:event]; - } + [helper doCommandBySelector:selector]; } - (BOOL)performKeyEquivalent:(NSEvent *)event { - //NSLog(@"%s %@", _cmd, event); - // Called for Cmd+key keystrokes, function keys, arrow keys, page - // up/down, home, end. - // - // NOTE: This message cannot be ignored since Cmd+letter keys never are - // passed to keyDown:. It seems as if the main menu consumes Cmd-key - // strokes, unless the key is a function key. - - // NOTE: If the event that triggered this method represents a function key - // down then we do nothing, otherwise the input method never gets the key - // stroke (some input methods use e.g. arrow keys). The function key down - // event will still reach Vim though (via keyDown:). The exceptions to - // this rule are: PageUp/PageDown (keycode 116/121). - int flags = [event modifierFlags]; - if ([event type] != NSKeyDown || flags & NSFunctionKeyMask - && !(116 == [event keyCode] || 121 == [event keyCode])) - return NO; - - // HACK! KeyCode 50 represent the key which switches between windows - // within an application (like Cmd+Tab is used to switch between - // applications). Return NO here, else the window switching does not work. - if ([event keyCode] == 50) - return NO; - - // HACK! Let the main menu try to handle any key down event, before - // passing it on to vim, otherwise key equivalents for menus will - // effectively be disabled. - if ([[NSApp mainMenu] performKeyEquivalent:event]) - return YES; - - // HACK! On Leopard Ctrl-key events end up here instead of keyDown:. - if (flags & NSControlKeyMask) { - [self keyDown:event]; - return YES; - } - - // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard. - NSString *unmodchars = [event charactersIgnoringModifiers]; - if ([unmodchars isEqual:@"?"]) - return NO; - - //NSLog(@"%s%@", _cmd, event); - - NSString *chars = [event characters]; - int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - NSMutableData *data = [NSMutableData data]; - - if (len <= 0) - return NO; - - // If 'chars' and 'unmodchars' differs when shift flag is present, then we - // can clear the shift flag as it is already included in 'unmodchars'. - // Failing to clear the shift flag means turns into (on - // an English keyboard). - if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars]) - flags &= ~NSShiftKeyMask; - - if (0x3 == [unmodchars characterAtIndex:0]) { - // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to - // handle it separately (else Cmd-enter turns into Ctrl-C). - unmodchars = MMKeypadEnterString; - len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - } - - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&len length:sizeof(int)]; - [data appendBytes:[unmodchars UTF8String] length:len]; - - [[self vimController] sendMessage:CmdKeyMsgID data:data]; - - return YES; + return [helper performKeyEquivalent:event]; } - (BOOL)hasMarkedText @@ -906,231 +734,83 @@ enum { - (void)scrollWheel:(NSEvent *)event { - if ([event deltaY] == 0) - return; - - int row, col; - NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil]; - if (![self convertPoint:pt toRow:&row column:&col]) - return; - - int flags = [event modifierFlags]; - float dy = [event deltaY]; - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&row length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&dy length:sizeof(float)]; - - [[self vimController] sendMessage:ScrollWheelMsgID data:data]; + [helper scrollWheel:event]; } - (void)mouseDown:(NSEvent *)event { - int row, col; - NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil]; - if (![self convertPoint:pt toRow:&row column:&col]) - return; - - int button = [event buttonNumber]; - int flags = [event modifierFlags]; - int count = [event clickCount]; - NSMutableData *data = [NSMutableData data]; - - // If desired, intepret Ctrl-Click as a right mouse click. - BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults] - boolForKey:MMTranslateCtrlClickKey]; - flags = flags & NSDeviceIndependentModifierFlagsMask; - if (translateCtrlClick && button == 0 && - (flags == NSControlKeyMask || - flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) { - button = 1; - flags &= ~NSControlKeyMask; - } - - [data appendBytes:&row length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - [data appendBytes:&button length:sizeof(int)]; - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&count length:sizeof(int)]; - - [[self vimController] sendMessage:MouseDownMsgID data:data]; + [helper mouseDown:event]; } - (void)rightMouseDown:(NSEvent *)event { - [self mouseDown:event]; + [helper mouseDown:event]; } - (void)otherMouseDown:(NSEvent *)event { - [self mouseDown:event]; + [helper mouseDown:event]; } - (void)mouseUp:(NSEvent *)event { - int row, col; - NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil]; - if (![self convertPoint:pt toRow:&row column:&col]) - return; - - int flags = [event modifierFlags]; - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&row length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - [data appendBytes:&flags length:sizeof(int)]; - - [[self vimController] sendMessage:MouseUpMsgID data:data]; - - isDragging = NO; + [helper mouseUp:event]; } - (void)rightMouseUp:(NSEvent *)event { - [self mouseUp:event]; + [helper mouseUp:event]; } - (void)otherMouseUp:(NSEvent *)event { - [self mouseUp:event]; + [helper mouseUp:event]; } - (void)mouseDragged:(NSEvent *)event { - int flags = [event modifierFlags]; - int row, col; - NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil]; - if (![self convertPoint:pt toRow:&row column:&col]) - return; - - // Autoscrolling is done in dragTimerFired: - if (!isAutoscrolling) { - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&row length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - [data appendBytes:&flags length:sizeof(int)]; - - [[self vimController] sendMessage:MouseDraggedMsgID data:data]; - } - - dragPoint = pt; - dragRow = row; dragColumn = col; dragFlags = flags; - if (!isDragging) { - [self startDragTimerWithInterval:.5]; - isDragging = YES; - } + [helper mouseDragged:event]; } - (void)rightMouseDragged:(NSEvent *)event { - [self mouseDragged:event]; + [helper mouseDragged:event]; } - (void)otherMouseDragged:(NSEvent *)event { - [self mouseDragged:event]; + [helper mouseDragged:event]; } - (void)mouseMoved:(NSEvent *)event { - MMTextStorage *ts = (MMTextStorage*)[self textStorage]; - if (!ts) return; - - // HACK! NSTextView has a nasty habit of resetting the cursor to the - // default I-beam cursor at random moments. The only reliable way we know - // of to work around this is to set the cursor each time the mouse moves. - [self setCursor]; - - NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil]; - int row, col; - if (![self convertPoint:pt toRow:&row column:&col]) - return; - - // HACK! It seems impossible to get the tracking rects set up before the - // view is visible, which means that the first mouseEntered: or - // mouseExited: events are never received. This forces us to check if the - // mouseMoved: event really happened over the text. - int rows, cols; - [ts getMaxRows:&rows columns:&cols]; - if (row >= 0 && row < rows && col >= 0 && col < cols) { - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&row length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - - [[self vimController] sendMessage:MouseMovedMsgID data:data]; - - //NSLog(@"Moved %d %d\n", col, row); - } + [helper mouseMoved:event]; } - (void)mouseEntered:(NSEvent *)event { - //NSLog(@"%s", _cmd); - - // NOTE: This event is received even when the window is not key; thus we - // have to take care not to enable mouse moved events unless our window is - // key. - if ([[self window] isKeyWindow]) { - [[self window] setAcceptsMouseMovedEvents:YES]; - } + [helper mouseEntered:event]; } - (void)mouseExited:(NSEvent *)event { - //NSLog(@"%s", _cmd); - - [[self window] setAcceptsMouseMovedEvents:NO]; - - // NOTE: This event is received even when the window is not key; if the - // mouse shape is set when our window is not key, the hollow (unfocused) - // cursor will become a block (focused) cursor. - if ([[self window] isKeyWindow]) { - int shape = 0; - NSMutableData *data = [NSMutableData data]; - [data appendBytes:&shape length:sizeof(int)]; - [[self vimController] sendMessage:SetMouseShapeMsgID data:data]; - } + [helper mouseExited:event]; } - (void)setFrame:(NSRect)frame { - //NSLog(@"%s", _cmd); - - // When the frame changes we also need to update the tracking rect. [super setFrame:frame]; - [self removeTrackingRect:trackingRectTag]; - trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self - userData:NULL assumeInside:YES]; + [helper setFrame:frame]; } - (void)viewDidMoveToWindow { - //NSLog(@"%s (window=%@)", _cmd, [self window]); - - // Set a tracking rect which covers the text. - // NOTE: While the mouse cursor is in this rect the view will receive - // 'mouseMoved:' events so that Vim can take care of updating the mouse - // cursor. - if ([self window]) { - [[self window] setAcceptsMouseMovedEvents:YES]; - trackingRectTag = [self addTrackingRect:[self trackingRect] owner:self - userData:NULL assumeInside:YES]; - } + [helper viewDidMoveToWindow]; } - (void)viewWillMoveToWindow:(NSWindow *)newWindow { - //NSLog(@"%s%@", _cmd, newWindow); - - // Remove tracking rect if view moves or is removed. - if ([self window] && trackingRectTag) { - [self removeTrackingRect:trackingRectTag]; - trackingRectTag = 0; - } + [helper viewWillMoveToWindow:newWindow]; } - (NSMenu*)menuForEvent:(NSEvent *)event @@ -1149,49 +829,17 @@ enum { - (BOOL)performDragOperation:(id )sender { - NSPasteboard *pboard = [sender draggingPasteboard]; - - if ([[pboard types] containsObject:NSStringPboardType]) { - NSString *string = [pboard stringForType:NSStringPboardType]; - [[self vimController] dropString:string]; - return YES; - } else if ([[pboard types] containsObject:NSFilenamesPboardType]) { - NSArray *files = [pboard propertyListForType:NSFilenamesPboardType]; - [[self vimController] dropFiles:files forceOpen:NO]; - return YES; - } - - return NO; + return [helper performDragOperation:sender]; } - (NSDragOperation)draggingEntered:(id )sender { - NSDragOperation sourceDragMask = [sender draggingSourceOperationMask]; - NSPasteboard *pboard = [sender draggingPasteboard]; - - if ( [[pboard types] containsObject:NSFilenamesPboardType] - && (sourceDragMask & NSDragOperationCopy) ) - return NSDragOperationCopy; - if ( [[pboard types] containsObject:NSStringPboardType] - && (sourceDragMask & NSDragOperationCopy) ) - return NSDragOperationCopy; - - return NSDragOperationNone; + return [helper draggingEntered:sender]; } - (NSDragOperation)draggingUpdated:(id )sender { - NSDragOperation sourceDragMask = [sender draggingSourceOperationMask]; - NSPasteboard *pboard = [sender draggingPasteboard]; - - if ( [[pboard types] containsObject:NSFilenamesPboardType] - && (sourceDragMask & NSDragOperationCopy) ) - return NSDragOperationCopy; - if ( [[pboard types] containsObject:NSStringPboardType] - && (sourceDragMask & NSDragOperationCopy) ) - return NSDragOperationCopy; - - return NSDragOperationNone; + return [helper draggingUpdated:sender]; } - (void)changeFont:(id)sender @@ -1285,64 +933,6 @@ enum { @implementation MMTextView (Private) -- (void)setCursor -{ - static NSCursor *customIbeamCursor = nil; - - if (!customIbeamCursor) { - // Use a custom Ibeam cursor that has better contrast against dark - // backgrounds. - // TODO: Is the hotspot ok? - NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"]; - if (ibeamImage) { - NSSize size = [ibeamImage size]; - NSPoint hotSpot = { size.width*.5f, size.height*.5f }; - - customIbeamCursor = [[NSCursor alloc] - initWithImage:ibeamImage hotSpot:hotSpot]; - } - if (!customIbeamCursor) { - NSLog(@"WARNING: Failed to load custom Ibeam cursor"); - customIbeamCursor = [NSCursor IBeamCursor]; - } - } - - // This switch should match mshape_names[] in misc2.c. - // - // TODO: Add missing cursor shapes. - switch (mouseShape) { - case 2: [customIbeamCursor set]; break; - case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break; - case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break; - case 9: [[NSCursor crosshairCursor] set]; break; - case 10: [[NSCursor pointingHandCursor] set]; break; - case 11: [[NSCursor openHandCursor] set]; break; - default: - [[NSCursor arrowCursor] set]; break; - } - - // Shape 1 indicates that the mouse cursor should be hidden. - if (1 == mouseShape) - [NSCursor setHiddenUntilMouseMoves:YES]; -} - -- (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column -{ - MMTextStorage *ts = (MMTextStorage*)[self textStorage]; - NSSize cellSize = [ts cellSize]; - if (!(cellSize.width > 0 && cellSize.height > 0)) - return NO; - NSPoint origin = [self textContainerOrigin]; - - if (row) *row = floor((point.y-origin.y-1) / cellSize.height); - if (column) *column = floor((point.x-origin.x-1) / cellSize.width); - - //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point), - // *row, *column); - - return YES; -} - - (BOOL)convertRow:(int)row column:(int)column toPoint:(NSPoint *)point { MMTextStorage *ts = (MMTextStorage*)[self textStorage]; @@ -1374,67 +964,6 @@ enum { return YES; } -- (NSRect)trackingRect -{ - NSRect rect = [self frame]; - NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; - int left = [ud integerForKey:MMTextInsetLeftKey]; - int top = [ud integerForKey:MMTextInsetTopKey]; - int right = [ud integerForKey:MMTextInsetRightKey]; - int bot = [ud integerForKey:MMTextInsetBottomKey]; - - rect.origin.x = left; - rect.origin.y = top; - rect.size.width -= left + right - 1; - rect.size.height -= top + bot - 1; - - return rect; -} - -- (void)dispatchKeyEvent:(NSEvent *)event -{ - // Only handle the command if it came from a keyDown event - if ([event type] != NSKeyDown) - return; - - NSString *chars = [event characters]; - NSString *unmodchars = [event charactersIgnoringModifiers]; - unichar c = [chars characterAtIndex:0]; - unichar imc = [unmodchars characterAtIndex:0]; - int len = 0; - const char *bytes = 0; - int mods = [event modifierFlags]; - - //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)", - // _cmd, c, imc, chars, unmodchars); - - if (' ' == imc && 0xa0 != c) { - // HACK! The AppKit turns into which is not standard - // Vim behaviour, so bypass this problem. (0xa0 is , which - // should be passed on as is.) - len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - bytes = [unmodchars UTF8String]; - } else if (imc == c && '2' == c) { - // HACK! Translate Ctrl+2 to . - static char ctrl_at = 0; - len = 1; bytes = &ctrl_at; - } else if (imc == c && '6' == c) { - // HACK! Translate Ctrl+6 to . - static char ctrl_hat = 0x1e; - len = 1; bytes = &ctrl_hat; - } else if (c == 0x19 && imc == 0x19) { - // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it - // separately (else Ctrl-Y doesn't work). - static char tab = 0x9; - len = 1; bytes = &tab; mods |= NSShiftKeyMask; - } else { - len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; - bytes = [chars UTF8String]; - } - - [self sendKeyDown:bytes length:len modifiers:mods]; -} - - (MMWindowController *)windowController { id windowController = [[self window] windowController]; @@ -1448,82 +977,6 @@ enum { return [[self windowController] vimController]; } -- (void)startDragTimerWithInterval:(NSTimeInterval)t -{ - [NSTimer scheduledTimerWithTimeInterval:t target:self - selector:@selector(dragTimerFired:) - userInfo:nil repeats:NO]; -} - -- (void)dragTimerFired:(NSTimer *)timer -{ - // TODO: Autoscroll in horizontal direction? - static unsigned tick = 1; - MMTextStorage *ts = (MMTextStorage *)[self textStorage]; - - isAutoscrolling = NO; - - if (isDragging && ts && (dragRow < 0 || dragRow >= [ts maxRows])) { - // HACK! If the mouse cursor is outside the text area, then send a - // dragged event. However, if row&col hasn't changed since the last - // dragged event, Vim won't do anything (see gui_send_mouse_event()). - // Thus we fiddle with the column to make sure something happens. - int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2)); - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&dragRow length:sizeof(int)]; - [data appendBytes:&col length:sizeof(int)]; - [data appendBytes:&dragFlags length:sizeof(int)]; - - [[self vimController] sendMessage:MouseDraggedMsgID data:data]; - - isAutoscrolling = YES; - } - - if (isDragging) { - // Compute timer interval depending on how far away the mouse cursor is - // from the text view. - NSRect rect = [self trackingRect]; - float dy = 0; - if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y; - else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect); - if (dy > MMDragAreaSize) dy = MMDragAreaSize; - - NSTimeInterval t = MMDragTimerMaxInterval - - dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize; - - [self startDragTimerWithInterval:t]; - } - - ++tick; -} - -- (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags -{ - if (chars && len > 0) { - NSMutableData *data = [NSMutableData data]; - - [data appendBytes:&flags length:sizeof(int)]; - [data appendBytes:&len length:sizeof(int)]; - [data appendBytes:chars length:len]; - - [self hideMouseCursor]; - - //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]); - [[self vimController] sendMessage:KeyDownMsgID data:data]; - } -} - -- (void)hideMouseCursor -{ - // Check 'mousehide' option - id mh = [[[self vimController] vimState] objectForKey:@"p_mh"]; - if (mh && ![mh boolValue]) - [NSCursor setHiddenUntilMouseMoves:NO]; - else - [NSCursor setHiddenUntilMouseMoves:YES]; -} - - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape fraction:(int)percent color:(NSColor *)color { diff --git a/src/MacVim/MMTextViewHelper.h b/src/MacVim/MMTextViewHelper.h new file mode 100644 index 00000000..ef7e1798 --- /dev/null +++ b/src/MacVim/MMTextViewHelper.h @@ -0,0 +1,56 @@ +/* vi:set ts=8 sts=4 sw=4 ft=objc: + * + * VIM - Vi IMproved by Bram Moolenaar + * MacVim GUI port by Bjorn Winckler + * + * Do ":help uganda" in Vim to read copying and usage conditions. + * Do ":help credits" in Vim to see a list of people who contributed. + * See README.txt for an overview of the Vim source code. + */ + +#import + + +enum { + // These values are chosen so that the min text view size is not too small + // with the default font (they only affect resizing with the mouse, you can + // still use e.g. ":set lines=2" to go below these values). + MMMinRows = 4, + MMMinColumns = 30 +}; + + +@interface MMTextViewHelper : NSObject { + id textView; + BOOL isDragging; + int dragRow; + int dragColumn; + int dragFlags; + NSPoint dragPoint; + BOOL isAutoscrolling; + int mouseShape; + NSTrackingRectTag trackingRectTag; +} + +- (void)setTextView:(id)view; + +- (void)keyDown:(NSEvent *)event; +- (void)insertText:(id)string; +- (void)doCommandBySelector:(SEL)selector; +- (BOOL)performKeyEquivalent:(NSEvent *)event; +- (void)scrollWheel:(NSEvent *)event; +- (void)mouseDown:(NSEvent *)event; +- (void)mouseUp:(NSEvent *)event; +- (void)mouseDragged:(NSEvent *)event; +- (void)mouseMoved:(NSEvent *)event; +- (void)mouseEntered:(NSEvent *)event; +- (void)mouseExited:(NSEvent *)event; +- (void)setFrame:(NSRect)frame; +- (void)viewDidMoveToWindow; +- (void)viewWillMoveToWindow:(NSWindow *)newWindow; +- (BOOL)performDragOperation:(id )sender; +- (NSDragOperation)draggingEntered:(id )sender; +- (NSDragOperation)draggingUpdated:(id )sender; +- (void)setMouseShape:(int)shape; + +@end diff --git a/src/MacVim/MMTextViewHelper.m b/src/MacVim/MMTextViewHelper.m new file mode 100644 index 00000000..1deb102c --- /dev/null +++ b/src/MacVim/MMTextViewHelper.m @@ -0,0 +1,709 @@ +/* vi:set ts=8 sts=4 sw=4 ft=objc: + * + * VIM - Vi IMproved by Bram Moolenaar + * MacVim GUI port by Bjorn Winckler + * + * Do ":help uganda" in Vim to read copying and usage conditions. + * Do ":help credits" in Vim to see a list of people who contributed. + * See README.txt for an overview of the Vim source code. + */ +/* + * MMTextViewHelper + * + * Contains code shared between the different text renderers. Unfortunately it + * is not possible to let the text renderers inherit from this class since + * MMTextView needs to inherit from NSTextView whereas MMAtsuiTextView needs to + * inherit from NSView. + */ + +#import "MMTextView.h" +#import "MMTextViewHelper.h" +#import "MMVimController.h" +#import "MMWindowController.h" +#import "Miscellaneous.h" + + +static char MMKeypadEnter[2] = { 'K', 'A' }; +static NSString *MMKeypadEnterString = @"KA"; + +// The max/min drag timer interval in seconds +static NSTimeInterval MMDragTimerMaxInterval = .3f; +static NSTimeInterval MMDragTimerMinInterval = .01f; + +// The number of pixels in which the drag timer interval changes +static float MMDragAreaSize = 73.0f; + + +@interface MMTextViewHelper (Private) +- (MMWindowController *)windowController; +- (MMVimController *)vimController; +- (void)dispatchKeyEvent:(NSEvent *)event; +- (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags; +- (void)hideMouseCursor; +- (void)startDragTimerWithInterval:(NSTimeInterval)t; +- (void)dragTimerFired:(NSTimer *)timer; +- (void)setCursor; +- (NSRect)trackingRect; +@end + + +@implementation MMTextViewHelper + +- (void)setTextView:(id)view +{ + // Only keep a weak reference to owning text view. + textView = view; +} + +- (void)keyDown:(NSEvent *)event +{ + //NSLog(@"%s %@", _cmd, event); + // HACK! If control modifier is held, don't pass the event along to + // interpretKeyEvents: since some keys are bound to multiple commands which + // means doCommandBySelector: is called several times. Do the same for + // Alt+Function key presses (Alt+Up and Alt+Down are bound to two + // commands). This hack may break input management, but unless we can + // figure out a way to disable key bindings there seems little else to do. + // + // TODO: Figure out a way to disable Cocoa key bindings entirely, without + // affecting input management. + + // When the Input Method is activated, some special key inputs + // should be treated as key inputs for Input Method. + if ([textView hasMarkedText]) { + [textView interpretKeyEvents:[NSArray arrayWithObject:event]]; + [textView setNeedsDisplay:YES]; + return; + } + + int flags = [event modifierFlags]; + if ((flags & NSControlKeyMask) || + ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) { + NSString *unmod = [event charactersIgnoringModifiers]; + if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f + && [unmod characterAtIndex:0] >= 0x60) { + // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_) + // as normal text to be added to the Vim input buffer. This must + // be done in order for the backend to be able to separate e.g. + // Ctrl-i and Ctrl-tab. + [self insertText:[event characters]]; + } else { + [self dispatchKeyEvent:event]; + } + } else { + [textView interpretKeyEvents:[NSArray arrayWithObject:event]]; + } +} + +- (void)insertText:(id)string +{ + //NSLog(@"%s %@", _cmd, string); + // NOTE! This method is called for normal key presses but also for + // Option-key presses --- even when Ctrl is held as well as Option. When + // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke, + // so 'string' need not be a printable character! In this case it still + // works to pass 'string' on to Vim as a printable character (since + // modifiers are already included and should not be added to the input + // buffer using CSI, K_MODIFIER). + + if ([textView hasMarkedText]) { + [textView unmarkText]; + } + + NSEvent *event = [NSApp currentEvent]; + + // HACK! In order to be able to bind to , , etc. we have + // to watch for them here. + if ([event type] == NSKeyDown + && [[event charactersIgnoringModifiers] length] > 0 + && [event modifierFlags] + & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) { + unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0]; + + // translates to 0x19 + if (' ' == c || 0x19 == c) { + [self dispatchKeyEvent:event]; + return; + } + } + + [self hideMouseCursor]; + + // NOTE: 'string' is either an NSString or an NSAttributedString. Since we + // do not support attributes, simply pass the corresponding NSString in the + // latter case. + if ([string isKindOfClass:[NSAttributedString class]]) + string = [string string]; + + //NSLog(@"send InsertTextMsgID: %@", string); + + [[self vimController] sendMessage:InsertTextMsgID + data:[string dataUsingEncoding:NSUTF8StringEncoding]]; +} + +- (void)doCommandBySelector:(SEL)selector +{ + //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector)); + // By ignoring the selector we effectively disable the key binding + // mechanism of Cocoa. Hopefully this is what the user will expect + // (pressing Ctrl+P would otherwise result in moveUp: instead of previous + // match, etc.). + // + // We usually end up here if the user pressed Ctrl+key (but not + // Ctrl+Option+key). + + NSEvent *event = [NSApp currentEvent]; + + if (selector == @selector(cancelOperation:) + || selector == @selector(insertNewline:)) { + // HACK! If there was marked text which got abandoned as a result of + // hitting escape or enter, then 'insertText:' is called with the + // abandoned text but '[event characters]' includes the abandoned text + // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we + // must intercept these keys here or the abandonded text gets inserted + // twice. + NSString *key = [event charactersIgnoringModifiers]; + const char *chars = [key UTF8String]; + int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + + if (0x3 == chars[0]) { + // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to + // handle it separately (else Ctrl-C doesn't work). + len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]); + chars = MMKeypadEnter; + } + + [self sendKeyDown:chars length:len modifiers:[event modifierFlags]]; + } else { + [self dispatchKeyEvent:event]; + } +} + +- (BOOL)performKeyEquivalent:(NSEvent *)event +{ + //NSLog(@"%s %@", _cmd, event); + // Called for Cmd+key keystrokes, function keys, arrow keys, page + // up/down, home, end. + // + // NOTE: This message cannot be ignored since Cmd+letter keys never are + // passed to keyDown:. It seems as if the main menu consumes Cmd-key + // strokes, unless the key is a function key. + + // NOTE: If the event that triggered this method represents a function key + // down then we do nothing, otherwise the input method never gets the key + // stroke (some input methods use e.g. arrow keys). The function key down + // event will still reach Vim though (via keyDown:). The exceptions to + // this rule are: PageUp/PageDown (keycode 116/121). + int flags = [event modifierFlags]; + if ([event type] != NSKeyDown || flags & NSFunctionKeyMask + && !(116 == [event keyCode] || 121 == [event keyCode])) + return NO; + + // HACK! KeyCode 50 represent the key which switches between windows + // within an application (like Cmd+Tab is used to switch between + // applications). Return NO here, else the window switching does not work. + if ([event keyCode] == 50) + return NO; + + // HACK! Let the main menu try to handle any key down event, before + // passing it on to vim, otherwise key equivalents for menus will + // effectively be disabled. + if ([[NSApp mainMenu] performKeyEquivalent:event]) + return YES; + + // HACK! On Leopard Ctrl-key events end up here instead of keyDown:. + if (flags & NSControlKeyMask) { + [self keyDown:event]; + return YES; + } + + // HACK! Don't handle Cmd-? or the "Help" menu does not work on Leopard. + NSString *unmodchars = [event charactersIgnoringModifiers]; + if ([unmodchars isEqual:@"?"]) + return NO; + + //NSLog(@"%s%@", _cmd, event); + + NSString *chars = [event characters]; + int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + NSMutableData *data = [NSMutableData data]; + + if (len <= 0) + return NO; + + // If 'chars' and 'unmodchars' differs when shift flag is present, then we + // can clear the shift flag as it is already included in 'unmodchars'. + // Failing to clear the shift flag means turns into (on + // an English keyboard). + if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars]) + flags &= ~NSShiftKeyMask; + + if (0x3 == [unmodchars characterAtIndex:0]) { + // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to + // handle it separately (else Cmd-enter turns into Ctrl-C). + unmodchars = MMKeypadEnterString; + len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + } + + [data appendBytes:&flags length:sizeof(int)]; + [data appendBytes:&len length:sizeof(int)]; + [data appendBytes:[unmodchars UTF8String] length:len]; + + [[self vimController] sendMessage:CmdKeyMsgID data:data]; + + return YES; +} + +- (void)scrollWheel:(NSEvent *)event +{ + if ([event deltaY] == 0) + return; + + int row, col; + NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil]; + if (![textView convertPoint:pt toRow:&row column:&col]) + return; + + int flags = [event modifierFlags]; + float dy = [event deltaY]; + NSMutableData *data = [NSMutableData data]; + + [data appendBytes:&row length:sizeof(int)]; + [data appendBytes:&col length:sizeof(int)]; + [data appendBytes:&flags length:sizeof(int)]; + [data appendBytes:&dy length:sizeof(float)]; + + [[self vimController] sendMessage:ScrollWheelMsgID data:data]; +} + +- (void)mouseDown:(NSEvent *)event +{ + int row, col; + NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil]; + if (![textView convertPoint:pt toRow:&row column:&col]) + return; + + int button = [event buttonNumber]; + int flags = [event modifierFlags]; + int count = [event clickCount]; + NSMutableData *data = [NSMutableData data]; + + // If desired, intepret Ctrl-Click as a right mouse click. + BOOL translateCtrlClick = [[NSUserDefaults standardUserDefaults] + boolForKey:MMTranslateCtrlClickKey]; + flags = flags & NSDeviceIndependentModifierFlagsMask; + if (translateCtrlClick && button == 0 && + (flags == NSControlKeyMask || + flags == (NSControlKeyMask|NSAlphaShiftKeyMask))) { + button = 1; + flags &= ~NSControlKeyMask; + } + + [data appendBytes:&row length:sizeof(int)]; + [data appendBytes:&col length:sizeof(int)]; + [data appendBytes:&button length:sizeof(int)]; + [data appendBytes:&flags length:sizeof(int)]; + [data appendBytes:&count length:sizeof(int)]; + + [[self vimController] sendMessage:MouseDownMsgID data:data]; +} + +- (void)mouseUp:(NSEvent *)event +{ + int row, col; + NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil]; + if (![textView convertPoint:pt toRow:&row column:&col]) + return; + + int flags = [event modifierFlags]; + NSMutableData *data = [NSMutableData data]; + + [data appendBytes:&row length:sizeof(int)]; + [data appendBytes:&col length:sizeof(int)]; + [data appendBytes:&flags length:sizeof(int)]; + + [[self vimController] sendMessage:MouseUpMsgID data:data]; + + isDragging = NO; +} + +- (void)mouseDragged:(NSEvent *)event +{ + int flags = [event modifierFlags]; + int row, col; + NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil]; + if (![textView convertPoint:pt toRow:&row column:&col]) + return; + + // Autoscrolling is done in dragTimerFired: + if (!isAutoscrolling) { + NSMutableData *data = [NSMutableData data]; + + [data appendBytes:&row length:sizeof(int)]; + [data appendBytes:&col length:sizeof(int)]; + [data appendBytes:&flags length:sizeof(int)]; + + [[self vimController] sendMessage:MouseDraggedMsgID data:data]; + } + + dragPoint = pt; + dragRow = row; + dragColumn = col; + dragFlags = flags; + + if (!isDragging) { + [self startDragTimerWithInterval:.5]; + isDragging = YES; + } +} + +- (void)mouseMoved:(NSEvent *)event +{ + // HACK! NSTextView has a nasty habit of resetting the cursor to the + // default I-beam cursor at random moments. The only reliable way we know + // of to work around this is to set the cursor each time the mouse moves. + [self setCursor]; + + NSPoint pt = [textView convertPoint:[event locationInWindow] fromView:nil]; + int row, col; + if (![textView convertPoint:pt toRow:&row column:&col]) + return; + + // HACK! It seems impossible to get the tracking rects set up before the + // view is visible, which means that the first mouseEntered: or + // mouseExited: events are never received. This forces us to check if the + // mouseMoved: event really happened over the text. + int rows, cols; + [textView getMaxRows:&rows columns:&cols]; + if (row >= 0 && row < rows && col >= 0 && col < cols) { + NSMutableData *data = [NSMutableData data]; + + [data appendBytes:&row length:sizeof(int)]; + [data appendBytes:&col length:sizeof(int)]; + + [[self vimController] sendMessage:MouseMovedMsgID data:data]; + + //NSLog(@"Moved %d %d\n", col, row); + } +} + +- (void)mouseEntered:(NSEvent *)event +{ + //NSLog(@"%s", _cmd); + + // NOTE: This event is received even when the window is not key; thus we + // have to take care not to enable mouse moved events unless our window is + // key. + if ([[textView window] isKeyWindow]) { + [[textView window] setAcceptsMouseMovedEvents:YES]; + } +} + +- (void)mouseExited:(NSEvent *)event +{ + //NSLog(@"%s", _cmd); + + [[textView window] setAcceptsMouseMovedEvents:NO]; + + // NOTE: This event is received even when the window is not key; if the + // mouse shape is set when our window is not key, the hollow (unfocused) + // cursor will become a block (focused) cursor. + if ([[textView window] isKeyWindow]) { + int shape = 0; + NSMutableData *data = [NSMutableData data]; + [data appendBytes:&shape length:sizeof(int)]; + [[self vimController] sendMessage:SetMouseShapeMsgID data:data]; + } +} + +- (void)setFrame:(NSRect)frame +{ + //NSLog(@"%s", _cmd); + + // When the frame changes we also need to update the tracking rect. + [textView removeTrackingRect:trackingRectTag]; + trackingRectTag = [textView addTrackingRect:[self trackingRect] + owner:textView + userData:NULL + assumeInside:YES]; +} + +- (void)viewDidMoveToWindow +{ + //NSLog(@"%s (window=%@)", _cmd, [self window]); + + // Set a tracking rect which covers the text. + // NOTE: While the mouse cursor is in this rect the view will receive + // 'mouseMoved:' events so that Vim can take care of updating the mouse + // cursor. + if ([textView window]) { + [[textView window] setAcceptsMouseMovedEvents:YES]; + trackingRectTag = [textView addTrackingRect:[self trackingRect] + owner:textView + userData:NULL + assumeInside:YES]; + } +} + +- (void)viewWillMoveToWindow:(NSWindow *)newWindow +{ + //NSLog(@"%s%@", _cmd, newWindow); + + // Remove tracking rect if view moves or is removed. + if ([textView window] && trackingRectTag) { + [textView removeTrackingRect:trackingRectTag]; + trackingRectTag = 0; + } +} + +- (BOOL)performDragOperation:(id )sender +{ + NSPasteboard *pboard = [sender draggingPasteboard]; + + if ([[pboard types] containsObject:NSStringPboardType]) { + NSString *string = [pboard stringForType:NSStringPboardType]; + [[self vimController] dropString:string]; + return YES; + } else if ([[pboard types] containsObject:NSFilenamesPboardType]) { + NSArray *files = [pboard propertyListForType:NSFilenamesPboardType]; + [[self vimController] dropFiles:files forceOpen:NO]; + return YES; + } + + return NO; +} + +- (NSDragOperation)draggingEntered:(id )sender +{ + NSDragOperation sourceDragMask = [sender draggingSourceOperationMask]; + NSPasteboard *pboard = [sender draggingPasteboard]; + + if ( [[pboard types] containsObject:NSFilenamesPboardType] + && (sourceDragMask & NSDragOperationCopy) ) + return NSDragOperationCopy; + if ( [[pboard types] containsObject:NSStringPboardType] + && (sourceDragMask & NSDragOperationCopy) ) + return NSDragOperationCopy; + + return NSDragOperationNone; +} + +- (NSDragOperation)draggingUpdated:(id )sender +{ + NSDragOperation sourceDragMask = [sender draggingSourceOperationMask]; + NSPasteboard *pboard = [sender draggingPasteboard]; + + if ( [[pboard types] containsObject:NSFilenamesPboardType] + && (sourceDragMask & NSDragOperationCopy) ) + return NSDragOperationCopy; + if ( [[pboard types] containsObject:NSStringPboardType] + && (sourceDragMask & NSDragOperationCopy) ) + return NSDragOperationCopy; + + return NSDragOperationNone; +} + +- (void)setMouseShape:(int)shape +{ + mouseShape = shape; + [self setCursor]; +} + +@end // MMTextViewHelper + + + + +@implementation MMTextViewHelper (Private) + +- (MMWindowController *)windowController +{ + id windowController = [[textView window] windowController]; + if ([windowController isKindOfClass:[MMWindowController class]]) + return (MMWindowController*)windowController; + return nil; +} + +- (MMVimController *)vimController +{ + return [[self windowController] vimController]; +} + +- (void)dispatchKeyEvent:(NSEvent *)event +{ + // Only handle the command if it came from a keyDown event + if ([event type] != NSKeyDown) + return; + + NSString *chars = [event characters]; + NSString *unmodchars = [event charactersIgnoringModifiers]; + unichar c = [chars characterAtIndex:0]; + unichar imc = [unmodchars characterAtIndex:0]; + int len = 0; + const char *bytes = 0; + int mods = [event modifierFlags]; + + //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)", + // _cmd, c, imc, chars, unmodchars); + + if (' ' == imc && 0xa0 != c) { + // HACK! The AppKit turns into which is not standard + // Vim behaviour, so bypass this problem. (0xa0 is , which + // should be passed on as is.) + len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + bytes = [unmodchars UTF8String]; + } else if (imc == c && '2' == c) { + // HACK! Translate Ctrl+2 to . + static char ctrl_at = 0; + len = 1; bytes = &ctrl_at; + } else if (imc == c && '6' == c) { + // HACK! Translate Ctrl+6 to . + static char ctrl_hat = 0x1e; + len = 1; bytes = &ctrl_hat; + } else if (c == 0x19 && imc == 0x19) { + // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it + // separately (else Ctrl-Y doesn't work). + static char tab = 0x9; + len = 1; bytes = &tab; mods |= NSShiftKeyMask; + } else { + len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding]; + bytes = [chars UTF8String]; + } + + [self sendKeyDown:bytes length:len modifiers:mods]; +} + +- (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags +{ + if (chars && len > 0) { + NSMutableData *data = [NSMutableData data]; + + [data appendBytes:&flags length:sizeof(int)]; + [data appendBytes:&len length:sizeof(int)]; + [data appendBytes:chars length:len]; + + [self hideMouseCursor]; + + //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]); + [[self vimController] sendMessage:KeyDownMsgID data:data]; + } +} + +- (void)hideMouseCursor +{ + // Check 'mousehide' option + id mh = [[[self vimController] vimState] objectForKey:@"p_mh"]; + if (mh && ![mh boolValue]) + [NSCursor setHiddenUntilMouseMoves:NO]; + else + [NSCursor setHiddenUntilMouseMoves:YES]; +} + +- (void)startDragTimerWithInterval:(NSTimeInterval)t +{ + [NSTimer scheduledTimerWithTimeInterval:t target:self + selector:@selector(dragTimerFired:) + userInfo:nil repeats:NO]; +} + +- (void)dragTimerFired:(NSTimer *)timer +{ + // TODO: Autoscroll in horizontal direction? + static unsigned tick = 1; + + isAutoscrolling = NO; + + if (isDragging && (dragRow < 0 || dragRow >= [textView maxRows])) { + // HACK! If the mouse cursor is outside the text area, then send a + // dragged event. However, if row&col hasn't changed since the last + // dragged event, Vim won't do anything (see gui_send_mouse_event()). + // Thus we fiddle with the column to make sure something happens. + int col = dragColumn + (dragRow < 0 ? -(tick % 2) : +(tick % 2)); + NSMutableData *data = [NSMutableData data]; + + [data appendBytes:&dragRow length:sizeof(int)]; + [data appendBytes:&col length:sizeof(int)]; + [data appendBytes:&dragFlags length:sizeof(int)]; + + [[self vimController] sendMessage:MouseDraggedMsgID data:data]; + + isAutoscrolling = YES; + } + + if (isDragging) { + // Compute timer interval depending on how far away the mouse cursor is + // from the text view. + NSRect rect = [self trackingRect]; + float dy = 0; + if (dragPoint.y < rect.origin.y) dy = rect.origin.y - dragPoint.y; + else if (dragPoint.y > NSMaxY(rect)) dy = dragPoint.y - NSMaxY(rect); + if (dy > MMDragAreaSize) dy = MMDragAreaSize; + + NSTimeInterval t = MMDragTimerMaxInterval - + dy*(MMDragTimerMaxInterval-MMDragTimerMinInterval)/MMDragAreaSize; + + [self startDragTimerWithInterval:t]; + } + + ++tick; +} + +- (void)setCursor +{ + static NSCursor *customIbeamCursor = nil; + + if (!customIbeamCursor) { + // Use a custom Ibeam cursor that has better contrast against dark + // backgrounds. + // TODO: Is the hotspot ok? + NSImage *ibeamImage = [NSImage imageNamed:@"ibeam"]; + if (ibeamImage) { + NSSize size = [ibeamImage size]; + NSPoint hotSpot = { size.width*.5f, size.height*.5f }; + + customIbeamCursor = [[NSCursor alloc] + initWithImage:ibeamImage hotSpot:hotSpot]; + } + if (!customIbeamCursor) { + NSLog(@"WARNING: Failed to load custom Ibeam cursor"); + customIbeamCursor = [NSCursor IBeamCursor]; + } + } + + // This switch should match mshape_names[] in misc2.c. + // + // TODO: Add missing cursor shapes. + switch (mouseShape) { + case 2: [customIbeamCursor set]; break; + case 3: case 4: [[NSCursor resizeUpDownCursor] set]; break; + case 5: case 6: [[NSCursor resizeLeftRightCursor] set]; break; + case 9: [[NSCursor crosshairCursor] set]; break; + case 10: [[NSCursor pointingHandCursor] set]; break; + case 11: [[NSCursor openHandCursor] set]; break; + default: + [[NSCursor arrowCursor] set]; break; + } + + // Shape 1 indicates that the mouse cursor should be hidden. + if (1 == mouseShape) + [NSCursor setHiddenUntilMouseMoves:YES]; +} + +- (NSRect)trackingRect +{ + NSRect rect = [textView frame]; + NSUserDefaults *ud = [NSUserDefaults standardUserDefaults]; + int left = [ud integerForKey:MMTextInsetLeftKey]; + int top = [ud integerForKey:MMTextInsetTopKey]; + int right = [ud integerForKey:MMTextInsetRightKey]; + int bot = [ud integerForKey:MMTextInsetBottomKey]; + + rect.origin.x = left; + rect.origin.y = top; + rect.size.width -= left + right - 1; + rect.size.height -= top + bot - 1; + + return rect; +} + +@end // MMTextViewHelper (Private) diff --git a/src/MacVim/MacVim.xcodeproj/project.pbxproj b/src/MacVim/MacVim.xcodeproj/project.pbxproj index 5e1ee7af..347d915d 100644 --- a/src/MacVim/MacVim.xcodeproj/project.pbxproj +++ b/src/MacVim/MacVim.xcodeproj/project.pbxproj @@ -16,6 +16,7 @@ 0395AAAD0D76E94000881434 /* Edit in ODBEditor.bundle in CopyFiles */ = {isa = PBXBuildFile; fileRef = 0395AA210D76E22700881434 /* Edit in ODBEditor.bundle */; }; 1D09AB420C6A4D520045497E /* MMTypesetter.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D09AB400C6A4D520045497E /* MMTypesetter.m */; }; 1D0E051C0BA5F83800B6049E /* Colors.plist in Resources */ = {isa = PBXBuildFile; fileRef = 1D0E051B0BA5F83800B6049E /* Colors.plist */; }; + 1D145C7F0E5227CE00691AA0 /* MMTextViewHelper.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D145C7E0E5227CE00691AA0 /* MMTextViewHelper.m */; }; 1D1474980C56703C0038FA2B /* MacVim.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D1474960C56703C0038FA2B /* MacVim.m */; }; 1D1474A00C5673AE0038FA2B /* MMAppController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D14749E0C5673AE0038FA2B /* MMAppController.m */; }; 1D1474AA0C5677450038FA2B /* MMTextStorage.m in Sources */ = {isa = PBXBuildFile; fileRef = 1D1474A80C5677450038FA2B /* MMTextStorage.m */; }; @@ -188,6 +189,8 @@ 1D09AB3F0C6A4D520045497E /* MMTypesetter.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MMTypesetter.h; sourceTree = ""; }; 1D09AB400C6A4D520045497E /* MMTypesetter.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = MMTypesetter.m; sourceTree = ""; }; 1D0E051B0BA5F83800B6049E /* Colors.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = Colors.plist; sourceTree = ""; }; + 1D145C7D0E5227CE00691AA0 /* MMTextViewHelper.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MMTextViewHelper.h; sourceTree = ""; }; + 1D145C7E0E5227CE00691AA0 /* MMTextViewHelper.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = MMTextViewHelper.m; sourceTree = ""; }; 1D1474950C56703C0038FA2B /* MacVim.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MacVim.h; sourceTree = ""; }; 1D1474960C56703C0038FA2B /* MacVim.m */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.objc; path = MacVim.m; sourceTree = ""; }; 1D14749D0C5673AE0038FA2B /* MMAppController.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MMAppController.h; sourceTree = ""; }; @@ -325,6 +328,8 @@ 080E96DDFE201D6D7F000001 /* MacVim Source */ = { isa = PBXGroup; children = ( + 1D145C7D0E5227CE00691AA0 /* MMTextViewHelper.h */, + 1D145C7E0E5227CE00691AA0 /* MMTextViewHelper.m */, 1D8059220E118663001699D1 /* Miscellaneous.h */, 1D80591D0E1185EA001699D1 /* Miscellaneous.m */, BD9DF0F90DB48C860025C97C /* CTGradient.h */, @@ -696,6 +701,7 @@ BD476E310DAAD74400F08A5C /* RBSplitView.m in Sources */, BD9DF0B00DB41E780025C97C /* PlugInGUI.m in Sources */, BD9DF0FB0DB48C860025C97C /* CTGradient.m in Sources */, + 1D145C7F0E5227CE00691AA0 /* MMTextViewHelper.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; -- 2.11.4.GIT