Implemented CoreText renderer
[MacVim.git] / src / MacVim / MMVimView.m
blob3a3643e4839bd86b444d1f99145b73fc8fdf9287
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  * MMVimView
12  *
13  * A view class with a tabline, scrollbars, and a text view.  The tabline may
14  * appear at the top of the view in which case it fills up the view from left
15  * to right edge.  Any number of scrollbars may appear adjacent to all other
16  * edges of the view (there may be more than one scrollbar per edge and
17  * scrollbars may also be placed on the left edge of the view).  The rest of
18  * the view is filled by the text view.
19  */
21 #if MM_ENABLE_ATSUI
22 # import "MMAtsuiTextView.h"
23 #else
24 # import "MMCoreTextView.h"
25 #endif
26 #import "MMTextView.h"
27 #import "MMVimController.h"
28 #import "MMVimView.h"
29 #import "MMWindowController.h"
30 #import "Miscellaneous.h"
31 #import <PSMTabBarControl/PSMTabBarControl.h>
35 // Scroller type; these must match SBAR_* in gui.h
36 enum {
37     MMScrollerTypeLeft = 0,
38     MMScrollerTypeRight,
39     MMScrollerTypeBottom
43 // TODO:  Move!
44 @interface MMScroller : NSScroller {
45     int32_t identifier;
46     int type;
47     NSRange range;
49 - (id)initWithIdentifier:(int32_t)ident type:(int)type;
50 - (int32_t)scrollerId;
51 - (int)type;
52 - (NSRange)range;
53 - (void)setRange:(NSRange)newRange;
54 @end
57 @interface MMVimView (Private)
58 - (BOOL)bottomScrollbarVisible;
59 - (BOOL)leftScrollbarVisible;
60 - (BOOL)rightScrollbarVisible;
61 - (void)placeScrollbars;
62 - (NSUInteger)representedIndexOfTabViewItem:(NSTabViewItem *)tvi;
63 - (MMScroller *)scrollbarForIdentifier:(int32_t)ident index:(unsigned *)idx;
64 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize;
65 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize;
66 - (NSTabView *)tabView;
67 - (void)frameSizeMayHaveChanged;
68 @end
71 // This is an informal protocol implemented by MMWindowController (maybe it
72 // shold be a formal protocol, but ...).
73 @interface NSWindowController (MMVimViewDelegate)
74 - (void)liveResizeWillStart;
75 - (void)liveResizeDidEnd;
76 @end
80 @implementation MMVimView
82 - (MMVimView *)initWithFrame:(NSRect)frame
83                vimController:(MMVimController *)controller
85     if (![super initWithFrame:frame])
86         return nil;
87     
88     vimController = controller;
89     scrollbars = [[NSMutableArray alloc] init];
91     // Only the tabline is autoresized, all other subview placement is done in
92     // frameSizeMayHaveChanged.
93     [self setAutoresizesSubviews:YES];
95     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
96     if ([ud boolForKey:MMAtsuiRendererKey]) {
97         // Use ATSUI or CoreText for text rendering.
98         //
99         // HACK! 'textView' has type MMTextView, but MM[Atsui|Core]TextView
100         // is not derived from MMTextView.
101 #if MM_ENABLE_ATSUI
102         textView = [[MMAtsuiTextView alloc] initWithFrame:frame];
103 #else
104         textView = [[MMCoreTextView alloc] initWithFrame:frame];
105 #endif
106     } else {
107         // Use Cocoa text system for text rendering.
108         textView = [[MMTextView alloc] initWithFrame:frame];
109     }
111     // Allow control of text view inset via MMTextInset* user defaults.
112     int left = [ud integerForKey:MMTextInsetLeftKey];
113     int top = [ud integerForKey:MMTextInsetTopKey];
114     [textView setTextContainerInset:NSMakeSize(left, top)];
116     [textView setAutoresizingMask:NSViewNotSizable];
117     [self addSubview:textView];
118     
119     // Create the tab view (which is never visible, but the tab bar control
120     // needs it to function).
121     tabView = [[NSTabView alloc] initWithFrame:NSZeroRect];
123     // Create the tab bar control (which is responsible for actually
124     // drawing the tabline and tabs).
125     NSRect tabFrame = { { 0, frame.size.height - 22 },
126                         { frame.size.width, 22 } };
127     tabBarControl = [[PSMTabBarControl alloc] initWithFrame:tabFrame];
129     [tabView setDelegate:tabBarControl];
131     [tabBarControl setTabView:tabView];
132     [tabBarControl setDelegate:self];
133     [tabBarControl setHidden:YES];
135     [tabBarControl setCellMinWidth:[ud integerForKey:MMTabMinWidthKey]];
136     [tabBarControl setCellMaxWidth:[ud integerForKey:MMTabMaxWidthKey]];
137     [tabBarControl setCellOptimumWidth:
138                                      [ud integerForKey:MMTabOptimumWidthKey]];
140     [tabBarControl setShowAddTabButton:[ud boolForKey:MMShowAddTabButtonKey]];
141     [[tabBarControl addTabButton] setTarget:self];
142     [[tabBarControl addTabButton] setAction:@selector(addNewTab:)];
143     [tabBarControl setAllowsDragBetweenWindows:NO];
144     [tabBarControl registerForDraggedTypes:
145                             [NSArray arrayWithObject:NSFilenamesPboardType]];
147     [tabBarControl setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
148     
149     //[tabBarControl setPartnerView:textView];
150     
151     // tab bar resizing only works if awakeFromNib is called (that's where
152     // the NSViewFrameDidChangeNotification callback is installed). Sounds like
153     // a PSMTabBarControl bug, let's live with it for now.
154     [tabBarControl awakeFromNib];
156     [self addSubview:tabBarControl];
158     return self;
161 - (void)dealloc
163     ASLogDebug(@"");
165     [tabBarControl release];  tabBarControl = nil;
166     [tabView release];  tabView = nil;
167     [scrollbars release];  scrollbars = nil;
169     // HACK! The text storage is the principal owner of the text system, but we
170     // keep only a reference to the text view, so release the text storage
171     // first (unless we are using the ATSUI renderer).
172     if ([textView isKindOfClass:[MMTextView class]])
173         [[textView textStorage] release];
175     [textView release];  textView = nil;
177     [super dealloc];
180 - (BOOL)isOpaque
182     return YES;
185 - (void)drawRect:(NSRect)rect
187     // On Leopard, we want to have a textured window background for nice
188     // looking tabs. However, the textured window background looks really
189     // weird behind the window resize throbber, so emulate the look of an
190     // NSScrollView in the bottom right corner.
191     if (![[self window] showsResizeIndicator]  // XXX: make this a flag
192             || !([[self window] styleMask] & NSTexturedBackgroundWindowMask))
193         return;
195     int sw = [NSScroller scrollerWidth];
197     // add .5 to the pixel locations to put the lines on a pixel boundary.
198     // the top and right edges of the rect will be outside of the bounds rect
199     // and clipped away.
200     NSRect sizerRect = NSMakeRect([self bounds].size.width - sw + .5, -.5,
201             sw, sw);
202     //NSBezierPath* path = [NSBezierPath bezierPath];
203     NSBezierPath* path = [NSBezierPath bezierPathWithRect:sizerRect];
205     // On Tiger, we have color #E8E8E8 behind the resize throbber
206     // (which is windowBackgroundColor on untextured windows or controlColor in
207     // general). Terminal.app on Leopard has #FFFFFF background and #D9D9D9 as
208     // stroke. The colors below are #FFFFFF and #D4D4D4, which is close enough
209     // for me.
210     [[NSColor controlBackgroundColor] set];
211     [path fill];
213     [[NSColor secondarySelectedControlColor] set];
214     [path stroke];
217 - (MMTextView *)textView
219     return textView;
222 - (PSMTabBarControl *)tabBarControl
224     return tabBarControl;
227 - (void)cleanup
229     vimController = nil;
230     
231     // NOTE! There is a bug in PSMTabBarControl in that it retains the delegate
232     // so reset the delegate here, otherwise the delegate may never get
233     // released.
234     [tabView setDelegate:nil];
235     [tabBarControl setDelegate:nil];
236     [tabBarControl setTabView:nil];
237     [[self window] setDelegate:nil];
239     // NOTE! There is another bug in PSMTabBarControl where the control is not
240     // removed as an observer, so remove it here (failing to remove an observer
241     // may lead to very strange bugs).
242     [[NSNotificationCenter defaultCenter] removeObserver:tabBarControl];
244     [tabBarControl removeFromSuperviewWithoutNeedingDisplay];
245     [textView removeFromSuperviewWithoutNeedingDisplay];
247     unsigned i, count = [scrollbars count];
248     for (i = 0; i < count; ++i) {
249         MMScroller *sb = [scrollbars objectAtIndex:i];
250         [sb removeFromSuperviewWithoutNeedingDisplay];
251     }
253     [tabView removeAllTabViewItems];
256 - (NSSize)desiredSize
258     return [self vimViewSizeForTextViewSize:[textView desiredSize]];
261 - (NSSize)minSize
263     return [self vimViewSizeForTextViewSize:[textView minSize]];
266 - (NSSize)constrainRows:(int *)r columns:(int *)c toSize:(NSSize)size
268     NSSize textViewSize = [self textViewRectForVimViewSize:size].size;
269     textViewSize = [textView constrainRows:r columns:c toSize:textViewSize];
270     return [self vimViewSizeForTextViewSize:textViewSize];
273 - (void)setDesiredRows:(int)r columns:(int)c
275     [textView setMaxRows:r columns:c];
278 - (IBAction)addNewTab:(id)sender
280     [vimController sendMessage:AddNewTabMsgID data:nil];
283 - (void)updateTabsWithData:(NSData *)data
285     const void *p = [data bytes];
286     const void *end = p + [data length];
287     int tabIdx = 0;
289     // HACK!  Current tab is first in the message.  This way it is not
290     // necessary to guess which tab should be the selected one (this can be
291     // problematic for instance when new tabs are created).
292     int curtabIdx = *((int*)p);  p += sizeof(int);
294     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
296     while (p < end) {
297         NSTabViewItem *tvi = nil;
299         //int wincount = *((int*)p);  p += sizeof(int);
300         int infoCount = *((int*)p); p += sizeof(int);
301         unsigned i;
302         for (i = 0; i < infoCount; ++i) {
303             int length = *((int*)p);  p += sizeof(int);
304             if (length <= 0)
305                 continue;
307             NSString *val = [[NSString alloc]
308                     initWithBytes:(void*)p length:length
309                          encoding:NSUTF8StringEncoding];
310             p += length;
312             switch (i) {
313                 case MMTabLabel:
314                     // Set the label of the tab, adding a new tab when needed.
315                     tvi = [[self tabView] numberOfTabViewItems] <= tabIdx
316                             ? [self addNewTabViewItem]
317                             : [tabViewItems objectAtIndex:tabIdx];
318                     [tvi setLabel:val];
319                     ++tabIdx;
320                     break;
321                 case MMTabToolTip:
322                     if (tvi)
323                         [[self tabBarControl] setToolTip:val
324                                           forTabViewItem:tvi];
325                     break;
326                 default:
327                     ASLogWarn(@"Unknown tab info for index: %d", i);
328             }
330             [val release];
331         }
332     }
334     // Remove unused tabs from the NSTabView.  Note that when a tab is closed
335     // the NSTabView will automatically select another tab, but we want Vim to
336     // take care of which tab to select so set the vimTaskSelectedTab flag to
337     // prevent the tab selection message to be passed on to the VimTask.
338     vimTaskSelectedTab = YES;
339     int i, count = [[self tabView] numberOfTabViewItems];
340     for (i = count-1; i >= tabIdx; --i) {
341         id tvi = [tabViewItems objectAtIndex:i];
342         [[self tabView] removeTabViewItem:tvi];
343     }
344     vimTaskSelectedTab = NO;
346     [self selectTabWithIndex:curtabIdx];
349 - (void)selectTabWithIndex:(int)idx
351     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
352     if (idx < 0 || idx >= [tabViewItems count]) {
353         ASLogWarn(@"No tab with index %d exists.", idx);
354         return;
355     }
357     // Do not try to select a tab if already selected.
358     NSTabViewItem *tvi = [tabViewItems objectAtIndex:idx];
359     if (tvi != [[self tabView] selectedTabViewItem]) {
360         vimTaskSelectedTab = YES;
361         [[self tabView] selectTabViewItem:tvi];
362         vimTaskSelectedTab = NO;
364         // We might need to change the scrollbars that are visible.
365         [self placeScrollbars];
366     }
369 - (NSTabViewItem *)addNewTabViewItem
371     // NOTE!  A newly created tab is not by selected by default; Vim decides
372     // which tab should be selected at all times.  However, the AppKit will
373     // automatically select the first tab added to a tab view.
375     NSTabViewItem *tvi = [[NSTabViewItem alloc] initWithIdentifier:nil];
377     // NOTE: If this is the first tab it will be automatically selected.
378     vimTaskSelectedTab = YES;
379     [[self tabView] addTabViewItem:tvi];
380     vimTaskSelectedTab = NO;
382     [tvi autorelease];
384     return tvi;
387 - (void)createScrollbarWithIdentifier:(int32_t)ident type:(int)type
389     MMScroller *scroller = [[MMScroller alloc] initWithIdentifier:ident
390                                                              type:type];
391     [scroller setTarget:self];
392     [scroller setAction:@selector(scroll:)];
394     [self addSubview:scroller];
395     [scrollbars addObject:scroller];
396     [scroller release];
399 - (BOOL)destroyScrollbarWithIdentifier:(int32_t)ident
401     unsigned idx = 0;
402     MMScroller *scroller = [self scrollbarForIdentifier:ident index:&idx];
403     if (!scroller) return NO;
405     [scroller removeFromSuperview];
406     [scrollbars removeObjectAtIndex:idx];
408     // If a visible scroller was removed then the vim view must resize.  This
409     // is handled by the window controller (the vim view never resizes itself).
410     return ![scroller isHidden];
413 - (BOOL)showScrollbarWithIdentifier:(int32_t)ident state:(BOOL)visible
415     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
416     if (!scroller) return NO;
418     BOOL wasVisible = ![scroller isHidden];
419     [scroller setHidden:!visible];
421     // If a scroller was hidden or shown then the vim view must resize.  This
422     // is handled by the window controller (the vim view never resizes itself).
423     return wasVisible != visible;
426 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
427                     identifier:(int32_t)ident
429     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
430 #if (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
431     [scroller setDoubleValue:val];
432     [scroller setKnobProportion:prop];
433 #else
434     [scroller setFloatValue:val knobProportion:prop];
435 #endif
436     [scroller setEnabled:prop != 1.f];
440 - (void)scroll:(id)sender
442     NSMutableData *data = [NSMutableData data];
443     int32_t ident = [(MMScroller*)sender scrollerId];
444     int hitPart = [sender hitPart];
445     float value = [sender floatValue];
447     [data appendBytes:&ident length:sizeof(int32_t)];
448     [data appendBytes:&hitPart length:sizeof(int)];
449     [data appendBytes:&value length:sizeof(float)];
451     [vimController sendMessage:ScrollbarEventMsgID data:data];
454 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(int32_t)ident
456     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
457     NSRange range = NSMakeRange(pos, len);
458     if (!NSEqualRanges(range, [scroller range])) {
459         [scroller setRange:range];
460         // TODO!  Should only do this once per update.
462         // This could be sent because a text window was created or closed, so
463         // we might need to update which scrollbars are visible.
464         [self placeScrollbars];
465     }
468 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
470     [textView setDefaultColorsBackground:back foreground:fore];
474 // -- PSMTabBarControl delegate ----------------------------------------------
477 - (BOOL)tabView:(NSTabView *)theTabView shouldSelectTabViewItem:
478     (NSTabViewItem *)tabViewItem
480     // NOTE: It would be reasonable to think that 'shouldSelect...' implies
481     // that this message only gets sent when the user clicks the tab.
482     // Unfortunately it is not so, which is why we need the
483     // 'vimTaskSelectedTab' flag.
484     //
485     // HACK!  The selection message should not be propagated to Vim if Vim
486     // selected the tab (e.g. as opposed the user clicking the tab).  The
487     // delegate method has no way of knowing who initiated the selection so a
488     // flag is set when Vim initiated the selection.
489     if (!vimTaskSelectedTab) {
490         // Propagate the selection message to Vim.
491         NSUInteger idx = [self representedIndexOfTabViewItem:tabViewItem];
492         if (NSNotFound != idx) {
493             int i = (int)idx;   // HACK! Never more than MAXINT tabs?!
494             NSData *data = [NSData dataWithBytes:&i length:sizeof(int)];
495             [vimController sendMessage:SelectTabMsgID data:data];
496         }
497     }
499     // Unless Vim selected the tab, return NO, and let Vim decide if the tab
500     // should get selected or not.
501     return vimTaskSelectedTab;
504 - (BOOL)tabView:(NSTabView *)theTabView shouldCloseTabViewItem:
505         (NSTabViewItem *)tabViewItem
507     // HACK!  This method is only called when the user clicks the close button
508     // on the tab.  Instead of letting the tab bar close the tab, we return NO
509     // and pass a message on to Vim to let it handle the closing.
510     NSUInteger idx = [self representedIndexOfTabViewItem:tabViewItem];
511     int i = (int)idx;   // HACK! Never more than MAXINT tabs?!
512     NSData *data = [NSData dataWithBytes:&i length:sizeof(int)];
513     [vimController sendMessage:CloseTabMsgID data:data];
515     return NO;
518 - (void)tabView:(NSTabView *)theTabView didDragTabViewItem:
519         (NSTabViewItem *)tabViewItem toIndex:(int)idx
521     NSMutableData *data = [NSMutableData data];
522     [data appendBytes:&idx length:sizeof(int)];
524     [vimController sendMessage:DraggedTabMsgID data:data];
527 - (NSDragOperation)tabBarControl:(PSMTabBarControl *)theTabBarControl
528         draggingEntered:(id <NSDraggingInfo>)sender
529         forTabAtIndex:(NSUInteger)tabIndex
531     NSPasteboard *pb = [sender draggingPasteboard];
532     return [[pb types] containsObject:NSFilenamesPboardType]
533             ? NSDragOperationCopy
534             : NSDragOperationNone;
537 - (BOOL)tabBarControl:(PSMTabBarControl *)theTabBarControl
538         performDragOperation:(id <NSDraggingInfo>)sender
539         forTabAtIndex:(NSUInteger)tabIndex
541     NSPasteboard *pb = [sender draggingPasteboard];
542     if ([[pb types] containsObject:NSFilenamesPboardType]) {
543         NSArray *filenames = [pb propertyListForType:NSFilenamesPboardType];
544         if ([filenames count] == 0)
545             return NO;
546         if (tabIndex != NSNotFound) {
547             // If dropping on a specific tab, only open one file
548             [vimController file:[filenames objectAtIndex:0]
549                 draggedToTabAtIndex:tabIndex];
550         } else {
551             // Files were dropped on empty part of tab bar; open them all
552             [vimController filesDraggedToTabBar:filenames];
553         }
554         return YES;
555     } else {
556         return NO;
557     }
562 // -- NSView customization ---------------------------------------------------
565 - (void)viewWillStartLiveResize
567     id windowController = [[self window] windowController];
568     [windowController liveResizeWillStart];
570     [super viewWillStartLiveResize];
573 - (void)viewDidEndLiveResize
575     id windowController = [[self window] windowController];
576     [windowController liveResizeDidEnd];
578     [super viewDidEndLiveResize];
581 - (void)setFrameSize:(NSSize)size
583     // NOTE: Instead of only acting when a frame was resized, we do some
584     // updating each time a frame may be resized.  (At the moment, if we only
585     // respond to actual frame changes then typing ":set lines=1000" twice in a
586     // row will result in the vim view holding more rows than the can fit
587     // inside the window.)
588     [super setFrameSize:size];
589     [self frameSizeMayHaveChanged];
592 - (void)setFrame:(NSRect)frame
594     // See comment in setFrameSize: above.
595     [super setFrame:frame];
596     [self frameSizeMayHaveChanged];
599 @end // MMVimView
604 @implementation MMVimView (Private)
606 - (BOOL)bottomScrollbarVisible
608     unsigned i, count = [scrollbars count];
609     for (i = 0; i < count; ++i) {
610         MMScroller *scroller = [scrollbars objectAtIndex:i];
611         if ([scroller type] == MMScrollerTypeBottom && ![scroller isHidden])
612             return YES;
613     }
615     return NO;
618 - (BOOL)leftScrollbarVisible
620     unsigned i, count = [scrollbars count];
621     for (i = 0; i < count; ++i) {
622         MMScroller *scroller = [scrollbars objectAtIndex:i];
623         if ([scroller type] == MMScrollerTypeLeft && ![scroller isHidden])
624             return YES;
625     }
627     return NO;
630 - (BOOL)rightScrollbarVisible
632     unsigned i, count = [scrollbars count];
633     for (i = 0; i < count; ++i) {
634         MMScroller *scroller = [scrollbars objectAtIndex:i];
635         if ([scroller type] == MMScrollerTypeRight && ![scroller isHidden])
636             return YES;
637     }
639     return NO;
642 - (void)placeScrollbars
644     NSRect textViewFrame = [textView frame];
645     BOOL lsbVisible = [self leftScrollbarVisible];
647     // HACK!  Find the lowest left&right vertical scrollbars, as well as the
648     // rightmost horizontal scrollbar.  This hack continues further down.
649     //
650     // TODO!  Can there be no more than one horizontal scrollbar?  If so, the
651     // code can be simplified.
652     unsigned lowestLeftSbIdx = (unsigned)-1;
653     unsigned lowestRightSbIdx = (unsigned)-1;
654     unsigned rightmostSbIdx = (unsigned)-1;
655     unsigned rowMaxLeft = 0, rowMaxRight = 0, colMax = 0;
656     unsigned i, count = [scrollbars count];
657     for (i = 0; i < count; ++i) {
658         MMScroller *scroller = [scrollbars objectAtIndex:i];
659         if (![scroller isHidden]) {
660             NSRange range = [scroller range];
661             if ([scroller type] == MMScrollerTypeLeft
662                     && range.location >= rowMaxLeft) {
663                 rowMaxLeft = range.location;
664                 lowestLeftSbIdx = i;
665             } else if ([scroller type] == MMScrollerTypeRight
666                     && range.location >= rowMaxRight) {
667                 rowMaxRight = range.location;
668                 lowestRightSbIdx = i;
669             } else if ([scroller type] == MMScrollerTypeBottom
670                     && range.location >= colMax) {
671                 colMax = range.location;
672                 rightmostSbIdx = i;
673             }
674         }
675     }
677     // Place the scrollbars.
678     for (i = 0; i < count; ++i) {
679         MMScroller *scroller = [scrollbars objectAtIndex:i];
680         if ([scroller isHidden])
681             continue;
683         NSRect rect;
684         if ([scroller type] == MMScrollerTypeBottom) {
685             rect = [textView rectForColumnsInRange:[scroller range]];
686             rect.size.height = [NSScroller scrollerWidth];
687             if (lsbVisible)
688                 rect.origin.x += [NSScroller scrollerWidth];
690             // HACK!  Make sure the rightmost horizontal scrollbar covers the
691             // text view all the way to the right, otherwise it looks ugly when
692             // the user drags the window to resize.
693             if (i == rightmostSbIdx) {
694                 float w = NSMaxX(textViewFrame) - NSMaxX(rect);
695                 if (w > 0)
696                     rect.size.width += w;
697             }
699             // Make sure scrollbar rect is bounded by the text view frame.
700             if (rect.origin.x < textViewFrame.origin.x)
701                 rect.origin.x = textViewFrame.origin.x;
702             else if (rect.origin.x > NSMaxX(textViewFrame))
703                 rect.origin.x = NSMaxX(textViewFrame);
704             if (NSMaxX(rect) > NSMaxX(textViewFrame))
705                 rect.size.width -= NSMaxX(rect) - NSMaxX(textViewFrame);
706             if (rect.size.width < 0)
707                 rect.size.width = 0;
708         } else {
709             rect = [textView rectForRowsInRange:[scroller range]];
710             // Adjust for the fact that text layout is flipped.
711             rect.origin.y = NSMaxY(textViewFrame) - rect.origin.y
712                     - rect.size.height;
713             rect.size.width = [NSScroller scrollerWidth];
714             if ([scroller type] == MMScrollerTypeRight)
715                 rect.origin.x = NSMaxX(textViewFrame);
717             // HACK!  Make sure the lowest vertical scrollbar covers the text
718             // view all the way to the bottom.  This is done because Vim only
719             // makes the scrollbar cover the (vim-)window it is associated with
720             // and this means there is always an empty gap in the scrollbar
721             // region next to the command line.
722             // TODO!  Find a nicer way to do this.
723             if (i == lowestLeftSbIdx || i == lowestRightSbIdx) {
724                 float h = rect.origin.y + rect.size.height
725                           - textViewFrame.origin.y;
726                 if (rect.size.height < h) {
727                     rect.origin.y = textViewFrame.origin.y;
728                     rect.size.height = h;
729                 }
730             }
732             // Vertical scrollers must not cover the resize box in the
733             // bottom-right corner of the window.
734             if ([[self window] showsResizeIndicator]  // XXX: make this a flag
735                 && rect.origin.y < [NSScroller scrollerWidth]) {
736                 rect.size.height -= [NSScroller scrollerWidth] - rect.origin.y;
737                 rect.origin.y = [NSScroller scrollerWidth];
738             }
740             // Make sure scrollbar rect is bounded by the text view frame.
741             if (rect.origin.y < textViewFrame.origin.y) {
742                 rect.size.height -= textViewFrame.origin.y - rect.origin.y;
743                 rect.origin.y = textViewFrame.origin.y;
744             } else if (rect.origin.y > NSMaxY(textViewFrame))
745                 rect.origin.y = NSMaxY(textViewFrame);
746             if (NSMaxY(rect) > NSMaxY(textViewFrame))
747                 rect.size.height -= NSMaxY(rect) - NSMaxY(textViewFrame);
748             if (rect.size.height < 0)
749                 rect.size.height = 0;
750         }
752         NSRect oldRect = [scroller frame];
753         if (!NSEqualRects(oldRect, rect)) {
754             [scroller setFrame:rect];
755             // Clear behind the old scroller frame, or parts of the old
756             // scroller might still be visible after setFrame:.
757             [[[self window] contentView] setNeedsDisplayInRect:oldRect];
758             [scroller setNeedsDisplay:YES];
759         }
760     }
763 - (NSUInteger)representedIndexOfTabViewItem:(NSTabViewItem *)tvi
765     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
766     return [tabViewItems indexOfObject:tvi];
769 - (MMScroller *)scrollbarForIdentifier:(int32_t)ident index:(unsigned *)idx
771     unsigned i, count = [scrollbars count];
772     for (i = 0; i < count; ++i) {
773         MMScroller *scroller = [scrollbars objectAtIndex:i];
774         if ([scroller scrollerId] == ident) {
775             if (idx) *idx = i;
776             return scroller;
777         }
778     }
780     return nil;
783 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize
785     NSSize size = textViewSize;
787     if (![[self tabBarControl] isHidden])
788         size.height += [[self tabBarControl] frame].size.height;
790     if ([self bottomScrollbarVisible])
791         size.height += [NSScroller scrollerWidth];
792     if ([self leftScrollbarVisible])
793         size.width += [NSScroller scrollerWidth];
794     if ([self rightScrollbarVisible])
795         size.width += [NSScroller scrollerWidth];
797     return size;
800 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize
802     NSRect rect = { {0, 0}, {contentSize.width, contentSize.height} };
804     if (![[self tabBarControl] isHidden])
805         rect.size.height -= [[self tabBarControl] frame].size.height;
807     if ([self bottomScrollbarVisible]) {
808         rect.size.height -= [NSScroller scrollerWidth];
809         rect.origin.y += [NSScroller scrollerWidth];
810     }
811     if ([self leftScrollbarVisible]) {
812         rect.size.width -= [NSScroller scrollerWidth];
813         rect.origin.x += [NSScroller scrollerWidth];
814     }
815     if ([self rightScrollbarVisible])
816         rect.size.width -= [NSScroller scrollerWidth];
818     return rect;
821 - (NSTabView *)tabView
823     return tabView;
826 - (void)frameSizeMayHaveChanged
828     // NOTE: Whenever a call is made that may have changed the frame size we
829     // take the opportunity to make sure all subviews are in place and that the
830     // (rows,columns) are constrained to lie inside the new frame.  We not only
831     // do this when the frame really has changed since it is possible to modify
832     // the number of (rows,columns) without changing the frame size.
834     // Give all superfluous space to the text view. It might be smaller or
835     // larger than it wants to be, but this is needed during live resizing.
836     NSRect textViewRect = [self textViewRectForVimViewSize:[self frame].size];
837     [textView setFrame:textViewRect];
839     [self placeScrollbars];
841     // It is possible that the current number of (rows,columns) is too big or
842     // too small to fit the new frame.  If so, notify Vim that the text
843     // dimensions should change, but don't actually change the number of
844     // (rows,columns).  These numbers may only change when Vim initiates the
845     // change (as opposed to the user dragging the window resizer, for
846     // example).
847     //
848     // Note that the message sent to Vim depends on whether we're in
849     // a live resize or not -- this is necessary to avoid the window jittering
850     // when the user drags to resize.
851     int constrained[2];
852     NSSize textViewSize = [textView frame].size;
853     [textView constrainRows:&constrained[0] columns:&constrained[1]
854                      toSize:textViewSize];
856     int rows, cols;
857     [textView getMaxRows:&rows columns:&cols];
859     if (constrained[0] != rows || constrained[1] != cols) {
860         NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
861         int msgid = [self inLiveResize] ? LiveResizeMsgID
862                                         : SetTextDimensionsMsgID;
864         ASLogDebug(@"Notify Vim that text dimensions changed from %dx%d to "
865                    "%dx%d (%s)", cols, rows, constrained[1], constrained[0],
866                    MessageStrings[msgid]);
868         [vimController sendMessage:msgid data:data];
870         // We only want to set the window title if this resize came from
871         // a live-resize, not (for example) setting 'columns' or 'lines'.
872         if ([self inLiveResize]) {
873             [[self window] setTitle:[NSString stringWithFormat:@"%dx%d",
874                     constrained[1], constrained[0]]];
875         }
876     }
879 @end // MMVimView (Private)
884 @implementation MMScroller
886 - (id)initWithIdentifier:(int32_t)ident type:(int)theType
888     // HACK! NSScroller creates a horizontal scroller if it is init'ed with a
889     // frame whose with exceeds its height; so create a bogus rect and pass it
890     // to initWithFrame.
891     NSRect frame = theType == MMScrollerTypeBottom
892             ? NSMakeRect(0, 0, 1, 0)
893             : NSMakeRect(0, 0, 0, 1);
895     self = [super initWithFrame:frame];
896     if (!self) return nil;
898     identifier = ident;
899     type = theType;
900     [self setHidden:YES];
901     [self setEnabled:YES];
902     [self setAutoresizingMask:NSViewNotSizable];
904     return self;
907 - (int32_t)scrollerId
909     return identifier;
912 - (int)type
914     return type;
917 - (NSRange)range
919     return range;
922 - (void)setRange:(NSRange)newRange
924     range = newRange;
927 - (void)scrollWheel:(NSEvent *)event
929     // HACK! Pass message on to the text view.
930     NSView *vimView = [self superview];
931     if ([vimView isKindOfClass:[MMVimView class]])
932         [[(MMVimView*)vimView textView] scrollWheel:event];
935 - (void)mouseDown:(NSEvent *)event
937     // TODO: This is an ugly way of getting the connection to the backend.
938     NSConnection *connection = nil;
939     id wc = [[self window] windowController];
940     if ([wc isKindOfClass:[MMWindowController class]]) {
941         MMVimController *vc = [(MMWindowController*)wc vimController];
942         id proxy = [vc backendProxy];
943         connection = [(NSDistantObject*)proxy connectionForProxy];
944     }
946     // NOTE: The scroller goes into "event tracking mode" when the user clicks
947     // (and holds) the mouse button.  We have to manually add the backend
948     // connection to this mode while the mouse button is held, else DO messages
949     // from Vim will not be processed until the mouse button is released.
950     [connection addRequestMode:NSEventTrackingRunLoopMode];
951     [super mouseDown:event];
952     [connection removeRequestMode:NSEventTrackingRunLoopMode];
955 @end // MMScroller