More file opening options (plus quickstart feature)
[MacVim.git] / src / MacVim / MMVimView.m
blobc76b100a87efd1456d25fc56cbd644c79439a935
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 (![[NSUserDefaults standardUserDefaults]
162             boolForKey:MMAtsuiRendererKey])
163         [[textView textStorage] release];
165     [textView release];  textView = nil;
167     [super dealloc];
170 - (void)drawRect:(NSRect)rect
172     // On Leopard, we want to have a textured window background for nice
173     // looking tabs. However, the textured window background looks really
174     // weird behind the window resize throbber, so emulate the look of an
175     // NSScrollView in the bottom right corner.
176     if (![[self window] showsResizeIndicator]  // XXX: make this a flag
177             || !([[self window] styleMask] & NSTexturedBackgroundWindowMask))
178         return;
180     int sw = [NSScroller scrollerWidth];
182     // add .5 to the pixel locations to put the lines on a pixel boundary.
183     // the top and right edges of the rect will be outside of the bounds rect
184     // and clipped away.
185     NSRect sizerRect = NSMakeRect([self bounds].size.width - sw + .5, -.5,
186             sw, sw);
187     //NSBezierPath* path = [NSBezierPath bezierPath];
188     NSBezierPath* path = [NSBezierPath bezierPathWithRect:sizerRect];
190     // On Tiger, we have color #E8E8E8 behind the resize throbber
191     // (which is windowBackgroundColor on untextured windows or controlColor in
192     // general). Terminal.app on Leopard has #FFFFFF background and #D9D9D9 as
193     // stroke. The colors below are #FFFFFF and #D4D4D4, which is close enough
194     // for me.
195     [[NSColor controlBackgroundColor] set];
196     [path fill];
198     [[NSColor secondarySelectedControlColor] set];
199     [path stroke];
202 - (MMTextView *)textView
204     return textView;
207 - (PSMTabBarControl *)tabBarControl
209     return tabBarControl;
212 - (void)cleanup
214     vimController = nil;
215     
216     // NOTE! There is a bug in PSMTabBarControl in that it retains the delegate
217     // so reset the delegate here, otherwise the delegate may never get
218     // released.
219     [tabView setDelegate:nil];
220     [tabBarControl setDelegate:nil];
221     [tabBarControl setTabView:nil];
222     [[self window] setDelegate:nil];
224     // NOTE! There is another bug in PSMTabBarControl where the control is not
225     // removed as an observer, so remove it here (failing to remove an observer
226     // may lead to very strange bugs).
227     [[NSNotificationCenter defaultCenter] removeObserver:tabBarControl];
229     [tabBarControl removeFromSuperviewWithoutNeedingDisplay];
230     [textView removeFromSuperviewWithoutNeedingDisplay];
232     unsigned i, count = [scrollbars count];
233     for (i = 0; i < count; ++i) {
234         MMScroller *sb = [scrollbars objectAtIndex:i];
235         [sb removeFromSuperviewWithoutNeedingDisplay];
236     }
238     [tabView removeAllTabViewItems];
241 - (NSSize)desiredSize
243     return [self vimViewSizeForTextViewSize:[textView desiredSize]];
246 - (NSSize)minSize
248     return [self vimViewSizeForTextViewSize:[textView minSize]];
251 - (NSSize)constrainRows:(int *)r columns:(int *)c toSize:(NSSize)size
253     NSSize textViewSize = [self textViewRectForVimViewSize:size].size;
254     textViewSize = [textView constrainRows:r columns:c toSize:textViewSize];
255     return [self vimViewSizeForTextViewSize:textViewSize];
258 - (void)setDesiredRows:(int)r columns:(int)c
260     [textView setMaxRows:r columns:c];
263 - (IBAction)addNewTab:(id)sender
265     [vimController sendMessage:AddNewTabMsgID data:nil];
268 - (void)updateTabsWithData:(NSData *)data
270     const void *p = [data bytes];
271     const void *end = p + [data length];
272     int tabIdx = 0;
274     // HACK!  Current tab is first in the message.  This way it is not
275     // necessary to guess which tab should be the selected one (this can be
276     // problematic for instance when new tabs are created).
277     int curtabIdx = *((int*)p);  p += sizeof(int);
279     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
281     while (p < end) {
282         //int wincount = *((int*)p);  p += sizeof(int);
283         int length = *((int*)p);  p += sizeof(int);
285         NSString *label = [[NSString alloc]
286                 initWithBytes:(void*)p length:length
287                      encoding:NSUTF8StringEncoding];
288         p += length;
290         // Set the label of the tab;  add a new tab when needed.
291         NSTabViewItem *tvi = [[self tabView] numberOfTabViewItems] <= tabIdx
292                 ? [self addNewTabViewItem]
293                 : [tabViewItems objectAtIndex:tabIdx];
295         [tvi setLabel:label];
297         [label release];
299         ++tabIdx;
300     }
302     // Remove unused tabs from the NSTabView.  Note that when a tab is closed
303     // the NSTabView will automatically select another tab, but we want Vim to
304     // take care of which tab to select so set the vimTaskSelectedTab flag to
305     // prevent the tab selection message to be passed on to the VimTask.
306     vimTaskSelectedTab = YES;
307     int i, count = [[self tabView] numberOfTabViewItems];
308     for (i = count-1; i >= tabIdx; --i) {
309         id tvi = [tabViewItems objectAtIndex:i];
310         //NSLog(@"Removing tab with index %d", i);
311         [[self tabView] removeTabViewItem:tvi];
312     }
313     vimTaskSelectedTab = NO;
315     [self selectTabWithIndex:curtabIdx];
318 - (void)selectTabWithIndex:(int)idx
320     //NSLog(@"%s%d", _cmd, idx);
322     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
323     if (idx < 0 || idx >= [tabViewItems count]) {
324         NSLog(@"WARNING: No tab with index %d exists.", idx);
325         return;
326     }
328     // Do not try to select a tab if already selected.
329     NSTabViewItem *tvi = [tabViewItems objectAtIndex:idx];
330     if (tvi != [[self tabView] selectedTabViewItem]) {
331         vimTaskSelectedTab = YES;
332         [[self tabView] selectTabViewItem:tvi];
333         vimTaskSelectedTab = NO;
335         // We might need to change the scrollbars that are visible.
336         [self placeScrollbars];
337     }
340 - (NSTabViewItem *)addNewTabViewItem
342     // NOTE!  A newly created tab is not by selected by default; Vim decides
343     // which tab should be selected at all times.  However, the AppKit will
344     // automatically select the first tab added to a tab view.
346     NSTabViewItem *tvi = [[NSTabViewItem alloc] initWithIdentifier:nil];
348     // NOTE: If this is the first tab it will be automatically selected.
349     vimTaskSelectedTab = YES;
350     [[self tabView] addTabViewItem:tvi];
351     vimTaskSelectedTab = NO;
353     [tvi autorelease];
355     return tvi;
358 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
360     //NSLog(@"Create scroller %d of type %d", ident, type);
362     MMScroller *scroller = [[MMScroller alloc] initWithIdentifier:ident
363                                                              type:type];
364     [scroller setTarget:self];
365     [scroller setAction:@selector(scroll:)];
367     [self addSubview:scroller];
368     [scrollbars addObject:scroller];
369     [scroller release];
372 - (BOOL)destroyScrollbarWithIdentifier:(long)ident
374     //NSLog(@"Destroy scroller %d", ident);
376     unsigned idx = 0;
377     MMScroller *scroller = [self scrollbarForIdentifier:ident index:&idx];
378     if (!scroller) return NO;
380     [scroller removeFromSuperview];
381     [scrollbars removeObjectAtIndex:idx];
383     // If a visible scroller was removed then the vim view must resize.  This
384     // is handled by the window controller (the vim view never resizes itself).
385     return ![scroller isHidden];
388 - (BOOL)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
390     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
391     if (!scroller) return NO;
393     BOOL wasVisible = ![scroller isHidden];
394     //NSLog(@"%s scroller %d (was %svisible)", visible ? "Show" : "Hide",
395     //      ident, wasVisible ? "" : "in");
396     [scroller setHidden:!visible];
398     // If a scroller was hidden or shown then the vim view must resize.  This
399     // is handled by the window controller (the vim view never resizes itself).
400     return wasVisible != visible;
403 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
404                     identifier:(long)ident
406     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
407     //NSLog(@"Set thumb value %.2f proportion %.2f for scroller %d",
408     //        val, prop, ident);
409     [scroller setFloatValue:val knobProportion:prop];
410     [scroller setEnabled:prop != 1.f];
414 - (void)scroll:(id)sender
416     NSMutableData *data = [NSMutableData data];
417     long ident = [(MMScroller*)sender identifier];
418     int hitPart = [sender hitPart];
419     float value = [sender floatValue];
421     [data appendBytes:&ident length:sizeof(long)];
422     [data appendBytes:&hitPart length:sizeof(int)];
423     [data appendBytes:&value length:sizeof(float)];
425     [vimController sendMessage:ScrollbarEventMsgID data:data];
428 - (void)setScrollbarPosition:(int)pos length:(int)len identifier:(long)ident
430     MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
431     NSRange range = NSMakeRange(pos, len);
432     if (!NSEqualRanges(range, [scroller range])) {
433         //NSLog(@"Set range %@ for scroller %d",
434         //        NSStringFromRange(range), ident);
435         [scroller setRange:range];
436         // TODO!  Should only do this once per update.
438         // This could be sent because a text window was created or closed, so
439         // we might need to update which scrollbars are visible.
440         [self placeScrollbars];
441     }
444 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
446     [textView setDefaultColorsBackground:back foreground:fore];
450 // -- PSMTabBarControl delegate ----------------------------------------------
453 - (BOOL)tabView:(NSTabView *)theTabView shouldSelectTabViewItem:
454     (NSTabViewItem *)tabViewItem
456     // NOTE: It would be reasonable to think that 'shouldSelect...' implies
457     // that this message only gets sent when the user clicks the tab.
458     // Unfortunately it is not so, which is why we need the
459     // 'vimTaskSelectedTab' flag.
460     //
461     // HACK!  The selection message should not be propagated to Vim if Vim
462     // selected the tab (e.g. as opposed the user clicking the tab).  The
463     // delegate method has no way of knowing who initiated the selection so a
464     // flag is set when Vim initiated the selection.
465     if (!vimTaskSelectedTab) {
466         // Propagate the selection message to Vim.
467         int idx = [self representedIndexOfTabViewItem:tabViewItem];
468         if (NSNotFound != idx) {
469             NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
470             [vimController sendMessage:SelectTabMsgID data:data];
471         }
472     }
474     // Unless Vim selected the tab, return NO, and let Vim decide if the tab
475     // should get selected or not.
476     return vimTaskSelectedTab;
479 - (BOOL)tabView:(NSTabView *)theTabView shouldCloseTabViewItem:
480         (NSTabViewItem *)tabViewItem
482     // HACK!  This method is only called when the user clicks the close button
483     // on the tab.  Instead of letting the tab bar close the tab, we return NO
484     // and pass a message on to Vim to let it handle the closing.
485     int idx = [self representedIndexOfTabViewItem:tabViewItem];
486     //NSLog(@"Closing tab with index %d", idx);
487     NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
488     [vimController sendMessage:CloseTabMsgID data:data];
490     return NO;
493 - (void)tabView:(NSTabView *)theTabView didDragTabViewItem:
494         (NSTabViewItem *)tabViewItem toIndex:(int)idx
496     NSMutableData *data = [NSMutableData data];
497     [data appendBytes:&idx length:sizeof(int)];
499     [vimController sendMessage:DraggedTabMsgID data:data];
503 // -- NSView customization ---------------------------------------------------
506 - (void)viewWillStartLiveResize
508     id windowController = [[self window] windowController];
509     [windowController liveResizeWillStart];
511     [super viewWillStartLiveResize];
514 - (void)viewDidEndLiveResize
516     id windowController = [[self window] windowController];
517     [windowController liveResizeDidEnd];
519     [super viewDidEndLiveResize];
522 - (void)setFrameSize:(NSSize)size
524     // NOTE: Instead of only acting when a frame was resized, we do some
525     // updating each time a frame may be resized.  (At the moment, if we only
526     // respond to actual frame changes then typing ":set lines=1000" twice in a
527     // row will result in the vim view holding more rows than the can fit
528     // inside the window.)
529     [super setFrameSize:size];
530     [self frameSizeMayHaveChanged];
533 - (void)setFrame:(NSRect)frame
535     // See comment in setFrameSize: above.
536     [super setFrame:frame];
537     [self frameSizeMayHaveChanged];
540 @end // MMVimView
545 @implementation MMVimView (Private)
547 - (BOOL)bottomScrollbarVisible
549     unsigned i, count = [scrollbars count];
550     for (i = 0; i < count; ++i) {
551         MMScroller *scroller = [scrollbars objectAtIndex:i];
552         if ([scroller type] == MMScrollerTypeBottom && ![scroller isHidden])
553             return YES;
554     }
556     return NO;
559 - (BOOL)leftScrollbarVisible
561     unsigned i, count = [scrollbars count];
562     for (i = 0; i < count; ++i) {
563         MMScroller *scroller = [scrollbars objectAtIndex:i];
564         if ([scroller type] == MMScrollerTypeLeft && ![scroller isHidden])
565             return YES;
566     }
568     return NO;
571 - (BOOL)rightScrollbarVisible
573     unsigned i, count = [scrollbars count];
574     for (i = 0; i < count; ++i) {
575         MMScroller *scroller = [scrollbars objectAtIndex:i];
576         if ([scroller type] == MMScrollerTypeRight && ![scroller isHidden])
577             return YES;
578     }
580     return NO;
583 - (void)placeScrollbars
585     NSRect textViewFrame = [textView frame];
586     BOOL lsbVisible = [self leftScrollbarVisible];
588     // HACK!  Find the lowest left&right vertical scrollbars, as well as the
589     // rightmost horizontal scrollbar.  This hack continues further down.
590     //
591     // TODO!  Can there be no more than one horizontal scrollbar?  If so, the
592     // code can be simplified.
593     unsigned lowestLeftSbIdx = (unsigned)-1;
594     unsigned lowestRightSbIdx = (unsigned)-1;
595     unsigned rightmostSbIdx = (unsigned)-1;
596     unsigned rowMaxLeft = 0, rowMaxRight = 0, colMax = 0;
597     unsigned i, count = [scrollbars count];
598     for (i = 0; i < count; ++i) {
599         MMScroller *scroller = [scrollbars objectAtIndex:i];
600         if (![scroller isHidden]) {
601             NSRange range = [scroller range];
602             if ([scroller type] == MMScrollerTypeLeft
603                     && range.location >= rowMaxLeft) {
604                 rowMaxLeft = range.location;
605                 lowestLeftSbIdx = i;
606             } else if ([scroller type] == MMScrollerTypeRight
607                     && range.location >= rowMaxRight) {
608                 rowMaxRight = range.location;
609                 lowestRightSbIdx = i;
610             } else if ([scroller type] == MMScrollerTypeBottom
611                     && range.location >= colMax) {
612                 colMax = range.location;
613                 rightmostSbIdx = i;
614             }
615         }
616     }
618     // Place the scrollbars.
619     for (i = 0; i < count; ++i) {
620         MMScroller *scroller = [scrollbars objectAtIndex:i];
621         if ([scroller isHidden])
622             continue;
624         NSRect rect;
625         if ([scroller type] == MMScrollerTypeBottom) {
626             rect = [textView rectForColumnsInRange:[scroller range]];
627             rect.size.height = [NSScroller scrollerWidth];
628             if (lsbVisible)
629                 rect.origin.x += [NSScroller scrollerWidth];
631             // HACK!  Make sure the rightmost horizontal scrollbar covers the
632             // text view all the way to the right, otherwise it looks ugly when
633             // the user drags the window to resize.
634             if (i == rightmostSbIdx) {
635                 float w = NSMaxX(textViewFrame) - NSMaxX(rect);
636                 if (w > 0)
637                     rect.size.width += w;
638             }
640             // Make sure scrollbar rect is bounded by the text view frame.
641             if (rect.origin.x < textViewFrame.origin.x)
642                 rect.origin.x = textViewFrame.origin.x;
643             else if (rect.origin.x > NSMaxX(textViewFrame))
644                 rect.origin.x = NSMaxX(textViewFrame);
645             if (NSMaxX(rect) > NSMaxX(textViewFrame))
646                 rect.size.width -= NSMaxX(rect) - NSMaxX(textViewFrame);
647             if (rect.size.width < 0)
648                 rect.size.width = 0;
649         } else {
650             rect = [textView rectForRowsInRange:[scroller range]];
651             // Adjust for the fact that text layout is flipped.
652             rect.origin.y = NSMaxY(textViewFrame) - rect.origin.y
653                     - rect.size.height;
654             rect.size.width = [NSScroller scrollerWidth];
655             if ([scroller type] == MMScrollerTypeRight)
656                 rect.origin.x = NSMaxX(textViewFrame);
658             // HACK!  Make sure the lowest vertical scrollbar covers the text
659             // view all the way to the bottom.  This is done because Vim only
660             // makes the scrollbar cover the (vim-)window it is associated with
661             // and this means there is always an empty gap in the scrollbar
662             // region next to the command line.
663             // TODO!  Find a nicer way to do this.
664             if (i == lowestLeftSbIdx || i == lowestRightSbIdx) {
665                 float h = rect.origin.y + rect.size.height
666                           - textViewFrame.origin.y;
667                 if (rect.size.height < h) {
668                     rect.origin.y = textViewFrame.origin.y;
669                     rect.size.height = h;
670                 }
671             }
673             // Vertical scrollers must not cover the resize box in the
674             // bottom-right corner of the window.
675             if ([[self window] showsResizeIndicator]  // XXX: make this a flag
676                 && rect.origin.y < [NSScroller scrollerWidth]) {
677                 rect.size.height -= [NSScroller scrollerWidth] - rect.origin.y;
678                 rect.origin.y = [NSScroller scrollerWidth];
679             }
681             // Make sure scrollbar rect is bounded by the text view frame.
682             if (rect.origin.y < textViewFrame.origin.y) {
683                 rect.size.height -= textViewFrame.origin.y - rect.origin.y;
684                 rect.origin.y = textViewFrame.origin.y;
685             } else if (rect.origin.y > NSMaxY(textViewFrame))
686                 rect.origin.y = NSMaxY(textViewFrame);
687             if (NSMaxY(rect) > NSMaxY(textViewFrame))
688                 rect.size.height -= NSMaxY(rect) - NSMaxY(textViewFrame);
689             if (rect.size.height < 0)
690                 rect.size.height = 0;
691         }
693         //NSLog(@"set scroller #%d frame = %@", i, NSStringFromRect(rect));
694         NSRect oldRect = [scroller frame];
695         if (!NSEqualRects(oldRect, rect)) {
696             [scroller setFrame:rect];
697             // Clear behind the old scroller frame, or parts of the old
698             // scroller might still be visible after setFrame:.
699             [[[self window] contentView] setNeedsDisplayInRect:oldRect];
700             [scroller setNeedsDisplay:YES];
701         }
702     }
705 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi
707     NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
708     return [tabViewItems indexOfObject:tvi];
711 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx
713     unsigned i, count = [scrollbars count];
714     for (i = 0; i < count; ++i) {
715         MMScroller *scroller = [scrollbars objectAtIndex:i];
716         if ([scroller identifier] == ident) {
717             if (idx) *idx = i;
718             return scroller;
719         }
720     }
722     return nil;
725 - (NSSize)vimViewSizeForTextViewSize:(NSSize)textViewSize
727     NSSize size = textViewSize;
729     if (![[self tabBarControl] isHidden])
730         size.height += [[self tabBarControl] frame].size.height;
732     if ([self bottomScrollbarVisible])
733         size.height += [NSScroller scrollerWidth];
734     if ([self leftScrollbarVisible])
735         size.width += [NSScroller scrollerWidth];
736     if ([self rightScrollbarVisible])
737         size.width += [NSScroller scrollerWidth];
739     return size;
742 - (NSRect)textViewRectForVimViewSize:(NSSize)contentSize
744     NSRect rect = { 0, 0, contentSize.width, contentSize.height };
746     if (![[self tabBarControl] isHidden])
747         rect.size.height -= [[self tabBarControl] frame].size.height;
749     if ([self bottomScrollbarVisible]) {
750         rect.size.height -= [NSScroller scrollerWidth];
751         rect.origin.y += [NSScroller scrollerWidth];
752     }
753     if ([self leftScrollbarVisible]) {
754         rect.size.width -= [NSScroller scrollerWidth];
755         rect.origin.x += [NSScroller scrollerWidth];
756     }
757     if ([self rightScrollbarVisible])
758         rect.size.width -= [NSScroller scrollerWidth];
760     return rect;
763 - (NSTabView *)tabView
765     return tabView;
768 - (void)frameSizeMayHaveChanged
770     // NOTE: Whenever a call is made that may have changed the frame size we
771     // take the opportunity to make sure all subviews are in place and that the
772     // (rows,columns) are constrained to lie inside the new frame.  We not only
773     // do this when the frame really has changed since it is possible to modify
774     // the number of (rows,columns) without changing the frame size.
776     // Give all superfluous space to the text view. It might be smaller or
777     // larger than it wants to be, but this is needed during live resizing.
778     NSRect textViewRect = [self textViewRectForVimViewSize:[self frame].size];
779     [textView setFrame:textViewRect];
781     [self placeScrollbars];
783     // It is possible that the current number of (rows,columns) is too big or
784     // too small to fit the new frame.  If so, notify Vim that the text
785     // dimensions should change, but don't actually change the number of
786     // (rows,columns).  These numbers may only change when Vim initiates the
787     // change (as opposed to the user dragging the window resizer, for
788     // example).
789     //
790     // Note that the message sent to Vim depends on whether we're in
791     // a live resize or not -- this is necessary to avoid the window jittering
792     // when the user drags to resize.
793     int constrained[2];
794     NSSize textViewSize = [textView frame].size;
795     [textView constrainRows:&constrained[0] columns:&constrained[1]
796                      toSize:textViewSize];
798     int rows, cols;
799     [textView getMaxRows:&rows columns:&cols];
801     if (constrained[0] != rows || constrained[1] != cols) {
802         NSData *data = [NSData dataWithBytes:constrained length:2*sizeof(int)];
803         int msgid = [self inLiveResize] ? LiveResizeMsgID
804                                         : SetTextDimensionsMsgID;
806         //NSLog(@"Notify Vim that text dimensions changed from %dx%d to %dx%d"
807         //       " (%s)", cols, rows, constrained[1], constrained[0],
808         //       MessageStrings[msgid]);
810         [vimController sendMessage:msgid data:data];
812         // We only want to set the window title if this resize came from
813         // a live-resize, not (for example) setting 'columns' or 'lines'.
814         if ([self inLiveResize]) {
815             [[self window] setTitle:[NSString stringWithFormat:@"%dx%d",
816                     constrained[1], constrained[0]]];
817         }
818     }
821 @end // MMVimView (Private)
826 @implementation MMScroller
828 - (id)initWithIdentifier:(long)ident type:(int)theType
830     // HACK! NSScroller creates a horizontal scroller if it is init'ed with a
831     // frame whose with exceeds its height; so create a bogus rect and pass it
832     // to initWithFrame.
833     NSRect frame = theType == MMScrollerTypeBottom
834             ? NSMakeRect(0, 0, 1, 0)
835             : NSMakeRect(0, 0, 0, 1);
837     self = [super initWithFrame:frame];
838     if (!self) return nil;
840     identifier = ident;
841     type = theType;
842     [self setHidden:YES];
843     [self setEnabled:YES];
844     [self setAutoresizingMask:NSViewNotSizable];
846     return self;
849 - (long)identifier
851     return identifier;
854 - (int)type
856     return type;
859 - (NSRange)range
861     return range;
864 - (void)setRange:(NSRange)newRange
866     range = newRange;
869 - (void)scrollWheel:(NSEvent *)event
871     // HACK! Pass message on to the text view.
872     NSView *vimView = [self superview];
873     if ([vimView isKindOfClass:[MMVimView class]])
874         [[(MMVimView*)vimView textView] scrollWheel:event];
877 @end // MMScroller