Dialogs are always displayed in the default run loop mode
[MacVim.git] / src / MacVim / MMVimView.m
blob4c2a064b7ac0af87d1c22e282386d7d71420647d
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 #import "MMAtsuiTextView.h"
22 #import "MMTextView.h"
23 #import "MMVimController.h"
24 #import "MMVimView.h"
25 #import "Miscellaneous.h"
26 #import <PSMTabBarControl.h>
30 // Scroller type; these must match SBAR_* in gui.h
31 enum {
32     MMScrollerTypeLeft = 0,
33     MMScrollerTypeRight,
34     MMScrollerTypeBottom
38 // TODO:  Move!
39 @interface MMScroller : NSScroller {
40     long identifier;
41     int type;
42     NSRange range;
44 - (id)initWithIdentifier:(long)ident type:(int)type;
45 - (long)identifier;
46 - (int)type;
47 - (NSRange)range;
48 - (void)setRange:(NSRange)newRange;
49 @end
52 @interface MMVimView (Private)
53 - (BOOL)bottomScrollbarVisible;
54 - (BOOL)leftScrollbarVisible;
55 - (BOOL)rightScrollbarVisible;
56 - (void)placeScrollbars;
57 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi;
58 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx;
59 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize;
60 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize;
61 - (NSTabView *)tabView;
62 - (void)frameSizeMayHaveChanged;
63 @end
66 // This is an informal protocol implemented by MMWindowController (maybe it
67 // shold be a formal protocol, but ...).
68 @interface NSWindowController (MMVimViewDelegate)
69 - (void)liveResizeWillStart;
70 - (void)liveResizeDidEnd;
71 @end
75 @implementation MMVimView
77 - (MMVimView *)initWithFrame:(NSRect)frame
78                vimController:(MMVimController *)controller
80     if (![super initWithFrame:frame])
81         return nil;
82     
83     vimController = controller;
84     scrollbars = [[NSMutableArray alloc] init];
86     // Only the tabline is autoresized, all other subview placement is done in
87     // frameSizeMayHaveChanged.
88     [self setAutoresizesSubviews:YES];
90     if ([[NSUserDefaults standardUserDefaults] boolForKey:MMAtsuiRendererKey]) {
91         // Use ATSUI for text rendering.
92         //
93         // HACK! 'textView' has type MMTextView, but MMAtsuiTextView is not
94         // derived from MMTextView.
95         textView = [[MMAtsuiTextView alloc] initWithFrame:frame];
96     } else {
97         // Use Cocoa text system for text rendering.
98         textView = [[MMTextView alloc] initWithFrame:frame];
99     }
101     // Allow control of text view inset via MMTextInset* user defaults.
102     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
103     int left = [ud integerForKey:MMTextInsetLeftKey];
104     int top = [ud integerForKey:MMTextInsetTopKey];
105     [textView setTextContainerInset:NSMakeSize(left, top)];
107     [textView setAutoresizingMask:NSViewNotSizable];
108     [self addSubview:textView];
109     
110     // Create the tab view (which is never visible, but the tab bar control
111     // needs it to function).
112     tabView = [[NSTabView alloc] initWithFrame:NSZeroRect];
114     // Create the tab bar control (which is responsible for actually
115     // drawing the tabline and tabs).
116     NSRect tabFrame = { { 0, frame.size.height - 22 },
117                         { frame.size.width, 22 } };
118     tabBarControl = [[PSMTabBarControl alloc] initWithFrame:tabFrame];
120     [tabView setDelegate:tabBarControl];
122     [tabBarControl setTabView:tabView];
123     [tabBarControl setDelegate:self];
124     [tabBarControl setHidden:YES];
126     [tabBarControl setCellMinWidth:[ud integerForKey:MMTabMinWidthKey]];
127     [tabBarControl setCellMaxWidth:[ud integerForKey:MMTabMaxWidthKey]];
128     [tabBarControl setCellOptimumWidth:
129                                      [ud integerForKey:MMTabOptimumWidthKey]];
131     [tabBarControl setShowAddTabButton:YES];
132     [[tabBarControl addTabButton] setTarget:self];
133     [[tabBarControl addTabButton] setAction:@selector(addNewTab:)];
134     [tabBarControl setAllowsDragBetweenWindows:NO];
136     [tabBarControl setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
137     
138     //[tabBarControl setPartnerView:textView];
139     
140     // tab bar resizing only works if awakeFromNib is called (that's where
141     // the NSViewFrameDidChangeNotification callback is installed). Sounds like
142     // a PSMTabBarControl bug, let's live with it for now.
143     [tabBarControl awakeFromNib];
145     [self addSubview:tabBarControl];
147     return self;
150 - (void)dealloc
152     [tabBarControl release];  tabBarControl = nil;
153     [tabView release];  tabView = nil;
154     [scrollbars release];  scrollbars = nil;
156     // HACK! The text storage is the principal owner of the text system, but we
157     // keep only a reference to the text view, so release the text storage
158     // first (unless we are using the ATSUI renderer).
159     if (![[NSUserDefaults standardUserDefaults]
160             boolForKey:MMAtsuiRendererKey])
161         [[textView textStorage] release];
163     [textView release];  textView = nil;
165     [super dealloc];
168 - (void)drawRect:(NSRect)rect
170     // On Leopard, we want to have a textured window background for nice
171     // looking tabs. However, the textured window background looks really
172     // weird behind the window resize throbber, so emulate the look of an
173     // NSScrollView in the bottom right corner.
174     if (![[self window] showsResizeIndicator]  // XXX: make this a flag
175             || !([[self window] styleMask] & NSTexturedBackgroundWindowMask))
176         return;
178     int sw = [NSScroller scrollerWidth];
180     // add .5 to the pixel locations to put the lines on a pixel boundary.
181     // the top and right edges of the rect will be outside of the bounds rect
182     // and clipped away.
183     NSRect sizerRect = NSMakeRect([self bounds].size.width - sw + .5, -.5,
184             sw, sw);
185     //NSBezierPath* path = [NSBezierPath bezierPath];
186     NSBezierPath* path = [NSBezierPath bezierPathWithRect:sizerRect];
188     // On Tiger, we have color #E8E8E8 behind the resize throbber
189     // (which is windowBackgroundColor on untextured windows or controlColor in
190     // general). Terminal.app on Leopard has #FFFFFF background and #D9D9D9 as
191     // stroke. The colors below are #FFFFFF and #D4D4D4, which is close enough
192     // for me.
193     [[NSColor controlBackgroundColor] set];
194     [path fill];
196     [[NSColor secondarySelectedControlColor] set];
197     [path stroke];
200 - (MMTextView *)textView
202     return textView;
205 - (PSMTabBarControl *)tabBarControl
207     return tabBarControl;
210 - (void)cleanup
212     vimController = nil;
213     
214     // NOTE! There is a bug in PSMTabBarControl in that it retains the delegate
215     // so reset the delegate here, otherwise the delegate may never get
216     // released.
217     [tabView setDelegate:nil];
218     [tabBarControl setDelegate:nil];
219     [tabBarControl setTabView:nil];
220     [[self window] setDelegate:nil];
222     // NOTE! There is another bug in PSMTabBarControl where the control is not
223     // removed as an observer, so remove it here (failing to remove an observer
224     // may lead to very strange bugs).
225     [[NSNotificationCenter defaultCenter] removeObserver:tabBarControl];
227     [tabBarControl removeFromSuperviewWithoutNeedingDisplay];
228     [textView removeFromSuperviewWithoutNeedingDisplay];
230     unsigned i, count = [scrollbars count];
231     for (i = 0; i < count; ++i) {
232         MMScroller *sb = [scrollbars objectAtIndex:i];
233         [sb removeFromSuperviewWithoutNeedingDisplay];
234     }
236     [tabView removeAllTabViewItems];
239 - (NSSize)desiredSize
241     return [self vimViewSizeForTextViewSize:[textView desiredSize]];
244 - (NSSize)minSize
246     return [self vimViewSizeForTextViewSize:[textView minSize]];
249 - (NSSize)constrainRows:(int *)r columns:(int *)c toSize:(NSSize)size
251     NSSize textViewSize = [self textViewRectForVimViewSize:size].size;
252     textViewSize = [textView constrainRows:r columns:c toSize:textViewSize];
253     return [self vimViewSizeForTextViewSize:textViewSize];
256 - (void)setDesiredRows:(int)r columns:(int)c
258     [textView setMaxRows:r columns:c];
261 - (IBAction)addNewTab:(id)sender
263     [vimController sendMessage:AddNewTabMsgID data:nil];
266 - (void)updateTabsWithData:(NSData *)data
268     const void *p = [data bytes];
269     const void *end = p + [data length];
270     int tabIdx = 0;
272     // HACK!  Current tab is first in the message.  This way it is not
273     // necessary to guess which tab should be the selected one (this can be
274     // problematic for instance when new tabs are created).
275     int curtabIdx = *((int*)p);  p += sizeof(int);
277     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
279     while (p < end) {
280         //int wincount = *((int*)p);  p += sizeof(int);
281         int length = *((int*)p);  p += sizeof(int);
283         NSString *label = [[NSString alloc]
284                 initWithBytes:(void*)p length:length
285                      encoding:NSUTF8StringEncoding];
286         p += length;
288         // Set the label of the tab;  add a new tab when needed.
289         NSTabViewItem *tvi = [[self tabView] numberOfTabViewItems] <= tabIdx
290                 ? [self addNewTabViewItem]
291                 : [tabViewItems objectAtIndex:tabIdx];
293         [tvi setLabel:label];
295         [label release];
297         ++tabIdx;
298     }
300     // Remove unused tabs from the NSTabView.  Note that when a tab is closed
301     // the NSTabView will automatically select another tab, but we want Vim to
302     // take care of which tab to select so set the vimTaskSelectedTab flag to
303     // prevent the tab selection message to be passed on to the VimTask.
304     vimTaskSelectedTab = YES;
305     int i, count = [[self tabView] numberOfTabViewItems];
306     for (i = count-1; i >= tabIdx; --i) {
307         id tvi = [tabViewItems objectAtIndex:i];
308         //NSLog(@"Removing tab with index %d", i);
309         [[self tabView] removeTabViewItem:tvi];
310     }
311     vimTaskSelectedTab = NO;
313     [self selectTabWithIndex:curtabIdx];
316 - (void)selectTabWithIndex:(int)idx
318     //NSLog(@"%s%d", _cmd, idx);
320     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
321     if (idx < 0 || idx >= [tabViewItems count]) {
322         NSLog(@"WARNING: No tab with index %d exists.", idx);
323         return;
324     }
326     // Do not try to select a tab if already selected.
327     NSTabViewItem *tvi = [tabViewItems objectAtIndex:idx];
328     if (tvi != [[self tabView] selectedTabViewItem]) {
329         vimTaskSelectedTab = YES;
330         [[self tabView] selectTabViewItem:tvi];
331         vimTaskSelectedTab = NO;
333         // We might need to change the scrollbars that are visible.
334         [self placeScrollbars];
335     }
338 - (NSTabViewItem *)addNewTabViewItem
340     // NOTE!  A newly created tab is not by selected by default; Vim decides
341     // which tab should be selected at all times.  However, the AppKit will
342     // automatically select the first tab added to a tab view.
344     NSTabViewItem *tvi = [[NSTabViewItem alloc] initWithIdentifier:nil];
346     // NOTE: If this is the first tab it will be automatically selected.
347     vimTaskSelectedTab = YES;
348     [[self tabView] addTabViewItem:tvi];
349     vimTaskSelectedTab = NO;
351     [tvi autorelease];
353     return tvi;
356 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
358     //NSLog(@"Create scroller %d of type %d", ident, type);
360     MMScroller *scroller = [[MMScroller alloc] initWithIdentifier:ident
361                                                              type:type];
362     [scroller setTarget:self];
363     [scroller setAction:@selector(scroll:)];
365     [self addSubview:scroller];
366     [scrollbars addObject:scroller];
367     [scroller release];
370 - (BOOL)destroyScrollbarWithIdentifier:(long)ident
372     //NSLog(@"Destroy scroller %d", ident);
374     unsigned idx = 0;
375     MMScroller *scroller = [self scrollbarForIdentifier:ident index:&idx];
376     if (!scroller) return NO;
378     [scroller removeFromSuperview];
379     [scrollbars removeObjectAtIndex:idx];
381     // If a visible scroller was removed then the vim view must resize.  This
382     // is handled by the window controller (the vim view never resizes itself).
383     return ![scroller isHidden];
386 - (BOOL)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
388     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
389     if (!scroller) return NO;
391     BOOL wasVisible = ![scroller isHidden];
392     //NSLog(@"%s scroller %d (was %svisible)", visible ? "Show" : "Hide",
393     //      ident, wasVisible ? "" : "in");
394     [scroller setHidden:!visible];
396     // If a scroller was hidden or shown then the vim view must resize.  This
397     // is handled by the window controller (the vim view never resizes itself).
398     return wasVisible != visible;
401 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
402                     identifier:(long)ident
404     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
405     //NSLog(@"Set thumb value %.2f proportion %.2f for scroller %d",
406     //        val, prop, ident);
407     [scroller setFloatValue:val knobProportion:prop];
408     [scroller setEnabled:prop != 1.f];
412 - (void)scroll:(id)sender
414     NSMutableData *data = [NSMutableData data];
415     long ident = [(MMScroller*)sender identifier];
416     int hitPart = [sender hitPart];
417     float value = [sender floatValue];
419     [data appendBytes:&ident length:sizeof(long)];
420     [data appendBytes:&hitPart length:sizeof(int)];
421     [data appendBytes:&value length:sizeof(float)];
423     [vimController sendMessage:ScrollbarEventMsgID data:data];
426 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
428     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
429     NSRange range = NSMakeRange(pos, len);
430     if (!NSEqualRanges(range, [scroller range])) {
431         //NSLog(@"Set range %@ for scroller %d",
432         //        NSStringFromRange(range), ident);
433         [scroller setRange:range];
434         // TODO!  Should only do this once per update.
436         // This could be sent because a text window was created or closed, so
437         // we might need to update which scrollbars are visible.
438         [self placeScrollbars];
439     }
442 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
444     [textView setDefaultColorsBackground:back foreground:fore];
448 // -- PSMTabBarControl delegate ----------------------------------------------
451 - (BOOL)tabView:(NSTabView *)theTabView shouldSelectTabViewItem:
452     (NSTabViewItem *)tabViewItem
454     // NOTE: It would be reasonable to think that 'shouldSelect...' implies
455     // that this message only gets sent when the user clicks the tab.
456     // Unfortunately it is not so, which is why we need the
457     // 'vimTaskSelectedTab' flag.
458     //
459     // HACK!  The selection message should not be propagated to Vim if Vim
460     // selected the tab (e.g. as opposed the user clicking the tab).  The
461     // delegate method has no way of knowing who initiated the selection so a
462     // flag is set when Vim initiated the selection.
463     if (!vimTaskSelectedTab) {
464         // Propagate the selection message to Vim.
465         int idx = [self representedIndexOfTabViewItem:tabViewItem];
466         if (NSNotFound != idx) {
467             NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
468             [vimController sendMessage:SelectTabMsgID data:data];
469         }
470     }
472     // Unless Vim selected the tab, return NO, and let Vim decide if the tab
473     // should get selected or not.
474     return vimTaskSelectedTab;
477 - (BOOL)tabView:(NSTabView *)theTabView shouldCloseTabViewItem:
478         (NSTabViewItem *)tabViewItem
480     // HACK!  This method is only called when the user clicks the close button
481     // on the tab.  Instead of letting the tab bar close the tab, we return NO
482     // and pass a message on to Vim to let it handle the closing.
483     int idx = [self representedIndexOfTabViewItem:tabViewItem];
484     //NSLog(@"Closing tab with index %d", idx);
485     NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
486     [vimController sendMessage:CloseTabMsgID data:data];
488     return NO;
491 - (void)tabView:(NSTabView *)theTabView didDragTabViewItem:
492         (NSTabViewItem *)tabViewItem toIndex:(int)idx
494     NSMutableData *data = [NSMutableData data];
495     [data appendBytes:&idx length:sizeof(int)];
497     [vimController sendMessage:DraggedTabMsgID data:data];
501 // -- NSView customization ---------------------------------------------------
504 - (void)viewWillStartLiveResize
506     id windowController = [[self window] windowController];
507     [windowController liveResizeWillStart];
509     [super viewWillStartLiveResize];
512 - (void)viewDidEndLiveResize
514     id windowController = [[self window] windowController];
515     [windowController liveResizeDidEnd];
517     [super viewDidEndLiveResize];
520 - (void)setFrameSize:(NSSize)size
522     // NOTE: Instead of only acting when a frame was resized, we do some
523     // updating each time a frame may be resized.  (At the moment, if we only
524     // respond to actual frame changes then typing ":set lines=1000" twice in a
525     // row will result in the vim view holding more rows than the can fit
526     // inside the window.)
527     [super setFrameSize:size];
528     [self frameSizeMayHaveChanged];
531 - (void)setFrame:(NSRect)frame
533     // See comment in setFrameSize: above.
534     [super setFrame:frame];
535     [self frameSizeMayHaveChanged];
538 @end // MMVimView
543 @implementation MMVimView (Private)
545 - (BOOL)bottomScrollbarVisible
547     unsigned i, count = [scrollbars count];
548     for (i = 0; i < count; ++i) {
549         MMScroller *scroller = [scrollbars objectAtIndex:i];
550         if ([scroller type] == MMScrollerTypeBottom && ![scroller isHidden])
551             return YES;
552     }
554     return NO;
557 - (BOOL)leftScrollbarVisible
559     unsigned i, count = [scrollbars count];
560     for (i = 0; i < count; ++i) {
561         MMScroller *scroller = [scrollbars objectAtIndex:i];
562         if ([scroller type] == MMScrollerTypeLeft && ![scroller isHidden])
563             return YES;
564     }
566     return NO;
569 - (BOOL)rightScrollbarVisible
571     unsigned i, count = [scrollbars count];
572     for (i = 0; i < count; ++i) {
573         MMScroller *scroller = [scrollbars objectAtIndex:i];
574         if ([scroller type] == MMScrollerTypeRight && ![scroller isHidden])
575             return YES;
576     }
578     return NO;
581 - (void)placeScrollbars
583     NSRect textViewFrame = [textView frame];
584     BOOL lsbVisible = [self leftScrollbarVisible];
586     // HACK!  Find the lowest left&right vertical scrollbars, as well as the
587     // rightmost horizontal scrollbar.  This hack continues further down.
588     //
589     // TODO!  Can there be no more than one horizontal scrollbar?  If so, the
590     // code can be simplified.
591     unsigned lowestLeftSbIdx = (unsigned)-1;
592     unsigned lowestRightSbIdx = (unsigned)-1;
593     unsigned rightmostSbIdx = (unsigned)-1;
594     unsigned rowMaxLeft = 0, rowMaxRight = 0, colMax = 0;
595     unsigned i, count = [scrollbars count];
596     for (i = 0; i < count; ++i) {
597         MMScroller *scroller = [scrollbars objectAtIndex:i];
598         if (![scroller isHidden]) {
599             NSRange range = [scroller range];
600             if ([scroller type] == MMScrollerTypeLeft
601                     && range.location >= rowMaxLeft) {
602                 rowMaxLeft = range.location;
603                 lowestLeftSbIdx = i;
604             } else if ([scroller type] == MMScrollerTypeRight
605                     && range.location >= rowMaxRight) {
606                 rowMaxRight = range.location;
607                 lowestRightSbIdx = i;
608             } else if ([scroller type] == MMScrollerTypeBottom
609                     && range.location >= colMax) {
610                 colMax = range.location;
611                 rightmostSbIdx = i;
612             }
613         }
614     }
616     // Place the scrollbars.
617     for (i = 0; i < count; ++i) {
618         MMScroller *scroller = [scrollbars objectAtIndex:i];
619         if ([scroller isHidden])
620             continue;
622         NSRect rect;
623         if ([scroller type] == MMScrollerTypeBottom) {
624             rect = [textView rectForColumnsInRange:[scroller range]];
625             rect.size.height = [NSScroller scrollerWidth];
626             if (lsbVisible)
627                 rect.origin.x += [NSScroller scrollerWidth];
629             // HACK!  Make sure the rightmost horizontal scrollbar covers the
630             // text view all the way to the right, otherwise it looks ugly when
631             // the user drags the window to resize.
632             if (i == rightmostSbIdx) {
633                 float w = NSMaxX(textViewFrame) - NSMaxX(rect);
634                 if (w > 0)
635                     rect.size.width += w;
636             }
638             // Make sure scrollbar rect is bounded by the text view frame.
639             if (rect.origin.x < textViewFrame.origin.x)
640                 rect.origin.x = textViewFrame.origin.x;
641             else if (rect.origin.x > NSMaxX(textViewFrame))
642                 rect.origin.x = NSMaxX(textViewFrame);
643             if (NSMaxX(rect) > NSMaxX(textViewFrame))
644                 rect.size.width -= NSMaxX(rect) - NSMaxX(textViewFrame);
645             if (rect.size.width < 0)
646                 rect.size.width = 0;
647         } else {
648             rect = [textView rectForRowsInRange:[scroller range]];
649             // Adjust for the fact that text layout is flipped.
650             rect.origin.y = NSMaxY(textViewFrame) - rect.origin.y
651                     - rect.size.height;
652             rect.size.width = [NSScroller scrollerWidth];
653             if ([scroller type] == MMScrollerTypeRight)
654                 rect.origin.x = NSMaxX(textViewFrame);
656             // HACK!  Make sure the lowest vertical scrollbar covers the text
657             // view all the way to the bottom.  This is done because Vim only
658             // makes the scrollbar cover the (vim-)window it is associated with
659             // and this means there is always an empty gap in the scrollbar
660             // region next to the command line.
661             // TODO!  Find a nicer way to do this.
662             if (i == lowestLeftSbIdx || i == lowestRightSbIdx) {
663                 float h = rect.origin.y + rect.size.height
664                           - textViewFrame.origin.y;
665                 if (rect.size.height < h) {
666                     rect.origin.y = textViewFrame.origin.y;
667                     rect.size.height = h;
668                 }
669             }
671             // Vertical scrollers must not cover the resize box in the
672             // bottom-right corner of the window.
673             if ([[self window] showsResizeIndicator]  // XXX: make this a flag
674                 && rect.origin.y < [NSScroller scrollerWidth]) {
675                 rect.size.height -= [NSScroller scrollerWidth] - rect.origin.y;
676                 rect.origin.y = [NSScroller scrollerWidth];
677             }
679             // Make sure scrollbar rect is bounded by the text view frame.
680             if (rect.origin.y < textViewFrame.origin.y) {
681                 rect.size.height -= textViewFrame.origin.y - rect.origin.y;
682                 rect.origin.y = textViewFrame.origin.y;
683             } else if (rect.origin.y > NSMaxY(textViewFrame))
684                 rect.origin.y = NSMaxY(textViewFrame);
685             if (NSMaxY(rect) > NSMaxY(textViewFrame))
686                 rect.size.height -= NSMaxY(rect) - NSMaxY(textViewFrame);
687             if (rect.size.height < 0)
688                 rect.size.height = 0;
689         }
691         //NSLog(@"set scroller #%d frame = %@", i, NSStringFromRect(rect));
692         NSRect oldRect = [scroller frame];
693         if (!NSEqualRects(oldRect, rect)) {
694             [scroller setFrame:rect];
695             // Clear behind the old scroller frame, or parts of the old
696             // scroller might still be visible after setFrame:.
697             [[[self window] contentView] setNeedsDisplayInRect:oldRect];
698             [scroller setNeedsDisplay:YES];
699         }
700     }
703 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi
705     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
706     return [tabViewItems indexOfObject:tvi];
709 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx
711     unsigned i, count = [scrollbars count];
712     for (i = 0; i < count; ++i) {
713         MMScroller *scroller = [scrollbars objectAtIndex:i];
714         if ([scroller identifier] == ident) {
715             if (idx) *idx = i;
716             return scroller;
717         }
718     }
720     return nil;
723 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize
725     NSSize size = textViewSize;
727     if (![[self tabBarControl] isHidden])
728         size.height += [[self tabBarControl] frame].size.height;
730     if ([self bottomScrollbarVisible])
731         size.height += [NSScroller scrollerWidth];
732     if ([self leftScrollbarVisible])
733         size.width += [NSScroller scrollerWidth];
734     if ([self rightScrollbarVisible])
735         size.width += [NSScroller scrollerWidth];
737     return size;
740 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize
742     NSRect rect = { 0, 0, contentSize.width, contentSize.height };
744     if (![[self tabBarControl] isHidden])
745         rect.size.height -= [[self tabBarControl] frame].size.height;
747     if ([self bottomScrollbarVisible]) {
748         rect.size.height -= [NSScroller scrollerWidth];
749         rect.origin.y += [NSScroller scrollerWidth];
750     }
751     if ([self leftScrollbarVisible]) {
752         rect.size.width -= [NSScroller scrollerWidth];
753         rect.origin.x += [NSScroller scrollerWidth];
754     }
755     if ([self rightScrollbarVisible])
756         rect.size.width -= [NSScroller scrollerWidth];
758     return rect;
761 - (NSTabView *)tabView
763     return tabView;
766 - (void)frameSizeMayHaveChanged
768     // NOTE: Whenever a call is made that may have changed the frame size we
769     // take the opportunity to make sure all subviews are in place and that the
770     // (rows,columns) are constrained to lie inside the new frame.  We not only
771     // do this when the frame really has changed since it is possible to modify
772     // the number of (rows,columns) without changing the frame size.
774     // Give all superfluous space to the text view. It might be smaller or
775     // larger than it wants to be, but this is needed during live resizing.
776     NSRect textViewRect = [self textViewRectForVimViewSize:[self frame].size];
777     [textView setFrame:textViewRect];
779     [self placeScrollbars];
781     // It is possible that the current number of (rows,columns) is too big or
782     // too small to fit the new frame.  If so, notify Vim that the text
783     // dimensions should change, but don't actually change the number of
784     // (rows,columns).  These numbers may only change when Vim initiates the
785     // change (as opposed to the user dragging the window resizer, for
786     // example).
787     //
788     // Note that the message sent to Vim depends on whether we're in
789     // a live resize or not -- this is necessary to avoid the window jittering
790     // when the user drags to resize.
791     int constrained[2];
792     NSSize textViewSize = [textView frame].size;
793     [textView constrainRows:&constrained[0] columns:&constrained[1]
794                      toSize:textViewSize];
796     int rows, cols;
797     [textView getMaxRows:&rows columns:&cols];
799     if (constrained[0] != rows || constrained[1] != cols) {
800         NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
801         int msgid = [self inLiveResize] ? LiveResizeMsgID
802                                         : SetTextDimensionsMsgID;
804         //NSLog(@"Notify Vim that text dimensions changed from %dx%d to %dx%d"
805         //       " (%s)", cols, rows, constrained[1], constrained[0],
806         //       MessageStrings[msgid]);
808         [vimController sendMessage:msgid data:data];
810         // We only want to set the window title if this resize came from
811         // a live-resize, not (for example) setting 'columns' or 'lines'.
812         if ([self inLiveResize]) {
813             [[self window] setTitle:[NSString stringWithFormat:@"%dx%d",
814                     constrained[1], constrained[0]]];
815         }
816     }
819 @end // MMVimView (Private)
824 @implementation MMScroller
826 - (id)initWithIdentifier:(long)ident type:(int)theType
828     // HACK! NSScroller creates a horizontal scroller if it is init'ed with a
829     // frame whose with exceeds its height; so create a bogus rect and pass it
830     // to initWithFrame.
831     NSRect frame = theType == MMScrollerTypeBottom
832             ? NSMakeRect(0, 0, 1, 0)
833             : NSMakeRect(0, 0, 0, 1);
835     self = [super initWithFrame:frame];
836     if (!self) return nil;
838     identifier = ident;
839     type = theType;
840     [self setHidden:YES];
841     [self setEnabled:YES];
842     [self setAutoresizingMask:NSViewNotSizable];
844     return self;
847 - (long)identifier
849     return identifier;
852 - (int)type
854     return type;
857 - (NSRange)range
859     return range;
862 - (void)setRange:(NSRange)newRange
864     range = newRange;
867 - (void)scrollWheel:(NSEvent *)event
869     // HACK! Pass message on to the text view.
870     NSView *vimView = [self superview];
871     if ([vimView isKindOfClass:[MMVimView class]])
872         [[(MMVimView*)vimView textView] scrollWheel:event];
875 @end // MMScroller