Revert "Modifier key sends Esc" related commits
[MacVim.git] / src / MacVim / MMAtsuiTextView.m
blob77218015063de21a34d3b92b84f01f1a7c15e8ba
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 "MMTextViewHelper.h"
31 #import "MMVimController.h"
32 #import "MMWindowController.h"
33 #import "Miscellaneous.h"
36 // TODO: What does DRAW_TRANSP flag do?  If the background isn't drawn when
37 // this flag is set, then sometimes the character after the cursor becomes
38 // blank.  Everything seems to work fine by just ignoring this flag.
39 #define DRAW_TRANSP               0x01    /* draw with transparant bg */
40 #define DRAW_BOLD                 0x02    /* draw bold text */
41 #define DRAW_UNDERL               0x04    /* draw underline text */
42 #define DRAW_UNDERC               0x08    /* draw undercurl text */
43 #define DRAW_ITALIC               0x10    /* draw italic text */
44 #define DRAW_CURSOR               0x20
46 #define kUnderlineOffset            (-2)
47 #define kUnderlineHeight            1
48 #define kUndercurlHeight            2
49 #define kUndercurlOffset            (-2)
50 #define kUndercurlDotWidth          2
51 #define kUndercurlDotDistance       2
54 @interface NSFont (AppKitPrivate)
55 - (ATSUFontID) _atsFontID;
56 @end
59 @interface MMAtsuiTextView (Private)
60 - (void)initAtsuStyles;
61 - (void)disposeAtsuStyles;
62 - (void)updateAtsuStyles;
63 - (MMWindowController *)windowController;
64 - (MMVimController *)vimController;
65 @end
68 @interface MMAtsuiTextView (Drawing)
69 - (NSPoint)originForRow:(int)row column:(int)column;
70 - (NSRect)rectFromRow:(int)row1 column:(int)col1
71                 toRow:(int)row2 column:(int)col2;
72 - (NSSize)textAreaSize;
73 - (void)resizeContentImage;
74 - (void)beginDrawing;
75 - (void)endDrawing;
76 - (void)drawString:(UniChar *)string length:(UniCharCount)length
77              atRow:(int)row column:(int)col cells:(int)cells
78          withFlags:(int)flags foregroundColor:(NSColor *)fg
79    backgroundColor:(NSColor *)bg specialColor:(NSColor *)sp;
80 - (void)deleteLinesFromRow:(int)row lineCount:(int)count
81               scrollBottom:(int)bottom left:(int)left right:(int)right
82                      color:(NSColor *)color;
83 - (void)insertLinesAtRow:(int)row lineCount:(int)count
84             scrollBottom:(int)bottom left:(int)left right:(int)right
85                    color:(NSColor *)color;
86 - (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
87                    column:(int)col2 color:(NSColor *)color;
88 - (void)clearAll;
89 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
90                        fraction:(int)percent;
91 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
92                    numColumns:(int)ncols;
93 @end
97     static float
98 defaultLineHeightForFont(NSFont *font)
100     // HACK: -[NSFont defaultLineHeightForFont] is deprecated but since the
101     // ATSUI renderer does not use NSLayoutManager we create one temporarily.
102     NSLayoutManager *lm = [[NSLayoutManager alloc] init];
103     float height = [lm defaultLineHeightForFont:font];
104     [lm release];
106     return height;
109 @implementation MMAtsuiTextView
111 - (id)initWithFrame:(NSRect)frame
113     if (!(self = [super initWithFrame:frame]))
114         return nil;
116     // NOTE!  It does not matter which font is set here, Vim will set its
117     // own font on startup anyway.  Just set some bogus values.
118     font = [[NSFont userFixedPitchFontOfSize:0] retain];
119     ascender = 0;
120     cellSize.width = cellSize.height = 1;
121     contentImage = nil;
122     imageSize = NSZeroSize;
123     insetSize = NSZeroSize;
125     // NOTE: If the default changes to 'NO' then the intialization of
126     // p_antialias in option.c must change as well.
127     antialias = YES;
129     helper = [[MMTextViewHelper alloc] init];
130     [helper setTextView:self];
132     [self initAtsuStyles];
134     [self registerForDraggedTypes:[NSArray arrayWithObjects:
135             NSFilenamesPboardType, NSStringPboardType, nil]];
137     return self;
140 - (void)dealloc
142     LOG_DEALLOC
144     [self disposeAtsuStyles];
145     [font release];  font = nil;
146     [defaultBackgroundColor release];  defaultBackgroundColor = nil;
147     [defaultForegroundColor release];  defaultForegroundColor = nil;
149     [helper setTextView:nil];
150     [helper dealloc];  helper = nil;
152     [super dealloc];
155 - (int)maxRows
157     return maxRows;
160 - (int)maxColumns
162     return maxColumns;
165 - (void)getMaxRows:(int*)rows columns:(int*)cols
167     if (rows) *rows = maxRows;
168     if (cols) *cols = maxColumns;
171 - (void)setMaxRows:(int)rows columns:(int)cols
173     // NOTE: Just remember the new values, the actual resizing is done lazily.
174     maxRows = rows;
175     maxColumns = cols;
178 - (void)setDefaultColorsBackground:(NSColor *)bgColor
179                         foreground:(NSColor *)fgColor
181     if (defaultBackgroundColor != bgColor) {
182         [defaultBackgroundColor release];
183         defaultBackgroundColor = bgColor ? [bgColor retain] : nil;
184     }
186     if (defaultForegroundColor != fgColor) {
187         [defaultForegroundColor release];
188         defaultForegroundColor = fgColor ? [fgColor retain] : nil;
189     }
192 - (NSColor *)defaultBackgroundColor
194     return defaultBackgroundColor;
197 - (NSColor *)defaultForegroundColor
199     return defaultForegroundColor;
202 - (void)setTextContainerInset:(NSSize)size
204     insetSize = size;
207 - (NSRect)rectForRowsInRange:(NSRange)range
209     NSRect rect = { 0, 0, 0, 0 };
210     unsigned start = range.location > maxRows ? maxRows : range.location;
211     unsigned length = range.length;
213     if (start + length > maxRows)
214         length = maxRows - start;
216     rect.origin.y = cellSize.height * start + insetSize.height;
217     rect.size.height = cellSize.height * length;
219     return rect;
222 - (NSRect)rectForColumnsInRange:(NSRange)range
224     NSRect rect = { 0, 0, 0, 0 };
225     unsigned start = range.location > maxColumns ? maxColumns : range.location;
226     unsigned length = range.length;
228     if (start+length > maxColumns)
229         length = maxColumns - start;
231     rect.origin.x = cellSize.width * start + insetSize.width;
232     rect.size.width = cellSize.width * length;
234     return rect;
238 - (void)setFont:(NSFont *)newFont
240     if (newFont && font != newFont) {
241         [font release];
242         font = [newFont retain];
243         ascender = roundf([font ascender]);
245         float em = [@"m" sizeWithAttributes:
246                 [NSDictionary dictionaryWithObject:newFont
247                                             forKey:NSFontAttributeName]].width;
248         float cellWidthMultiplier = [[NSUserDefaults standardUserDefaults]
249                 floatForKey:MMCellWidthMultiplierKey];
251         // NOTE! Even though NSFontFixedAdvanceAttribute is a float, it will
252         // only render at integer sizes.  Hence, we restrict the cell width to
253         // an integer here, otherwise the window width and the actual text
254         // width will not match.
255         cellSize.width = ceilf(em * cellWidthMultiplier);
256         cellSize.height = linespace + defaultLineHeightForFont(newFont);
258         [self updateAtsuStyles];
259     }
262 - (void)setWideFont:(NSFont *)newFont
264     if (!newFont) {
265         if (font) [self setWideFont:font];
266     } else if (newFont != fontWide) {
267         float pointSize = [newFont pointSize];
268         NSFontDescriptor *desc = [newFont fontDescriptor];
269         NSDictionary *dictWide = [NSDictionary
270             dictionaryWithObject:[NSNumber numberWithFloat:2*cellSize.width]
271                           forKey:NSFontFixedAdvanceAttribute];
272         desc = [desc fontDescriptorByAddingAttributes:dictWide];
273         fontWide = [NSFont fontWithDescriptor:desc size:pointSize];
274         [fontWide retain];
275     }
278 - (NSFont *)font
280     return font;
283 - (NSFont *)fontWide
285     return fontWide;
288 - (NSSize)cellSize
290     return cellSize;
293 - (void)setLinespace:(float)newLinespace
295     linespace = newLinespace;
297     // NOTE: The linespace is added to the cell height in order for a multiline
298     // selection not to have white (background color) gaps between lines.  Also
299     // this simplifies the code a lot because there is no need to check the
300     // linespace when calculating the size of the text view etc.  When the
301     // linespace is non-zero the baseline will be adjusted as well; check
302     // MMTypesetter.
303     cellSize.height = linespace + defaultLineHeightForFont(font);
308 - (void)setShouldDrawInsertionPoint:(BOOL)on
312 - (void)setPreEditRow:(int)row column:(int)col
314     [helper setPreEditRow:row column:col];
317 - (void)setMouseShape:(int)shape
319     [helper setMouseShape:shape];
322 - (void)setAntialias:(BOOL)state
324     antialias = state;
327 - (void)keyDown:(NSEvent *)event
329     [helper keyDown:event];
332 - (void)insertText:(id)string
334     [helper insertText:string];
337 - (void)doCommandBySelector:(SEL)selector
339     [helper doCommandBySelector:selector];
342 - (BOOL)performKeyEquivalent:(NSEvent *)event
344     return [helper performKeyEquivalent:event];
347 - (BOOL)hasMarkedText
349     return [helper hasMarkedText];
352 - (NSRange)markedRange
354     return [helper markedRange];
357 - (NSDictionary *)markedTextAttributes
359     return [helper markedTextAttributes];
362 - (void)setMarkedTextAttributes:(NSDictionary *)attr
364     [helper setMarkedTextAttributes:attr];
367 - (void)setMarkedText:(id)text selectedRange:(NSRange)range
369     [helper setMarkedText:text selectedRange:range];
372 - (void)unmarkText
374     [helper unmarkText];
377 - (void)scrollWheel:(NSEvent *)event
379     [helper scrollWheel:event];
382 - (void)mouseDown:(NSEvent *)event
384     [helper mouseDown:event];
387 - (void)rightMouseDown:(NSEvent *)event
389     [helper mouseDown:event];
392 - (void)otherMouseDown:(NSEvent *)event
394     [helper mouseDown:event];
397 - (void)mouseUp:(NSEvent *)event
399     [helper mouseUp:event];
402 - (void)rightMouseUp:(NSEvent *)event
404     [helper mouseUp:event];
407 - (void)otherMouseUp:(NSEvent *)event
409     [helper mouseUp:event];
412 - (void)mouseDragged:(NSEvent *)event
414     [helper mouseDragged:event];
417 - (void)rightMouseDragged:(NSEvent *)event
419     [helper mouseDragged:event];
422 - (void)otherMouseDragged:(NSEvent *)event
424     [helper mouseDragged:event];
427 - (void)mouseMoved:(NSEvent *)event
429     [helper mouseMoved:event];
432 - (void)mouseEntered:(NSEvent *)event
434     [helper mouseEntered:event];
437 - (void)mouseExited:(NSEvent *)event
439     [helper mouseExited:event];
442 - (void)setFrame:(NSRect)frame
444     [super setFrame:frame];
445     [helper setFrame:frame];
448 - (void)viewDidMoveToWindow
450     [helper viewDidMoveToWindow];
453 - (void)viewWillMoveToWindow:(NSWindow *)newWindow
455     [helper viewWillMoveToWindow:newWindow];
458 - (NSMenu*)menuForEvent:(NSEvent *)event
460     // HACK! Return nil to disable default popup menus (Vim provides its own).
461     // Called when user Ctrl-clicks in the view (this is already handled in
462     // rightMouseDown:).
463     return nil;
466 - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
468     return [helper performDragOperation:sender];
471 - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
473     return [helper draggingEntered:sender];
476 - (NSDragOperation)draggingUpdated:(id <NSDraggingInfo>)sender
478     return [helper draggingUpdated:sender];
483 - (BOOL)mouseDownCanMoveWindow
485     return NO;
488 - (BOOL)isOpaque
490     return YES;
493 - (BOOL)acceptsFirstResponder
495     return YES;
498 - (BOOL)isFlipped
500     return NO;
503 - (void)drawRect:(NSRect)rect
505     [defaultBackgroundColor set];
506     NSRectFill(rect);
508     NSPoint pt = { insetSize.width, insetSize.height };
509     [contentImage compositeToPoint:pt operation:NSCompositeCopy];
511     if ([self hasMarkedText]) {
512         int len = [[helper markedText] length];
513         int rows = 0;
514         int cols = maxColumns - [helper preEditColumn];
515         NSFont *theFont = [[self markedTextAttributes]
516             valueForKey:NSFontAttributeName];
517         if (theFont == [self fontWide])
518             cols = cols / 2;
519         int done = 0;
520         int lend = cols > len ? len : cols;
521         NSAttributedString *aString = [[helper markedText]
522                 attributedSubstringFromRange:NSMakeRange(done, lend)];
523         NSPoint pt = [self pointForRow:[helper preEditRow]
524                                 column:[helper preEditColumn]];
525         [aString drawAtPoint:pt];
526         done = lend;
527         if (done != len) {
528             int r;
529             rows = (len - done) / (maxColumns / 2) + 1;
530             for (r = 1; r <= rows; r++) {
531             lend = len - done > maxColumns / 2
532                 ? maxColumns / 2 : len - done;
533                 aString = [[helper markedText] attributedSubstringFromRange:
534                         NSMakeRange(done, lend)];
535                 NSPoint pt = [self pointForRow:[helper preEditRow]+r
536                                         column:0];
537                 [aString drawAtPoint:pt];
538                 done += lend;
539             }
540         }
542         rows = maxRows - 1 - [helper preEditRow];
543         cols = [helper preEditColumn];
544         if (theFont == fontWide) {
545             cols += ([helper imRange].location+[helper imRange].length) * 2;
546             if (cols >= maxColumns - 1) {
547                 rows -= cols / maxColumns;
548                 cols = cols % 2 ? cols % maxColumns + 1 :
549                                   cols % maxColumns;
550             }
551         } else {
552             cols += ([helper imRange].location+[helper imRange].length);
553             if (cols >= maxColumns) {
554                 rows -= cols / maxColumns;
555                 cols = cols % 2 ? cols % maxColumns + 1 :
556                                   cols % maxColumns;
557             }
558         }
560         // TODO: Could IM be in "right-left" mode?  If so the insertion point
561         // will be on the wrong side.
562         [self drawInsertionPointAtRow:rows
563                                column:cols
564                                 shape:MMInsertionPointVertical
565                              fraction:25];
566     }
569 - (BOOL) wantsDefaultClipping
571     return NO;
575 #define MM_DEBUG_DRAWING 0
577 - (void)performBatchDrawWithData:(NSData *)data
579     const void *bytes = [data bytes];
580     const void *end = bytes + [data length];
582     if (! NSEqualSizes(imageSize, [self textAreaSize]))
583         [self resizeContentImage];
585 #if MM_DEBUG_DRAWING
586     NSLog(@"====> BEGIN %s", _cmd);
587 #endif
588     [self beginDrawing];
590     // TODO: Sanity check input
592     while (bytes < end) {
593         int type = *((int*)bytes);  bytes += sizeof(int);
595         if (ClearAllDrawType == type) {
596 #if MM_DEBUG_DRAWING
597             NSLog(@"   Clear all");
598 #endif
599             [self clearAll];
600         } else if (ClearBlockDrawType == type) {
601             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
602             int row1 = *((int*)bytes);  bytes += sizeof(int);
603             int col1 = *((int*)bytes);  bytes += sizeof(int);
604             int row2 = *((int*)bytes);  bytes += sizeof(int);
605             int col2 = *((int*)bytes);  bytes += sizeof(int);
607 #if MM_DEBUG_DRAWING
608             NSLog(@"   Clear block (%d,%d) -> (%d,%d)", row1, col1,
609                     row2,col2);
610 #endif
611             [self clearBlockFromRow:row1 column:col1
612                     toRow:row2 column:col2
613                     color:[NSColor colorWithArgbInt:color]];
614         } else if (DeleteLinesDrawType == type) {
615             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
616             int row = *((int*)bytes);  bytes += sizeof(int);
617             int count = *((int*)bytes);  bytes += sizeof(int);
618             int bot = *((int*)bytes);  bytes += sizeof(int);
619             int left = *((int*)bytes);  bytes += sizeof(int);
620             int right = *((int*)bytes);  bytes += sizeof(int);
622 #if MM_DEBUG_DRAWING
623             NSLog(@"   Delete %d line(s) from %d", count, row);
624 #endif
625             [self deleteLinesFromRow:row lineCount:count
626                     scrollBottom:bot left:left right:right
627                            color:[NSColor colorWithArgbInt:color]];
628         } else if (DrawStringDrawType == type) {
629             int bg = *((int*)bytes);  bytes += sizeof(int);
630             int fg = *((int*)bytes);  bytes += sizeof(int);
631             int sp = *((int*)bytes);  bytes += sizeof(int);
632             int row = *((int*)bytes);  bytes += sizeof(int);
633             int col = *((int*)bytes);  bytes += sizeof(int);
634             int cells = *((int*)bytes);  bytes += sizeof(int);
635             int flags = *((int*)bytes);  bytes += sizeof(int);
636             int len = *((int*)bytes);  bytes += sizeof(int);
637             // UniChar *string = (UniChar*)bytes;  bytes += len;
638             NSString *string = [[NSString alloc]
639                     initWithBytesNoCopy:(void*)bytes
640                                  length:len
641                                encoding:NSUTF8StringEncoding
642                            freeWhenDone:NO];
643             bytes += len;
644 #if MM_DEBUG_DRAWING
645             NSLog(@"   Draw string at (%d,%d) length=%d flags=%d fg=0x%x "
646                     "bg=0x%x sp=0x%x", row, col, len, flags, fg, bg, sp);
647 #endif
648             unichar *characters = malloc(sizeof(unichar) * [string length]);
649             [string getCharacters:characters];
651             [self drawString:characters
652                              length:[string length]
653                               atRow:row
654                              column:col
655                               cells:cells withFlags:flags
656                     foregroundColor:[NSColor colorWithRgbInt:fg]
657                     backgroundColor:[NSColor colorWithArgbInt:bg]
658                        specialColor:[NSColor colorWithRgbInt:sp]];
659             free(characters);
660             [string release];
661         } else if (InsertLinesDrawType == type) {
662             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
663             int row = *((int*)bytes);  bytes += sizeof(int);
664             int count = *((int*)bytes);  bytes += sizeof(int);
665             int bot = *((int*)bytes);  bytes += sizeof(int);
666             int left = *((int*)bytes);  bytes += sizeof(int);
667             int right = *((int*)bytes);  bytes += sizeof(int);
669 #if MM_DEBUG_DRAWING
670             NSLog(@"   Insert %d line(s) at row %d", count, row);
671 #endif
672             [self insertLinesAtRow:row lineCount:count
673                              scrollBottom:bot left:left right:right
674                                     color:[NSColor colorWithArgbInt:color]];
675         } else if (DrawCursorDrawType == type) {
676             unsigned color = *((unsigned*)bytes);  bytes += sizeof(unsigned);
677             int row = *((int*)bytes);  bytes += sizeof(int);
678             int col = *((int*)bytes);  bytes += sizeof(int);
679             int shape = *((int*)bytes);  bytes += sizeof(int);
680             int percent = *((int*)bytes);  bytes += sizeof(int);
682 #if MM_DEBUG_DRAWING
683             NSLog(@"   Draw cursor at (%d,%d)", row, col);
684 #endif
685             [helper setInsertionPointColor:[NSColor colorWithRgbInt:color]];
686             [self drawInsertionPointAtRow:row column:col shape:shape
687                                  fraction:percent];
688         } else if (DrawInvertedRectDrawType == type) {
689             int row = *((int*)bytes);  bytes += sizeof(int);
690             int col = *((int*)bytes);  bytes += sizeof(int);
691             int nr = *((int*)bytes);  bytes += sizeof(int);
692             int nc = *((int*)bytes);  bytes += sizeof(int);
693             /*int invert = *((int*)bytes);*/  bytes += sizeof(int);
695 #if MM_DEBUG_DRAWING
696             NSLog(@"   Draw inverted rect: row=%d col=%d nrows=%d ncols=%d",
697                     row, col, nr, nc);
698 #endif
699             [self drawInvertedRectAtRow:row column:col numRows:nr
700                              numColumns:nc];
701         } else if (SetCursorPosDrawType == type) {
702             // TODO: This is used for Voice Over support in MMTextView,
703             // MMAtsuiTextView currently does not support Voice Over.
704             /*cursorRow = *((int*)bytes);*/  bytes += sizeof(int);
705             /*cursorCol = *((int*)bytes);*/  bytes += sizeof(int);
706         } else {
707             NSLog(@"WARNING: Unknown draw type (type=%d)", type);
708         }
709     }
711     [self endDrawing];
713     // NOTE: During resizing, Cocoa only sends draw messages before Vim's rows
714     // and columns are changed (due to ipc delays). Force a redraw here.
715     [self setNeedsDisplay:YES];
716     // [self displayIfNeeded];
718 #if MM_DEBUG_DRAWING
719     NSLog(@"<==== END   %s", _cmd);
720 #endif
723 - (NSSize)constrainRows:(int *)rows columns:(int *)cols toSize:(NSSize)size
725     // TODO:
726     // - Rounding errors may cause size change when there should be none
727     // - Desired rows/columns shold not be 'too small'
729     // Constrain the desired size to the given size.  Values for the minimum
730     // rows and columns is taken from Vim.
731     NSSize desiredSize = [self desiredSize];
732     int desiredRows = maxRows;
733     int desiredCols = maxColumns;
735     if (size.height != desiredSize.height) {
736         float fh = cellSize.height;
737         float ih = 2 * insetSize.height;
738         if (fh < 1.0f) fh = 1.0f;
740         desiredRows = floor((size.height - ih)/fh);
741         desiredSize.height = fh*desiredRows + ih;
742     }
744     if (size.width != desiredSize.width) {
745         float fw = cellSize.width;
746         float iw = 2 * insetSize.width;
747         if (fw < 1.0f) fw = 1.0f;
749         desiredCols = floor((size.width - iw)/fw);
750         desiredSize.width = fw*desiredCols + iw;
751     }
753     if (rows) *rows = desiredRows;
754     if (cols) *cols = desiredCols;
756     return desiredSize;
759 - (NSSize)desiredSize
761     // Compute the size the text view should be for the entire text area and
762     // inset area to be visible with the present number of rows and columns.
763     return NSMakeSize(maxColumns * cellSize.width + 2 * insetSize.width,
764                       maxRows * cellSize.height + 2 * insetSize.height);
767 - (NSSize)minSize
769     // Compute the smallest size the text view is allowed to be.
770     return NSMakeSize(MMMinColumns * cellSize.width + 2 * insetSize.width,
771                       MMMinRows * cellSize.height + 2 * insetSize.height);
774 - (void)changeFont:(id)sender
776     NSFont *newFont = [sender convertFont:font];
778     if (newFont) {
779         NSString *name = [newFont displayName];
780         unsigned len = [name lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
781         if (len > 0) {
782             NSMutableData *data = [NSMutableData data];
783             float pointSize = [newFont pointSize];
785             [data appendBytes:&pointSize length:sizeof(float)];
787             ++len;  // include NUL byte
788             [data appendBytes:&len length:sizeof(unsigned)];
789             [data appendBytes:[name UTF8String] length:len];
791             [[self vimController] sendMessage:SetFontMsgID data:data];
792         }
793     }
798 // NOTE: The menu items cut/copy/paste/undo/redo/select all/... must be bound
799 // to the same actions as in IB otherwise they will not work with dialogs.  All
800 // we do here is forward these actions to the Vim process.
802 - (IBAction)cut:(id)sender
804     [[self windowController] vimMenuItemAction:sender];
807 - (IBAction)copy:(id)sender
809     [[self windowController] vimMenuItemAction:sender];
812 - (IBAction)paste:(id)sender
814     [[self windowController] vimMenuItemAction:sender];
817 - (IBAction)undo:(id)sender
819     [[self windowController] vimMenuItemAction:sender];
822 - (IBAction)redo:(id)sender
824     [[self windowController] vimMenuItemAction:sender];
827 - (IBAction)selectAll:(id)sender
829     [[self windowController] vimMenuItemAction:sender];
832 - (BOOL)convertPoint:(NSPoint)point toRow:(int *)row column:(int *)column
834     // View is not flipped, instead the atsui code draws to a flipped image;
835     // thus we need to 'flip' the coordinate here since the column number
836     // increases in an up-to-down order.
837     point.y = [self frame].size.height - point.y;
839     NSPoint origin = { insetSize.width, insetSize.height };
841     if (!(cellSize.width > 0 && cellSize.height > 0))
842         return NO;
844     if (row) *row = floor((point.y-origin.y-1) / cellSize.height);
845     if (column) *column = floor((point.x-origin.x-1) / cellSize.width);
847     return YES;
850 - (NSPoint)pointForRow:(int)row column:(int)col
852     // Return the lower left coordinate of the cell at (row,column).
853     NSPoint pt;
855     pt.x = insetSize.width + col*cellSize.width;
856     pt.y = [self frame].size.height -
857            (insetSize.height + (1+row)*cellSize.height);
859     return pt;
862 - (NSRect)rectForRow:(int)row column:(int)col numRows:(int)nr
863           numColumns:(int)nc
865     // Return the rect for the block which covers the specified rows and
866     // columns.  The lower-left corner is the origin of this rect.
867     NSRect rect;
869     rect.origin.x = insetSize.width + col*cellSize.width;
870     rect.origin.y = [self frame].size.height -
871                     (insetSize.height + (nr+row)*cellSize.height);
872     rect.size.width = nc*cellSize.width;
873     rect.size.height = nr*cellSize.height;
875     return rect;
878 - (NSArray *)validAttributesForMarkedText
880     return nil;
883 - (NSAttributedString *)attributedSubstringFromRange:(NSRange)range
885     return nil;
888 - (NSUInteger)characterIndexForPoint:(NSPoint)point
890     return NSNotFound;
893 - (NSInteger)conversationIdentifier
895     return (NSInteger)self;
898 - (NSRange)selectedRange
900     return [helper imRange];
903 - (NSRect)firstRectForCharacterRange:(NSRange)range
905     return [helper firstRectForCharacterRange:range];
908 @end // MMAtsuiTextView
913 @implementation MMAtsuiTextView (Private)
915 - (void)initAtsuStyles
917     int i;
918     for (i = 0; i < MMMaxCellsPerChar; i++)
919         ATSUCreateStyle(&atsuStyles[i]);
922 - (void)disposeAtsuStyles
924     int i;
926     for (i = 0; i < MMMaxCellsPerChar; i++)
927         if (atsuStyles[i] != NULL)
928         {
929             if (ATSUDisposeStyle(atsuStyles[i]) != noErr)
930                 atsuStyles[i] = NULL;
931         }
934 - (void)updateAtsuStyles
936     ATSUFontID        fontID;
937     Fixed             fontSize;
938     Fixed             fontWidth;
939     int               i;
940     CGAffineTransform transform = CGAffineTransformMakeScale(1, -1);
941     ATSStyleRenderingOptions options;
943     fontID    = [font _atsFontID];
944     fontSize  = Long2Fix([font pointSize]);
945     options   = kATSStyleApplyAntiAliasing;
947     ATSUAttributeTag attribTags[] =
948     {
949         kATSUFontTag, kATSUSizeTag, kATSUImposeWidthTag,
950         kATSUFontMatrixTag, kATSUStyleRenderingOptionsTag,
951         kATSUMaxATSUITagValue + 1
952     };
954     ByteCount attribSizes[] =
955     {
956         sizeof(ATSUFontID), sizeof(Fixed), sizeof(fontWidth),
957         sizeof(CGAffineTransform), sizeof(ATSStyleRenderingOptions),
958         sizeof(font)
959     };
961     ATSUAttributeValuePtr attribValues[] =
962     {
963         &fontID, &fontSize, &fontWidth, &transform, &options, &font
964     };
966     ATSUFontFeatureType featureTypes[] = {
967         kLigaturesType, kLigaturesType
968     };
970     ATSUFontFeatureSelector featureSelectors[] = {
971         kCommonLigaturesOffSelector, kRareLigaturesOffSelector
972     };
974     for (i = 0; i < MMMaxCellsPerChar; i++)
975     {
976         fontWidth = Long2Fix(cellSize.width * (i + 1));
978         if (ATSUSetAttributes(atsuStyles[i],
979                               (sizeof attribTags) / sizeof(ATSUAttributeTag),
980                               attribTags, attribSizes, attribValues) != noErr)
981         {
982             ATSUDisposeStyle(atsuStyles[i]);
983             atsuStyles[i] = NULL;
984         }
986         // Turn off ligatures by default
987         ATSUSetFontFeatures(atsuStyles[i],
988                             sizeof(featureTypes) / sizeof(featureTypes[0]),
989                             featureTypes, featureSelectors);
990     }
993 - (MMWindowController *)windowController
995     id windowController = [[self window] windowController];
996     if ([windowController isKindOfClass:[MMWindowController class]])
997         return (MMWindowController*)windowController;
998     return nil;
1001 - (MMVimController *)vimController
1003     return [[self windowController] vimController];
1006 @end // MMAtsuiTextView (Private)
1011 @implementation MMAtsuiTextView (Drawing)
1013 - (NSPoint)originForRow:(int)row column:(int)col
1015     return NSMakePoint(col * cellSize.width, row * cellSize.height);
1018 - (NSRect)rectFromRow:(int)row1 column:(int)col1
1019                 toRow:(int)row2 column:(int)col2
1021     NSPoint origin = [self originForRow:row1 column:col1];
1022     return NSMakeRect(origin.x, origin.y,
1023                       (col2 + 1 - col1) * cellSize.width,
1024                       (row2 + 1 - row1) * cellSize.height);
1027 - (NSSize)textAreaSize
1029     // Calculate the (desired) size of the text area, i.e. the text view area
1030     // minus the inset area.
1031     return NSMakeSize(maxColumns * cellSize.width, maxRows * cellSize.height);
1034 - (void)resizeContentImage
1036     //NSLog(@"resizeContentImage");
1037     [contentImage release];
1038     contentImage = [[NSImage alloc] initWithSize:[self textAreaSize]];
1039     [contentImage setFlipped:YES];
1040     imageSize = [self textAreaSize];
1043 - (void)beginDrawing
1045     [contentImage lockFocus];
1048 - (void)endDrawing
1050     [contentImage unlockFocus];
1053 #define atsu_style_set_bool(s, t, b) \
1054     ATSUSetAttributes(s, 1, &t, &(sizeof(Boolean)), &&b);
1055 #define FILL_Y(y)    (y * cellSize.height)
1057 - (void)drawString:(UniChar *)string length:(UniCharCount)length
1058              atRow:(int)row column:(int)col cells:(int)cells
1059          withFlags:(int)flags foregroundColor:(NSColor *)fg
1060    backgroundColor:(NSColor *)bg specialColor:(NSColor *)sp
1062     // 'string' consists of 'length' utf-16 code pairs and should cover 'cells'
1063     // display cells (a normal character takes up one display cell, a wide
1064     // character takes up two)
1065     ATSUStyle       style = (flags & DRAW_WIDE) ? atsuStyles[1] : atsuStyles[0];
1066     ATSUTextLayout  layout;
1068     // Font selection and rendering options for ATSUI
1069     ATSUAttributeTag      attribTags[3] = { kATSUQDBoldfaceTag,
1070                                             kATSUFontMatrixTag,
1071                                             kATSUStyleRenderingOptionsTag };
1073     ByteCount             attribSizes[] = { sizeof(Boolean),
1074                                             sizeof(CGAffineTransform),
1075                                             sizeof(UInt32) };
1076     Boolean               useBold;
1077     CGAffineTransform     theTransform = CGAffineTransformMakeScale(1.0, -1.0);
1078     UInt32                useAntialias;
1080     ATSUAttributeValuePtr attribValues[3] = { &useBold, &theTransform,
1081                                               &useAntialias };
1083     useBold      = (flags & DRAW_BOLD) ? true : false;
1085     if (flags & DRAW_ITALIC)
1086         theTransform.c = Fix2X(kATSItalicQDSkew);
1088     useAntialias = antialias ? kATSStyleApplyAntiAliasing
1089                              : kATSStyleNoAntiAliasing;
1091     ATSUSetAttributes(style, sizeof(attribValues) / sizeof(attribValues[0]),
1092                       attribTags, attribSizes, attribValues);
1094     // NSLog(@"drawString: %d", length);
1096     ATSUCreateTextLayout(&layout);
1097     ATSUSetTextPointerLocation(layout, string,
1098                                kATSUFromTextBeginning, kATSUToTextEnd,
1099                                length);
1100     ATSUSetRunStyle(layout, style, kATSUFromTextBeginning, kATSUToTextEnd);
1102     NSRect rect = NSMakeRect(col * cellSize.width, row * cellSize.height,
1103                              length * cellSize.width, cellSize.height);
1104     if (flags & DRAW_WIDE)
1105         rect.size.width = rect.size.width * 2;
1106     CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
1108     ATSUAttributeTag tags[] = { kATSUCGContextTag };
1109     ByteCount sizes[] = { sizeof(CGContextRef) };
1110     ATSUAttributeValuePtr values[] = { &context };
1111     ATSUSetLayoutControls(layout, 1, tags, sizes, values);
1113     if (! (flags & DRAW_TRANSP))
1114     {
1115         [bg set];
1116         NSRectFill(rect);
1117     }
1119     [fg set];
1121     ATSUSetTransientFontMatching(layout, TRUE);
1122     ATSUDrawText(layout,
1123                  kATSUFromTextBeginning,
1124                  kATSUToTextEnd,
1125                  X2Fix(rect.origin.x),
1126                  X2Fix(rect.origin.y + ascender));
1127     ATSUDisposeTextLayout(layout);
1129     if (flags & DRAW_UNDERL)
1130     {
1131         [fg set];
1132         NSRectFill(NSMakeRect(rect.origin.x,
1133                               (row + 1) * cellSize.height + kUnderlineOffset,
1134                               rect.size.width, kUnderlineHeight));
1135     }
1137     if (flags & DRAW_UNDERC)
1138     {
1139         [sp set];
1141         float line_end_x = rect.origin.x + rect.size.width;
1142         int i = 0;
1143         NSRect line_rect = NSMakeRect(
1144                 rect.origin.x,
1145                 (row + 1) * cellSize.height + kUndercurlOffset,
1146                 kUndercurlDotWidth, kUndercurlHeight);
1148         while (line_rect.origin.x < line_end_x)
1149         {
1150             if (i % 2)
1151                 NSRectFill(line_rect);
1153             line_rect.origin.x += kUndercurlDotDistance;
1154             i++;
1155         }
1156     }
1159 - (void)scrollRect:(NSRect)rect lineCount:(int)count
1161     NSPoint destPoint = rect.origin;
1162     destPoint.y += count * cellSize.height;
1164     NSCopyBits(0, rect, destPoint);
1167 - (void)deleteLinesFromRow:(int)row lineCount:(int)count
1168               scrollBottom:(int)bottom left:(int)left right:(int)right
1169                      color:(NSColor *)color
1171     NSRect rect = [self rectFromRow:row + count
1172                              column:left
1173                               toRow:bottom
1174                              column:right];
1175     [color set];
1176     // move rect up for count lines
1177     [self scrollRect:rect lineCount:-count];
1178     [self clearBlockFromRow:bottom - count + 1
1179                      column:left
1180                       toRow:bottom
1181                      column:right
1182                       color:color];
1185 - (void)insertLinesAtRow:(int)row lineCount:(int)count
1186             scrollBottom:(int)bottom left:(int)left right:(int)right
1187                    color:(NSColor *)color
1189     NSRect rect = [self rectFromRow:row
1190                              column:left
1191                               toRow:bottom - count
1192                              column:right];
1193     [color set];
1194     // move rect down for count lines
1195     [self scrollRect:rect lineCount:count];
1196     [self clearBlockFromRow:row
1197                      column:left
1198                       toRow:row + count - 1
1199                      column:right
1200                       color:color];
1203 - (void)clearBlockFromRow:(int)row1 column:(int)col1 toRow:(int)row2
1204                    column:(int)col2 color:(NSColor *)color
1206     [color set];
1207     NSRectFill([self rectFromRow:row1 column:col1 toRow:row2 column:col2]);
1210 - (void)clearAll
1212     [defaultBackgroundColor set];
1213     NSRectFill(NSMakeRect(0, 0, imageSize.width, imageSize.height));
1216 - (void)drawInsertionPointAtRow:(int)row column:(int)col shape:(int)shape
1217                        fraction:(int)percent
1219     NSPoint origin = [self originForRow:row column:col];
1220     NSRect rect = NSMakeRect(origin.x, origin.y,
1221                              cellSize.width, cellSize.height);
1223     // NSLog(@"shape = %d, fraction: %d", shape, percent);
1225     if (MMInsertionPointHorizontal == shape) {
1226         int frac = (cellSize.height * percent + 99)/100;
1227         rect.origin.y += rect.size.height - frac;
1228         rect.size.height = frac;
1229     } else if (MMInsertionPointVertical == shape) {
1230         int frac = (cellSize.width * percent + 99)/100;
1231         rect.size.width = frac;
1232     } else if (MMInsertionPointVerticalRight == shape) {
1233         int frac = (cellSize.width * percent + 99)/100;
1234         rect.origin.x += rect.size.width - frac;
1235         rect.size.width = frac;
1236     }
1238     [[helper insertionPointColor] set];
1239     if (MMInsertionPointHollow == shape) {
1240         NSFrameRect(rect);
1241     } else {
1242         NSRectFill(rect);
1243     }
1246 - (void)drawInvertedRectAtRow:(int)row column:(int)col numRows:(int)nrows
1247                    numColumns:(int)ncols
1249     // TODO: THIS CODE HAS NOT BEEN TESTED!
1250     CGContextRef cgctx = [[NSGraphicsContext currentContext] graphicsPort];
1251     CGContextSaveGState(cgctx);
1252     CGContextSetBlendMode(cgctx, kCGBlendModeDifference);
1253     CGContextSetRGBFillColor(cgctx, 1.0, 1.0, 1.0, 1.0);
1255     CGRect rect = { col * cellSize.width, row * cellSize.height,
1256                     ncols * cellSize.width, nrows * cellSize.height };
1257     CGContextFillRect(cgctx, rect);
1259     CGContextRestoreGState(cgctx);
1262 @end // MMAtsuiTextView (Drawing)