Add file for misc code in frontend
[MacVim.git] / src / MacVim / MMAtsuiTextView.m
blob4072d6393064ba8059fd4ea01c59e6c920dbd819
1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
2  *
3  * VIM - Vi IMproved            by Bram Moolenaar
4  *                              MacVim GUI port by Bjorn Winckler
5  *
6  * Do ":help uganda"  in Vim to read copying and usage conditions.
7  * Do ":help credits" in Vim to see a list of people who contributed.
8  * See README.txt for an overview of the Vim source code.
9  */
11  * MMAtsuiTextView
12  *
13  * Dispatches keyboard and mouse input to the backend.  Handles drag-n-drop of
14  * files onto window.  The rendering is done using ATSUI.
15  *
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].
21  *
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
25  * resized.
26  */
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";
49 enum {
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).
53     MMMinRows = 4,
54     MMMinColumns = 30
58 @interface NSFont (AppKitPrivate)
59 - (ATSUFontID) _atsFontID;
60 @end
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;
73 @end
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;
82 - (void)beginDrawing;
83 - (void)endDrawing;
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;
96 - (void)clearAll;
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;
101 @end
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;
113         contentImage = nil;
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.
119         antialias = YES;
121         [self initAtsuStyles];
122     }
124     return self;
127 - (void)dealloc
129     [self disposeAtsuStyles];
130     [font release];  font = nil;
131     [defaultBackgroundColor release];  defaultBackgroundColor = nil;
132     [defaultForegroundColor release];  defaultForegroundColor = nil;
134     [super dealloc];
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.
146     maxRows = rows;
147     maxColumns = cols;
150 - (void)setDefaultColorsBackground:(NSColor *)bgColor
151                         foreground:(NSColor *)fgColor
153     if (defaultBackgroundColor != bgColor) {
154         [defaultBackgroundColor release];
155         defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
156     }
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
160     // here.
161     if (defaultForegroundColor != fgColor) {
162         [defaultForegroundColor release];
163         defaultForegroundColor = fgColor ? [fgColor retain] : nil;
164     }
167 - (void)setTextContainerInset:(NSSize)size
169     insetSize = 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;
184     return rect;
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;
199     return rect;
203 - (void)setFont:(NSFont *)newFont
205     if (newFont && font != newFont) {
206         [font release];
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];
221     }
224 - (void)setWideFont:(NSFont *)newFont
228 - (NSFont *)font
230     return font;
233 - (NSSize)cellSize
235     return cellSize;
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
247     // MMTypesetter.
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
272     antialias = 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.
287     //
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]];
301         } else {
302             [self dispatchKeyEvent:event];
303         }
304     } else {
305         [self interpretKeyEvents:[NSArray arrayWithObject:event]];
306     }
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];
335             return;
336         }
337     }
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
343     // latter case.
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
359     // match, etc.).
360     //
361     // We usually end up here if the user pressed Ctrl+key (but not
362     // Ctrl+Option+key).
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
373         // twice.
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;
383         }
385         [self sendKeyDown:chars length:len modifiers:[event modifierFlags]];
386     } else {
387         [self dispatchKeyEvent:event];
388     }
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.
396     //
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]))
409         return NO;
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)
415         return NO;
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])
421         return YES;
423     // HACK!  On Leopard Ctrl-key events end up here instead of keyDown:.
424     if (flags & NSControlKeyMask) {
425         [self keyDown:event];
426         return YES;
427     }
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];
436     if (len <= 0)
437         return NO;
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];
451     }
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];
459     return YES;
465 - (BOOL)acceptsFirstResponder
467     return YES;
470 - (BOOL)isFlipped
472     return NO;
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
484                     fromRect: srcRect
485                    operation: NSCompositeCopy
486                     fraction: 1.0];
489 - (BOOL) wantsDefaultClipping
491     return NO;
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];
505 #if MM_DEBUG_DRAWING
506     NSLog(@"====> BEGIN %s", _cmd);
507 #endif
508     [self beginDrawing];
510     // TODO: Sanity check input
512     while (bytes < end) {
513         int type = *((int*)bytes);  bytes += sizeof(int);
515         if (ClearAllDrawType == type) {
516 #if MM_DEBUG_DRAWING
517             NSLog(@"   Clear all");
518 #endif
519             [self clearAll];
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);
527 #if MM_DEBUG_DRAWING
528             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
529                     row2,col2);
530 #endif
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);
542 #if MM_DEBUG_DRAWING
543             NSLog(@"   Delete %d line(s) from %d", count, row);
544 #endif
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
559                                                               length:len
560                                                             encoding:NSUTF8StringEncoding
561                                                         freeWhenDone:NO];
562             bytes += len;
563 #if MM_DEBUG_DRAWING
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);
566 #endif
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]];
575             free(characters);
576             [string release];
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);
585 #if MM_DEBUG_DRAWING
586             NSLog(@"   Insert %d line(s) at row %d", count, row);
587 #endif
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);
598 #if MM_DEBUG_DRAWING
599             NSLog(@"   Draw cursor at (%d,%d)", row, col);
600 #endif
601             [self drawInsertionPointAtRow:row column:col shape:shape
602                                      fraction:percent
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);
611 #if MM_DEBUG_DRAWING
612             NSLog(@"   Draw inverted rect: row=%d col=%d nrows=%d ncols=%d",
613                     row, col, nr, nc);
614 #endif
615             [self drawInvertedRectAtRow:row column:col numRows:nr
616                              numColumns:nc];
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);
622         } else {
623             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
624         }
625     }
627     [self endDrawing];
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];
634 #if MM_DEBUG_DRAWING
635     NSLog(@"<==== END   %s", _cmd);
636 #endif
639 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
641     // TODO:
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;
658     }
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;
667     }
669     if (rows) *rows = desiredRows;
670     if (cols) *cols = desiredCols;
672     return desiredSize;
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);
683 - (NSSize)minSize
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];
694     if (newFont) {
695         NSString *name = [newFont displayName];
696         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
697         if (len > 0) {
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];
708         }
709     }
712 - (void)scrollWheel:(NSEvent *)event
714     if ([event deltaY] == 0)
715         return;
717     int row, col;
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])
726         return;
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))
788         return NO;
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),
794     //        *row, *column);
796     return YES;
799 - (void)initAtsuStyles
801     int i;
802     for (i = 0; i < MMMaxCellsPerChar; i++)
803         ATSUCreateStyle(&atsuStyles[i]);
806 - (void)disposeAtsuStyles
808     int i;
810     for (i = 0; i < MMMaxCellsPerChar; i++)
811         if (atsuStyles[i] != NULL)
812         {
813             if (ATSUDisposeStyle(atsuStyles[i]) != noErr)
814                 atsuStyles[i] = NULL;
815         }
818 - (void)updateAtsuStyles
820     ATSUFontID        fontID;
821     Fixed             fontSize;
822     Fixed             fontWidth;
823     int               i;
824     CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
825     ATSStyleRenderingOptions options;
827     fontID    = [font _atsFontID];
828     fontSize  = Long2Fix([font pointSize]);
829     options   = kATSStyleApplyAntiAliasing;
831     ATSUAttributeTag attribTags[] =
832     {
833         kATSUFontTag, kATSUSizeTag, kATSUImposeWidthTag,
834         kATSUFontMatrixTag, kATSUStyleRenderingOptionsTag,
835         kATSUMaxATSUITagValue + 1
836     };
838     ByteCount attribSizes[] =
839     {
840         sizeof(ATSUFontID), sizeof(Fixed), sizeof(fontWidth),
841         sizeof(CGAffineTransform), sizeof(ATSStyleRenderingOptions),
842         sizeof(font)
843     };
845     ATSUAttributeValuePtr attribValues[] =
846     {
847         &fontID, &fontSize, &fontWidth, &transform, &options, &font
848     };
850     for (i = 0; i < MMMaxCellsPerChar; i++)
851     {
852         fontWidth = Long2Fix(cellSize.width * (i + 1));
854         if (ATSUSetAttributes(atsuStyles[i],
855                               (sizeof attribTags) / sizeof(ATSUAttributeTag),
856                               attribTags, attribSizes, attribValues) != noErr)
857         {
858             ATSUDisposeStyle(atsuStyles[i]);
859             atsuStyles[i] = NULL;
860         }
861     }
864 - (void)dispatchKeyEvent:(NSEvent *)event
866     // Only handle the command if it came from a keyDown event
867     if ([event type] != NSKeyDown)
868         return;
870     NSString *chars = [event characters];
871     NSString *unmodchars = [event charactersIgnoringModifiers];
872     unichar c = [chars characterAtIndex:0];
873     unichar imc = [unmodchars characterAtIndex:0];
874     int len = 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;
900     } else {
901         len = [chars lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
902         bytes = [chars UTF8String];
903     }
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];
921     }
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];
930     else
931         [NSCursor setHiddenUntilMouseMoves:YES];
934 - (MMWindowController *)windowController
936     id windowController = [[self window] windowController];
937     if ([windowController isKindOfClass:[MMWindowController class]])
938         return (MMWindowController*)windowController;
939     return nil;
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];
984 - (void)beginDrawing
986     [contentImage lockFocus];
989 - (void)endDrawing
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,
1010                                             kATSUQDItalicTag,
1011                                             kATSUStyleRenderingOptionsTag };
1012     ByteCount             attribSizes[] = { sizeof(Boolean),
1013                                             sizeof(Boolean),
1014                                             sizeof(UInt32) };
1015     Boolean               useBold, useItalic;
1016     UInt32                useAntialias;
1017     ATSUAttributeValuePtr attribValues[3] = { &useBold, &useItalic,
1018                                               &useAntialias };
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,
1033                                length);
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))
1048     {
1049         [bg set];
1050         NSRectFill(rect);
1051     }
1053     [fg set];
1055     ATSUSetTransientFontMatching(layout, TRUE);
1056     ATSUDrawText(layout,
1057                  kATSUFromTextBeginning,
1058                  kATSUToTextEnd,
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
1077                              column:left
1078                               toRow:bottom
1079                              column:right];
1080     [color set];
1081     // move rect up for count lines
1082     [self scrollRect:rect lineCount:-count];
1083     [self clearBlockFromRow:bottom - count + 1
1084                      column:left
1085                       toRow:bottom
1086                      column:right
1087                       color:color];
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
1095                              column:left
1096                               toRow:bottom - count
1097                              column:right];
1098     [color set];
1099     // move rect down for count lines
1100     [self scrollRect:rect lineCount:count];
1101     [self clearBlockFromRow:row
1102                      column:left
1103                       toRow:row + count - 1
1104                      column:right
1105                       color:color];
1108 - (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
1109                    column:(int)col2 color:(NSColor *)color
1111     [color set];
1112     NSRectFill([self rectFromRow:row1 column:col1 toRow:row2 column:col2]);
1115 - (void)clearAll
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;
1141     }
1143     [color set];
1144     if (MMInsertionPointHollow == shape) {
1145         NSFrameRect(rect);
1146     } else {
1147         NSRectFill(rect);
1148     }
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)