1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "chrome/browser/ui/cocoa/tabs/tab_strip_controller.h"
7 #import <QuartzCore/QuartzCore.h>
13 #include "base/command_line.h"
14 #include "base/mac/mac_util.h"
15 #include "base/mac/scoped_nsautorelease_pool.h"
16 #include "base/metrics/histogram.h"
17 #include "base/prefs/pref_service.h"
18 #include "base/strings/sys_string_conversions.h"
19 #include "chrome/app/chrome_command_ids.h"
20 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
21 #include "chrome/browser/autocomplete/autocomplete_classifier_factory.h"
22 #include "chrome/browser/extensions/tab_helper.h"
23 #include "chrome/browser/favicon/favicon_tab_helper.h"
24 #include "chrome/browser/profiles/profile.h"
25 #include "chrome/browser/profiles/profile_manager.h"
26 #include "chrome/browser/themes/theme_service.h"
27 #include "chrome/browser/ui/browser.h"
28 #include "chrome/browser/ui/browser_navigator.h"
29 #include "chrome/browser/ui/browser_tabstrip.h"
30 #import "chrome/browser/ui/cocoa/browser_window_controller.h"
31 #import "chrome/browser/ui/cocoa/constrained_window/constrained_window_sheet_controller.h"
32 #include "chrome/browser/ui/cocoa/drag_util.h"
33 #import "chrome/browser/ui/cocoa/image_button_cell.h"
34 #import "chrome/browser/ui/cocoa/new_tab_button.h"
35 #import "chrome/browser/ui/cocoa/tab_contents/favicon_util_mac.h"
36 #import "chrome/browser/ui/cocoa/tab_contents/tab_contents_controller.h"
37 #import "chrome/browser/ui/cocoa/tabs/media_indicator_button_cocoa.h"
38 #import "chrome/browser/ui/cocoa/tabs/tab_controller.h"
39 #import "chrome/browser/ui/cocoa/tabs/tab_strip_drag_controller.h"
40 #import "chrome/browser/ui/cocoa/tabs/tab_strip_model_observer_bridge.h"
41 #import "chrome/browser/ui/cocoa/tabs/tab_strip_view.h"
42 #import "chrome/browser/ui/cocoa/tabs/tab_view.h"
43 #include "chrome/browser/ui/find_bar/find_bar.h"
44 #include "chrome/browser/ui/find_bar/find_bar_controller.h"
45 #include "chrome/browser/ui/find_bar/find_tab_helper.h"
46 #include "chrome/browser/ui/tabs/tab_menu_model.h"
47 #include "chrome/browser/ui/tabs/tab_strip_model.h"
48 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
49 #include "chrome/browser/ui/tabs/tab_utils.h"
50 #include "chrome/common/chrome_switches.h"
51 #include "chrome/grit/generated_resources.h"
52 #include "components/metrics/proto/omnibox_event.pb.h"
53 #include "components/omnibox/autocomplete_match.h"
54 #include "components/url_fixer/url_fixer.h"
55 #include "components/web_modal/web_contents_modal_dialog_manager.h"
56 #include "content/public/browser/navigation_controller.h"
57 #include "content/public/browser/user_metrics.h"
58 #include "content/public/browser/web_contents.h"
59 #include "grit/theme_resources.h"
60 #include "skia/ext/skia_utils_mac.h"
61 #import "third_party/google_toolbox_for_mac/src/AppKit/GTMNSAnimation+Duration.h"
62 #include "ui/base/cocoa/animation_utils.h"
63 #import "ui/base/cocoa/tracking_area.h"
64 #include "ui/base/l10n/l10n_util.h"
65 #include "ui/base/models/list_selection_model.h"
66 #include "ui/base/resource/resource_bundle.h"
67 #include "ui/base/theme_provider.h"
68 #include "ui/gfx/image/image.h"
69 #include "ui/gfx/mac/scoped_ns_disable_screen_updates.h"
70 #include "ui/resources/grit/ui_resources.h"
72 using base::UserMetricsAction;
73 using content::OpenURLParams;
74 using content::Referrer;
75 using content::WebContents;
79 // A value to indicate tab layout should use the full available width of the
81 const CGFloat kUseFullAvailableWidth = -1.0;
83 // The amount by which tabs overlap.
84 // Needs to be <= the x position of the favicon within a tab. Else, every time
85 // the throbber is painted, the throbber's invalidation will also invalidate
86 // parts of the tab to the left, and two tabs's backgrounds need to be painted
87 // on each throbber frame instead of one.
88 const CGFloat kTabOverlap = 19.0;
90 // The amount by which mini tabs are separated from normal tabs.
91 const CGFloat kLastMiniTabSpacing = 2.0;
93 // The amount by which the new tab button is offset (from the tabs).
94 const CGFloat kNewTabButtonOffset = 8.0;
96 // Time (in seconds) in which tabs animate to their final position.
97 const NSTimeInterval kAnimationDuration = 0.125;
99 // Helper class for doing NSAnimationContext calls that takes a bool to disable
100 // all the work. Useful for code that wants to conditionally animate.
101 class ScopedNSAnimationContextGroup {
103 explicit ScopedNSAnimationContextGroup(bool animate)
104 : animate_(animate) {
106 [NSAnimationContext beginGrouping];
110 ~ScopedNSAnimationContextGroup() {
112 [NSAnimationContext endGrouping];
116 void SetCurrentContextDuration(NSTimeInterval duration) {
118 [[NSAnimationContext currentContext] gtm_setDuration:duration
119 eventMask:NSLeftMouseUpMask];
123 void SetCurrentContextShortestDuration() {
125 // The minimum representable time interval. This used to stop an
126 // in-progress animation as quickly as possible.
127 const NSTimeInterval kMinimumTimeInterval =
128 std::numeric_limits<NSTimeInterval>::min();
129 // Directly set the duration to be short, avoiding the Steve slowmotion
130 // ettect the gtm_setDuration: provides.
131 [[NSAnimationContext currentContext] setDuration:kMinimumTimeInterval];
137 DISALLOW_COPY_AND_ASSIGN(ScopedNSAnimationContextGroup);
140 // Creates an NSImage with size |size| and bitmap image representations for both
141 // 1x and 2x scale factors. |drawingHandler| is called once for every scale
142 // factor. This is similar to -[NSImage imageWithSize:flipped:drawingHandler:],
143 // but this function always evaluates drawingHandler eagerly, and it works on
145 NSImage* CreateImageWithSize(NSSize size,
146 void (^drawingHandler)(NSSize)) {
147 base::scoped_nsobject<NSImage> result([[NSImage alloc] initWithSize:size]);
148 [NSGraphicsContext saveGraphicsState];
149 for (ui::ScaleFactor scale_factor : ui::GetSupportedScaleFactors()) {
150 float scale = GetScaleForScaleFactor(scale_factor);
151 NSBitmapImageRep *bmpImageRep = [[[NSBitmapImageRep alloc]
152 initWithBitmapDataPlanes:NULL
153 pixelsWide:size.width * scale
154 pixelsHigh:size.height * scale
159 colorSpaceName:NSDeviceRGBColorSpace
161 bitsPerPixel:0] autorelease];
162 [bmpImageRep setSize:size];
163 [NSGraphicsContext setCurrentContext:
164 [NSGraphicsContext graphicsContextWithBitmapImageRep:bmpImageRep]];
165 drawingHandler(size);
166 [result addRepresentation:bmpImageRep];
168 [NSGraphicsContext restoreGraphicsState];
170 return result.release();
173 // Takes a normal bitmap and a mask image and returns an image the size of the
174 // mask that has pixels from |image| but alpha information from |mask|.
175 NSImage* ApplyMask(NSImage* image, NSImage* mask) {
176 return [CreateImageWithSize([mask size], ^(NSSize size) {
177 // Skip a few pixels from the top of the tab background gradient, because
178 // the new tab button is not drawn at the very top of the browser window.
179 const int kYOffset = 10;
180 CGFloat width = size.width;
181 CGFloat height = size.height;
183 // In some themes, the tab background image is narrower than the
184 // new tab button, so tile the background image.
186 // The floor() is to make sure images with odd widths don't draw to the
187 // same pixel twice on retina displays. (Using NSDrawThreePartImage()
188 // caused a startup perf regression, so that cannot be used.)
189 CGFloat tileWidth = floor(std::min(width, [image size].width));
191 [image drawAtPoint:NSMakePoint(x, 0)
192 fromRect:NSMakeRect(0,
193 [image size].height - height - kYOffset,
196 operation:NSCompositeCopy
201 [mask drawAtPoint:NSZeroPoint
202 fromRect:NSMakeRect(0, 0, width, height)
203 operation:NSCompositeDestinationIn
208 // Paints |overlay| on top of |ground|.
209 NSImage* Overlay(NSImage* ground, NSImage* overlay, CGFloat alpha) {
210 DCHECK_EQ([ground size].width, [overlay size].width);
211 DCHECK_EQ([ground size].height, [overlay size].height);
213 return [CreateImageWithSize([ground size], ^(NSSize size) {
214 CGFloat width = size.width;
215 CGFloat height = size.height;
216 [ground drawAtPoint:NSZeroPoint
217 fromRect:NSMakeRect(0, 0, width, height)
218 operation:NSCompositeCopy
220 [overlay drawAtPoint:NSZeroPoint
221 fromRect:NSMakeRect(0, 0, width, height)
222 operation:NSCompositeSourceOver
229 @interface TabStripController (Private)
230 - (void)addSubviewToPermanentList:(NSView*)aView;
231 - (void)regenerateSubviewList;
232 - (NSInteger)indexForContentsView:(NSView*)view;
233 - (NSImage*)iconImageForContents:(content::WebContents*)contents;
234 - (void)updateIconsForContents:(content::WebContents*)contents
235 atIndex:(NSInteger)modelIndex;
236 - (void)layoutTabsWithAnimation:(BOOL)animate
237 regenerateSubviews:(BOOL)doUpdate;
238 - (void)animationDidStop:(CAAnimation*)animation
239 forController:(TabController*)controller
240 finished:(BOOL)finished;
241 - (NSInteger)indexFromModelIndex:(NSInteger)index;
242 - (void)clickNewTabButton:(id)sender;
243 - (NSInteger)numberOfOpenTabs;
244 - (NSInteger)numberOfOpenMiniTabs;
245 - (NSInteger)numberOfOpenNonMiniTabs;
246 - (void)mouseMoved:(NSEvent*)event;
247 - (void)setTabTrackingAreasEnabled:(BOOL)enabled;
248 - (void)droppingURLsAt:(NSPoint)point
249 givesIndex:(NSInteger*)index
250 disposition:(WindowOpenDisposition*)disposition;
251 - (void)setNewTabButtonHoverState:(BOOL)showHover;
252 - (void)themeDidChangeNotification:(NSNotification*)notification;
253 - (void)setNewTabImages;
256 // A simple view class that prevents the Window Server from dragging the area
257 // behind tabs. Sometimes core animation confuses it. Unfortunately, it can also
258 // falsely pick up clicks during rapid tab closure, so we have to account for
260 @interface TabStripControllerDragBlockingView : NSView {
261 TabStripController* controller_; // weak; owns us
264 - (id)initWithFrame:(NSRect)frameRect
265 controller:(TabStripController*)controller;
267 // Runs a nested runloop to do window move tracking. Overriding
268 // -mouseDownCanMoveWindow with a dynamic result instead doesn't work:
269 // http://www.cocoabuilder.com/archive/cocoa/219261-conditional-mousedowncanmovewindow-for-nsview.html
270 // http://www.cocoabuilder.com/archive/cocoa/92973-brushed-metal-window-dragging.html
271 - (void)trackClickForWindowMove:(NSEvent*)event;
274 @implementation TabStripControllerDragBlockingView
275 - (BOOL)mouseDownCanMoveWindow {
279 - (id)initWithFrame:(NSRect)frameRect
280 controller:(TabStripController*)controller {
281 if ((self = [super initWithFrame:frameRect])) {
282 controller_ = controller;
287 // In "rapid tab closure" mode (i.e., the user is clicking close tab buttons in
288 // rapid succession), the animations confuse Cocoa's hit testing (which appears
289 // to use cached results, among other tricks), so this view can somehow end up
290 // getting a mouse down event. Thus we do an explicit hit test during rapid tab
291 // closure, and if we find that we got a mouse down we shouldn't have, we send
292 // it off to the appropriate view.
293 - (void)mouseDown:(NSEvent*)event {
294 NSView* superview = [self superview];
295 NSPoint hitLocation =
296 [[superview superview] convertPoint:[event locationInWindow]
298 NSView* hitView = [superview hitTest:hitLocation];
300 if ([controller_ inRapidClosureMode]) {
301 if (hitView != self) {
302 [hitView mouseDown:event];
307 if (hitView == self) {
308 BrowserWindowController* windowController =
309 [BrowserWindowController browserWindowControllerForView:self];
310 if (![windowController isInAnyFullscreenMode]) {
311 [self trackClickForWindowMove:event];
315 [super mouseDown:event];
318 - (void)trackClickForWindowMove:(NSEvent*)event {
319 NSWindow* window = [self window];
320 NSPoint frameOrigin = [window frame].origin;
321 NSPoint lastEventLoc = [window convertBaseToScreen:[event locationInWindow]];
322 while ((event = [NSApp nextEventMatchingMask:
323 NSLeftMouseDownMask|NSLeftMouseDraggedMask|NSLeftMouseUpMask
324 untilDate:[NSDate distantFuture]
325 inMode:NSEventTrackingRunLoopMode
327 [event type] != NSLeftMouseUp) {
328 base::mac::ScopedNSAutoreleasePool pool;
330 NSPoint now = [window convertBaseToScreen:[event locationInWindow]];
331 frameOrigin.x += now.x - lastEventLoc.x;
332 frameOrigin.y += now.y - lastEventLoc.y;
333 [window setFrameOrigin:frameOrigin];
342 // A delegate, owned by the CAAnimation system, that is alerted when the
343 // animation to close a tab is completed. Calls back to the given tab strip
344 // to let it know that |controller_| is ready to be removed from the model.
345 // Since we only maintain weak references, the tab strip must call -invalidate:
346 // to prevent the use of dangling pointers.
347 @interface TabCloseAnimationDelegate : NSObject {
349 TabStripController* strip_; // weak; owns us indirectly
350 TabController* controller_; // weak
353 // Will tell |strip| when the animation for |controller|'s view has completed.
354 // These should not be nil, and will not be retained.
355 - (id)initWithTabStrip:(TabStripController*)strip
356 tabController:(TabController*)controller;
358 // Invalidates this object so that no further calls will be made to
359 // |strip_|. This should be called when |strip_| is released, to
360 // prevent attempts to call into the released object.
363 // CAAnimation delegate method
364 - (void)animationDidStop:(CAAnimation*)animation finished:(BOOL)finished;
368 @implementation TabCloseAnimationDelegate
370 - (id)initWithTabStrip:(TabStripController*)strip
371 tabController:(TabController*)controller {
372 if ((self = [super init])) {
373 DCHECK(strip && controller);
375 controller_ = controller;
385 - (void)animationDidStop:(CAAnimation*)animation finished:(BOOL)finished {
386 [strip_ animationDidStop:animation
387 forController:controller_
395 // In general, there is a one-to-one correspondence between TabControllers,
396 // TabViews, TabContentsControllers, and the WebContents in the
397 // TabStripModel. In the steady-state, the indices line up so an index coming
398 // from the model is directly mapped to the same index in the parallel arrays
399 // holding our views and controllers. This is also true when new tabs are
400 // created (even though there is a small period of animation) because the tab is
401 // present in the model while the TabView is animating into place. As a result,
402 // nothing special need be done to handle "new tab" animation.
404 // This all goes out the window with the "close tab" animation. The animation
405 // kicks off in |-tabDetachedWithContents:atIndex:| with the notification that
406 // the tab has been removed from the model. The simplest solution at this
407 // point would be to remove the views and controllers as well, however once
408 // the TabView is removed from the view list, the tab z-order code takes care of
409 // removing it from the tab strip and we'll get no animation. That means if
410 // there is to be any visible animation, the TabView needs to stay around until
411 // its animation is complete. In order to maintain consistency among the
412 // internal parallel arrays, this means all structures are kept around until
413 // the animation completes. At this point, though, the model and our internal
414 // structures are out of sync: the indices no longer line up. As a result,
415 // there is a concept of a "model index" which represents an index valid in
416 // the TabStripModel. During steady-state, the "model index" is just the same
417 // index as our parallel arrays (as above), but during tab close animations,
418 // it is different, offset by the number of tabs preceding the index which
419 // are undergoing tab closing animation. As a result, the caller needs to be
420 // careful to use the available conversion routines when accessing the internal
421 // parallel arrays (e.g., -indexFromModelIndex:). Care also needs to be taken
422 // during tab layout to ignore closing tabs in the total width calculations and
423 // in individual tab positioning (to avoid moving them right back to where they
426 // In order to prevent actions being taken on tabs which are closing, the tab
427 // itself gets marked as such so it no longer will send back its select action
428 // or allow itself to be dragged. In addition, drags on the tab strip as a
429 // whole are disabled while there are tabs closing.
431 @implementation TabStripController
433 @synthesize leftIndentForControls = leftIndentForControls_;
434 @synthesize rightIndentForControls = rightIndentForControls_;
436 - (id)initWithView:(TabStripView*)view
437 switchView:(NSView*)switchView
438 browser:(Browser*)browser
439 delegate:(id<TabStripControllerDelegate>)delegate {
440 DCHECK(view && switchView && browser && delegate);
441 if ((self = [super init])) {
442 tabStripView_.reset([view retain]);
443 [tabStripView_ setController:self];
444 switchView_ = switchView;
446 tabStripModel_ = browser_->tab_strip_model();
447 hoverTabSelector_.reset(new HoverTabSelector(tabStripModel_));
448 delegate_ = delegate;
449 bridge_.reset(new TabStripModelObserverBridge(tabStripModel_, self));
450 dragController_.reset(
451 [[TabStripDragController alloc] initWithTabStripController:self]);
452 tabContentsArray_.reset([[NSMutableArray alloc] init]);
453 tabArray_.reset([[NSMutableArray alloc] init]);
454 NSWindow* browserWindow = [view window];
456 // Important note: any non-tab subviews not added to |permanentSubviews_|
457 // (see |-addSubviewToPermanentList:|) will be wiped out.
458 permanentSubviews_.reset([[NSMutableArray alloc] init]);
460 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
461 defaultFavicon_.reset(
462 rb.GetNativeImageNamed(IDR_DEFAULT_FAVICON).CopyNSImage());
464 [self setLeftIndentForControls:[[self class] defaultLeftIndentForControls]];
465 [self setRightIndentForControls:0];
467 // Add this invisible view first so that it is ordered below other views.
468 dragBlockingView_.reset(
469 [[TabStripControllerDragBlockingView alloc] initWithFrame:NSZeroRect
471 [self addSubviewToPermanentList:dragBlockingView_];
473 newTabButton_ = [view getNewTabButton];
474 [newTabButton_ setWantsLayer:YES];
475 [self addSubviewToPermanentList:newTabButton_];
476 [newTabButton_ setTarget:self];
477 [newTabButton_ setAction:@selector(clickNewTabButton:)];
479 [self setNewTabImages];
480 newTabButtonShowingHoverImage_ = NO;
481 newTabTrackingArea_.reset(
482 [[CrTrackingArea alloc] initWithRect:[newTabButton_ bounds]
483 options:(NSTrackingMouseEnteredAndExited |
484 NSTrackingActiveAlways)
487 if (browserWindow) // Nil for Browsers without a tab strip (e.g. popups).
488 [newTabTrackingArea_ clearOwnerWhenWindowWillClose:browserWindow];
489 [newTabButton_ addTrackingArea:newTabTrackingArea_.get()];
490 targetFrames_.reset([[NSMutableDictionary alloc] init]);
492 newTabTargetFrame_ = NSZeroRect;
493 availableResizeWidth_ = kUseFullAvailableWidth;
495 closingControllers_.reset([[NSMutableSet alloc] init]);
497 // Install the permanent subviews.
498 [self regenerateSubviewList];
500 // Watch for notifications that the tab strip view has changed size so
501 // we can tell it to layout for the new size.
502 [[NSNotificationCenter defaultCenter]
504 selector:@selector(tabViewFrameChanged:)
505 name:NSViewFrameDidChangeNotification
506 object:tabStripView_];
508 [[NSNotificationCenter defaultCenter]
510 selector:@selector(themeDidChangeNotification:)
511 name:kBrowserThemeDidChangeNotification
514 trackingArea_.reset([[CrTrackingArea alloc]
515 initWithRect:NSZeroRect // Ignored by NSTrackingInVisibleRect
516 options:NSTrackingMouseEnteredAndExited |
517 NSTrackingMouseMoved |
518 NSTrackingActiveAlways |
519 NSTrackingInVisibleRect
522 if (browserWindow) // Nil for Browsers without a tab strip (e.g. popups).
523 [trackingArea_ clearOwnerWhenWindowWillClose:browserWindow];
524 [tabStripView_ addTrackingArea:trackingArea_.get()];
526 // Check to see if the mouse is currently in our bounds so we can
527 // enable the tracking areas. Otherwise we won't get hover states
528 // or tab gradients if we load the window up under the mouse.
529 NSPoint mouseLoc = [[view window] mouseLocationOutsideOfEventStream];
530 mouseLoc = [view convertPoint:mouseLoc fromView:nil];
531 if (NSPointInRect(mouseLoc, [view bounds])) {
532 [self setTabTrackingAreasEnabled:YES];
536 // Set accessibility descriptions. http://openradar.appspot.com/7496255
537 NSString* description = l10n_util::GetNSStringWithFixup(IDS_ACCNAME_NEWTAB);
538 [[newTabButton_ cell]
539 accessibilitySetOverrideValue:description
540 forAttribute:NSAccessibilityDescriptionAttribute];
542 // Controller may have been (re-)created by switching layout modes, which
543 // means the tab model is already fully formed with tabs. Need to walk the
544 // list and create the UI for each.
545 const int existingTabCount = tabStripModel_->count();
546 const content::WebContents* selection =
547 tabStripModel_->GetActiveWebContents();
548 for (int i = 0; i < existingTabCount; ++i) {
549 content::WebContents* currentContents =
550 tabStripModel_->GetWebContentsAt(i);
551 [self insertTabWithContents:currentContents
554 if (selection == currentContents) {
555 // Must manually force a selection since the model won't send
556 // selection messages in this scenario.
558 activateTabWithContents:currentContents
559 previousContents:NULL
561 reason:TabStripModelObserver::CHANGE_REASON_NONE];
564 // Don't lay out the tabs until after the controller has been fully
566 if (existingTabCount) {
567 [self performSelectorOnMainThread:@selector(layoutTabs)
576 [tabStripView_ setController:nil];
578 if (trackingArea_.get())
579 [tabStripView_ removeTrackingArea:trackingArea_.get()];
581 [newTabButton_ removeTrackingArea:newTabTrackingArea_.get()];
582 // Invalidate all closing animations so they don't call back to us after
584 for (TabController* controller in closingControllers_.get()) {
585 NSView* view = [controller view];
586 [[[view animationForKey:@"frameOrigin"] delegate] invalidate];
588 [[NSNotificationCenter defaultCenter] removeObserver:self];
592 + (CGFloat)defaultTabHeight {
593 return [TabController defaultTabHeight];
596 + (CGFloat)defaultLeftIndentForControls {
597 // Default indentation leaves enough room so tabs don't overlap with the
602 // Finds the TabContentsController associated with the given index into the tab
603 // model and swaps out the sole child of the contentArea to display its
605 - (void)swapInTabAtIndex:(NSInteger)modelIndex {
606 DCHECK(modelIndex >= 0 && modelIndex < tabStripModel_->count());
607 NSInteger index = [self indexFromModelIndex:modelIndex];
608 TabContentsController* controller = [tabContentsArray_ objectAtIndex:index];
610 // Make sure we do not draw any transient arrangements of views.
611 gfx::ScopedNSDisableScreenUpdates ns_disabler;
612 // Make sure that any layers that move are not animated to their new
614 ScopedCAActionDisabler ca_disabler;
616 // Resize the new view to fit the window. Calling |view| may lazily
617 // instantiate the TabContentsController from the nib. Until we call
618 // |-ensureContentsVisible|, the controller doesn't install the RWHVMac into
619 // the view hierarchy. This is in order to avoid sending the renderer a
620 // spurious default size loaded from the nib during the call to |-view|.
621 NSView* newView = [controller view];
623 // Turns content autoresizing off, so removing and inserting views won't
624 // trigger unnecessary content relayout.
625 [controller ensureContentsSizeDoesNotChange];
627 // Remove the old view from the view hierarchy. We know there's only one
628 // child of |switchView_| because we're the one who put it there. There
629 // may not be any children in the case of a tab that's been closed, in
630 // which case there's no swapping going on.
631 NSArray* subviews = [switchView_ subviews];
632 if ([subviews count]) {
633 NSView* oldView = [subviews objectAtIndex:0];
634 // Set newView frame to the oldVew frame to prevent NSSplitView hosting
635 // sidebar and tab content from resizing sidebar's content view.
636 // ensureContentsVisible (see below) sets content size and autoresizing
638 [newView setFrame:[oldView frame]];
639 [switchView_ replaceSubview:oldView with:newView];
641 [newView setFrame:[switchView_ bounds]];
642 [switchView_ addSubview:newView];
645 // New content is in place, delegate should adjust itself accordingly.
646 [delegate_ onActivateTabWithContents:[controller webContents]];
648 // It also restores content autoresizing properties.
649 [controller ensureContentsVisible];
651 NSWindow* parentWindow = [switchView_ window];
652 ConstrainedWindowSheetController* sheetController =
653 [ConstrainedWindowSheetController
654 controllerForParentWindow:parentWindow];
655 [sheetController parentViewDidBecomeActive:newView];
658 // Create a new tab view and set its cell correctly so it draws the way we want
659 // it to. It will be sized and positioned by |-layoutTabs| so there's no need to
660 // set the frame here. This also creates the view as hidden, it will be
661 // shown during layout.
662 - (TabController*)newTab {
663 TabController* controller = [[[TabController alloc] init] autorelease];
664 [controller setTarget:self];
665 [controller setAction:@selector(selectTab:)];
666 [[controller view] setHidden:YES];
671 // (Private) Handles a click on the new tab button.
672 - (void)clickNewTabButton:(id)sender {
673 content::RecordAction(UserMetricsAction("NewTab_Button"));
674 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", TabStripModel::NEW_TAB_BUTTON,
675 TabStripModel::NEW_TAB_ENUM_COUNT);
676 tabStripModel_->delegate()->AddTabAt(GURL(), -1, true);
679 // (Private) Returns the number of open tabs in the tab strip. This is the
680 // number of TabControllers we know about (as there's a 1-to-1 mapping from
681 // these controllers to a tab) less the number of closing tabs.
682 - (NSInteger)numberOfOpenTabs {
683 return static_cast<NSInteger>(tabStripModel_->count());
686 // (Private) Returns the number of open, mini-tabs.
687 - (NSInteger)numberOfOpenMiniTabs {
688 // Ask the model for the number of mini tabs. Note that tabs which are in
689 // the process of closing (i.e., whose controllers are in
690 // |closingControllers_|) have already been removed from the model.
691 return tabStripModel_->IndexOfFirstNonMiniTab();
694 // (Private) Returns the number of open, non-mini tabs.
695 - (NSInteger)numberOfOpenNonMiniTabs {
696 NSInteger number = [self numberOfOpenTabs] - [self numberOfOpenMiniTabs];
697 DCHECK_GE(number, 0);
701 // Given an index into the tab model, returns the index into the tab controller
702 // or tab contents controller array accounting for tabs that are currently
703 // closing. For example, if there are two tabs in the process of closing before
704 // |index|, this returns |index| + 2. If there are no closing tabs, this will
706 - (NSInteger)indexFromModelIndex:(NSInteger)index {
712 for (TabController* controller in tabArray_.get()) {
713 if ([closingControllers_ containsObject:controller]) {
714 DCHECK([[controller tabView] isClosing]);
717 if (i == index) // No need to check anything after, it has no effect.
724 // Given an index into |tabArray_|, return the corresponding index into
725 // |tabStripModel_| or NSNotFound if the specified tab does not exist in
726 // the model (if it's closing, for example).
727 - (NSInteger)modelIndexFromIndex:(NSInteger)index {
728 NSInteger modelIndex = 0;
729 NSInteger arrayIndex = 0;
730 for (TabController* controller in tabArray_.get()) {
731 if (![closingControllers_ containsObject:controller]) {
732 if (arrayIndex == index)
735 } else if (arrayIndex == index) {
736 // Tab is closing - no model index.
744 // Returns the index of the subview |view|. Returns -1 if not present. Takes
745 // closing tabs into account such that this index will correctly match the tab
746 // model. If |view| is in the process of closing, returns -1, as closing tabs
747 // are no longer in the model.
748 - (NSInteger)modelIndexForTabView:(NSView*)view {
750 for (TabController* current in tabArray_.get()) {
751 // If |current| is closing, skip it.
752 if ([closingControllers_ containsObject:current])
754 else if ([current view] == view)
761 // Returns the index of the contents subview |view|. Returns -1 if not present.
762 // Takes closing tabs into account such that this index will correctly match the
763 // tab model. If |view| is in the process of closing, returns -1, as closing
764 // tabs are no longer in the model.
765 - (NSInteger)modelIndexForContentsView:(NSView*)view {
768 for (TabContentsController* current in tabContentsArray_.get()) {
769 // If the TabController corresponding to |current| is closing, skip it.
770 TabController* controller = [tabArray_ objectAtIndex:i];
771 if ([closingControllers_ containsObject:controller]) {
774 } else if ([current view] == view) {
783 - (NSArray*)selectedViews {
784 NSMutableArray* views = [NSMutableArray arrayWithCapacity:[tabArray_ count]];
785 for (TabController* tab in tabArray_.get()) {
787 [views addObject:[tab tabView]];
792 // Returns the view at the given index, using the array of TabControllers to
793 // get the associated view. Returns nil if out of range.
794 - (NSView*)viewAtIndex:(NSUInteger)index {
795 if (index >= [tabArray_ count])
797 return [[tabArray_ objectAtIndex:index] view];
800 - (NSUInteger)viewsCount {
801 return [tabArray_ count];
804 // Called when the user clicks a tab. Tell the model the selection has changed,
805 // which feeds back into us via a notification.
806 - (void)selectTab:(id)sender {
807 DCHECK([sender isKindOfClass:[NSView class]]);
808 int index = [self modelIndexForTabView:sender];
809 NSUInteger modifiers = [[NSApp currentEvent] modifierFlags];
810 if (tabStripModel_->ContainsIndex(index)) {
811 if (modifiers & NSCommandKeyMask && modifiers & NSShiftKeyMask) {
812 tabStripModel_->AddSelectionFromAnchorTo(index);
813 } else if (modifiers & NSShiftKeyMask) {
814 tabStripModel_->ExtendSelectionTo(index);
815 } else if (modifiers & NSCommandKeyMask) {
816 tabStripModel_->ToggleSelectionAt(index);
818 tabStripModel_->ActivateTabAt(index, true);
823 // Called when the user clicks the tab audio indicator to mute the tab.
824 - (void)toggleMute:(id)sender {
825 DCHECK([sender isKindOfClass:[TabView class]]);
826 NSInteger index = [self modelIndexForTabView:sender];
827 if (!tabStripModel_->ContainsIndex(index))
829 WebContents* contents = tabStripModel_->GetWebContentsAt(index);
830 chrome::SetTabAudioMuted(contents, !chrome::IsTabAudioMuted(contents),
831 chrome::kMutedToggleCauseUser);
834 // Called when the user closes a tab. Asks the model to close the tab. |sender|
835 // is the TabView that is potentially going away.
836 - (void)closeTab:(id)sender {
837 DCHECK([sender isKindOfClass:[TabView class]]);
839 // Cancel any pending tab transition.
840 hoverTabSelector_->CancelTabTransition();
842 if ([hoveredTab_ isEqual:sender])
843 [self setHoveredTab:nil];
845 NSInteger index = [self modelIndexForTabView:sender];
846 if (!tabStripModel_->ContainsIndex(index))
849 content::RecordAction(UserMetricsAction("CloseTab_Mouse"));
850 const NSInteger numberOfOpenTabs = [self numberOfOpenTabs];
851 if (numberOfOpenTabs > 1) {
852 bool isClosingLastTab = index == numberOfOpenTabs - 1;
853 if (!isClosingLastTab) {
854 // Limit the width available for laying out tabs so that tabs are not
855 // resized until a later time (when the mouse leaves the tab strip).
856 // However, if the tab being closed is a pinned tab, break out of
857 // rapid-closure mode since the mouse is almost guaranteed not to be over
858 // the closebox of the adjacent tab (due to the difference in widths).
859 // TODO(pinkerton): re-visit when handling tab overflow.
860 // http://crbug.com/188
861 if (tabStripModel_->IsTabPinned(index)) {
862 availableResizeWidth_ = kUseFullAvailableWidth;
864 NSView* penultimateTab = [self viewAtIndex:numberOfOpenTabs - 2];
865 availableResizeWidth_ = NSMaxX([penultimateTab frame]);
868 // If the rightmost tab is closed, change the available width so that
869 // another tab's close button lands below the cursor (assuming the tabs
870 // are currently below their maximum width and can grow).
871 NSView* lastTab = [self viewAtIndex:numberOfOpenTabs - 1];
872 availableResizeWidth_ = NSMaxX([lastTab frame]);
874 tabStripModel_->CloseWebContentsAt(
876 TabStripModel::CLOSE_USER_GESTURE |
877 TabStripModel::CLOSE_CREATE_HISTORICAL_TAB);
879 // Use the standard window close if this is the last tab
880 // this prevents the tab from being removed from the model until after
881 // the window dissapears
882 [[tabStripView_ window] performClose:nil];
886 // Dispatch context menu commands for the given tab controller.
887 - (void)commandDispatch:(TabStripModel::ContextMenuCommand)command
888 forController:(TabController*)controller {
889 int index = [self modelIndexForTabView:[controller view]];
890 if (tabStripModel_->ContainsIndex(index))
891 tabStripModel_->ExecuteContextMenuCommand(index, command);
894 // Returns YES if the specificed command should be enabled for the given
896 - (BOOL)isCommandEnabled:(TabStripModel::ContextMenuCommand)command
897 forController:(TabController*)controller {
898 int index = [self modelIndexForTabView:[controller view]];
899 if (!tabStripModel_->ContainsIndex(index))
901 return tabStripModel_->IsContextMenuCommandEnabled(index, command) ? YES : NO;
904 // Returns a context menu model for a given controller. Caller owns the result.
905 - (ui::SimpleMenuModel*)contextMenuModelForController:(TabController*)controller
906 menuDelegate:(ui::SimpleMenuModel::Delegate*)delegate {
907 int index = [self modelIndexForTabView:[controller view]];
908 return new TabMenuModel(delegate, tabStripModel_, index);
911 // Returns a weak reference to the controller that manages dragging of tabs.
912 - (id<TabDraggingEventTarget>)dragController {
913 return dragController_.get();
916 - (void)insertPlaceholderForTab:(TabView*)tab frame:(NSRect)frame {
917 placeholderTab_ = tab;
918 placeholderFrame_ = frame;
919 [self layoutTabsWithAnimation:initialLayoutComplete_ regenerateSubviews:NO];
922 - (BOOL)isDragSessionActive {
923 return placeholderTab_ != nil;
926 - (BOOL)isTabFullyVisible:(TabView*)tab {
927 NSRect frame = [tab frame];
928 return NSMinX(frame) >= [self leftIndentForControls] &&
929 NSMaxX(frame) <= (NSMaxX([tabStripView_ frame]) -
930 [self rightIndentForControls]);
933 - (void)showNewTabButton:(BOOL)show {
934 forceNewTabButtonHidden_ = show ? NO : YES;
935 if (forceNewTabButtonHidden_)
936 [newTabButton_ setHidden:YES];
939 // Lay out all tabs in the order of their TabContentsControllers, which matches
940 // the ordering in the TabStripModel. This call isn't that expensive, though
941 // it is O(n) in the number of tabs. Tabs will animate to their new position
942 // if the window is visible and |animate| is YES.
943 // TODO(pinkerton): Note this doesn't do too well when the number of min-sized
944 // tabs would cause an overflow. http://crbug.com/188
945 - (void)layoutTabsWithAnimation:(BOOL)animate
946 regenerateSubviews:(BOOL)doUpdate {
947 DCHECK([NSThread isMainThread]);
948 if (![tabArray_ count])
951 const CGFloat kMaxTabWidth = [TabController maxTabWidth];
952 const CGFloat kMinTabWidth = [TabController minTabWidth];
953 const CGFloat kMinActiveTabWidth = [TabController minActiveTabWidth];
954 const CGFloat kMiniTabWidth = [TabController miniTabWidth];
955 const CGFloat kAppTabWidth = [TabController appTabWidth];
957 NSRect enclosingRect = NSZeroRect;
958 ScopedNSAnimationContextGroup mainAnimationGroup(animate);
959 mainAnimationGroup.SetCurrentContextDuration(kAnimationDuration);
961 // Update the current subviews and their z-order if requested.
963 [self regenerateSubviewList];
965 // Compute the base width of tabs given how much room we're allowed. Note that
966 // mini-tabs have a fixed width. We may not be able to use the entire width
967 // if the user is quickly closing tabs. This may be negative, but that's okay
968 // (taken care of by |MAX()| when calculating tab sizes).
969 CGFloat availableSpace = 0;
970 if ([self inRapidClosureMode]) {
971 availableSpace = availableResizeWidth_;
973 availableSpace = NSWidth([tabStripView_ frame]);
975 // Account for the width of the new tab button.
977 NSWidth([newTabButton_ frame]) + kNewTabButtonOffset - kTabOverlap;
979 // Account for the right-side controls if not in rapid closure mode.
980 // (In rapid closure mode, the available width is set based on the
981 // position of the rightmost tab, not based on the width of the tab strip,
982 // so the right controls have already been accounted for.)
983 availableSpace -= [self rightIndentForControls];
986 // Need to leave room for the left-side controls even in rapid closure mode.
987 availableSpace -= [self leftIndentForControls];
989 // This may be negative, but that's okay (taken care of by |MAX()| when
990 // calculating tab sizes). "mini" tabs in horizontal mode just get a special
991 // section, they don't change size.
992 CGFloat availableSpaceForNonMini = availableSpace;
993 if ([self numberOfOpenMiniTabs]) {
994 availableSpaceForNonMini -=
995 [self numberOfOpenMiniTabs] * (kMiniTabWidth - kTabOverlap);
996 availableSpaceForNonMini -= kLastMiniTabSpacing;
999 // Initialize |nonMiniTabWidth| in case there aren't any non-mini-tabs; this
1000 // value shouldn't actually be used.
1001 CGFloat nonMiniTabWidth = kMaxTabWidth;
1002 CGFloat nonMiniTabWidthFraction = 0;
1003 NSInteger numberOfNonMiniTabs = MIN(
1004 [self numberOfOpenNonMiniTabs],
1005 (availableSpaceForNonMini - kTabOverlap) / (kMinTabWidth - kTabOverlap));
1007 if (numberOfNonMiniTabs) {
1008 // Find the width of a non-mini-tab. This only applies to horizontal
1009 // mode. Add in the amount we "get back" from the tabs overlapping.
1011 ((availableSpaceForNonMini - kTabOverlap) / numberOfNonMiniTabs) +
1014 // Clamp the width between the max and min.
1015 nonMiniTabWidth = MAX(MIN(nonMiniTabWidth, kMaxTabWidth), kMinTabWidth);
1017 // When there are multiple tabs, we'll have one active and some inactive
1018 // tabs. If the desired width was between the minimum sizes of these types,
1019 // try to shrink the tabs with the smaller minimum. For example, if we have
1020 // a strip of width 10 with 4 tabs, the desired width per tab will be 2.5.
1021 // If selected tabs have a minimum width of 4 and unselected tabs have
1022 // minimum width of 1, the above code would set *unselected_width = 2.5,
1023 // *selected_width = 4, which results in a total width of 11.5. Instead, we
1024 // want to set *unselected_width = 2, *selected_width = 4, for a total width
1026 if (numberOfNonMiniTabs > 1 && nonMiniTabWidth < kMinActiveTabWidth) {
1027 nonMiniTabWidth = (availableSpaceForNonMini - kMinActiveTabWidth) /
1028 (numberOfNonMiniTabs - 1) +
1030 if (nonMiniTabWidth < kMinTabWidth) {
1031 // The above adjustment caused the tabs to not fit, show 1 less tab.
1032 --numberOfNonMiniTabs;
1034 ((availableSpaceForNonMini - kTabOverlap) / numberOfNonMiniTabs) +
1039 // Separate integral and fractional parts.
1040 CGFloat integralPart = std::floor(nonMiniTabWidth);
1041 nonMiniTabWidthFraction = nonMiniTabWidth - integralPart;
1042 nonMiniTabWidth = integralPart;
1045 BOOL visible = [[tabStripView_ window] isVisible];
1047 CGFloat offset = [self leftIndentForControls];
1048 bool hasPlaceholderGap = false;
1049 // Whether or not the last tab processed by the loop was a mini tab.
1050 BOOL isLastTabMini = NO;
1051 CGFloat tabWidthAccumulatedFraction = 0;
1052 NSInteger laidOutNonMiniTabs = 0;
1054 for (TabController* tab in tabArray_.get()) {
1055 // Ignore a tab that is going through a close animation.
1056 if ([closingControllers_ containsObject:tab])
1059 BOOL isPlaceholder = [[tab view] isEqual:placeholderTab_];
1060 NSRect tabFrame = [[tab view] frame];
1061 tabFrame.size.height = [[self class] defaultTabHeight];
1062 tabFrame.origin.y = 0;
1063 tabFrame.origin.x = offset;
1065 // If the tab is hidden, we consider it a new tab. We make it visible
1066 // and animate it in.
1067 BOOL newTab = [[tab view] isHidden];
1069 [[tab view] setHidden:NO];
1071 if (isPlaceholder) {
1072 // Move the current tab to the correct location instantly.
1073 // We need a duration or else it doesn't cancel an inflight animation.
1074 ScopedNSAnimationContextGroup localAnimationGroup(animate);
1075 localAnimationGroup.SetCurrentContextShortestDuration();
1076 tabFrame.origin.x = placeholderFrame_.origin.x;
1077 id target = animate ? [[tab view] animator] : [tab view];
1078 [target setFrame:tabFrame];
1080 // Store the frame by identifier to avoid redundant calls to animator.
1081 NSValue* identifier = [NSValue valueWithPointer:[tab view]];
1082 [targetFrames_ setObject:[NSValue valueWithRect:tabFrame]
1087 if (placeholderTab_ && !hasPlaceholderGap) {
1088 const CGFloat placeholderMin = NSMinX(placeholderFrame_);
1089 // If the left edge is to the left of the placeholder's left, but the
1090 // mid is to the right of it slide over to make space for it.
1091 if (NSMidX(tabFrame) > placeholderMin) {
1092 hasPlaceholderGap = true;
1093 offset += NSWidth(placeholderFrame_);
1094 offset -= kTabOverlap;
1095 tabFrame.origin.x = offset;
1099 // Set the width. Selected tabs are slightly wider when things get really
1100 // small and thus we enforce a different minimum width.
1101 BOOL isMini = [tab mini];
1103 tabFrame.size.width = [tab app] ? kAppTabWidth : kMiniTabWidth;
1105 // Tabs have non-integer widths. Assign the integer part to the tab, and
1106 // keep an accumulation of the fractional parts. When the fractional
1107 // accumulation gets to be more than one pixel, assign that to the current
1108 // tab being laid out. This is vaguely inspired by Bresenham's line
1110 tabFrame.size.width = nonMiniTabWidth;
1111 tabWidthAccumulatedFraction += nonMiniTabWidthFraction;
1113 if (tabWidthAccumulatedFraction >= 1.0) {
1114 ++tabFrame.size.width;
1115 --tabWidthAccumulatedFraction;
1118 // In case of rounding error, give any left over pixels to the last tab.
1119 if (laidOutNonMiniTabs == numberOfNonMiniTabs - 1 &&
1120 tabWidthAccumulatedFraction > 0.5) {
1121 ++tabFrame.size.width;
1124 ++laidOutNonMiniTabs;
1128 tabFrame.size.width = MAX(tabFrame.size.width, kMinActiveTabWidth);
1130 // If this is the first non-mini tab, then add a bit of spacing between this
1131 // and the last mini tab.
1132 if (!isMini && isLastTabMini) {
1133 offset += kLastMiniTabSpacing;
1134 tabFrame.origin.x = offset;
1136 isLastTabMini = isMini;
1138 if (laidOutNonMiniTabs > numberOfNonMiniTabs) {
1139 // There is not enough space to fit this tab.
1140 tabFrame.size.width = 0;
1141 [self setFrame:tabFrame ofTabView:[tab view]];
1145 // Animate a new tab in by putting it below the horizon unless told to put
1146 // it in a specific location (i.e., from a drop).
1147 if (newTab && visible && animate) {
1148 if (NSEqualRects(droppedTabFrame_, NSZeroRect)) {
1149 [[tab view] setFrame:NSOffsetRect(tabFrame, 0, -NSHeight(tabFrame))];
1151 [[tab view] setFrame:droppedTabFrame_];
1152 droppedTabFrame_ = NSZeroRect;
1156 // Check the frame by identifier to avoid redundant calls to animator.
1157 id frameTarget = visible && animate ? [[tab view] animator] : [tab view];
1158 NSValue* identifier = [NSValue valueWithPointer:[tab view]];
1159 NSValue* oldTargetValue = [targetFrames_ objectForKey:identifier];
1160 if (!oldTargetValue ||
1161 !NSEqualRects([oldTargetValue rectValue], tabFrame)) {
1162 [frameTarget setFrame:tabFrame];
1163 [targetFrames_ setObject:[NSValue valueWithRect:tabFrame]
1167 enclosingRect = NSUnionRect(tabFrame, enclosingRect);
1169 offset += NSWidth(tabFrame);
1170 offset -= kTabOverlap;
1173 // Hide the new tab button if we're explicitly told to. It may already
1174 // be hidden, doing it again doesn't hurt. Otherwise position it
1175 // appropriately, showing it if necessary.
1176 if (forceNewTabButtonHidden_) {
1177 [newTabButton_ setHidden:YES];
1179 NSRect newTabNewFrame = [newTabButton_ frame];
1180 // We've already ensured there's enough space for the new tab button
1181 // so we don't have to check it against the available space. We do need
1182 // to make sure we put it after any placeholder.
1183 CGFloat maxTabX = MAX(offset, NSMaxX(placeholderFrame_) - kTabOverlap);
1184 newTabNewFrame.origin = NSMakePoint(maxTabX + kNewTabButtonOffset, 0);
1185 if ([tabContentsArray_ count])
1186 [newTabButton_ setHidden:NO];
1188 if (!NSEqualRects(newTabTargetFrame_, newTabNewFrame)) {
1189 // Set the new tab button image correctly based on where the cursor is.
1190 NSWindow* window = [tabStripView_ window];
1191 NSPoint currentMouse = [window mouseLocationOutsideOfEventStream];
1192 currentMouse = [tabStripView_ convertPoint:currentMouse fromView:nil];
1194 BOOL shouldShowHover = [newTabButton_ pointIsOverButton:currentMouse];
1195 [self setNewTabButtonHoverState:shouldShowHover];
1197 // Move the new tab button into place. We want to animate the new tab
1198 // button if it's moving to the left (closing a tab), but not when it's
1199 // moving to the right (inserting a new tab). If moving right, we need
1200 // to use a very small duration to make sure we cancel any in-flight
1201 // animation to the left.
1202 if (visible && animate) {
1203 ScopedNSAnimationContextGroup localAnimationGroup(true);
1204 BOOL movingLeft = NSMinX(newTabNewFrame) < NSMinX(newTabTargetFrame_);
1206 localAnimationGroup.SetCurrentContextShortestDuration();
1208 [[newTabButton_ animator] setFrame:newTabNewFrame];
1209 newTabTargetFrame_ = newTabNewFrame;
1211 [newTabButton_ setFrame:newTabNewFrame];
1212 newTabTargetFrame_ = newTabNewFrame;
1217 [dragBlockingView_ setFrame:enclosingRect];
1219 // Mark that we've successfully completed layout of at least one tab.
1220 initialLayoutComplete_ = YES;
1223 // When we're told to layout from the public API we usually want to animate,
1224 // except when it's the first time.
1225 - (void)layoutTabs {
1226 [self layoutTabsWithAnimation:initialLayoutComplete_ regenerateSubviews:YES];
1229 - (void)layoutTabsWithoutAnimation {
1230 [self layoutTabsWithAnimation:NO regenerateSubviews:YES];
1233 // Handles setting the title of the tab based on the given |contents|. Uses
1234 // a canned string if |contents| is NULL.
1235 - (void)setTabTitle:(TabController*)tab withContents:(WebContents*)contents {
1236 base::string16 title;
1238 title = contents->GetTitle();
1240 title = l10n_util::GetStringUTF16(IDS_BROWSER_WINDOW_MAC_TAB_UNTITLED);
1241 [tab setTitle:base::SysUTF16ToNSString(title)];
1243 const base::string16& toolTip = chrome::AssembleTabTooltipText(
1244 title, chrome::GetTabMediaStateForContents(contents));
1245 [tab setToolTip:base::SysUTF16ToNSString(toolTip)];
1248 // Called when a notification is received from the model to insert a new tab
1250 - (void)insertTabWithContents:(content::WebContents*)contents
1251 atIndex:(NSInteger)modelIndex
1252 inForeground:(bool)inForeground {
1254 DCHECK(modelIndex == TabStripModel::kNoTab ||
1255 tabStripModel_->ContainsIndex(modelIndex));
1257 // Cancel any pending tab transition.
1258 hoverTabSelector_->CancelTabTransition();
1260 // Take closing tabs into account.
1261 NSInteger index = [self indexFromModelIndex:modelIndex];
1263 // Make a new tab. Load the contents of this tab from the nib and associate
1264 // the new controller with |contents| so it can be looked up later.
1265 base::scoped_nsobject<TabContentsController> contentsController(
1266 [[TabContentsController alloc] initWithContents:contents]);
1267 [tabContentsArray_ insertObject:contentsController atIndex:index];
1269 // Make a new tab and add it to the strip. Keep track of its controller.
1270 TabController* newController = [self newTab];
1271 [newController setMini:tabStripModel_->IsMiniTab(modelIndex)];
1272 [newController setPinned:tabStripModel_->IsTabPinned(modelIndex)];
1273 [newController setApp:tabStripModel_->IsAppTab(modelIndex)];
1274 [newController setUrl:contents->GetURL()];
1275 [tabArray_ insertObject:newController atIndex:index];
1276 NSView* newView = [newController view];
1278 // Set the originating frame to just below the strip so that it animates
1279 // upwards as it's being initially layed out. Oddly, this works while doing
1280 // something similar in |-layoutTabs| confuses the window server.
1281 [newView setFrame:NSOffsetRect([newView frame],
1282 0, -[[self class] defaultTabHeight])];
1284 [self setTabTitle:newController withContents:contents];
1286 // If a tab is being inserted, we can again use the entire tab strip width
1288 availableResizeWidth_ = kUseFullAvailableWidth;
1290 // We don't need to call |-layoutTabs| if the tab will be in the foreground
1291 // because it will get called when the new tab is selected by the tab model.
1292 // Whenever |-layoutTabs| is called, it'll also add the new subview.
1293 if (!inForeground) {
1297 // During normal loading, we won't yet have a favicon and we'll get
1298 // subsequent state change notifications to show the throbber, but when we're
1299 // dragging a tab out into a new window, we have to put the tab's favicon
1300 // into the right state up front as we won't be told to do it from anywhere
1302 [self updateIconsForContents:contents atIndex:modelIndex];
1305 // Called before |contents| is deactivated.
1306 - (void)tabDeactivatedWithContents:(content::WebContents*)contents {
1307 contents->StoreFocus();
1310 // Called when a notification is received from the model to select a particular
1311 // tab. Swaps in the toolbar and content area associated with |newContents|.
1312 - (void)activateTabWithContents:(content::WebContents*)newContents
1313 previousContents:(content::WebContents*)oldContents
1314 atIndex:(NSInteger)modelIndex
1315 reason:(int)reason {
1316 // Take closing tabs into account.
1319 browser_->tab_strip_model()->GetIndexOfWebContents(oldContents);
1320 if (oldModelIndex != -1) { // When closing a tab, the old tab may be gone.
1321 NSInteger oldIndex = [self indexFromModelIndex:oldModelIndex];
1322 TabContentsController* oldController =
1323 [tabContentsArray_ objectAtIndex:oldIndex];
1324 [oldController willBecomeUnselectedTab];
1325 oldContents->WasHidden();
1329 NSUInteger activeIndex = [self indexFromModelIndex:modelIndex];
1331 [tabArray_ enumerateObjectsUsingBlock:^(TabController* current,
1334 [current setActive:index == activeIndex];
1337 // Tell the new tab contents it is about to become the selected tab. Here it
1338 // can do things like make sure the toolbar is up to date.
1339 TabContentsController* newController =
1340 [tabContentsArray_ objectAtIndex:activeIndex];
1341 [newController willBecomeSelectedTab];
1343 // Relayout for new tabs and to let the selected tab grow to be larger in
1344 // size than surrounding tabs if the user has many. This also raises the
1345 // selected tab to the top.
1348 // Swap in the contents for the new tab.
1349 [self swapInTabAtIndex:modelIndex];
1352 newContents->WasShown();
1353 newContents->RestoreFocus();
1357 - (void)tabSelectionChanged {
1358 // First get the vector of indices, which is allays sorted in ascending order.
1359 ui::ListSelectionModel::SelectedIndices selection(
1360 tabStripModel_->selection_model().selected_indices());
1361 // Iterate through all of the tabs, selecting each as necessary.
1362 ui::ListSelectionModel::SelectedIndices::iterator iter = selection.begin();
1364 for (TabController* current in tabArray_.get()) {
1365 BOOL selected = iter != selection.end() &&
1366 [self indexFromModelIndex:*iter] == i;
1367 [current setSelected:selected];
1374 - (void)tabReplacedWithContents:(content::WebContents*)newContents
1375 previousContents:(content::WebContents*)oldContents
1376 atIndex:(NSInteger)modelIndex {
1377 NSInteger index = [self indexFromModelIndex:modelIndex];
1378 TabContentsController* oldController =
1379 [tabContentsArray_ objectAtIndex:index];
1380 DCHECK_EQ(oldContents, [oldController webContents]);
1382 // Simply create a new TabContentsController for |newContents| and place it
1383 // into the array, replacing |oldContents|. An ActiveTabChanged notification
1384 // will follow, at which point we will install the new view.
1385 base::scoped_nsobject<TabContentsController> newController(
1386 [[TabContentsController alloc] initWithContents:newContents]);
1388 // Bye bye, |oldController|.
1389 [tabContentsArray_ replaceObjectAtIndex:index withObject:newController];
1391 // Fake a tab changed notification to force tab titles and favicons to update.
1392 [self tabChangedWithContents:newContents
1394 changeType:TabStripModelObserver::ALL];
1397 // Remove all knowledge about this tab and its associated controller, and remove
1398 // the view from the strip.
1399 - (void)removeTab:(TabController*)controller {
1400 // Cancel any pending tab transition.
1401 hoverTabSelector_->CancelTabTransition();
1403 NSUInteger index = [tabArray_ indexOfObject:controller];
1405 // Release the tab contents controller so those views get destroyed. This
1406 // will remove all the tab content Cocoa views from the hierarchy. A
1407 // subsequent "select tab" notification will follow from the model. To
1408 // tell us what to swap in in its absence.
1409 [tabContentsArray_ removeObjectAtIndex:index];
1411 // Remove the view from the tab strip.
1412 NSView* tab = [controller view];
1413 [tab removeFromSuperview];
1415 // Remove ourself as an observer.
1416 [[NSNotificationCenter defaultCenter]
1418 name:NSViewDidUpdateTrackingAreasNotification
1421 // Clear the tab controller's target.
1422 // TODO(viettrungluu): [crbug.com/23829] Find a better way to handle the tab
1423 // controller's target.
1424 [controller setTarget:nil];
1426 if ([hoveredTab_ isEqual:tab])
1427 [self setHoveredTab:nil];
1429 NSValue* identifier = [NSValue valueWithPointer:tab];
1430 [targetFrames_ removeObjectForKey:identifier];
1432 // Once we're totally done with the tab, delete its controller
1433 [tabArray_ removeObjectAtIndex:index];
1436 // Called by the CAAnimation delegate when the tab completes the closing
1438 - (void)animationDidStop:(CAAnimation*)animation
1439 forController:(TabController*)controller
1440 finished:(BOOL)finished{
1441 [[animation delegate] invalidate];
1442 [closingControllers_ removeObject:controller];
1443 [self removeTab:controller];
1446 // Save off which TabController is closing and tell its view's animator
1447 // where to move the tab to. Registers a delegate to call back when the
1448 // animation is complete in order to remove the tab from the model.
1449 - (void)startClosingTabWithAnimation:(TabController*)closingTab {
1450 DCHECK([NSThread isMainThread]);
1452 // Cancel any pending tab transition.
1453 hoverTabSelector_->CancelTabTransition();
1455 // Save off the controller into the set of animating tabs. This alerts
1456 // the layout method to not do anything with it and allows us to correctly
1457 // calculate offsets when working with indices into the model.
1458 [closingControllers_ addObject:closingTab];
1460 // Mark the tab as closing. This prevents it from generating any drags or
1461 // selections while it's animating closed.
1462 [[closingTab tabView] setClosing:YES];
1464 // Register delegate (owned by the animation system).
1465 NSView* tabView = [closingTab view];
1466 CAAnimation* animation = [[tabView animationForKey:@"frameOrigin"] copy];
1467 [animation autorelease];
1468 base::scoped_nsobject<TabCloseAnimationDelegate> delegate(
1469 [[TabCloseAnimationDelegate alloc] initWithTabStrip:self
1470 tabController:closingTab]);
1471 [animation setDelegate:delegate.get()]; // Retains delegate.
1472 NSMutableDictionary* animationDictionary =
1473 [NSMutableDictionary dictionaryWithDictionary:[tabView animations]];
1474 [animationDictionary setObject:animation forKey:@"frameOrigin"];
1475 [tabView setAnimations:animationDictionary];
1477 // Periscope down! Animate the tab.
1478 NSRect newFrame = [tabView frame];
1479 newFrame = NSOffsetRect(newFrame, 0, -newFrame.size.height);
1480 ScopedNSAnimationContextGroup animationGroup(true);
1481 animationGroup.SetCurrentContextDuration(kAnimationDuration);
1482 [[tabView animator] setFrame:newFrame];
1485 // Called when a notification is received from the model that the given tab
1486 // has gone away. Start an animation then force a layout to put everything
1488 - (void)tabDetachedWithContents:(content::WebContents*)contents
1489 atIndex:(NSInteger)modelIndex {
1490 // Take closing tabs into account.
1491 NSInteger index = [self indexFromModelIndex:modelIndex];
1493 // Cancel any pending tab transition.
1494 hoverTabSelector_->CancelTabTransition();
1496 TabController* tab = [tabArray_ objectAtIndex:index];
1497 if (tabStripModel_->count() > 0) {
1498 [self startClosingTabWithAnimation:tab];
1501 // Don't remove the tab, as that makes the window look jarring without any
1502 // tabs. Instead, simply mark it as closing to prevent the tab from
1503 // generating any drags or selections.
1504 [[tab tabView] setClosing:YES];
1507 [delegate_ onTabDetachedWithContents:contents];
1510 // A helper routine for creating an NSImageView to hold the favicon or app icon
1512 - (NSImage*)iconImageForContents:(content::WebContents*)contents {
1513 extensions::TabHelper* extensions_tab_helper =
1514 extensions::TabHelper::FromWebContents(contents);
1515 BOOL isApp = extensions_tab_helper->is_app();
1516 NSImage* image = nil;
1517 // Favicons come from the renderer, and the renderer draws everything in the
1518 // system color space.
1519 CGColorSpaceRef colorSpace = base::mac::GetSystemColorSpace();
1521 SkBitmap* icon = extensions_tab_helper->GetExtensionAppIcon();
1523 image = gfx::SkBitmapToNSImageWithColorSpace(*icon, colorSpace);
1525 image = mac::FaviconForWebContents(contents);
1528 // Either we don't have a valid favicon or there was some issue converting it
1529 // from an SkBitmap. Either way, just show the default.
1531 image = defaultFavicon_.get();
1536 // Updates the current loading state, replacing the icon view with a favicon,
1537 // a throbber, the default icon, or nothing at all.
1538 - (void)updateIconsForContents:(content::WebContents*)contents
1539 atIndex:(NSInteger)modelIndex {
1543 static NSImage* throbberWaitingImage =
1544 ResourceBundle::GetSharedInstance().GetNativeImageNamed(
1545 IDR_THROBBER_WAITING).CopyNSImage();
1546 static NSImage* throbberLoadingImage =
1547 ResourceBundle::GetSharedInstance().GetNativeImageNamed(
1548 IDR_THROBBER).CopyNSImage();
1549 static NSImage* sadFaviconImage =
1550 ResourceBundle::GetSharedInstance().GetNativeImageNamed(
1551 IDR_SAD_FAVICON).CopyNSImage();
1553 // Take closing tabs into account.
1554 NSInteger index = [self indexFromModelIndex:modelIndex];
1555 TabController* tabController = [tabArray_ objectAtIndex:index];
1557 FaviconTabHelper* favicon_tab_helper =
1558 FaviconTabHelper::FromWebContents(contents);
1559 bool oldHasIcon = [tabController iconView] != nil;
1560 bool newHasIcon = favicon_tab_helper->ShouldDisplayFavicon() ||
1561 tabStripModel_->IsMiniTab(modelIndex); // Always show icon if mini.
1563 TabLoadingState oldState = [tabController loadingState];
1564 TabLoadingState newState = kTabDone;
1565 NSImage* throbberImage = nil;
1566 if (contents->IsCrashed()) {
1567 newState = kTabCrashed;
1569 } else if (contents->IsWaitingForResponse()) {
1570 newState = kTabWaiting;
1571 throbberImage = throbberWaitingImage;
1572 } else if (contents->IsLoadingToDifferentDocument()) {
1573 newState = kTabLoading;
1574 throbberImage = throbberLoadingImage;
1577 if (oldState != newState)
1578 [tabController setLoadingState:newState];
1580 // While loading, this function is called repeatedly with the same state.
1581 // To avoid expensive unnecessary view manipulation, only make changes when
1582 // the state is actually changing. When loading is complete (kTabDone),
1583 // every call to this function is significant.
1584 if (newState == kTabDone || oldState != newState ||
1585 oldHasIcon != newHasIcon) {
1587 if (newState == kTabDone) {
1588 [tabController setIconImage:[self iconImageForContents:contents]];
1589 } else if (newState == kTabCrashed) {
1590 [tabController setIconImage:sadFaviconImage withToastAnimation:YES];
1592 [tabController setIconImage:throbberImage];
1595 [tabController setIconImage:nil];
1599 [tabController setMediaState:chrome::GetTabMediaStateForContents(contents)];
1601 [tabController updateVisibility];
1604 // Called when a notification is received from the model that the given tab
1605 // has been updated. |loading| will be YES when we only want to update the
1606 // throbber state, not anything else about the (partially) loading tab.
1607 - (void)tabChangedWithContents:(content::WebContents*)contents
1608 atIndex:(NSInteger)modelIndex
1609 changeType:(TabStripModelObserver::TabChangeType)change {
1610 // Take closing tabs into account.
1611 NSInteger index = [self indexFromModelIndex:modelIndex];
1613 if (modelIndex == tabStripModel_->active_index())
1614 [delegate_ onTabChanged:change withContents:contents];
1616 if (change == TabStripModelObserver::TITLE_NOT_LOADING) {
1617 // TODO(sky): make this work.
1618 // We'll receive another notification of the change asynchronously.
1622 TabController* tabController = [tabArray_ objectAtIndex:index];
1624 if (change != TabStripModelObserver::LOADING_ONLY)
1625 [self setTabTitle:tabController withContents:contents];
1627 [self updateIconsForContents:contents atIndex:modelIndex];
1629 TabContentsController* updatedController =
1630 [tabContentsArray_ objectAtIndex:index];
1631 [updatedController tabDidChange:contents];
1634 // Called when a tab is moved (usually by drag&drop). Keep our parallel arrays
1635 // in sync with the tab strip model. It can also be pinned/unpinned
1636 // simultaneously, so we need to take care of that.
1637 - (void)tabMovedWithContents:(content::WebContents*)contents
1638 fromIndex:(NSInteger)modelFrom
1639 toIndex:(NSInteger)modelTo {
1640 // Take closing tabs into account.
1641 NSInteger from = [self indexFromModelIndex:modelFrom];
1642 NSInteger to = [self indexFromModelIndex:modelTo];
1644 // Cancel any pending tab transition.
1645 hoverTabSelector_->CancelTabTransition();
1647 base::scoped_nsobject<TabContentsController> movedTabContentsController(
1648 [[tabContentsArray_ objectAtIndex:from] retain]);
1649 [tabContentsArray_ removeObjectAtIndex:from];
1650 [tabContentsArray_ insertObject:movedTabContentsController.get()
1652 base::scoped_nsobject<TabController> movedTabController(
1653 [[tabArray_ objectAtIndex:from] retain]);
1654 DCHECK([movedTabController isKindOfClass:[TabController class]]);
1655 [tabArray_ removeObjectAtIndex:from];
1656 [tabArray_ insertObject:movedTabController.get() atIndex:to];
1658 // The tab moved, which means that the mini-tab state may have changed.
1659 if (tabStripModel_->IsMiniTab(modelTo) != [movedTabController mini])
1660 [self tabMiniStateChangedWithContents:contents atIndex:modelTo];
1665 // Called when a tab is pinned or unpinned without moving.
1666 - (void)tabMiniStateChangedWithContents:(content::WebContents*)contents
1667 atIndex:(NSInteger)modelIndex {
1668 // Take closing tabs into account.
1669 NSInteger index = [self indexFromModelIndex:modelIndex];
1671 TabController* tabController = [tabArray_ objectAtIndex:index];
1672 DCHECK([tabController isKindOfClass:[TabController class]]);
1674 // Don't do anything if the change was already picked up by the move event.
1675 if (tabStripModel_->IsMiniTab(modelIndex) == [tabController mini])
1678 [tabController setMini:tabStripModel_->IsMiniTab(modelIndex)];
1679 [tabController setPinned:tabStripModel_->IsTabPinned(modelIndex)];
1680 [tabController setApp:tabStripModel_->IsAppTab(modelIndex)];
1681 [tabController setUrl:contents->GetURL()];
1682 [self updateIconsForContents:contents atIndex:modelIndex];
1683 // If the tab is being restored and it's pinned, the mini state is set after
1684 // the tab has already been rendered, so re-layout the tabstrip. In all other
1685 // cases, the state is set before the tab is rendered so this isn't needed.
1689 - (void)setFrame:(NSRect)frame ofTabView:(NSView*)view {
1690 NSValue* identifier = [NSValue valueWithPointer:view];
1691 [targetFrames_ setObject:[NSValue valueWithRect:frame]
1693 [view setFrame:frame];
1696 - (TabStripModel*)tabStripModel {
1697 return tabStripModel_;
1700 - (NSArray*)tabViews {
1701 NSMutableArray* views = [NSMutableArray arrayWithCapacity:[tabArray_ count]];
1702 for (TabController* tab in tabArray_.get()) {
1703 [views addObject:[tab tabView]];
1708 - (NSView*)activeTabView {
1709 int activeIndex = tabStripModel_->active_index();
1710 // Take closing tabs into account. They can't ever be selected.
1711 activeIndex = [self indexFromModelIndex:activeIndex];
1712 return [self viewAtIndex:activeIndex];
1715 - (int)indexOfPlaceholder {
1716 // Use |tabArray_| here instead of the tab strip count in order to get the
1717 // correct index when there are closing tabs to the left of the placeholder.
1718 const int count = [tabArray_ count];
1720 // No placeholder, return the end of the strip.
1721 if (placeholderTab_ == nil)
1724 double placeholderX = placeholderFrame_.origin.x;
1727 while (index < count) {
1728 // Ignore closing tabs for simplicity. The only drawback of this is that
1729 // if the placeholder is placed right before one or several contiguous
1730 // currently closing tabs, the associated TabController will start at the
1731 // end of the closing tabs.
1732 if ([closingControllers_ containsObject:[tabArray_ objectAtIndex:index]]) {
1736 NSView* curr = [self viewAtIndex:index];
1737 // The placeholder tab works by changing the frame of the tab being dragged
1738 // to be the bounds of the placeholder, so we need to skip it while we're
1739 // iterating, otherwise we'll end up off by one. Note This only effects
1740 // dragging to the right, not to the left.
1741 if (curr == placeholderTab_) {
1745 if (placeholderX <= NSMinX([curr frame]))
1753 // Move the given tab at index |from| in this window to the location of the
1754 // current placeholder.
1755 - (void)moveTabFromIndex:(NSInteger)from {
1756 int toIndex = [self indexOfPlaceholder];
1757 // Cancel any pending tab transition.
1758 hoverTabSelector_->CancelTabTransition();
1759 tabStripModel_->MoveWebContentsAt(from, toIndex, true);
1762 // Drop a given WebContents at the location of the current placeholder.
1763 // If there is no placeholder, it will go at the end. Used when dragging from
1764 // another window when we don't have access to the WebContents as part of our
1765 // strip. |frame| is in the coordinate system of the tab strip view and
1766 // represents where the user dropped the new tab so it can be animated into its
1767 // correct location when the tab is added to the model. If the tab was pinned in
1768 // its previous window, setting |pinned| to YES will propagate that state to the
1769 // new window. Mini-tabs are either app or pinned tabs; the app state is stored
1770 // by the |contents|, but the |pinned| state is the caller's responsibility.
1771 - (void)dropWebContents:(WebContents*)contents
1772 atIndex:(int)modelIndex
1773 withFrame:(NSRect)frame
1774 asPinnedTab:(BOOL)pinned
1775 activate:(BOOL)activate {
1776 // Mark that the new tab being created should start at |frame|. It will be
1777 // reset as soon as the tab has been positioned.
1778 droppedTabFrame_ = frame;
1780 // Insert it into this tab strip. We want it in the foreground and to not
1781 // inherit the current tab's group.
1782 tabStripModel_->InsertWebContentsAt(
1785 (activate ? TabStripModel::ADD_ACTIVE : TabStripModel::ADD_NONE) |
1786 (pinned ? TabStripModel::ADD_PINNED : TabStripModel::ADD_NONE));
1789 // Called when the tab strip view changes size. As we only registered for
1790 // changes on our view, we know it's only for our view. Layout w/out
1791 // animations since they are blocked by the resize nested runloop. We need
1792 // the views to adjust immediately. Neither the tabs nor their z-order are
1793 // changed, so we don't need to update the subviews.
1794 - (void)tabViewFrameChanged:(NSNotification*)info {
1795 [self layoutTabsWithAnimation:NO regenerateSubviews:NO];
1798 // Called when the tracking areas for any given tab are updated. This allows
1799 // the individual tabs to update their hover states correctly.
1800 // Only generates the event if the cursor is in the tab strip.
1801 - (void)tabUpdateTracking:(NSNotification*)notification {
1802 DCHECK([[notification object] isKindOfClass:[TabView class]]);
1803 DCHECK(mouseInside_);
1804 NSWindow* window = [tabStripView_ window];
1805 NSPoint location = [window mouseLocationOutsideOfEventStream];
1806 if (NSPointInRect(location, [tabStripView_ frame])) {
1807 NSEvent* mouseEvent = [NSEvent mouseEventWithType:NSMouseMoved
1811 windowNumber:[window windowNumber]
1816 [self mouseMoved:mouseEvent];
1820 - (BOOL)inRapidClosureMode {
1821 return availableResizeWidth_ != kUseFullAvailableWidth;
1824 // Disable tab dragging when there are any pending animations.
1825 - (BOOL)tabDraggingAllowed {
1826 return [closingControllers_ count] == 0;
1829 - (void)mouseMoved:(NSEvent*)event {
1830 // We don't want the draggged tab to repeatedly redraw its glow unnecessarily.
1831 // We also want the dragged tab to keep the glow even when it slides behind
1833 if ([dragController_ draggedTab])
1836 // Use hit test to figure out what view we are hovering over.
1837 NSView* targetView = [tabStripView_ hitTest:[event locationInWindow]];
1839 // Set the new tab button hover state iff the mouse is over the button.
1840 BOOL shouldShowHoverImage = [targetView isKindOfClass:[NewTabButton class]];
1841 [self setNewTabButtonHoverState:shouldShowHoverImage];
1843 TabView* tabView = (TabView*)targetView;
1844 if (![tabView isKindOfClass:[TabView class]]) {
1845 if ([[tabView superview] isKindOfClass:[TabView class]]) {
1846 tabView = (TabView*)[targetView superview];
1852 if (hoveredTab_ != tabView) {
1853 [self setHoveredTab:tabView];
1855 [hoveredTab_ mouseMoved:event];
1859 - (void)mouseEntered:(NSEvent*)event {
1860 NSTrackingArea* area = [event trackingArea];
1861 if ([area isEqual:trackingArea_]) {
1863 [self setTabTrackingAreasEnabled:YES];
1864 [self mouseMoved:event];
1868 // Called when the tracking area is in effect which means we're tracking to
1869 // see if the user leaves the tab strip with their mouse. When they do,
1870 // reset layout to use all available width.
1871 - (void)mouseExited:(NSEvent*)event {
1872 NSTrackingArea* area = [event trackingArea];
1873 if ([area isEqual:trackingArea_]) {
1875 [self setTabTrackingAreasEnabled:NO];
1876 availableResizeWidth_ = kUseFullAvailableWidth;
1877 [self setHoveredTab:nil];
1879 } else if ([area isEqual:newTabTrackingArea_]) {
1880 // If the mouse is moved quickly enough, it is possible for the mouse to
1881 // leave the tabstrip without sending any mouseMoved: messages at all.
1882 // Since this would result in the new tab button incorrectly staying in the
1883 // hover state, disable the hover image on every mouse exit.
1884 [self setNewTabButtonHoverState:NO];
1888 - (TabView*)hoveredTab {
1892 - (void)setHoveredTab:(TabView*)newHoveredTab {
1894 [hoveredTab_ mouseExited:nil];
1895 [toolTipView_ setFrame:NSZeroRect];
1898 hoveredTab_ = newHoveredTab;
1900 if (newHoveredTab) {
1901 [newHoveredTab mouseEntered:nil];
1903 // Use a transparent subview to show the hovered tab's tooltip while the
1904 // mouse pointer is inside the tab's custom shape.
1906 toolTipView_.reset([[NSView alloc] init]);
1907 [toolTipView_ setToolTip:[newHoveredTab toolTipText]];
1908 [toolTipView_ setFrame:[newHoveredTab frame]];
1909 if (![toolTipView_ superview]) {
1910 [tabStripView_ addSubview:toolTipView_
1911 positioned:NSWindowBelow
1917 // Enable/Disable the tracking areas for the tabs. They are only enabled
1918 // when the mouse is in the tabstrip.
1919 - (void)setTabTrackingAreasEnabled:(BOOL)enabled {
1920 NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
1921 for (TabController* controller in tabArray_.get()) {
1922 TabView* tabView = [controller tabView];
1924 // Set self up to observe tabs so hover states will be correct.
1925 [defaultCenter addObserver:self
1926 selector:@selector(tabUpdateTracking:)
1927 name:NSViewDidUpdateTrackingAreasNotification
1930 [defaultCenter removeObserver:self
1931 name:NSViewDidUpdateTrackingAreasNotification
1934 [tabView setTrackingEnabled:enabled];
1938 // Sets the new tab button's image based on the current hover state. Does
1939 // nothing if the hover state is already correct.
1940 - (void)setNewTabButtonHoverState:(BOOL)shouldShowHover {
1941 if (shouldShowHover && !newTabButtonShowingHoverImage_) {
1942 newTabButtonShowingHoverImage_ = YES;
1943 [[newTabButton_ cell] setIsMouseInside:YES];
1944 } else if (!shouldShowHover && newTabButtonShowingHoverImage_) {
1945 newTabButtonShowingHoverImage_ = NO;
1946 [[newTabButton_ cell] setIsMouseInside:NO];
1950 // Adds the given subview to (the end of) the list of permanent subviews
1951 // (specified from bottom up). These subviews will always be below the
1952 // transitory subviews (tabs). |-regenerateSubviewList| must be called to
1953 // effectuate the addition.
1954 - (void)addSubviewToPermanentList:(NSView*)aView {
1956 [permanentSubviews_ addObject:aView];
1959 // Update the subviews, keeping the permanent ones (or, more correctly, putting
1960 // in the ones listed in permanentSubviews_), and putting in the current tabs in
1961 // the correct z-order. Any current subviews which is neither in the permanent
1962 // list nor a (current) tab will be removed. So if you add such a subview, you
1963 // should call |-addSubviewToPermanentList:| (or better yet, call that and then
1964 // |-regenerateSubviewList| to actually add it).
1965 - (void)regenerateSubviewList {
1966 // Remove self as an observer from all the old tabs before a new set of
1967 // potentially different tabs is put in place.
1968 [self setTabTrackingAreasEnabled:NO];
1970 // Subviews to put in (in bottom-to-top order), beginning with the permanent
1972 NSMutableArray* subviews = [NSMutableArray arrayWithArray:permanentSubviews_];
1974 NSView* activeTabView = nil;
1975 // Go through tabs in reverse order, since |subviews| is bottom-to-top.
1976 for (TabController* tab in [tabArray_ reverseObjectEnumerator]) {
1977 NSView* tabView = [tab view];
1979 DCHECK(!activeTabView);
1980 activeTabView = tabView;
1982 [subviews addObject:tabView];
1985 if (activeTabView) {
1986 [subviews addObject:activeTabView];
1988 WithNoAnimation noAnimation;
1989 [tabStripView_ setSubviews:subviews];
1990 [self setTabTrackingAreasEnabled:mouseInside_];
1993 // Get the index and disposition for a potential URL(s) drop given a point (in
1994 // the |TabStripView|'s coordinates). It considers only the x-coordinate of the
1995 // given point. If it's in the "middle" of a tab, it drops on that tab. If it's
1996 // to the left, it inserts to the left, and similarly for the right.
1997 - (void)droppingURLsAt:(NSPoint)point
1998 givesIndex:(NSInteger*)index
1999 disposition:(WindowOpenDisposition*)disposition {
2000 // Proportion of the tab which is considered the "middle" (and causes things
2001 // to drop on that tab).
2002 const double kMiddleProportion = 0.5;
2003 const double kLRProportion = (1.0 - kMiddleProportion) / 2.0;
2005 DCHECK(index && disposition);
2007 for (TabController* tab in tabArray_.get()) {
2008 NSView* view = [tab view];
2009 DCHECK([view isKindOfClass:[TabView class]]);
2011 // Recall that |-[NSView frame]| is in its superview's coordinates, so a
2012 // |TabView|'s frame is in the coordinates of the |TabStripView| (which
2013 // matches the coordinate system of |point|).
2014 NSRect frame = [view frame];
2016 // Modify the frame to make it "unoverlapped".
2017 frame.origin.x += kTabOverlap / 2.0;
2018 frame.size.width -= kTabOverlap;
2019 if (frame.size.width < 1.0)
2020 frame.size.width = 1.0; // try to avoid complete failure
2022 // Drop in a new tab to the left of tab |i|?
2023 if (point.x < (frame.origin.x + kLRProportion * frame.size.width)) {
2025 *disposition = NEW_FOREGROUND_TAB;
2030 if (point.x <= (frame.origin.x +
2031 (1.0 - kLRProportion) * frame.size.width)) {
2033 *disposition = CURRENT_TAB;
2037 // (Dropping in a new tab to the right of tab |i| will be taken care of in
2038 // the next iteration.)
2042 // If we've made it here, we want to append a new tab to the end.
2044 *disposition = NEW_FOREGROUND_TAB;
2047 - (void)openURL:(GURL*)url inView:(NSView*)view at:(NSPoint)point {
2048 // Get the index and disposition.
2050 WindowOpenDisposition disposition;
2051 [self droppingURLsAt:point
2053 disposition:&disposition];
2055 // Either insert a new tab or open in a current tab.
2056 switch (disposition) {
2057 case NEW_FOREGROUND_TAB: {
2058 content::RecordAction(UserMetricsAction("Tab_DropURLBetweenTabs"));
2059 chrome::NavigateParams params(browser_, *url,
2060 ui::PAGE_TRANSITION_TYPED);
2061 params.disposition = disposition;
2062 params.tabstrip_index = index;
2063 params.tabstrip_add_types =
2064 TabStripModel::ADD_ACTIVE | TabStripModel::ADD_FORCE_INDEX;
2065 chrome::Navigate(¶ms);
2069 content::RecordAction(UserMetricsAction("Tab_DropURLOnTab"));
2070 OpenURLParams params(
2071 *url, Referrer(), CURRENT_TAB, ui::PAGE_TRANSITION_TYPED, false);
2072 tabStripModel_->GetWebContentsAt(index)->OpenURL(params);
2073 tabStripModel_->ActivateTabAt(index, true);
2081 // (URLDropTargetController protocol)
2082 - (void)dropURLs:(NSArray*)urls inView:(NSView*)view at:(NSPoint)point {
2083 DCHECK_EQ(view, tabStripView_.get());
2085 if ([urls count] < 1) {
2090 //TODO(viettrungluu): dropping multiple URLs.
2091 if ([urls count] > 1)
2094 // Get the first URL and fix it up.
2095 GURL url(GURL(url_fixer::FixupURL(
2096 base::SysNSStringToUTF8([urls objectAtIndex:0]), std::string())));
2098 [self openURL:&url inView:view at:point];
2101 // (URLDropTargetController protocol)
2102 - (void)dropText:(NSString*)text inView:(NSView*)view at:(NSPoint)point {
2103 DCHECK_EQ(view, tabStripView_.get());
2105 // If the input is plain text, classify the input and make the URL.
2106 AutocompleteMatch match;
2107 AutocompleteClassifierFactory::GetForProfile(browser_->profile())->Classify(
2108 base::SysNSStringToUTF16(text), false, false,
2109 metrics::OmniboxEventProto::BLANK, &match, NULL);
2110 GURL url(match.destination_url);
2112 [self openURL:&url inView:view at:point];
2115 // (URLDropTargetController protocol)
2116 - (void)indicateDropURLsInView:(NSView*)view at:(NSPoint)point {
2117 DCHECK_EQ(view, tabStripView_.get());
2119 // The minimum y-coordinate at which one should consider place the arrow.
2120 const CGFloat arrowBaseY = 25;
2123 WindowOpenDisposition disposition;
2124 [self droppingURLsAt:point
2126 disposition:&disposition];
2128 NSPoint arrowPos = NSMakePoint(0, arrowBaseY);
2130 // Append a tab at the end.
2131 DCHECK(disposition == NEW_FOREGROUND_TAB);
2132 NSInteger lastIndex = [tabArray_ count] - 1;
2133 NSRect overRect = [[[tabArray_ objectAtIndex:lastIndex] view] frame];
2134 arrowPos.x = overRect.origin.x + overRect.size.width - kTabOverlap / 2.0;
2136 NSRect overRect = [[[tabArray_ objectAtIndex:index] view] frame];
2137 switch (disposition) {
2138 case NEW_FOREGROUND_TAB:
2139 // Insert tab (to the left of the given tab).
2140 arrowPos.x = overRect.origin.x + kTabOverlap / 2.0;
2143 // Overwrite the given tab.
2144 arrowPos.x = overRect.origin.x + overRect.size.width / 2.0;
2151 [tabStripView_ setDropArrowPosition:arrowPos];
2152 [tabStripView_ setDropArrowShown:YES];
2153 [tabStripView_ setNeedsDisplay:YES];
2155 // Perform a delayed tab transition if hovering directly over a tab.
2156 if (index != -1 && disposition == CURRENT_TAB) {
2157 NSInteger modelIndex = [self modelIndexFromIndex:index];
2158 // Only start the transition if it has a valid model index (i.e. it's not
2159 // in the middle of closing).
2160 if (modelIndex != NSNotFound) {
2161 hoverTabSelector_->StartTabTransition(modelIndex);
2165 // If a tab transition was not started, cancel the pending one.
2166 hoverTabSelector_->CancelTabTransition();
2169 // (URLDropTargetController protocol)
2170 - (void)hideDropURLsIndicatorInView:(NSView*)view {
2171 DCHECK_EQ(view, tabStripView_.get());
2173 // Cancel any pending tab transition.
2174 hoverTabSelector_->CancelTabTransition();
2176 if ([tabStripView_ dropArrowShown]) {
2177 [tabStripView_ setDropArrowShown:NO];
2178 [tabStripView_ setNeedsDisplay:YES];
2182 // (URLDropTargetController protocol)
2183 - (BOOL)isUnsupportedDropData:(id<NSDraggingInfo>)info {
2184 return drag_util::IsUnsupportedDropData(browser_->profile(), info);
2187 - (TabContentsController*)activeTabContentsController {
2188 int modelIndex = tabStripModel_->active_index();
2191 NSInteger index = [self indexFromModelIndex:modelIndex];
2193 index >= (NSInteger)[tabContentsArray_ count])
2195 return [tabContentsArray_ objectAtIndex:index];
2198 - (void)addCustomWindowControls {
2199 if (!customWindowControls_) {
2200 // Make the container view.
2201 CGFloat height = NSHeight([tabStripView_ frame]);
2202 NSRect frame = NSMakeRect(0, 0, [self leftIndentForControls], height);
2203 customWindowControls_.reset([[NSView alloc] initWithFrame:frame]);
2204 [customWindowControls_
2205 setAutoresizingMask:NSViewMaxXMargin | NSViewHeightSizable];
2207 // Add the traffic light buttons. The horizontal layout was determined by
2208 // manual inspection on Yosemite.
2209 CGFloat closeButtonX = 11;
2210 CGFloat miniButtonX = 31;
2211 CGFloat zoomButtonX = 51;
2213 NSUInteger styleMask = [[tabStripView_ window] styleMask];
2214 NSButton* closeButton = [NSWindow standardWindowButton:NSWindowCloseButton
2215 forStyleMask:styleMask];
2217 // Vertically center the buttons in the tab strip.
2218 CGFloat buttonY = floor((height - NSHeight([closeButton bounds])) / 2);
2219 [closeButton setFrameOrigin:NSMakePoint(closeButtonX, buttonY)];
2220 [customWindowControls_ addSubview:closeButton];
2222 NSButton* miniaturizeButton =
2223 [NSWindow standardWindowButton:NSWindowMiniaturizeButton
2224 forStyleMask:styleMask];
2225 [miniaturizeButton setFrameOrigin:NSMakePoint(miniButtonX, buttonY)];
2226 [miniaturizeButton setEnabled:NO];
2227 [customWindowControls_ addSubview:miniaturizeButton];
2229 NSButton* zoomButton =
2230 [NSWindow standardWindowButton:NSWindowZoomButton
2231 forStyleMask:styleMask];
2232 [customWindowControls_ addSubview:zoomButton];
2233 [zoomButton setFrameOrigin:NSMakePoint(zoomButtonX, buttonY)];
2236 if (![permanentSubviews_ containsObject:customWindowControls_]) {
2237 [self addSubviewToPermanentList:customWindowControls_];
2238 [self regenerateSubviewList];
2242 - (void)removeCustomWindowControls {
2243 if (customWindowControls_)
2244 [permanentSubviews_ removeObject:customWindowControls_];
2245 [self regenerateSubviewList];
2248 - (void)themeDidChangeNotification:(NSNotification*)notification {
2249 [self setNewTabImages];
2252 - (void)setNewTabImages {
2253 ThemeService *theme =
2254 static_cast<ThemeService*>([[tabStripView_ window] themeProvider]);
2258 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
2259 NSImage* mask = rb.GetNativeImageNamed(IDR_NEWTAB_BUTTON_MASK).ToNSImage();
2260 NSImage* normal = rb.GetNativeImageNamed(IDR_NEWTAB_BUTTON).ToNSImage();
2261 NSImage* hover = rb.GetNativeImageNamed(IDR_NEWTAB_BUTTON_H).ToNSImage();
2262 NSImage* pressed = rb.GetNativeImageNamed(IDR_NEWTAB_BUTTON_P).ToNSImage();
2264 NSImage* foreground = ApplyMask(
2265 theme->GetNSImageNamed(IDR_THEME_TAB_BACKGROUND), mask);
2267 [[newTabButton_ cell] setImage:Overlay(foreground, normal, 1.0)
2268 forButtonState:image_button_cell::kDefaultState];
2269 [[newTabButton_ cell] setImage:Overlay(foreground, hover, 1.0)
2270 forButtonState:image_button_cell::kHoverState];
2271 [[newTabButton_ cell] setImage:Overlay(foreground, pressed, 1.0)
2272 forButtonState:image_button_cell::kPressedState];
2274 // IDR_THEME_TAB_BACKGROUND_INACTIVE is only used with the default theme.
2275 if (theme->UsingDefaultTheme()) {
2276 const CGFloat alpha = tabs::kImageNoFocusAlpha;
2277 NSImage* background = ApplyMask(
2278 theme->GetNSImageNamed(IDR_THEME_TAB_BACKGROUND_INACTIVE), mask);
2279 [[newTabButton_ cell] setImage:Overlay(background, normal, alpha)
2280 forButtonState:image_button_cell::kDefaultStateBackground];
2281 [[newTabButton_ cell] setImage:Overlay(background, hover, alpha)
2282 forButtonState:image_button_cell::kHoverStateBackground];
2284 [[newTabButton_ cell] setImage:nil
2285 forButtonState:image_button_cell::kDefaultStateBackground];
2286 [[newTabButton_ cell] setImage:nil
2287 forButtonState:image_button_cell::kHoverStateBackground];