1 /* vi:set ts=8 sts=4 sw=4 ft=objc:
3 * VIM - Vi IMproved by Bram Moolenaar
4 * MacVim GUI port by Bjorn Winckler
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.
13 #import <PSMTabBarControl.h>
15 #import "MMTextView.h"
16 #import "MMTextStorage.h"
17 #import "MMTypesetter.h"
18 #import "MMVimController.h"
20 #import "MMWindowController.h" // needed by MMScroller. TODO: remove
22 // Scroller type; these must match SBAR_* in gui.h
24 MMScrollerTypeLeft = 0,
30 @interface NSTabView (MMExtras)
31 - (void)removeAllTabViewItems;
35 @interface MMVimView (Private)
36 - (BOOL)bottomScrollbarVisible;
37 - (BOOL)leftScrollbarVisible;
38 - (BOOL)rightScrollbarVisible;
39 - (void)placeScrollbars;
43 @implementation MMVimView
45 - (MMVimView *)initWithFrame:(NSRect)frame
46 vimController:(MMVimController *)controller {
47 if (![super initWithFrame:frame])
50 vimController = controller;
51 scrollbars = [[NSMutableArray alloc] init];
53 // Set up a complete text system.
54 textStorage = [[MMTextStorage alloc] init];
55 NSLayoutManager *lm = [[NSLayoutManager alloc] init];
56 NSTextContainer *tc = [[NSTextContainer alloc] initWithContainerSize:
57 NSMakeSize(1.0e7,1.0e7)];
59 NSString *typesetterString = [[NSUserDefaults standardUserDefaults]
60 stringForKey:MMTypesetterKey];
61 if (![typesetterString isEqual:@"NSTypesetter"]) {
62 MMTypesetter *typesetter = [[MMTypesetter alloc] init];
63 [lm setTypesetter:typesetter];
66 // Only MMTypesetter supports different cell width multipliers.
67 [[NSUserDefaults standardUserDefaults]
68 setFloat:1.0 forKey:MMCellWidthMultiplierKey];
71 [tc setWidthTracksTextView:NO];
72 [tc setHeightTracksTextView:NO];
73 [tc setLineFragmentPadding:0];
75 [textStorage addLayoutManager:lm];
76 [lm addTextContainer:tc];
78 textView = [[MMTextView alloc] initWithFrame:frame
81 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
82 int left = [ud integerForKey:MMTextInsetLeftKey];
83 int top = [ud integerForKey:MMTextInsetTopKey];
84 [textView setTextContainerInset:NSMakeSize(left, top)];
86 [self addSubview:textView];
88 // The text storage retains the layout manager which in turn retains
89 // the text container.
93 // Create the tab view (which is never visible, but the tab bar control
94 // needs it to function).
95 tabView = [[NSTabView alloc] initWithFrame:NSZeroRect];
97 // Create the tab bar control (which is responsible for actually
98 // drawing the tabline and tabs).
99 NSRect tabFrame = frame;
100 tabFrame.origin.y = NSMaxY(tabFrame) - 22;
101 tabFrame.size.height = 22;
102 tabBarControl = [[PSMTabBarControl alloc] initWithFrame:tabFrame];
104 [tabView setDelegate:tabBarControl];
106 [tabBarControl setTabView:tabView];
107 [tabBarControl setDelegate:self];
108 [tabBarControl setHidden:YES];
109 [tabBarControl setAutoresizingMask:NSViewWidthSizable|NSViewMinYMargin];
110 [tabBarControl setCellMinWidth:[ud integerForKey:MMTabMinWidthKey]];
111 [tabBarControl setCellMaxWidth:[ud integerForKey:MMTabMaxWidthKey]];
112 [tabBarControl setCellOptimumWidth:
113 [ud integerForKey:MMTabOptimumWidthKey]];
114 [tabBarControl setShowAddTabButton:YES];
115 [[tabBarControl addTabButton] setTarget:self];
116 [[tabBarControl addTabButton] setAction:@selector(addNewTab:)];
117 [tabBarControl setAllowsDragBetweenWindows:NO];
119 [tabBarControl setPartnerView:[self textView]];
121 [self addSubview:tabBarControl];
128 [tabBarControl release]; tabBarControl = nil;
129 [tabView release]; tabView = nil;
130 [scrollbars release]; scrollbars = nil;
131 [textView release]; textView = nil;
132 [textStorage release]; textStorage = nil;
137 - (MMTextView *)textView
142 - (MMTextStorage *)textStorage
147 - (NSMutableArray *)scrollbars
154 return [textView inLiveResize];
157 - (PSMTabBarControl *)tabBarControl
159 return tabBarControl;
162 - (NSTabView *)tabView
172 // NOTE! There is a bug in PSMTabBarControl in that it retains the delegate
173 // (which is the MMWindowController) so reset the delegate here, otherwise
174 // the MMWindowController never gets released resulting in a pretty serious
176 [tabView setDelegate:nil];
177 [tabBarControl setDelegate:nil];
178 [tabBarControl setTabView:nil];
179 [[self window] setDelegate:nil];
181 // NOTE! There is another bug in PSMTabBarControl where the control is not
182 // removed as an observer, so remove it here (else lots of evil nasty bugs
183 // will come and gnaw at your feet while you are sleeping).
184 [[NSNotificationCenter defaultCenter] removeObserver:tabBarControl];
186 [tabBarControl removeFromSuperviewWithoutNeedingDisplay];
187 [textView removeFromSuperviewWithoutNeedingDisplay];
189 unsigned i, count = [scrollbars count];
190 for (i = 0; i < count; ++i) {
191 MMScroller *sb = [scrollbars objectAtIndex:i];
192 [sb removeFromSuperviewWithoutNeedingDisplay];
195 [tabView removeAllTabViewItems];
198 - (IBAction)addNewTab:(id)sender
200 // NOTE! This can get called a lot if the user holds down the key
201 // equivalent for this action, which causes the ports to fill up. If we
202 // wait for the message to be sent then the app might become unresponsive.
203 [vimController sendMessage:AddNewTabMsgID data:nil];
206 - (void)updateTabsWithData:(NSData *)data
208 const void *p = [data bytes];
209 const void *end = p + [data length];
212 // HACK! Current tab is first in the message. This way it is not
213 // necessary to guess which tab should be the selected one (this can be
214 // problematic for instance when new tabs are created).
215 int curtabIdx = *((int*)p); p += sizeof(int);
217 NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
220 //int wincount = *((int*)p); p += sizeof(int);
221 int length = *((int*)p); p += sizeof(int);
223 NSString *label = [[NSString alloc]
224 initWithBytesNoCopy:(void*)p
226 encoding:NSUTF8StringEncoding
230 // Set the label of the tab; add a new tab when needed.
231 NSTabViewItem *tvi = [[self tabView] numberOfTabViewItems] <= tabIdx
232 ? [self addNewTabViewItem]
233 : [tabViewItems objectAtIndex:tabIdx];
235 [tvi setLabel:label];
242 // Remove unused tabs from the NSTabView. Note that when a tab is closed
243 // the NSTabView will automatically select another tab, but we want Vim to
244 // take care of which tab to select so set the vimTaskSelectedTab flag to
245 // prevent the tab selection message to be passed on to the VimTask.
246 vimTaskSelectedTab = YES;
247 int i, count = [[self tabView] numberOfTabViewItems];
248 for (i = count-1; i >= tabIdx; --i) {
249 id tvi = [tabViewItems objectAtIndex:i];
250 //NSLog(@"Removing tab with index %d", i);
251 [[self tabView] removeTabViewItem:tvi];
253 vimTaskSelectedTab = NO;
255 [self selectTabWithIndex:curtabIdx];
258 - (void)selectTabWithIndex:(int)idx
260 //NSLog(@"%s%d", _cmd, idx);
262 NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
263 if (idx < 0 || idx >= [tabViewItems count]) {
264 NSLog(@"WARNING: No tab with index %d exists.", idx);
268 // Do not try to select a tab if already selected.
269 NSTabViewItem *tvi = [tabViewItems objectAtIndex:idx];
270 if (tvi != [[self tabView] selectedTabViewItem]) {
271 vimTaskSelectedTab = YES;
272 [[self tabView] selectTabViewItem:tvi];
273 vimTaskSelectedTab = NO;
277 - (NSTabViewItem *)addNewTabViewItem
279 // NOTE! A newly created tab is not by selected by default; the VimTask
280 // decides which tab should be selected at all times. However, the AppKit
281 // will automatically select the first tab added to a tab view.
283 NSTabViewItem *tvi = [[NSTabViewItem alloc] initWithIdentifier:nil];
285 // NOTE: If this is the first tab it will be automatically selected.
286 vimTaskSelectedTab = YES;
287 [[self tabView] addTabViewItem:tvi];
288 vimTaskSelectedTab = NO;
295 - (int)representedIndexOfTabViewItem:(NSTabViewItem *)tvi
297 NSArray *tabViewItems = [[self tabBarControl] representedTabViewItems];
298 return [tabViewItems indexOfObject:tvi];
301 - (BOOL)bottomScrollbarVisible
303 unsigned i, count = [scrollbars count];
304 for (i = 0; i < count; ++i) {
305 MMScroller *scroller = [scrollbars objectAtIndex:i];
306 if ([scroller type] == MMScrollerTypeBottom && ![scroller isHidden])
313 - (BOOL)leftScrollbarVisible
315 unsigned i, count = [scrollbars count];
316 for (i = 0; i < count; ++i) {
317 MMScroller *scroller = [scrollbars objectAtIndex:i];
318 if ([scroller type] == MMScrollerTypeLeft && ![scroller isHidden])
325 - (BOOL)rightScrollbarVisible
327 unsigned i, count = [scrollbars count];
328 for (i = 0; i < count; ++i) {
329 MMScroller *scroller = [scrollbars objectAtIndex:i];
330 if ([scroller type] == MMScrollerTypeRight && ![scroller isHidden])
337 - (void)createScrollbarWithIdentifier:(long)ident type:(int)type
339 //NSLog(@"Create scroller %d of type %d", ident, type);
341 MMScroller *scroller = [[MMScroller alloc] initWithIdentifier:ident
343 [scroller setTarget:self];
344 [scroller setAction:@selector(scroll:)];
346 [self addSubview:scroller];
347 [[self scrollbars] addObject:scroller];
351 - (void)destroyScrollbarWithIdentifier:(long)ident
353 //NSLog(@"Destroy scroller %d", ident);
356 MMScroller *scroller = [self scrollbarForIdentifier:ident index:&idx];
358 [scroller removeFromSuperview];
359 [[self scrollbars] removeObjectAtIndex:idx];
361 if (![scroller isHidden]) {
362 // A visible scroller was removed, so the window must resize to
364 //NSLog(@"Visible scroller %d was destroyed, resizing window.",
366 shouldUpdateWindowSize = YES;
371 - (void)showScrollbarWithIdentifier:(long)ident state:(BOOL)visible
373 MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
374 if (!scroller) return;
376 BOOL wasVisible = ![scroller isHidden];
377 //NSLog(@"%s scroller %d (was %svisible)", visible ? "Show" : "Hide",
378 // ident, wasVisible ? "" : "in");
379 [scroller setHidden:!visible];
381 if (wasVisible != visible) {
382 // A scroller was hidden or shown, so the window must resize to fit.
383 //NSLog(@"%s scroller %d and resize.", visible ? "Show" : "Hide",
385 shouldUpdateWindowSize = YES;
389 - (void)setScrollbarThumbValue:(float)val proportion:(float)prop
390 identifier:(long)ident
392 MMScroller *scroller = [self scrollbarForIdentifier:ident index:NULL];
393 //NSLog(@"Set thumb value %.2f proportion %.2f for scroller %d",
394 // val, prop, ident);
395 [scroller setFloatValue:val knobProportion:prop];
399 - (void)scroll:(id)sender
401 NSMutableData *data = [NSMutableData data];
402 long ident = [(MMScroller*)sender identifier];
403 int hitPart = [sender hitPart];
404 float value = [sender floatValue];
406 [data appendBytes:&ident length:sizeof(long)];
407 [data appendBytes:&hitPart length:sizeof(int)];
408 [data appendBytes:&value length:sizeof(float)];
410 [vimController sendMessage:ScrollbarEventMsgID data:data];
413 - (void)placeScrollbars
415 NSRect textViewFrame = [textView frame];
416 BOOL lsbVisible = [self leftScrollbarVisible];
418 // HACK! Find the lowest left&right vertical scrollbars, as well as the
419 // rightmost horizontal scrollbar. This hack continues further down.
421 // TODO! Can there be no more than one horizontal scrollbar? If so, the
422 // code can be simplified.
423 unsigned lowestLeftSbIdx = (unsigned)-1;
424 unsigned lowestRightSbIdx = (unsigned)-1;
425 unsigned rightmostSbIdx = (unsigned)-1;
426 unsigned rowMaxLeft = 0, rowMaxRight = 0, colMax = 0;
427 unsigned i, count = [scrollbars count];
428 for (i = 0; i < count; ++i) {
429 MMScroller *scroller = [scrollbars objectAtIndex:i];
430 if (![scroller isHidden]) {
431 NSRange range = [scroller range];
432 if ([scroller type] == MMScrollerTypeLeft
433 && range.location >= rowMaxLeft) {
434 rowMaxLeft = range.location;
436 } else if ([scroller type] == MMScrollerTypeRight
437 && range.location >= rowMaxRight) {
438 rowMaxRight = range.location;
439 lowestRightSbIdx = i;
440 } else if ([scroller type] == MMScrollerTypeBottom
441 && range.location >= colMax) {
442 colMax = range.location;
448 // Place the scrollbars.
449 for (i = 0; i < count; ++i) {
450 MMScroller *scroller = [scrollbars objectAtIndex:i];
451 if ([scroller isHidden])
455 if ([scroller type] == MMScrollerTypeBottom) {
456 rect = [textStorage rectForColumnsInRange:[scroller range]];
457 rect.size.height = [NSScroller scrollerWidth];
459 rect.origin.x += [NSScroller scrollerWidth];
461 // HACK! Make sure the rightmost horizontal scrollbar covers the
462 // text view all the way to the right, otherwise it looks ugly when
463 // the user drags the window to resize.
464 if (i == rightmostSbIdx) {
465 float w = NSMaxX(textViewFrame) - NSMaxX(rect);
467 rect.size.width += w;
470 // Make sure scrollbar rect is bounded by the text view frame.
471 if (rect.origin.x < textViewFrame.origin.x)
472 rect.origin.x = textViewFrame.origin.x;
473 else if (rect.origin.x > NSMaxX(textViewFrame))
474 rect.origin.x = NSMaxX(textViewFrame);
475 if (NSMaxX(rect) > NSMaxX(textViewFrame))
476 rect.size.width -= NSMaxX(rect) - NSMaxX(textViewFrame);
477 if (rect.size.width < 0)
480 rect = [textStorage rectForRowsInRange:[scroller range]];
481 // Adjust for the fact that text layout is flipped.
482 rect.origin.y = NSMaxY(textViewFrame) - rect.origin.y
484 rect.size.width = [NSScroller scrollerWidth];
485 if ([scroller type] == MMScrollerTypeRight)
486 rect.origin.x = NSMaxX(textViewFrame);
488 // HACK! Make sure the lowest vertical scrollbar covers the text
489 // view all the way to the bottom. This is done because Vim only
490 // makes the scrollbar cover the (vim-)window it is associated with
491 // and this means there is always an empty gap in the scrollbar
492 // region next to the command line.
493 // TODO! Find a nicer way to do this.
494 if (i == lowestLeftSbIdx || i == lowestRightSbIdx) {
495 float h = rect.origin.y + rect.size.height
496 - textViewFrame.origin.y;
497 if (rect.size.height < h) {
498 rect.origin.y = textViewFrame.origin.y;
499 rect.size.height = h;
503 // Vertical scrollers must not cover the resize box in the
504 // bottom-right corner of the window.
505 if ([[self window] showsResizeIndicator] // XXX: make this a flag
506 && rect.origin.y < [NSScroller scrollerWidth]) {
507 rect.size.height -= [NSScroller scrollerWidth] - rect.origin.y;
508 rect.origin.y = [NSScroller scrollerWidth];
511 // Make sure scrollbar rect is bounded by the text view frame.
512 if (rect.origin.y < textViewFrame.origin.y) {
513 rect.size.height -= textViewFrame.origin.y - rect.origin.y;
514 rect.origin.y = textViewFrame.origin.y;
515 } else if (rect.origin.y > NSMaxY(textViewFrame))
516 rect.origin.y = NSMaxY(textViewFrame);
517 if (NSMaxY(rect) > NSMaxY(textViewFrame))
518 rect.size.height -= NSMaxY(rect) - NSMaxY(textViewFrame);
519 if (rect.size.height < 0)
520 rect.size.height = 0;
523 //NSLog(@"set scroller #%d frame = %@", i, NSStringFromRect(rect));
524 NSRect oldRect = [scroller frame];
525 if (!NSEqualRects(oldRect, rect)) {
526 [scroller setFrame:rect];
527 // Clear behind the old scroller frame, or parts of the old
528 // scroller might still be visible after setFrame:.
529 [[[self window] contentView] setNeedsDisplayInRect:oldRect];
530 [scroller setNeedsDisplay:YES];
535 - (MMScroller *)scrollbarForIdentifier:(long)ident index:(unsigned *)idx
537 unsigned i, count = [[self scrollbars] count];
538 for (i = 0; i < count; ++i) {
539 MMScroller *scroller = [[self scrollbars] objectAtIndex:i];
540 if ([scroller identifier] == ident) {
549 - (void)setDefaultColorsBackground:(NSColor *)back foreground:(NSColor *)fore
551 [textStorage setDefaultColorsBackground:back foreground:fore];
552 [textView setBackgroundColor:back];
555 - (BOOL)shouldUpdateWindowSize
557 return shouldUpdateWindowSize;
560 - (void)setShouldUpdateWindowSize:(BOOL)b
562 shouldUpdateWindowSize = b;
565 - (NSSize)contentSizeForTextStorageSize:(NSSize)textViewSize
567 NSSize size = textViewSize;
569 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
570 int right = [ud integerForKey:MMTextInsetRightKey];
571 int bot = [ud integerForKey:MMTextInsetBottomKey];
573 size.width += [[self textView] textContainerOrigin].x + right;
574 size.height += [[self textView] textContainerOrigin].y + bot;
576 if (![[self tabBarControl] isHidden])
577 size.height += [[self tabBarControl] frame].size.height;
579 if ([self bottomScrollbarVisible])
580 size.height += [NSScroller scrollerWidth];
581 if ([self leftScrollbarVisible])
582 size.width += [NSScroller scrollerWidth];
583 if ([self rightScrollbarVisible])
584 size.width += [NSScroller scrollerWidth];
589 - (NSRect)textViewRectForContentSize:(NSSize)contentSize
591 NSRect rect = { 0, 0, contentSize.width, contentSize.height };
593 if (![[self tabBarControl] isHidden])
594 rect.size.height -= [[self tabBarControl] frame].size.height;
596 if ([self bottomScrollbarVisible]) {
597 rect.size.height -= [NSScroller scrollerWidth];
598 rect.origin.y += [NSScroller scrollerWidth];
600 if ([self leftScrollbarVisible]) {
601 rect.size.width -= [NSScroller scrollerWidth];
602 rect.origin.x += [NSScroller scrollerWidth];
604 if ([self rightScrollbarVisible])
605 rect.size.width -= [NSScroller scrollerWidth];
610 - (NSSize)textStorageSizeForTextViewSize:(NSSize)textViewSize
612 NSSize size = textViewSize;
614 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
615 int right = [ud integerForKey:MMTextInsetRightKey];
616 int bot = [ud integerForKey:MMTextInsetBottomKey];
618 size.width -= [[self textView] textContainerOrigin].x + right;
619 size.height -= [[self textView] textContainerOrigin].y + bot;
625 // -- PSMTabBarControl delegate ----------------------------------------------
628 - (BOOL)tabView:(NSTabView *)theTabView shouldSelectTabViewItem:
629 (NSTabViewItem *)tabViewItem
631 // NOTE: It would be reasonable to think that 'shouldSelect...' implies
632 // that this message only gets sent when the user clicks the tab.
633 // Unfortunately it is not so, which is why we need the
634 // 'vimTaskSelectedTab' flag.
636 // HACK! The selection message should not be propagated to the VimTask if
637 // the VimTask selected the tab (e.g. as opposed the user clicking the
638 // tab). The delegate method has no way of knowing who initiated the
639 // selection so a flag is set when the VimTask initiated the selection.
640 if (!vimTaskSelectedTab) {
641 // Propagate the selection message to the VimTask.
642 int idx = [self representedIndexOfTabViewItem:tabViewItem];
643 if (NSNotFound != idx) {
644 NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
645 [vimController sendMessage:SelectTabMsgID data:data];
649 // Unless Vim selected the tab, return NO, and let Vim decide if the tab
650 // should get selected or not.
651 return vimTaskSelectedTab;
654 - (BOOL)tabView:(NSTabView *)theTabView shouldCloseTabViewItem:
655 (NSTabViewItem *)tabViewItem
657 // HACK! This method is only called when the user clicks the close button
658 // on the tab. Instead of letting the tab bar close the tab, we return NO
659 // and pass a message on to Vim to let it handle the closing.
660 int idx = [self representedIndexOfTabViewItem:tabViewItem];
661 //NSLog(@"Closing tab with index %d", idx);
662 NSData *data = [NSData dataWithBytes:&idx length:sizeof(int)];
663 [vimController sendMessage:CloseTabMsgID data:data];
668 - (void)tabView:(NSTabView *)theTabView didDragTabViewItem:
669 (NSTabViewItem *)tabViewItem toIndex:(int)idx
671 NSMutableData *data = [NSMutableData data];
672 [data appendBytes:&idx length:sizeof(int)];
674 [vimController sendMessage:DraggedTabMsgID data:data];
682 @implementation NSTabView (MMExtras)
684 - (void)removeAllTabViewItems
686 NSArray *existingItems = [self tabViewItems];
687 NSEnumerator *e = [existingItems objectEnumerator];
689 while (item = [e nextObject]){
690 [self removeTabViewItem:item];
694 @end // NSTabView (MMExtras)
699 @implementation MMScroller
701 - (id)initWithIdentifier:(long)ident type:(int)theType
703 // HACK! NSScroller creates a horizontal scroller if it is init'ed with a
704 // frame whose with exceeds its height; so create a bogus rect and pass it
706 NSRect frame = theType == MMScrollerTypeBottom
707 ? NSMakeRect(0, 0, 1, 0)
708 : NSMakeRect(0, 0, 0, 1);
710 if ((self = [super initWithFrame:frame])) {
713 [self setHidden:YES];
714 [self setEnabled:YES];
735 - (void)setRange:(NSRange)newRange
740 - (void)scrollWheel:(NSEvent *)event
742 // HACK! Pass message on to the text view.
743 MMWindowController *wc = [[self window] windowController];
744 [[wc textView] scrollWheel:event];