Fix problems with 'fullscreen' and :mksession
[MacVim.git] / src / MacVim / MMVimView.m
blob79c134befd8054ef2b664670c7da71357ecb7f92
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     LOG_DEALLOC
154     [tabBarControl release];  tabBarControl = nil;
155     [tabView release];  tabView = nil;
156     [scrollbars release];  scrollbars = nil;
158     // HACK! The text storage is the principal owner of the text system, but we
159     // keep only a reference to the text view, so release the text storage
160     // first (unless we are using the ATSUI renderer).
161     if ([textView isKindOfClass:[MMTextView class]])
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 - (PSMTabBarControl *)tabBarControl
208     return tabBarControl;
211 - (void)cleanup
213     vimController = nil;
214     
215     // NOTE! There is a bug in PSMTabBarControl in that it retains the delegate
216     // so reset the delegate here, otherwise the delegate may never get
217     // released.
218     [tabView setDelegate:nil];
219     [tabBarControl setDelegate:nil];
220     [tabBarControl setTabView:nil];
221     [[self window] setDelegate:nil];
223     // NOTE! There is another bug in PSMTabBarControl where the control is not
224     // removed as an observer, so remove it here (failing to remove an observer
225     // may lead to very strange bugs).
226     [[NSNotificationCenter defaultCenter] removeObserver:tabBarControl];
228     [tabBarControl removeFromSuperviewWithoutNeedingDisplay];
229     [textView removeFromSuperviewWithoutNeedingDisplay];
231     unsigned i, count = [scrollbars count];
232     for (i = 0; i < count; ++i) {
233         MMScroller *sb = [scrollbars objectAtIndex:i];
234         [sb removeFromSuperviewWithoutNeedingDisplay];
235     }
237     [tabView removeAllTabViewItems];
240 - (NSSize)desiredSize
242     return [self vimViewSizeForTextViewSize:[textView desiredSize]];
245 - (NSSize)minSize
247     return [self vimViewSizeForTextViewSize:[textView minSize]];
250 - (NSSize)constrainRows:(int *)r columns:(int *)c toSize:(NSSize)size
252     NSSize textViewSize = [self textViewRectForVimViewSize:size].size;
253     textViewSize = [textView constrainRows:r columns:c toSize:textViewSize];
254     return [self vimViewSizeForTextViewSize:textViewSize];
257 - (void)setDesiredRows:(int)r columns:(int)c
259     [textView setMaxRows:r columns:c];
262 - (IBAction)addNewTab:(id)sender
264     [vimController sendMessage:AddNewTabMsgID data:nil];
267 - (void)updateTabsWithData:(NSData *)data
269     const void *p = [data bytes];
270     const void *end = p + [data length];
271     int tabIdx = 0;
273     // HACK!  Current tab is first in the message.  This way it is not
274     // necessary to guess which tab should be the selected one (this can be
275     // problematic for instance when new tabs are created).
276     int curtabIdx = *((int*)p);  p += sizeof(int);
278     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
280     while (p < end) {
281         //int wincount = *((int*)p);  p += sizeof(int);
282         int length = *((int*)p);  p += sizeof(int);
284         NSString *label = [[NSString alloc]
285                 initWithBytes:(void*)p length:length
286                      encoding:NSUTF8StringEncoding];
287         p += length;
289         // Set the label of the tab;  add a new tab when needed.
290         NSTabViewItem *tvi = [[self tabView] numberOfTabViewItems] <= tabIdx
291                 ? [self addNewTabViewItem]
292                 : [tabViewItems objectAtIndex:tabIdx];
294         [tvi setLabel:label];
296         [label release];
298         ++tabIdx;
299     }
301     // Remove unused tabs from the NSTabView.  Note that when a tab is closed
302     // the NSTabView will automatically select another tab, but we want Vim to
303     // take care of which tab to select so set the vimTaskSelectedTab flag to
304     // prevent the tab selection message to be passed on to the VimTask.
305     vimTaskSelectedTab = YES;
306     int i, count = [[self tabView] numberOfTabViewItems];
307     for (i = count-1; i >= tabIdx; --i) {
308         id tvi = [tabViewItems objectAtIndex:i];
309         //NSLog(@"Removing tab with index %d", i);
310         [[self tabView] removeTabViewItem:tvi];
311     }
312     vimTaskSelectedTab = NO;
314     [self selectTabWithIndex:curtabIdx];
317 - (void)selectTabWithIndex:(int)idx
319     //NSLog(@"%s%d", _cmd, idx);
321     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
322     if (idx < 0 || idx >= [tabViewItems count]) {
323         NSLog(@"WARNING: No tab with index %d exists.", idx);
324         return;
325     }
327     // Do not try to select a tab if already selected.
328     NSTabViewItem *tvi = [tabViewItems objectAtIndex:idx];
329     if (tvi != [[self tabView] selectedTabViewItem]) {
330         vimTaskSelectedTab = YES;
331         [[self tabView] selectTabViewItem:tvi];
332         vimTaskSelectedTab = NO;
334         // We might need to change the scrollbars that are visible.
335         [self placeScrollbars];
336     }
339 - (NSTabViewItem *)addNewTabViewItem
341     // NOTE!  A newly created tab is not by selected by default; Vim decides
342     // which tab should be selected at all times.  However, the AppKit will
343     // automatically select the first tab added to a tab view.
345     NSTabViewItem *tvi = [[NSTabViewItem alloc] initWithIdentifier:nil];
347     // NOTE: If this is the first tab it will be automatically selected.
348     vimTaskSelectedTab = YES;
349     [[self tabView] addTabViewItem:tvi];
350     vimTaskSelectedTab = NO;
352     [tvi autorelease];
354     return tvi;
357 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
359     //NSLog(@"Create scroller %d of type %d", ident, type);
361     MMScroller *scroller = [[MMScroller alloc] initWithIdentifier:ident
362                                                              type:type];
363     [scroller setTarget:self];
364     [scroller setAction:@selector(scroll:)];
366     [self addSubview:scroller];
367     [scrollbars addObject:scroller];
368     [scroller release];
371 - (BOOL)destroyScrollbarWithIdentifier:(long)ident
373     //NSLog(@"Destroy scroller %d", ident);
375     unsigned idx = 0;
376     MMScroller *scroller = [self scrollbarForIdentifier:ident index:&idx];
377     if (!scroller) return NO;
379     [scroller removeFromSuperview];
380     [scrollbars removeObjectAtIndex:idx];
382     // If a visible scroller was removed then the vim view must resize.  This
383     // is handled by the window controller (the vim view never resizes itself).
384     return ![scroller isHidden];
387 - (BOOL)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
389     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
390     if (!scroller) return NO;
392     BOOL wasVisible = ![scroller isHidden];
393     //NSLog(@"%s scroller %d (was %svisible)", visible ? "Show" : "Hide",
394     //      ident, wasVisible ? "" : "in");
395     [scroller setHidden:!visible];
397     // If a scroller was hidden or shown then the vim view must resize.  This
398     // is handled by the window controller (the vim view never resizes itself).
399     return wasVisible != visible;
402 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
403                     identifier:(long)ident
405     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
406     //NSLog(@"Set thumb value %.2f proportion %.2f for scroller %d",
407     //        val, prop, ident);
408     [scroller setFloatValue:val knobProportion:prop];
409     [scroller setEnabled:prop != 1.f];
413 - (void)scroll:(id)sender
415     NSMutableData *data = [NSMutableData data];
416     long ident = [(MMScroller*)sender identifier];
417     int hitPart = [sender hitPart];
418     float value = [sender floatValue];
420     [data appendBytes:&ident length:sizeof(long)];
421     [data appendBytes:&hitPart length:sizeof(int)];
422     [data appendBytes:&value length:sizeof(float)];
424     [vimController sendMessage:ScrollbarEventMsgID data:data];
427 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
429     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
430     NSRange range = NSMakeRange(pos, len);
431     if (!NSEqualRanges(range, [scroller range])) {
432         //NSLog(@"Set range %@ for scroller %d",
433         //        NSStringFromRange(range), ident);
434         [scroller setRange:range];
435         // TODO!  Should only do this once per update.
437         // This could be sent because a text window was created or closed, so
438         // we might need to update which scrollbars are visible.
439         [self placeScrollbars];
440     }
443 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
445     [textView setDefaultColorsBackground:back foreground:fore];
449 // -- PSMTabBarControl delegate ----------------------------------------------
452 - (BOOL)tabView:(NSTabView *)theTabView shouldSelectTabViewItem:
453     (NSTabViewItem *)tabViewItem
455     // NOTE: It would be reasonable to think that 'shouldSelect...' implies
456     // that this message only gets sent when the user clicks the tab.
457     // Unfortunately it is not so, which is why we need the
458     // 'vimTaskSelectedTab' flag.
459     //
460     // HACK!  The selection message should not be propagated to Vim if Vim
461     // selected the tab (e.g. as opposed the user clicking the tab).  The
462     // delegate method has no way of knowing who initiated the selection so a
463     // flag is set when Vim initiated the selection.
464     if (!vimTaskSelectedTab) {
465         // Propagate the selection message to Vim.
466         int idx = [self representedIndexOfTabViewItem:tabViewItem];
467         if (NSNotFound != idx) {
468             NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
469             [vimController sendMessage:SelectTabMsgID data:data];
470         }
471     }
473     // Unless Vim selected the tab, return NO, and let Vim decide if the tab
474     // should get selected or not.
475     return vimTaskSelectedTab;
478 - (BOOL)tabView:(NSTabView *)theTabView shouldCloseTabViewItem:
479         (NSTabViewItem *)tabViewItem
481     // HACK!  This method is only called when the user clicks the close button
482     // on the tab.  Instead of letting the tab bar close the tab, we return NO
483     // and pass a message on to Vim to let it handle the closing.
484     int idx = [self representedIndexOfTabViewItem:tabViewItem];
485     //NSLog(@"Closing tab with index %d", idx);
486     NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
487     [vimController sendMessage:CloseTabMsgID data:data];
489     return NO;
492 - (void)tabView:(NSTabView *)theTabView didDragTabViewItem:
493         (NSTabViewItem *)tabViewItem toIndex:(int)idx
495     NSMutableData *data = [NSMutableData data];
496     [data appendBytes:&idx length:sizeof(int)];
498     [vimController sendMessage:DraggedTabMsgID data:data];
502 // -- NSView customization ---------------------------------------------------
505 - (void)viewWillStartLiveResize
507     id windowController = [[self window] windowController];
508     [windowController liveResizeWillStart];
510     [super viewWillStartLiveResize];
513 - (void)viewDidEndLiveResize
515     id windowController = [[self window] windowController];
516     [windowController liveResizeDidEnd];
518     [super viewDidEndLiveResize];
521 - (void)setFrameSize:(NSSize)size
523     // NOTE: Instead of only acting when a frame was resized, we do some
524     // updating each time a frame may be resized.  (At the moment, if we only
525     // respond to actual frame changes then typing ":set lines=1000" twice in a
526     // row will result in the vim view holding more rows than the can fit
527     // inside the window.)
528     [super setFrameSize:size];
529     [self frameSizeMayHaveChanged];
532 - (void)setFrame:(NSRect)frame
534     // See comment in setFrameSize: above.
535     [super setFrame:frame];
536     [self frameSizeMayHaveChanged];
539 @end // MMVimView
544 @implementation MMVimView (Private)
546 - (BOOL)bottomScrollbarVisible
548     unsigned i, count = [scrollbars count];
549     for (i = 0; i < count; ++i) {
550         MMScroller *scroller = [scrollbars objectAtIndex:i];
551         if ([scroller type] == MMScrollerTypeBottom && ![scroller isHidden])
552             return YES;
553     }
555     return NO;
558 - (BOOL)leftScrollbarVisible
560     unsigned i, count = [scrollbars count];
561     for (i = 0; i < count; ++i) {
562         MMScroller *scroller = [scrollbars objectAtIndex:i];
563         if ([scroller type] == MMScrollerTypeLeft && ![scroller isHidden])
564             return YES;
565     }
567     return NO;
570 - (BOOL)rightScrollbarVisible
572     unsigned i, count = [scrollbars count];
573     for (i = 0; i < count; ++i) {
574         MMScroller *scroller = [scrollbars objectAtIndex:i];
575         if ([scroller type] == MMScrollerTypeRight && ![scroller isHidden])
576             return YES;
577     }
579     return NO;
582 - (void)placeScrollbars
584     NSRect textViewFrame = [textView frame];
585     BOOL lsbVisible = [self leftScrollbarVisible];
587     // HACK!  Find the lowest left&right vertical scrollbars, as well as the
588     // rightmost horizontal scrollbar.  This hack continues further down.
589     //
590     // TODO!  Can there be no more than one horizontal scrollbar?  If so, the
591     // code can be simplified.
592     unsigned lowestLeftSbIdx = (unsigned)-1;
593     unsigned lowestRightSbIdx = (unsigned)-1;
594     unsigned rightmostSbIdx = (unsigned)-1;
595     unsigned rowMaxLeft = 0, rowMaxRight = 0, colMax = 0;
596     unsigned i, count = [scrollbars count];
597     for (i = 0; i < count; ++i) {
598         MMScroller *scroller = [scrollbars objectAtIndex:i];
599         if (![scroller isHidden]) {
600             NSRange range = [scroller range];
601             if ([scroller type] == MMScrollerTypeLeft
602                     && range.location >= rowMaxLeft) {
603                 rowMaxLeft = range.location;
604                 lowestLeftSbIdx = i;
605             } else if ([scroller type] == MMScrollerTypeRight
606                     && range.location >= rowMaxRight) {
607                 rowMaxRight = range.location;
608                 lowestRightSbIdx = i;
609             } else if ([scroller type] == MMScrollerTypeBottom
610                     && range.location >= colMax) {
611                 colMax = range.location;
612                 rightmostSbIdx = i;
613             }
614         }
615     }
617     // Place the scrollbars.
618     for (i = 0; i < count; ++i) {
619         MMScroller *scroller = [scrollbars objectAtIndex:i];
620         if ([scroller isHidden])
621             continue;
623         NSRect rect;
624         if ([scroller type] == MMScrollerTypeBottom) {
625             rect = [textView rectForColumnsInRange:[scroller range]];
626             rect.size.height = [NSScroller scrollerWidth];
627             if (lsbVisible)
628                 rect.origin.x += [NSScroller scrollerWidth];
630             // HACK!  Make sure the rightmost horizontal scrollbar covers the
631             // text view all the way to the right, otherwise it looks ugly when
632             // the user drags the window to resize.
633             if (i == rightmostSbIdx) {
634                 float w = NSMaxX(textViewFrame) - NSMaxX(rect);
635                 if (w > 0)
636                     rect.size.width += w;
637             }
639             // Make sure scrollbar rect is bounded by the text view frame.
640             if (rect.origin.x < textViewFrame.origin.x)
641                 rect.origin.x = textViewFrame.origin.x;
642             else if (rect.origin.x > NSMaxX(textViewFrame))
643                 rect.origin.x = NSMaxX(textViewFrame);
644             if (NSMaxX(rect) > NSMaxX(textViewFrame))
645                 rect.size.width -= NSMaxX(rect) - NSMaxX(textViewFrame);
646             if (rect.size.width < 0)
647                 rect.size.width = 0;
648         } else {
649             rect = [textView rectForRowsInRange:[scroller range]];
650             // Adjust for the fact that text layout is flipped.
651             rect.origin.y = NSMaxY(textViewFrame) - rect.origin.y
652                     - rect.size.height;
653             rect.size.width = [NSScroller scrollerWidth];
654             if ([scroller type] == MMScrollerTypeRight)
655                 rect.origin.x = NSMaxX(textViewFrame);
657             // HACK!  Make sure the lowest vertical scrollbar covers the text
658             // view all the way to the bottom.  This is done because Vim only
659             // makes the scrollbar cover the (vim-)window it is associated with
660             // and this means there is always an empty gap in the scrollbar
661             // region next to the command line.
662             // TODO!  Find a nicer way to do this.
663             if (i == lowestLeftSbIdx || i == lowestRightSbIdx) {
664                 float h = rect.origin.y + rect.size.height
665                           - textViewFrame.origin.y;
666                 if (rect.size.height < h) {
667                     rect.origin.y = textViewFrame.origin.y;
668                     rect.size.height = h;
669                 }
670             }
672             // Vertical scrollers must not cover the resize box in the
673             // bottom-right corner of the window.
674             if ([[self window] showsResizeIndicator]  // XXX: make this a flag
675                 && rect.origin.y < [NSScroller scrollerWidth]) {
676                 rect.size.height -= [NSScroller scrollerWidth] - rect.origin.y;
677                 rect.origin.y = [NSScroller scrollerWidth];
678             }
680             // Make sure scrollbar rect is bounded by the text view frame.
681             if (rect.origin.y < textViewFrame.origin.y) {
682                 rect.size.height -= textViewFrame.origin.y - rect.origin.y;
683                 rect.origin.y = textViewFrame.origin.y;
684             } else if (rect.origin.y > NSMaxY(textViewFrame))
685                 rect.origin.y = NSMaxY(textViewFrame);
686             if (NSMaxY(rect) > NSMaxY(textViewFrame))
687                 rect.size.height -= NSMaxY(rect) - NSMaxY(textViewFrame);
688             if (rect.size.height < 0)
689                 rect.size.height = 0;
690         }
692         //NSLog(@"set scroller #%d frame = %@", i, NSStringFromRect(rect));
693         NSRect oldRect = [scroller frame];
694         if (!NSEqualRects(oldRect, rect)) {
695             [scroller setFrame:rect];
696             // Clear behind the old scroller frame, or parts of the old
697             // scroller might still be visible after setFrame:.
698             [[[self window] contentView] setNeedsDisplayInRect:oldRect];
699             [scroller setNeedsDisplay:YES];
700         }
701     }
704 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi
706     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
707     return [tabViewItems indexOfObject:tvi];
710 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx
712     unsigned i, count = [scrollbars count];
713     for (i = 0; i < count; ++i) {
714         MMScroller *scroller = [scrollbars objectAtIndex:i];
715         if ([scroller identifier] == ident) {
716             if (idx) *idx = i;
717             return scroller;
718         }
719     }
721     return nil;
724 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize
726     NSSize size = textViewSize;
728     if (![[self tabBarControl] isHidden])
729         size.height += [[self tabBarControl] frame].size.height;
731     if ([self bottomScrollbarVisible])
732         size.height += [NSScroller scrollerWidth];
733     if ([self leftScrollbarVisible])
734         size.width += [NSScroller scrollerWidth];
735     if ([self rightScrollbarVisible])
736         size.width += [NSScroller scrollerWidth];
738     return size;
741 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize
743     NSRect rect = { 0, 0, contentSize.width, contentSize.height };
745     if (![[self tabBarControl] isHidden])
746         rect.size.height -= [[self tabBarControl] frame].size.height;
748     if ([self bottomScrollbarVisible]) {
749         rect.size.height -= [NSScroller scrollerWidth];
750         rect.origin.y += [NSScroller scrollerWidth];
751     }
752     if ([self leftScrollbarVisible]) {
753         rect.size.width -= [NSScroller scrollerWidth];
754         rect.origin.x += [NSScroller scrollerWidth];
755     }
756     if ([self rightScrollbarVisible])
757         rect.size.width -= [NSScroller scrollerWidth];
759     return rect;
762 - (NSTabView *)tabView
764     return tabView;
767 - (void)frameSizeMayHaveChanged
769     // NOTE: Whenever a call is made that may have changed the frame size we
770     // take the opportunity to make sure all subviews are in place and that the
771     // (rows,columns) are constrained to lie inside the new frame.  We not only
772     // do this when the frame really has changed since it is possible to modify
773     // the number of (rows,columns) without changing the frame size.
775     // Give all superfluous space to the text view. It might be smaller or
776     // larger than it wants to be, but this is needed during live resizing.
777     NSRect textViewRect = [self textViewRectForVimViewSize:[self frame].size];
778     [textView setFrame:textViewRect];
780     [self placeScrollbars];
782     // It is possible that the current number of (rows,columns) is too big or
783     // too small to fit the new frame.  If so, notify Vim that the text
784     // dimensions should change, but don't actually change the number of
785     // (rows,columns).  These numbers may only change when Vim initiates the
786     // change (as opposed to the user dragging the window resizer, for
787     // example).
788     //
789     // Note that the message sent to Vim depends on whether we're in
790     // a live resize or not -- this is necessary to avoid the window jittering
791     // when the user drags to resize.
792     int constrained[2];
793     NSSize textViewSize = [textView frame].size;
794     [textView constrainRows:&constrained[0] columns:&constrained[1]
795                      toSize:textViewSize];
797     int rows, cols;
798     [textView getMaxRows:&rows columns:&cols];
800     if (constrained[0] != rows || constrained[1] != cols) {
801         NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
802         int msgid = [self inLiveResize] ? LiveResizeMsgID
803                                         : SetTextDimensionsMsgID;
805         //NSLog(@"Notify Vim that text dimensions changed from %dx%d to %dx%d"
806         //       " (%s)", cols, rows, constrained[1], constrained[0],
807         //       MessageStrings[msgid]);
809         [vimController sendMessage:msgid data:data];
811         // We only want to set the window title if this resize came from
812         // a live-resize, not (for example) setting 'columns' or 'lines'.
813         if ([self inLiveResize]) {
814             [[self window] setTitle:[NSString stringWithFormat:@"%dx%d",
815                     constrained[1], constrained[0]]];
816         }
817     }
820 @end // MMVimView (Private)
825 @implementation MMScroller
827 - (id)initWithIdentifier:(long)ident type:(int)theType
829     // HACK! NSScroller creates a horizontal scroller if it is init'ed with a
830     // frame whose with exceeds its height; so create a bogus rect and pass it
831     // to initWithFrame.
832     NSRect frame = theType == MMScrollerTypeBottom
833             ? NSMakeRect(0, 0, 1, 0)
834             : NSMakeRect(0, 0, 0, 1);
836     self = [super initWithFrame:frame];
837     if (!self) return nil;
839     identifier = ident;
840     type = theType;
841     [self setHidden:YES];
842     [self setEnabled:YES];
843     [self setAutoresizingMask:NSViewNotSizable];
845     return self;
848 - (long)identifier
850     return identifier;
853 - (int)type
855     return type;
858 - (NSRange)range
860     return range;
863 - (void)setRange:(NSRange)newRange
865     range = newRange;
868 - (void)scrollWheel:(NSEvent *)event
870     // HACK! Pass message on to the text view.
871     NSView *vimView = [self superview];
872     if ([vimView isKindOfClass:[MMVimView class]])
873         [[(MMVimView*)vimView textView] scrollWheel:event];
876 @end // MMScroller