Window and view refactoring
[MacVim.git] / src / MacVim / MMVimView.m
blob693565745033b80e06d5518c4a80d915878384cb
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 "MMVimView.h"
23 #import <PSMTabBarControl.h>
24 #import "MacVim.h"
25 #import "MMTextView.h"
26 #import "MMVimController.h"
27 #import "MMAtsuiTextView.h"
31 // Scroller type; these must match SBAR_* in gui.h
32 enum {
33     MMScrollerTypeLeft = 0,
34     MMScrollerTypeRight,
35     MMScrollerTypeBottom
38 // TODO:  Move!
39 @interface NSTabView (MMExtras)
40 - (void)removeAllTabViewItems;
41 @end
44 // TODO:  Move!
45 @interface MMScroller : NSScroller {
46     long identifier;
47     int type;
48     NSRange range;
50 - (id)initWithIdentifier:(long)ident type:(int)type;
51 - (long)identifier;
52 - (int)type;
53 - (NSRange)range;
54 - (void)setRange:(NSRange)newRange;
55 @end
58 @interface MMVimView (Private)
59 - (BOOL)bottomScrollbarVisible;
60 - (BOOL)leftScrollbarVisible;
61 - (BOOL)rightScrollbarVisible;
62 - (void)placeScrollbars;
63 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi;
64 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx;
65 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize;
66 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize;
67 - (NSTabView *)tabView;
68 - (void)frameSizeMayHaveChanged;
69 @end
72 // This is an informal protocol implemented by MMWindowController (maybe it
73 // shold be a formal protocol, but ...).
74 @interface NSWindowController (MMVimViewDelegate)
75 - (void)liveResizeWillStart;
76 - (void)liveResizeDidEnd;
77 @end
81 @implementation MMVimView
83 - (MMVimView *)initWithFrame:(NSRect)frame
84                vimController:(MMVimController *)controller
86     if (![super initWithFrame:frame])
87         return nil;
88     
89     vimController = controller;
90     scrollbars = [[NSMutableArray alloc] init];
92     // Only the tabline is autoresized, all other subview placement is done in
93     // frameSizeMayHaveChanged.
94     [self setAutoresizesSubviews:YES];
96     if ([[NSUserDefaults standardUserDefaults] boolForKey:MMAtsuiRendererKey]) {
97         // Use ATSUI for text rendering.
98         //
99         // HACK! 'textView' has type MMTextView, but MMAtsuiTextView is not
100         // derived from MMTextView.
101         textView = [[MMAtsuiTextView alloc] initWithFrame:frame];
102     } else {
103         // Use Cocoa text system for text rendering.
104         textView = [[MMTextView alloc] initWithFrame:frame];
105     }
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     NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
127     [tabBarControl setCellMinWidth:[ud integerForKey:MMTabMinWidthKey]];
128     [tabBarControl setCellMaxWidth:[ud integerForKey:MMTabMaxWidthKey]];
129     [tabBarControl setCellOptimumWidth:
130                                      [ud integerForKey:MMTabOptimumWidthKey]];
132     [tabBarControl setShowAddTabButton:YES];
133     [[tabBarControl addTabButton] setTarget:self];
134     [[tabBarControl addTabButton] setAction:@selector(addNewTab:)];
135     [tabBarControl setAllowsDragBetweenWindows:NO];
137     [tabBarControl setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
138     
139     //[tabBarControl setPartnerView:[self textView]];
140     
141     // tab bar resizing only works if awakeFromNib is called (that's where
142     // the NSViewFrameDidChangeNotification callback is installed). Sounds like
143     // a PSMTabBarControl bug, let's live with it for now.
144     [tabBarControl awakeFromNib];
146     [self addSubview:tabBarControl];
148     return self;
151 - (void)dealloc
153     [tabBarControl release];  tabBarControl = nil;
154     [tabView release];  tabView = nil;
155     [scrollbars release];  scrollbars = nil;
157     // HACK! The text storage is the principal owner of the text system, but we
158     // keep only a reference to the text view, so release the text storage
159     // first (unless we are using the ATSUI renderer).
160     if (![[NSUserDefaults standardUserDefaults]
161             boolForKey:MMAtsuiRendererKey])
162         [[textView textStorage] release];
164     [textView release];  textView = nil;
166     [super dealloc];
169 - (void)drawRect:(NSRect)rect
171     // On Leopard, we want to have a textured window background for nice
172     // looking tabs. However, the textured window background looks really
173     // weird behind the window resize throbber, so emulate the look of an
174     // NSScrollView in the bottom right corner.
175     if (![[self window] showsResizeIndicator]  // XXX: make this a flag
176             || !([[self window] styleMask] & NSTexturedBackgroundWindowMask))
177         return;
179     int sw = [NSScroller scrollerWidth];
181     // add .5 to the pixel locations to put the lines on a pixel boundary.
182     // the top and right edges of the rect will be outside of the bounds rect
183     // and clipped away.
184     NSRect sizerRect = NSMakeRect([self bounds].size.width - sw + .5, -.5,
185             sw, sw);
186     //NSBezierPath* path = [NSBezierPath bezierPath];
187     NSBezierPath* path = [NSBezierPath bezierPathWithRect:sizerRect];
189     // On Tiger, we have color #E8E8E8 behind the resize throbber
190     // (which is windowBackgroundColor on untextured windows or controlColor in
191     // general). Terminal.app on Leopard has #FFFFFF background and #D9D9D9 as
192     // stroke. The colors below are #FFFFFF and #D4D4D4, which is close enough
193     // for me.
194     [[NSColor controlBackgroundColor] set];
195     [path fill];
197     [[NSColor secondarySelectedControlColor] set];
198     [path stroke];
201 - (MMTextView *)textView
203     return textView;
206 - (NSMutableArray *)scrollbars
208     return scrollbars;
211 - (PSMTabBarControl *)tabBarControl
213     return tabBarControl;
216 - (void)cleanup
218     vimController = nil;
219     
220     // NOTE! There is a bug in PSMTabBarControl in that it retains the delegate
221     // so reset the delegate here, otherwise the delegate may never get
222     // released.
223     [tabView setDelegate:nil];
224     [tabBarControl setDelegate:nil];
225     [tabBarControl setTabView:nil];
226     [[self window] setDelegate:nil];
228     // NOTE! There is another bug in PSMTabBarControl where the control is not
229     // removed as an observer, so remove it here (failing to remove an observer
230     // may lead to very strange bugs).
231     [[NSNotificationCenter defaultCenter] removeObserver:tabBarControl];
233     [tabBarControl removeFromSuperviewWithoutNeedingDisplay];
234     [textView removeFromSuperviewWithoutNeedingDisplay];
236     unsigned i, count = [scrollbars count];
237     for (i = 0; i < count; ++i) {
238         MMScroller *sb = [scrollbars objectAtIndex:i];
239         [sb removeFromSuperviewWithoutNeedingDisplay];
240     }
242     [tabView removeAllTabViewItems];
245 - (NSSize)desiredSize
247     return [self vimViewSizeForTextViewSize:[[self textView] desiredSize]];
250 - (NSSize)minSize
252     return [self vimViewSizeForTextViewSize:[[self textView] minSize]];
255 - (NSSize)constrainRows:(int *)r columns:(int *)c toSize:(NSSize)size
257     NSSize textViewSize = [self textViewRectForVimViewSize:size].size;
258     textViewSize = [textView constrainRows:r columns:c toSize:textViewSize];
259     return [self vimViewSizeForTextViewSize:textViewSize];
262 - (void)setDesiredRows:(int)r columns:(int)c
264     [textView setMaxRows:r columns:c];
267 - (IBAction)addNewTab:(id)sender
269     [vimController sendMessage:AddNewTabMsgID data:nil];
272 - (void)updateTabsWithData:(NSData *)data
274     const void *p = [data bytes];
275     const void *end = p + [data length];
276     int tabIdx = 0;
278     // HACK!  Current tab is first in the message.  This way it is not
279     // necessary to guess which tab should be the selected one (this can be
280     // problematic for instance when new tabs are created).
281     int curtabIdx = *((int*)p);  p += sizeof(int);
283     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
285     while (p < end) {
286         //int wincount = *((int*)p);  p += sizeof(int);
287         int length = *((int*)p);  p += sizeof(int);
289         NSString *label = [[NSString alloc]
290                 initWithBytesNoCopy:(void*)p
291                              length:length
292                            encoding:NSUTF8StringEncoding
293                        freeWhenDone:NO];
294         p += length;
296         // Set the label of the tab;  add a new tab when needed.
297         NSTabViewItem *tvi = [[self tabView] numberOfTabViewItems] <= tabIdx
298                 ? [self addNewTabViewItem]
299                 : [tabViewItems objectAtIndex:tabIdx];
301         [tvi setLabel:label];
303         [label release];
305         ++tabIdx;
306     }
308     // Remove unused tabs from the NSTabView.  Note that when a tab is closed
309     // the NSTabView will automatically select another tab, but we want Vim to
310     // take care of which tab to select so set the vimTaskSelectedTab flag to
311     // prevent the tab selection message to be passed on to the VimTask.
312     vimTaskSelectedTab = YES;
313     int i, count = [[self tabView] numberOfTabViewItems];
314     for (i = count-1; i >= tabIdx; --i) {
315         id tvi = [tabViewItems objectAtIndex:i];
316         //NSLog(@"Removing tab with index %d", i);
317         [[self tabView] removeTabViewItem:tvi];
318     }
319     vimTaskSelectedTab = NO;
321     [self selectTabWithIndex:curtabIdx];
324 - (void)selectTabWithIndex:(int)idx
326     //NSLog(@"%s%d", _cmd, idx);
328     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
329     if (idx < 0 || idx >= [tabViewItems count]) {
330         NSLog(@"WARNING: No tab with index %d exists.", idx);
331         return;
332     }
334     // Do not try to select a tab if already selected.
335     NSTabViewItem *tvi = [tabViewItems objectAtIndex:idx];
336     if (tvi != [[self tabView] selectedTabViewItem]) {
337         vimTaskSelectedTab = YES;
338         [[self tabView] selectTabViewItem:tvi];
339         vimTaskSelectedTab = NO;
341         // We might need to change the scrollbars that are visible.
342         [self placeScrollbars];
343     }
346 - (NSTabViewItem *)addNewTabViewItem
348     // NOTE!  A newly created tab is not by selected by default; Vim decides
349     // which tab should be selected at all times.  However, the AppKit will
350     // automatically select the first tab added to a tab view.
352     NSTabViewItem *tvi = [[NSTabViewItem alloc] initWithIdentifier:nil];
354     // NOTE: If this is the first tab it will be automatically selected.
355     vimTaskSelectedTab = YES;
356     [[self tabView] addTabViewItem:tvi];
357     vimTaskSelectedTab = NO;
359     [tvi release];
361     return tvi;
364 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
366     //NSLog(@"Create scroller %d of type %d", ident, type);
368     MMScroller *scroller = [[MMScroller alloc] initWithIdentifier:ident
369                                                              type:type];
370     [scroller setTarget:self];
371     [scroller setAction:@selector(scroll:)];
373     [self addSubview:scroller];
374     [[self scrollbars] addObject:scroller];
375     [scroller release];
378 - (BOOL)destroyScrollbarWithIdentifier:(long)ident
380     //NSLog(@"Destroy scroller %d", ident);
382     unsigned idx = 0;
383     MMScroller *scroller = [self scrollbarForIdentifier:ident index:&idx];
384     if (!scroller) return NO;
386     [scroller removeFromSuperview];
387     [[self scrollbars] removeObjectAtIndex:idx];
389     // If a visible scroller was removed then the vim view must resize.  This
390     // is handled by the window controller (the vim view never resizes itself).
391     return ![scroller isHidden];
394 - (BOOL)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
396     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
397     if (!scroller) return NO;
399     BOOL wasVisible = ![scroller isHidden];
400     //NSLog(@"%s scroller %d (was %svisible)", visible ? "Show" : "Hide",
401     //      ident, wasVisible ? "" : "in");
402     [scroller setHidden:!visible];
404     // If a scroller was hidden or shown then the vim view must resize.  This
405     // is handled by the window controller (the vim view never resizes itself).
406     return wasVisible != visible;
409 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
410                     identifier:(long)ident
412     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
413     //NSLog(@"Set thumb value %.2f proportion %.2f for scroller %d",
414     //        val, prop, ident);
415     [scroller setFloatValue:val knobProportion:prop];
416     [scroller setEnabled:prop != 1.f];
420 - (void)scroll:(id)sender
422     NSMutableData *data = [NSMutableData data];
423     long ident = [(MMScroller*)sender identifier];
424     int hitPart = [sender hitPart];
425     float value = [sender floatValue];
427     [data appendBytes:&ident length:sizeof(long)];
428     [data appendBytes:&hitPart length:sizeof(int)];
429     [data appendBytes:&value length:sizeof(float)];
431     [vimController sendMessage:ScrollbarEventMsgID data:data];
434 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
436     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
437     NSRange range = NSMakeRange(pos, len);
438     if (!NSEqualRanges(range, [scroller range])) {
439         //NSLog(@"Set range %@ for scroller %d",
440         //        NSStringFromRange(range), ident);
441         [scroller setRange:range];
442         // TODO!  Should only do this once per update.
444         // This could be sent because a text window was created or closed, so
445         // we might need to update which scrollbars are visible.
446         [self placeScrollbars];
447     }
450 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
452     [textView setDefaultColorsBackground:back foreground:fore];
456 // -- PSMTabBarControl delegate ----------------------------------------------
459 - (BOOL)tabView:(NSTabView *)theTabView shouldSelectTabViewItem:
460     (NSTabViewItem *)tabViewItem
462     // NOTE: It would be reasonable to think that 'shouldSelect...' implies
463     // that this message only gets sent when the user clicks the tab.
464     // Unfortunately it is not so, which is why we need the
465     // 'vimTaskSelectedTab' flag.
466     //
467     // HACK!  The selection message should not be propagated to Vim if Vim
468     // selected the tab (e.g. as opposed the user clicking the tab).  The
469     // delegate method has no way of knowing who initiated the selection so a
470     // flag is set when Vim initiated the selection.
471     if (!vimTaskSelectedTab) {
472         // Propagate the selection message to Vim.
473         int idx = [self representedIndexOfTabViewItem:tabViewItem];
474         if (NSNotFound != idx) {
475             NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
476             [vimController sendMessage:SelectTabMsgID data:data];
477         }
478     }
480     // Unless Vim selected the tab, return NO, and let Vim decide if the tab
481     // should get selected or not.
482     return vimTaskSelectedTab;
485 - (BOOL)tabView:(NSTabView *)theTabView shouldCloseTabViewItem:
486         (NSTabViewItem *)tabViewItem
488     // HACK!  This method is only called when the user clicks the close button
489     // on the tab.  Instead of letting the tab bar close the tab, we return NO
490     // and pass a message on to Vim to let it handle the closing.
491     int idx = [self representedIndexOfTabViewItem:tabViewItem];
492     //NSLog(@"Closing tab with index %d", idx);
493     NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
494     [vimController sendMessage:CloseTabMsgID data:data];
496     return NO;
499 - (void)tabView:(NSTabView *)theTabView didDragTabViewItem:
500         (NSTabViewItem *)tabViewItem toIndex:(int)idx
502     NSMutableData *data = [NSMutableData data];
503     [data appendBytes:&idx length:sizeof(int)];
505     [vimController sendMessage:DraggedTabMsgID data:data];
509 // -- NSView customization ---------------------------------------------------
512 - (void)viewWillStartLiveResize
514     id windowController = [[self window] windowController];
515     [windowController liveResizeWillStart];
517     [super viewWillStartLiveResize];
520 - (void)viewDidEndLiveResize
522     id windowController = [[self window] windowController];
523     [windowController liveResizeDidEnd];
525     [super viewDidEndLiveResize];
528 - (void)setFrameSize:(NSSize)size
530     // NOTE: Instead of only acting when a frame was resized, we do some
531     // updating each time a frame may be resized.  (At the moment, if we only
532     // respond to actual frame changes then typing ":set lines=1000" twice in a
533     // row will result in the vim view holding more rows than the can fit
534     // inside the window.)
535     [super setFrameSize:size];
536     [self frameSizeMayHaveChanged];
539 - (void)setFrame:(NSRect)frame
541     // See comment in setFrameSize: above.
542     [super setFrame:frame];
543     [self frameSizeMayHaveChanged];
546 @end // MMVimView
551 @implementation MMVimView (Private)
553 - (BOOL)bottomScrollbarVisible
555     unsigned i, count = [scrollbars count];
556     for (i = 0; i < count; ++i) {
557         MMScroller *scroller = [scrollbars objectAtIndex:i];
558         if ([scroller type] == MMScrollerTypeBottom && ![scroller isHidden])
559             return YES;
560     }
562     return NO;
565 - (BOOL)leftScrollbarVisible
567     unsigned i, count = [scrollbars count];
568     for (i = 0; i < count; ++i) {
569         MMScroller *scroller = [scrollbars objectAtIndex:i];
570         if ([scroller type] == MMScrollerTypeLeft && ![scroller isHidden])
571             return YES;
572     }
574     return NO;
577 - (BOOL)rightScrollbarVisible
579     unsigned i, count = [scrollbars count];
580     for (i = 0; i < count; ++i) {
581         MMScroller *scroller = [scrollbars objectAtIndex:i];
582         if ([scroller type] == MMScrollerTypeRight && ![scroller isHidden])
583             return YES;
584     }
586     return NO;
589 - (void)placeScrollbars
591     NSRect textViewFrame = [textView frame];
592     BOOL lsbVisible = [self leftScrollbarVisible];
594     // HACK!  Find the lowest left&right vertical scrollbars, as well as the
595     // rightmost horizontal scrollbar.  This hack continues further down.
596     //
597     // TODO!  Can there be no more than one horizontal scrollbar?  If so, the
598     // code can be simplified.
599     unsigned lowestLeftSbIdx = (unsigned)-1;
600     unsigned lowestRightSbIdx = (unsigned)-1;
601     unsigned rightmostSbIdx = (unsigned)-1;
602     unsigned rowMaxLeft = 0, rowMaxRight = 0, colMax = 0;
603     unsigned i, count = [scrollbars count];
604     for (i = 0; i < count; ++i) {
605         MMScroller *scroller = [scrollbars objectAtIndex:i];
606         if (![scroller isHidden]) {
607             NSRange range = [scroller range];
608             if ([scroller type] == MMScrollerTypeLeft
609                     && range.location >= rowMaxLeft) {
610                 rowMaxLeft = range.location;
611                 lowestLeftSbIdx = i;
612             } else if ([scroller type] == MMScrollerTypeRight
613                     && range.location >= rowMaxRight) {
614                 rowMaxRight = range.location;
615                 lowestRightSbIdx = i;
616             } else if ([scroller type] == MMScrollerTypeBottom
617                     && range.location >= colMax) {
618                 colMax = range.location;
619                 rightmostSbIdx = i;
620             }
621         }
622     }
624     // Place the scrollbars.
625     for (i = 0; i < count; ++i) {
626         MMScroller *scroller = [scrollbars objectAtIndex:i];
627         if ([scroller isHidden])
628             continue;
630         NSRect rect;
631         if ([scroller type] == MMScrollerTypeBottom) {
632             rect = [textView rectForColumnsInRange:[scroller range]];
633             rect.size.height = [NSScroller scrollerWidth];
634             if (lsbVisible)
635                 rect.origin.x += [NSScroller scrollerWidth];
637             // HACK!  Make sure the rightmost horizontal scrollbar covers the
638             // text view all the way to the right, otherwise it looks ugly when
639             // the user drags the window to resize.
640             if (i == rightmostSbIdx) {
641                 float w = NSMaxX(textViewFrame) - NSMaxX(rect);
642                 if (w > 0)
643                     rect.size.width += w;
644             }
646             // Make sure scrollbar rect is bounded by the text view frame.
647             if (rect.origin.x < textViewFrame.origin.x)
648                 rect.origin.x = textViewFrame.origin.x;
649             else if (rect.origin.x > NSMaxX(textViewFrame))
650                 rect.origin.x = NSMaxX(textViewFrame);
651             if (NSMaxX(rect) > NSMaxX(textViewFrame))
652                 rect.size.width -= NSMaxX(rect) - NSMaxX(textViewFrame);
653             if (rect.size.width < 0)
654                 rect.size.width = 0;
655         } else {
656             rect = [textView rectForRowsInRange:[scroller range]];
657             // Adjust for the fact that text layout is flipped.
658             rect.origin.y = NSMaxY(textViewFrame) - rect.origin.y
659                     - rect.size.height;
660             rect.size.width = [NSScroller scrollerWidth];
661             if ([scroller type] == MMScrollerTypeRight)
662                 rect.origin.x = NSMaxX(textViewFrame);
664             // HACK!  Make sure the lowest vertical scrollbar covers the text
665             // view all the way to the bottom.  This is done because Vim only
666             // makes the scrollbar cover the (vim-)window it is associated with
667             // and this means there is always an empty gap in the scrollbar
668             // region next to the command line.
669             // TODO!  Find a nicer way to do this.
670             if (i == lowestLeftSbIdx || i == lowestRightSbIdx) {
671                 float h = rect.origin.y + rect.size.height
672                           - textViewFrame.origin.y;
673                 if (rect.size.height < h) {
674                     rect.origin.y = textViewFrame.origin.y;
675                     rect.size.height = h;
676                 }
677             }
679             // Vertical scrollers must not cover the resize box in the
680             // bottom-right corner of the window.
681             if ([[self window] showsResizeIndicator]  // XXX: make this a flag
682                 && rect.origin.y < [NSScroller scrollerWidth]) {
683                 rect.size.height -= [NSScroller scrollerWidth] - rect.origin.y;
684                 rect.origin.y = [NSScroller scrollerWidth];
685             }
687             // Make sure scrollbar rect is bounded by the text view frame.
688             if (rect.origin.y < textViewFrame.origin.y) {
689                 rect.size.height -= textViewFrame.origin.y - rect.origin.y;
690                 rect.origin.y = textViewFrame.origin.y;
691             } else if (rect.origin.y > NSMaxY(textViewFrame))
692                 rect.origin.y = NSMaxY(textViewFrame);
693             if (NSMaxY(rect) > NSMaxY(textViewFrame))
694                 rect.size.height -= NSMaxY(rect) - NSMaxY(textViewFrame);
695             if (rect.size.height < 0)
696                 rect.size.height = 0;
697         }
699         //NSLog(@"set scroller #%d frame = %@", i, NSStringFromRect(rect));
700         NSRect oldRect = [scroller frame];
701         if (!NSEqualRects(oldRect, rect)) {
702             [scroller setFrame:rect];
703             // Clear behind the old scroller frame, or parts of the old
704             // scroller might still be visible after setFrame:.
705             [[[self window] contentView] setNeedsDisplayInRect:oldRect];
706             [scroller setNeedsDisplay:YES];
707         }
708     }
711 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi
713     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
714     return [tabViewItems indexOfObject:tvi];
717 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx
719     unsigned i, count = [[self scrollbars] count];
720     for (i = 0; i < count; ++i) {
721         MMScroller *scroller = [[self scrollbars] objectAtIndex:i];
722         if ([scroller identifier] == ident) {
723             if (idx) *idx = i;
724             return scroller;
725         }
726     }
728     return nil;
731 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize
733     NSSize size = textViewSize;
735     if (![[self tabBarControl] isHidden])
736         size.height += [[self tabBarControl] frame].size.height;
738     if ([self bottomScrollbarVisible])
739         size.height += [NSScroller scrollerWidth];
740     if ([self leftScrollbarVisible])
741         size.width += [NSScroller scrollerWidth];
742     if ([self rightScrollbarVisible])
743         size.width += [NSScroller scrollerWidth];
745     return size;
748 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize
750     NSRect rect = { 0, 0, contentSize.width, contentSize.height };
752     if (![[self tabBarControl] isHidden])
753         rect.size.height -= [[self tabBarControl] frame].size.height;
755     if ([self bottomScrollbarVisible]) {
756         rect.size.height -= [NSScroller scrollerWidth];
757         rect.origin.y += [NSScroller scrollerWidth];
758     }
759     if ([self leftScrollbarVisible]) {
760         rect.size.width -= [NSScroller scrollerWidth];
761         rect.origin.x += [NSScroller scrollerWidth];
762     }
763     if ([self rightScrollbarVisible])
764         rect.size.width -= [NSScroller scrollerWidth];
766     return rect;
769 - (NSTabView *)tabView
771     return tabView;
774 - (void)frameSizeMayHaveChanged
776     // NOTE: Whenever a call is made that may have changed the frame size we
777     // take the opportunity to make sure all subviews are in place and that the
778     // (rows,columns) are constrained to lie inside the new frame.  We not only
779     // do this when the frame really has changed since it is possible to modify
780     // the number of (rows,columns) without changing the frame size.
782     // Give all superfluous space to the text view. It might be smaller or
783     // larger than it wants to be, but this is needed during live resizing.
784     NSRect textViewRect = [self textViewRectForVimViewSize:[self frame].size];
785     [[self textView] setFrame:textViewRect];
787     [self placeScrollbars];
789     // It is possible that the current number of (rows,columns) is too big or
790     // too small to fit the new frame.  If so, notify Vim that the text
791     // dimensions should change, but don't actually change the number of
792     // (rows,columns).  These numbers may only change when Vim initiates the
793     // change (as opposed to the user dragging the window resizer, for
794     // example).
795     //
796     // Note that the message sent to Vim depends on whether we're in
797     // a live resize or not -- this is necessary to avoid the window jittering
798     // when the user drags to resize.
799     int constrained[2];
800     NSSize textViewSize = [[self textView] frame].size;
801     [textView constrainRows:&constrained[0] columns:&constrained[1]
802                      toSize:textViewSize];
804     int rows, cols;
805     [textView getMaxRows:&rows columns:&cols];
807     if (constrained[0] != rows || constrained[1] != cols) {
808         NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
809         int msgid = [self inLiveResize] ? LiveResizeMsgID
810                                         : SetTextDimensionsMsgID;
812         //NSLog(@"Notify Vim that text dimensions changed from %dx%d to %dx%d"
813         //       " (%s)", cols, rows, constrained[1], constrained[0],
814         //       MessageStrings[msgid]);
816         [vimController sendMessage:msgid data:data];
818         // We only want to set the window title if this resize came from
819         // a live-resize, not (for example) setting 'columns' or 'lines'.
820         if ([self inLiveResize]) {
821             [[self window] setTitle:[NSString stringWithFormat:@"%dx%d",
822                     constrained[1], constrained[0]]];
823         }
824     }
827 @end // MMVimView (Private)
832 @implementation NSTabView (MMExtras)
834 - (void)removeAllTabViewItems
836     NSArray *existingItems = [self tabViewItems];
837     NSEnumerator *e = [existingItems objectEnumerator];
838     NSTabViewItem *item;
839     while (item = [e nextObject]){
840         [self removeTabViewItem:item];
841     }
844 @end // NSTabView (MMExtras)
849 @implementation MMScroller
851 - (id)initWithIdentifier:(long)ident type:(int)theType
853     // HACK! NSScroller creates a horizontal scroller if it is init'ed with a
854     // frame whose with exceeds its height; so create a bogus rect and pass it
855     // to initWithFrame.
856     NSRect frame = theType == MMScrollerTypeBottom
857             ? NSMakeRect(0, 0, 1, 0)
858             : NSMakeRect(0, 0, 0, 1);
860     self = [super initWithFrame:frame];
861     if (!self) return nil;
863     identifier = ident;
864     type = theType;
865     [self setHidden:YES];
866     [self setEnabled:YES];
867     [self setAutoresizingMask:NSViewNotSizable];
869     return self;
872 - (long)identifier
874     return identifier;
877 - (int)type
879     return type;
882 - (NSRange)range
884     return range;
887 - (void)setRange:(NSRange)newRange
889     range = newRange;
892 - (void)scrollWheel:(NSEvent *)event
894     // HACK! Pass message on to the text view.
895     NSView *vimView = [self superview];
896     if ([vimView isKindOfClass:[MMVimView class]])
897         [[(MMVimView*)vimView textView] scrollWheel:event];
900 @end // MMScroller