1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
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.
13 * Dispatches keyboard and mouse input to the backend. Handles drag-n-drop of
14 * files onto window. The rendering is done using ATSUI.
16 * The text view area consists of two parts:
17 * 1. The text area - this is where text is rendered; the size is governed by
18 * the current number of rows and columns.
19 * 2. The inset area - this is a border around the text area; the size is
20 * governed by the user defaults MMTextInset[Left|Right|Top|Bottom].
22 * The current size of the text view frame does not always match the desired
23 * area, i.e. the area determined by the number of rows, columns plus text
24 * inset. This distinction is particularly important when the view is being
28 #import "MMAppController.h"
29 #import "MMAtsuiTextView.h"
30 #import "MMVimController.h"
31 #import "MMWindowController.h"
32 #import "Miscellaneous.h"
35 // TODO: What does DRAW_TRANSP flag do? If the background isn't drawn when
36 // this flag is set, then sometimes the character after the cursor becomes
37 // blank. Everything seems to work fine by just ignoring this flag.
38 #define DRAW_TRANSP 0x01 /* draw with transparant bg */
39 #define DRAW_BOLD 0x02 /* draw bold text */
40 #define DRAW_UNDERL 0x04 /* draw underline text */
41 #define DRAW_UNDERC 0x08 /* draw undercurl text */
42 #define DRAW_ITALIC 0x10 /* draw italic text */
43 #define DRAW_CURSOR 0x20
46 static char MMKeypadEnter[2] = { 'K', 'A' };
47 static NSString *MMKeypadEnterString = @"KA";
50 // These values are chosen so that the min size is not too small with the
51 // default font (they only affect resizing with the mouse, you can still
52 // use e.g. ":set lines=2" to go below these values).
58 @interface NSFont (AppKitPrivate)
59 - (ATSUFontID) _atsFontID;
63 @interface MMAtsuiTextView (Private)
64 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column;
65 - (void)initAtsuStyles;
66 - (void)disposeAtsuStyles;
67 - (void)updateAtsuStyles;
68 - (void)dispatchKeyEvent:(NSEvent *)event;
69 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags;
70 - (void)hideMouseCursor;
71 - (MMWindowController *)windowController;
72 - (MMVimController *)vimController;
76 @interface MMAtsuiTextView (Drawing)
77 - (NSPoint)originForRow:(int)row column:(int)column;
78 - (NSRect)rectFromRow:(int)row1 column:(int)col1
79 toRow:(int)row2 column:(int)col2;
80 - (NSSize)textAreaSize;
81 - (void)resizeContentImage;
84 - (void)drawString:(UniChar *)string length:(UniCharCount)length
85 atRow:(int)row column:(int)col cells:(int)cells
86 withFlags:(int)flags foregroundColor:(NSColor *)fg
87 backgroundColor:(NSColor *)bg specialColor:(NSColor *)sp;
88 - (void)deleteLinesFromRow:(int)row lineCount:(int)count
89 scrollBottom:(int)bottom left:(int)left right:(int)right
90 color:(NSColor *)color;
91 - (void)insertLinesAtRow:(int)row lineCount:(int)count
92 scrollBottom:(int)bottom left:(int)left right:(int)right
93 color:(NSColor *)color;
94 - (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
95 column:(int)col2 color:(NSColor *)color;
97 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
98 fraction:(int)percent color:(NSColor *)color;
99 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
100 numColumns:(int)ncols;
104 @implementation MMAtsuiTextView
106 - (id)initWithFrame:(NSRect)frame
108 if ((self = [super initWithFrame:frame])) {
109 // NOTE! It does not matter which font is set here, Vim will set its
110 // own font on startup anyway. Just set some bogus values.
111 font = [[NSFont userFixedPitchFontOfSize:0] retain];
112 cellSize.width = cellSize.height = 1;
114 imageSize = NSZeroSize;
115 insetSize = NSZeroSize;
117 // NOTE: If the default changes to 'NO' then the intialization of
118 // p_antialias in option.c must change as well.
121 [self initAtsuStyles];
129 [self disposeAtsuStyles];
130 [font release]; font = nil;
131 [defaultBackgroundColor release]; defaultBackgroundColor = nil;
132 [defaultForegroundColor release]; defaultForegroundColor = nil;
137 - (void)getMaxRows:(int*)rows columns:(int*)cols
139 if (rows) *rows = maxRows;
140 if (cols) *cols = maxColumns;
143 - (void)setMaxRows:(int)rows columns:(int)cols
145 // NOTE: Just remember the new values, the actual resizing is done lazily.
150 - (void)setDefaultColorsBackground:(NSColor *)bgColor
151 foreground:(NSColor *)fgColor
153 if (defaultBackgroundColor != bgColor) {
154 [defaultBackgroundColor release];
155 defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
158 // NOTE: The default foreground color isn't actually used for anything, but
159 // other class instances might want to be able to access it so it is stored
161 if (defaultForegroundColor != fgColor) {
162 [defaultForegroundColor release];
163 defaultForegroundColor = fgColor ? [fgColor retain] : nil;
167 - (void)setTextContainerInset:(NSSize)size
172 - (NSRect)rectForRowsInRange:(NSRange)range
174 NSRect rect = { 0, 0, 0, 0 };
175 unsigned start = range.location > maxRows ? maxRows : range.location;
176 unsigned length = range.length;
178 if (start + length > maxRows)
179 length = maxRows - start;
181 rect.origin.y = cellSize.height * start + insetSize.height;
182 rect.size.height = cellSize.height * length;
187 - (NSRect)rectForColumnsInRange:(NSRange)range
189 NSRect rect = { 0, 0, 0, 0 };
190 unsigned start = range.location > maxColumns ? maxColumns : range.location;
191 unsigned length = range.length;
193 if (start+length > maxColumns)
194 length = maxColumns - start;
196 rect.origin.x = cellSize.width * start + insetSize.width;
197 rect.size.width = cellSize.width * length;
203 - (void)setFont:(NSFont *)newFont
205 if (newFont && font != newFont) {
207 font = [newFont retain];
209 float em = [newFont widthOfString:@"m"];
210 float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
211 floatForKey:MMCellWidthMultiplierKey];
213 // NOTE! Even though NSFontFixedAdvanceAttribute is a float, it will
214 // only render at integer sizes. Hence, we restrict the cell width to
215 // an integer here, otherwise the window width and the actual text
216 // width will not match.
217 cellSize.width = ceilf(em * cellWidthMultiplier);
218 cellSize.height = linespace + [newFont defaultLineHeightForFont];
220 [self updateAtsuStyles];
224 - (void)setWideFont:(NSFont *)newFont
238 - (void)setLinespace:(float)newLinespace
240 linespace = newLinespace;
242 // NOTE: The linespace is added to the cell height in order for a multiline
243 // selection not to have white (background color) gaps between lines. Also
244 // this simplifies the code a lot because there is no need to check the
245 // linespace when calculating the size of the text view etc. When the
246 // linespace is non-zero the baseline will be adjusted as well; check
248 cellSize.height = linespace + [font defaultLineHeightForFont];
254 - (void)setShouldDrawInsertionPoint:(BOOL)on
258 - (void)setPreEditRow:(int)row column:(int)col
262 - (void)hideMarkedTextField
266 - (void)setMouseShape:(int)shape
270 - (void)setAntialias:(BOOL)state
278 - (void)keyDown:(NSEvent *)event
280 //NSLog(@"%s %@", _cmd, event);
281 // HACK! If control modifier is held, don't pass the event along to
282 // interpretKeyEvents: since some keys are bound to multiple commands which
283 // means doCommandBySelector: is called several times. Do the same for
284 // Alt+Function key presses (Alt+Up and Alt+Down are bound to two
285 // commands). This hack may break input management, but unless we can
286 // figure out a way to disable key bindings there seems little else to do.
288 // TODO: Figure out a way to disable Cocoa key bindings entirely, without
289 // affecting input management.
290 int flags = [event modifierFlags];
291 if ((flags & NSControlKeyMask) ||
292 ((flags & NSAlternateKeyMask) && (flags & NSFunctionKeyMask))) {
293 NSString *unmod = [event charactersIgnoringModifiers];
294 if ([unmod length] == 1 && [unmod characterAtIndex:0] <= 0x7f
295 && [unmod characterAtIndex:0] >= 0x60) {
296 // HACK! Send Ctrl-letter keys (and C-@, C-[, C-\, C-], C-^, C-_)
297 // as normal text to be added to the Vim input buffer. This must
298 // be done in order for the backend to be able to separate e.g.
299 // Ctrl-i and Ctrl-tab.
300 [self insertText:[event characters]];
302 [self dispatchKeyEvent:event];
305 [self interpretKeyEvents:[NSArray arrayWithObject:event]];
309 - (void)insertText:(id)string
311 //NSLog(@"%s %@", _cmd, string);
312 // NOTE! This method is called for normal key presses but also for
313 // Option-key presses --- even when Ctrl is held as well as Option. When
314 // Ctrl is held, the AppKit translates the character to a Ctrl+key stroke,
315 // so 'string' need not be a printable character! In this case it still
316 // works to pass 'string' on to Vim as a printable character (since
317 // modifiers are already included and should not be added to the input
318 // buffer using CSI, K_MODIFIER).
320 [self hideMarkedTextField];
322 NSEvent *event = [NSApp currentEvent];
324 // HACK! In order to be able to bind to <S-Space>, <S-M-Tab>, etc. we have
325 // to watch for them here.
326 if ([event type] == NSKeyDown
327 && [[event charactersIgnoringModifiers] length] > 0
328 && [event modifierFlags]
329 & (NSShiftKeyMask|NSControlKeyMask|NSAlternateKeyMask)) {
330 unichar c = [[event charactersIgnoringModifiers] characterAtIndex:0];
332 // <S-M-Tab> translates to 0x19
333 if (' ' == c || 0x19 == c) {
334 [self dispatchKeyEvent:event];
339 [self hideMouseCursor];
341 // NOTE: 'string' is either an NSString or an NSAttributedString. Since we
342 // do not support attributes, simply pass the corresponding NSString in the
344 if ([string isKindOfClass:[NSAttributedString class]])
345 string = [string string];
347 //NSLog(@"send InsertTextMsgID: %@", string);
349 [[self vimController] sendMessage:InsertTextMsgID
350 data:[string dataUsingEncoding:NSUTF8StringEncoding]];
353 - (void)doCommandBySelector:(SEL)selector
355 //NSLog(@"%s %@", _cmd, NSStringFromSelector(selector));
356 // By ignoring the selector we effectively disable the key binding
357 // mechanism of Cocoa. Hopefully this is what the user will expect
358 // (pressing Ctrl+P would otherwise result in moveUp: instead of previous
361 // We usually end up here if the user pressed Ctrl+key (but not
364 NSEvent *event = [NSApp currentEvent];
366 if (selector == @selector(cancelOperation:)
367 || selector == @selector(insertNewline:)) {
368 // HACK! If there was marked text which got abandoned as a result of
369 // hitting escape or enter, then 'insertText:' is called with the
370 // abandoned text but '[event characters]' includes the abandoned text
371 // as well. Since 'dispatchKeyEvent:' looks at '[event characters]' we
372 // must intercept these keys here or the abandonded text gets inserted
374 NSString *key = [event charactersIgnoringModifiers];
375 const char *chars = [key UTF8String];
376 int len = [key lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
378 if (0x3 == chars[0]) {
379 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
380 // handle it separately (else Ctrl-C doesn't work).
381 len = sizeof(MMKeypadEnter)/sizeof(MMKeypadEnter[0]);
382 chars = MMKeypadEnter;
385 [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
387 [self dispatchKeyEvent:event];
391 - (BOOL)performKeyEquivalent:(NSEvent *)event
393 //NSLog(@"%s %@", _cmd, event);
394 // Called for Cmd+key keystrokes, function keys, arrow keys, page
395 // up/down, home, end.
397 // NOTE: This message cannot be ignored since Cmd+letter keys never are
398 // passed to keyDown:. It seems as if the main menu consumes Cmd-key
399 // strokes, unless the key is a function key.
401 // NOTE: If the event that triggered this method represents a function key
402 // down then we do nothing, otherwise the input method never gets the key
403 // stroke (some input methods use e.g. arrow keys). The function key down
404 // event will still reach Vim though (via keyDown:). The exceptions to
405 // this rule are: PageUp/PageDown (keycode 116/121).
406 int flags = [event modifierFlags];
407 if ([event type] != NSKeyDown || flags & NSFunctionKeyMask
408 && !(116 == [event keyCode] || 121 == [event keyCode]))
411 // HACK! KeyCode 50 represent the key which switches between windows
412 // within an application (like Cmd+Tab is used to switch between
413 // applications). Return NO here, else the window switching does not work.
414 if ([event keyCode] == 50)
417 // HACK! Let the main menu try to handle any key down event, before
418 // passing it on to vim, otherwise key equivalents for menus will
419 // effectively be disabled.
420 if ([[NSApp mainMenu] performKeyEquivalent:event])
423 // HACK! On Leopard Ctrl-key events end up here instead of keyDown:.
424 if (flags & NSControlKeyMask) {
425 [self keyDown:event];
429 //NSLog(@"%s%@", _cmd, event);
431 NSString *chars = [event characters];
432 NSString *unmodchars = [event charactersIgnoringModifiers];
433 int len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
434 NSMutableData *data = [NSMutableData data];
439 // If 'chars' and 'unmodchars' differs when shift flag is present, then we
440 // can clear the shift flag as it is already included in 'unmodchars'.
441 // Failing to clear the shift flag means <D-Bar> turns into <S-D-Bar> (on
442 // an English keyboard).
443 if (flags & NSShiftKeyMask && ![chars isEqual:unmodchars])
444 flags &= ~NSShiftKeyMask;
446 if (0x3 == [unmodchars characterAtIndex:0]) {
447 // HACK! AppKit turns enter (not return) into Ctrl-C, so we need to
448 // handle it separately (else Cmd-enter turns into Ctrl-C).
449 unmodchars = MMKeypadEnterString;
450 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
453 [data appendBytes:&flags length:sizeof(int)];
454 [data appendBytes:&len length:sizeof(int)];
455 [data appendBytes:[unmodchars UTF8String] length:len];
457 [[self vimController] sendMessage:CmdKeyMsgID data:data];
465 - (BOOL)acceptsFirstResponder
475 - (void)drawRect:(NSRect)rect
477 NSRect srcRect = NSMakeRect(0, 0, imageSize.width, imageSize.height);
478 NSRect dstRect = srcRect;
480 dstRect.origin.x += insetSize.width;
481 dstRect.origin.y += insetSize.height;
483 [contentImage drawInRect: dstRect
485 operation: NSCompositeCopy
489 - (BOOL) wantsDefaultClipping
495 #define MM_DEBUG_DRAWING 0
497 - (void)performBatchDrawWithData:(NSData *)data
499 const void *bytes = [data bytes];
500 const void *end = bytes + [data length];
502 if (! NSEqualSizes(imageSize, [self textAreaSize]))
503 [self resizeContentImage];
506 NSLog(@"====> BEGIN %s", _cmd);
510 // TODO: Sanity check input
512 while (bytes < end) {
513 int type = *((int*)bytes); bytes += sizeof(int);
515 if (ClearAllDrawType == type) {
517 NSLog(@" Clear all");
520 } else if (ClearBlockDrawType == type) {
521 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
522 int row1 = *((int*)bytes); bytes += sizeof(int);
523 int col1 = *((int*)bytes); bytes += sizeof(int);
524 int row2 = *((int*)bytes); bytes += sizeof(int);
525 int col2 = *((int*)bytes); bytes += sizeof(int);
528 NSLog(@" Clear block (%d,%d) -> (%d,%d)", row1, col1,
531 [self clearBlockFromRow:row1 column:col1
532 toRow:row2 column:col2
533 color:[NSColor colorWithArgbInt:color]];
534 } else if (DeleteLinesDrawType == type) {
535 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
536 int row = *((int*)bytes); bytes += sizeof(int);
537 int count = *((int*)bytes); bytes += sizeof(int);
538 int bot = *((int*)bytes); bytes += sizeof(int);
539 int left = *((int*)bytes); bytes += sizeof(int);
540 int right = *((int*)bytes); bytes += sizeof(int);
543 NSLog(@" Delete %d line(s) from %d", count, row);
545 [self deleteLinesFromRow:row lineCount:count
546 scrollBottom:bot left:left right:right
547 color:[NSColor colorWithArgbInt:color]];
548 } else if (DrawStringDrawType == type) {
549 int bg = *((int*)bytes); bytes += sizeof(int);
550 int fg = *((int*)bytes); bytes += sizeof(int);
551 int sp = *((int*)bytes); bytes += sizeof(int);
552 int row = *((int*)bytes); bytes += sizeof(int);
553 int col = *((int*)bytes); bytes += sizeof(int);
554 int cells = *((int*)bytes); bytes += sizeof(int);
555 int flags = *((int*)bytes); bytes += sizeof(int);
556 int len = *((int*)bytes); bytes += sizeof(int);
557 // UniChar *string = (UniChar*)bytes; bytes += len;
558 NSString *string = [[NSString alloc] initWithBytesNoCopy:(void*)bytes
560 encoding:NSUTF8StringEncoding
564 NSLog(@" Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
565 "bg=0x%x sp=0x%x", row, col, len, flags, fg, bg, sp);
567 unichar *characters = malloc(sizeof(unichar) * [string length]);
568 [string getCharacters:characters];
570 [self drawString:characters length:[string length] atRow:row column:col
571 cells:cells withFlags:flags
572 foregroundColor:[NSColor colorWithRgbInt:fg]
573 backgroundColor:[NSColor colorWithArgbInt:bg]
574 specialColor:[NSColor colorWithRgbInt:sp]];
577 } else if (InsertLinesDrawType == type) {
578 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
579 int row = *((int*)bytes); bytes += sizeof(int);
580 int count = *((int*)bytes); bytes += sizeof(int);
581 int bot = *((int*)bytes); bytes += sizeof(int);
582 int left = *((int*)bytes); bytes += sizeof(int);
583 int right = *((int*)bytes); bytes += sizeof(int);
586 NSLog(@" Insert %d line(s) at row %d", count, row);
588 [self insertLinesAtRow:row lineCount:count
589 scrollBottom:bot left:left right:right
590 color:[NSColor colorWithArgbInt:color]];
591 } else if (DrawCursorDrawType == type) {
592 unsigned color = *((unsigned*)bytes); bytes += sizeof(unsigned);
593 int row = *((int*)bytes); bytes += sizeof(int);
594 int col = *((int*)bytes); bytes += sizeof(int);
595 int shape = *((int*)bytes); bytes += sizeof(int);
596 int percent = *((int*)bytes); bytes += sizeof(int);
599 NSLog(@" Draw cursor at (%d,%d)", row, col);
601 [self drawInsertionPointAtRow:row column:col shape:shape
603 color:[NSColor colorWithRgbInt:color]];
604 } else if (DrawInvertedRectDrawType == type) {
605 int row = *((int*)bytes); bytes += sizeof(int);
606 int col = *((int*)bytes); bytes += sizeof(int);
607 int nr = *((int*)bytes); bytes += sizeof(int);
608 int nc = *((int*)bytes); bytes += sizeof(int);
609 /*int invert = *((int*)bytes);*/ bytes += sizeof(int);
612 NSLog(@" Draw inverted rect: row=%d col=%d nrows=%d ncols=%d",
615 [self drawInvertedRectAtRow:row column:col numRows:nr
617 } else if (SetCursorPosDrawType == type) {
618 // TODO: This is used for Voice Over support in MMTextView,
619 // MMAtsuiTextView currently does not support Voice Over.
620 /*cursorRow = *((int*)bytes);*/ bytes += sizeof(int);
621 /*cursorCol = *((int*)bytes);*/ bytes += sizeof(int);
623 NSLog(@"WARNING: Unknown draw type (type=%d)", type);
629 // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
630 // and columns are changed (due to ipc delays). Force a redraw here.
631 [self setNeedsDisplay:YES];
632 // [self displayIfNeeded];
635 NSLog(@"<==== END %s", _cmd);
639 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
642 // - Rounding errors may cause size change when there should be none
643 // - Desired rows/columns shold not be 'too small'
645 // Constrain the desired size to the given size. Values for the minimum
646 // rows and columns is taken from Vim.
647 NSSize desiredSize = [self desiredSize];
648 int desiredRows = maxRows;
649 int desiredCols = maxColumns;
651 if (size.height != desiredSize.height) {
652 float fh = cellSize.height;
653 float ih = 2 * insetSize.height;
654 if (fh < 1.0f) fh = 1.0f;
656 desiredRows = floor((size.height - ih)/fh);
657 desiredSize.height = fh*desiredRows + ih;
660 if (size.width != desiredSize.width) {
661 float fw = cellSize.width;
662 float iw = 2 * insetSize.width;
663 if (fw < 1.0f) fw = 1.0f;
665 desiredCols = floor((size.width - iw)/fw);
666 desiredSize.width = fw*desiredCols + iw;
669 if (rows) *rows = desiredRows;
670 if (cols) *cols = desiredCols;
675 - (NSSize)desiredSize
677 // Compute the size the text view should be for the entire text area and
678 // inset area to be visible with the present number of rows and columns.
679 return NSMakeSize(maxColumns * cellSize.width + 2 * insetSize.width,
680 maxRows * cellSize.height + 2 * insetSize.height);
685 // Compute the smallest size the text view is allowed to be.
686 return NSMakeSize(MMMinColumns * cellSize.width + 2 * insetSize.width,
687 MMMinRows * cellSize.height + 2 * insetSize.height);
690 - (void)changeFont:(id)sender
692 NSFont *newFont = [sender convertFont:font];
695 NSString *name = [newFont displayName];
696 unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
698 NSMutableData *data = [NSMutableData data];
699 float pointSize = [newFont pointSize];
701 [data appendBytes:&pointSize length:sizeof(float)];
703 ++len; // include NUL byte
704 [data appendBytes:&len length:sizeof(unsigned)];
705 [data appendBytes:[name UTF8String] length:len];
707 [[self vimController] sendMessage:SetFontMsgID data:data];
712 - (void)scrollWheel:(NSEvent *)event
714 if ([event deltaY] == 0)
718 NSPoint pt = [self convertPoint:[event locationInWindow] fromView:nil];
720 // View is not flipped, instead the atsui code draws to a flipped image;
721 // thus we need to 'flip' the coordinate here since the column number
722 // increases in an up-to-down order.
723 pt.y = [self frame].size.height - pt.y;
725 if (![self convertPoint:pt toRow:&row column:&col])
728 int flags = [event modifierFlags];
729 float dy = [event deltaY];
730 NSMutableData *data = [NSMutableData data];
732 [data appendBytes:&row length:sizeof(int)];
733 [data appendBytes:&col length:sizeof(int)];
734 [data appendBytes:&flags length:sizeof(int)];
735 [data appendBytes:&dy length:sizeof(float)];
737 [[self vimController] sendMessage:ScrollWheelMsgID data:data];
742 // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
743 // to the same actions as in IB otherwise they will not work with dialogs. All
744 // we do here is forward these actions to the Vim process.
746 - (IBAction)cut:(id)sender
748 [[self windowController] vimMenuItemAction:sender];
751 - (IBAction)copy:(id)sender
753 [[self windowController] vimMenuItemAction:sender];
756 - (IBAction)paste:(id)sender
758 [[self windowController] vimMenuItemAction:sender];
761 - (IBAction)undo:(id)sender
763 [[self windowController] vimMenuItemAction:sender];
766 - (IBAction)redo:(id)sender
768 [[self windowController] vimMenuItemAction:sender];
771 - (IBAction)selectAll:(id)sender
773 [[self windowController] vimMenuItemAction:sender];
776 @end // MMAtsuiTextView
781 @implementation MMAtsuiTextView (Private)
783 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
785 NSPoint origin = { insetSize.width, insetSize.height };
787 if (!(cellSize.width > 0 && cellSize.height > 0))
790 if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
791 if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
793 //NSLog(@"convertPoint:%@ toRow:%d column:%d", NSStringFromPoint(point),
799 - (void)initAtsuStyles
802 for (i = 0; i < MMMaxCellsPerChar; i++)
803 ATSUCreateStyle(&atsuStyles[i]);
806 - (void)disposeAtsuStyles
810 for (i = 0; i < MMMaxCellsPerChar; i++)
811 if (atsuStyles[i] != NULL)
813 if (ATSUDisposeStyle(atsuStyles[i]) != noErr)
814 atsuStyles[i] = NULL;
818 - (void)updateAtsuStyles
824 CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
825 ATSStyleRenderingOptions options;
827 fontID = [font _atsFontID];
828 fontSize = Long2Fix([font pointSize]);
829 options = kATSStyleApplyAntiAliasing;
831 ATSUAttributeTag attribTags[] =
833 kATSUFontTag, kATSUSizeTag, kATSUImposeWidthTag,
834 kATSUFontMatrixTag, kATSUStyleRenderingOptionsTag,
835 kATSUMaxATSUITagValue + 1
838 ByteCount attribSizes[] =
840 sizeof(ATSUFontID), sizeof(Fixed), sizeof(fontWidth),
841 sizeof(CGAffineTransform), sizeof(ATSStyleRenderingOptions),
845 ATSUAttributeValuePtr attribValues[] =
847 &fontID, &fontSize, &fontWidth, &transform, &options, &font
850 for (i = 0; i < MMMaxCellsPerChar; i++)
852 fontWidth = Long2Fix(cellSize.width * (i + 1));
854 if (ATSUSetAttributes(atsuStyles[i],
855 (sizeof attribTags) / sizeof(ATSUAttributeTag),
856 attribTags, attribSizes, attribValues) != noErr)
858 ATSUDisposeStyle(atsuStyles[i]);
859 atsuStyles[i] = NULL;
864 - (void)dispatchKeyEvent:(NSEvent *)event
866 // Only handle the command if it came from a keyDown event
867 if ([event type] != NSKeyDown)
870 NSString *chars = [event characters];
871 NSString *unmodchars = [event charactersIgnoringModifiers];
872 unichar c = [chars characterAtIndex:0];
873 unichar imc = [unmodchars characterAtIndex:0];
875 const char *bytes = 0;
876 int mods = [event modifierFlags];
878 //NSLog(@"%s chars[0]=0x%x unmodchars[0]=0x%x (chars=%@ unmodchars=%@)",
879 // _cmd, c, imc, chars, unmodchars);
881 if (' ' == imc && 0xa0 != c) {
882 // HACK! The AppKit turns <C-Space> into <C-@> which is not standard
883 // Vim behaviour, so bypass this problem. (0xa0 is <M-Space>, which
884 // should be passed on as is.)
885 len = [unmodchars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
886 bytes = [unmodchars UTF8String];
887 } else if (imc == c && '2' == c) {
888 // HACK! Translate Ctrl+2 to <C-@>.
889 static char ctrl_at = 0;
890 len = 1; bytes = &ctrl_at;
891 } else if (imc == c && '6' == c) {
892 // HACK! Translate Ctrl+6 to <C-^>.
893 static char ctrl_hat = 0x1e;
894 len = 1; bytes = &ctrl_hat;
895 } else if (c == 0x19 && imc == 0x19) {
896 // HACK! AppKit turns back tab into Ctrl-Y, so we need to handle it
897 // separately (else Ctrl-Y doesn't work).
898 static char tab = 0x9;
899 len = 1; bytes = &tab; mods |= NSShiftKeyMask;
901 len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
902 bytes = [chars UTF8String];
905 [self sendKeyDown:bytes length:len modifiers:mods];
908 - (void)sendKeyDown:(const char *)chars length:(int)len modifiers:(int)flags
910 if (chars && len > 0) {
911 NSMutableData *data = [NSMutableData data];
913 [data appendBytes:&flags length:sizeof(int)];
914 [data appendBytes:&len length:sizeof(int)];
915 [data appendBytes:chars length:len];
917 [self hideMouseCursor];
919 //NSLog(@"%s len=%d chars=0x%x", _cmd, len, chars[0]);
920 [[self vimController] sendMessage:KeyDownMsgID data:data];
924 - (void)hideMouseCursor
926 // Check 'mousehide' option
927 id mh = [[[self vimController] vimState] objectForKey:@"p_mh"];
928 if (mh && ![mh boolValue])
929 [NSCursor setHiddenUntilMouseMoves:NO];
931 [NSCursor setHiddenUntilMouseMoves:YES];
934 - (MMWindowController *)windowController
936 id windowController = [[self window] windowController];
937 if ([windowController isKindOfClass:[MMWindowController class]])
938 return (MMWindowController*)windowController;
942 - (MMVimController *)vimController
944 return [[self windowController] vimController];
947 @end // MMAtsuiTextView (Private)
952 @implementation MMAtsuiTextView (Drawing)
954 - (NSPoint)originForRow:(int)row column:(int)col
956 return NSMakePoint(col * cellSize.width, row * cellSize.height);
959 - (NSRect)rectFromRow:(int)row1 column:(int)col1
960 toRow:(int)row2 column:(int)col2
962 NSPoint origin = [self originForRow: row1 column: col1];
963 return NSMakeRect(origin.x, origin.y,
964 (col2 + 1 - col1) * cellSize.width,
965 (row2 + 1 - row1) * cellSize.height);
968 - (NSSize)textAreaSize
970 // Calculate the (desired) size of the text area, i.e. the text view area
971 // minus the inset area.
972 return NSMakeSize(maxColumns * cellSize.width, maxRows * cellSize.height);
975 - (void)resizeContentImage
977 //NSLog(@"resizeContentImage");
978 [contentImage release];
979 contentImage = [[NSImage alloc] initWithSize:[self textAreaSize]];
980 [contentImage setFlipped: YES];
981 imageSize = [self textAreaSize];
986 [contentImage lockFocus];
991 [contentImage unlockFocus];
994 #define atsu_style_set_bool(s, t, b) \
995 ATSUSetAttributes(s, 1, &t, &(sizeof(Boolean)), &&b);
997 - (void)drawString:(UniChar *)string length:(UniCharCount)length
998 atRow:(int)row column:(int)col cells:(int)cells
999 withFlags:(int)flags foregroundColor:(NSColor *)fg
1000 backgroundColor:(NSColor *)bg specialColor:(NSColor *)sp
1002 // 'string' consists of 'length' utf-16 code pairs and should cover 'cells'
1003 // display cells (a normal character takes up one display cell, a wide
1004 // character takes up two)
1005 ATSUStyle style = (flags & DRAW_WIDE) ? atsuStyles[1] : atsuStyles[0];
1006 ATSUTextLayout layout;
1008 // Font selection and rendering options for ATSUI
1009 ATSUAttributeTag attribTags[3] = { kATSUQDBoldfaceTag,
1011 kATSUStyleRenderingOptionsTag };
1012 ByteCount attribSizes[] = { sizeof(Boolean),
1015 Boolean useBold, useItalic;
1016 UInt32 useAntialias;
1017 ATSUAttributeValuePtr attribValues[3] = { &useBold, &useItalic,
1020 useBold = (flags & DRAW_BOLD) ? true : false;
1021 useItalic = (flags & DRAW_ITALIC) ? true : false;
1022 useAntialias = antialias ? kATSStyleApplyAntiAliasing
1023 : kATSStyleNoAntiAliasing;
1025 ATSUSetAttributes(style, sizeof(attribValues) / sizeof(attribValues[0]),
1026 attribTags, attribSizes, attribValues);
1028 // NSLog(@"drawString: %d", length);
1030 ATSUCreateTextLayout(&layout);
1031 ATSUSetTextPointerLocation(layout, string,
1032 kATSUFromTextBeginning, kATSUToTextEnd,
1034 ATSUSetRunStyle(layout, style, kATSUFromTextBeginning, kATSUToTextEnd);
1036 NSRect rect = NSMakeRect(col * cellSize.width, row * cellSize.height,
1037 length * cellSize.width, cellSize.height);
1038 if (flags & DRAW_WIDE)
1039 rect.size.width = rect.size.width * 2;
1040 CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
1042 ATSUAttributeTag tags[] = { kATSUCGContextTag };
1043 ByteCount sizes[] = { sizeof(CGContextRef) };
1044 ATSUAttributeValuePtr values[] = { &context };
1045 ATSUSetLayoutControls(layout, 1, tags, sizes, values);
1047 if (! (flags & DRAW_TRANSP))
1055 ATSUSetTransientFontMatching(layout, TRUE);
1056 ATSUDrawText(layout,
1057 kATSUFromTextBeginning,
1059 X2Fix(rect.origin.x),
1060 X2Fix(rect.origin.y + [font ascender]));
1061 ATSUDisposeTextLayout(layout);
1064 - (void)scrollRect:(NSRect)rect lineCount:(int)count
1066 NSPoint destPoint = rect.origin;
1067 destPoint.y += count * cellSize.height;
1069 NSCopyBits(0, rect, destPoint);
1072 - (void)deleteLinesFromRow:(int)row lineCount:(int)count
1073 scrollBottom:(int)bottom left:(int)left right:(int)right
1074 color:(NSColor *)color
1076 NSRect rect = [self rectFromRow:row + count
1081 // move rect up for count lines
1082 [self scrollRect:rect lineCount:-count];
1083 [self clearBlockFromRow:bottom - count + 1
1090 - (void)insertLinesAtRow:(int)row lineCount:(int)count
1091 scrollBottom:(int)bottom left:(int)left right:(int)right
1092 color:(NSColor *)color
1094 NSRect rect = [self rectFromRow:row
1096 toRow:bottom - count
1099 // move rect down for count lines
1100 [self scrollRect:rect lineCount:count];
1101 [self clearBlockFromRow:row
1103 toRow:row + count - 1
1108 - (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
1109 column:(int)col2 color:(NSColor *)color
1112 NSRectFill([self rectFromRow:row1 column:col1 toRow:row2 column:col2]);
1117 [defaultBackgroundColor set];
1118 NSRectFill(NSMakeRect(0, 0, imageSize.width, imageSize.height));
1121 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
1122 fraction:(int)percent color:(NSColor *)color
1124 NSPoint origin = [self originForRow:row column:col];
1125 NSRect rect = NSMakeRect(origin.x, origin.y,
1126 cellSize.width, cellSize.height);
1128 // NSLog(@"shape = %d, fraction: %d", shape, percent);
1130 if (MMInsertionPointHorizontal == shape) {
1131 int frac = (cellSize.height * percent + 99)/100;
1132 rect.origin.y += rect.size.height - frac;
1133 rect.size.height = frac;
1134 } else if (MMInsertionPointVertical == shape) {
1135 int frac = (cellSize.width * percent + 99)/100;
1136 rect.size.width = frac;
1137 } else if (MMInsertionPointVerticalRight == shape) {
1138 int frac = (cellSize.width * percent + 99)/100;
1139 rect.origin.x += rect.size.width - frac;
1140 rect.size.width = frac;
1144 if (MMInsertionPointHollow == shape) {
1151 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
1152 numColumns:(int)ncols
1154 // TODO: THIS CODE HAS NOT BEEN TESTED!
1155 CGContextRef cgctx = [[NSGraphicsContext currentContext] graphicsPort];
1156 CGContextSaveGState(cgctx);
1157 CGContextSetBlendMode(cgctx, kCGBlendModeDifference);
1158 CGContextSetRGBFillColor(cgctx, 1.0, 1.0, 1.0, 1.0);
1160 CGRect rect = { col * cellSize.width, row * cellSize.height,
1161 ncols * cellSize.width, nrows * cellSize.height };
1162 CGContextFillRect(cgctx, rect);
1164 CGContextRestoreGState(cgctx);
1167 @end // MMAtsuiTextView (Drawing)