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 #include "chrome/browser/ui/views/tabs/tab.h"
9 #include "base/command_line.h"
10 #include "base/debug/alias.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "chrome/browser/defaults.h"
13 #include "chrome/browser/themes/theme_properties.h"
14 #include "chrome/browser/ui/browser.h"
15 #include "chrome/browser/ui/tab_contents/core_tab_helper.h"
16 #include "chrome/browser/ui/tabs/tab_resources.h"
17 #include "chrome/browser/ui/tabs/tab_utils.h"
18 #include "chrome/browser/ui/view_ids.h"
19 #include "chrome/browser/ui/views/tabs/media_indicator_button.h"
20 #include "chrome/browser/ui/views/tabs/tab_controller.h"
21 #include "chrome/browser/ui/views/theme_image_mapper.h"
22 #include "chrome/browser/ui/views/touch_uma/touch_uma.h"
23 #include "chrome/common/chrome_switches.h"
24 #include "chrome/grit/generated_resources.h"
25 #include "content/public/browser/user_metrics.h"
26 #include "grit/theme_resources.h"
27 #include "third_party/skia/include/effects/SkGradientShader.h"
28 #include "ui/accessibility/ax_view_state.h"
29 #include "ui/aura/env.h"
30 #include "ui/base/l10n/l10n_util.h"
31 #include "ui/base/models/list_selection_model.h"
32 #include "ui/base/resource/resource_bundle.h"
33 #include "ui/base/theme_provider.h"
34 #include "ui/gfx/animation/animation_container.h"
35 #include "ui/gfx/animation/multi_animation.h"
36 #include "ui/gfx/animation/throb_animation.h"
37 #include "ui/gfx/canvas.h"
38 #include "ui/gfx/color_analysis.h"
39 #include "ui/gfx/favicon_size.h"
40 #include "ui/gfx/image/image_skia_operations.h"
41 #include "ui/gfx/path.h"
42 #include "ui/gfx/rect_conversions.h"
43 #include "ui/gfx/skia_util.h"
44 #include "ui/resources/grit/ui_resources.h"
45 #include "ui/views/border.h"
46 #include "ui/views/controls/button/image_button.h"
47 #include "ui/views/controls/label.h"
48 #include "ui/views/rect_based_targeting_utils.h"
49 #include "ui/views/view_targeter.h"
50 #include "ui/views/widget/tooltip_manager.h"
51 #include "ui/views/widget/widget.h"
52 #include "ui/views/window/non_client_view.h"
54 using base::UserMetricsAction;
58 // Padding around the "content" of a tab, occupied by the tab border graphics.
59 const int kLeftPadding = 22;
60 const int kTopPadding = 4;
61 const int kRightPadding = 17;
62 const int kBottomPadding = 2;
64 // Height of the shadow at the top of the tab image assets.
65 const int kDropShadowHeight = 4;
67 // How long the pulse throb takes.
68 const int kPulseDurationMs = 200;
70 // Width of touch tabs.
71 static const int kTouchWidth = 120;
73 static const int kToolbarOverlap = 1;
74 static const int kFaviconTitleSpacing = 4;
75 static const int kViewSpacing = 3;
76 static const int kStandardTitleWidth = 175;
78 // When a non-mini-tab becomes a mini-tab the width of the tab animates. If
79 // the width of a mini-tab is >= kMiniTabRendererAsNormalTabWidth then the tab
80 // is rendered as a normal tab. This is done to avoid having the title
81 // immediately disappear when transitioning a tab from normal to mini-tab.
82 static const int kMiniTabRendererAsNormalTabWidth =
83 browser_defaults::kMiniTabWidth + 30;
85 // How opaque to make the hover state (out of 1).
86 static const double kHoverOpacity = 0.33;
88 // Opacity for non-active selected tabs.
89 static const double kSelectedTabOpacity = .45;
91 // Selected (but not active) tabs have their throb value scaled down by this.
92 static const double kSelectedTabThrobScale = .5;
94 // Durations for the various parts of the mini tab title animation.
95 static const int kMiniTitleChangeAnimationDuration1MS = 1600;
96 static const int kMiniTitleChangeAnimationStart1MS = 0;
97 static const int kMiniTitleChangeAnimationEnd1MS = 1900;
98 static const int kMiniTitleChangeAnimationDuration2MS = 0;
99 static const int kMiniTitleChangeAnimationDuration3MS = 550;
100 static const int kMiniTitleChangeAnimationStart3MS = 150;
101 static const int kMiniTitleChangeAnimationEnd3MS = 800;
102 static const int kMiniTitleChangeAnimationIntervalMS = 40;
104 // Offset from the right edge for the start of the mini title change animation.
105 static const int kMiniTitleChangeInitialXOffset = 6;
107 // Radius of the radial gradient used for mini title change animation.
108 static const int kMiniTitleChangeGradientRadius = 20;
110 // Colors of the gradient used during the mini title change animation.
111 static const SkColor kMiniTitleChangeGradientColor1 = SK_ColorWHITE;
112 static const SkColor kMiniTitleChangeGradientColor2 =
113 SkColorSetARGB(0, 255, 255, 255);
115 // Max number of images to cache. This has to be at least two since rounding
116 // errors may lead to tabs in the same tabstrip having different sizes.
117 const size_t kMaxImageCacheSize = 4;
119 // Height of the miniature tab strip in immersive mode.
120 const int kImmersiveTabHeight = 3;
122 // Height of the small tab indicator rectangles in immersive mode.
123 const int kImmersiveBarHeight = 2;
125 // Color for active and inactive tabs in the immersive mode light strip. These
126 // should be a little brighter than the color of the normal art assets for tabs,
127 // which for active tabs is 230, 230, 230 and for inactive is 184, 184, 184.
128 const SkColor kImmersiveActiveTabColor = SkColorSetRGB(235, 235, 235);
129 const SkColor kImmersiveInactiveTabColor = SkColorSetRGB(190, 190, 190);
131 // The minimum opacity (out of 1) when a tab (either active or inactive) is
132 // throbbing in the immersive mode light strip.
133 const double kImmersiveTabMinThrobOpacity = 0.66;
135 // Number of steps in the immersive mode loading animation.
136 const int kImmersiveLoadingStepCount = 32;
138 const char kTabCloseButtonName[] = "TabCloseButton";
140 void DrawIconAtLocation(gfx::Canvas* canvas,
141 const gfx::ImageSkia& image,
148 const SkPaint& paint) {
149 // NOTE: the clipping is a work around for 69528, it shouldn't be necessary.
151 canvas->ClipRect(gfx::Rect(dst_x, dst_y, icon_width, icon_height));
152 canvas->DrawImageInt(image,
153 image_offset, 0, icon_width, icon_height,
154 dst_x, dst_y, icon_width, icon_height,
159 // Draws the icon image at the center of |bounds|.
160 void DrawIconCenter(gfx::Canvas* canvas,
161 const gfx::ImageSkia& image,
165 const gfx::Rect& bounds,
167 const SkPaint& paint) {
168 // Center the image within bounds.
169 int dst_x = bounds.x() - (icon_width - bounds.width()) / 2;
170 int dst_y = bounds.y() - (icon_height - bounds.height()) / 2;
171 DrawIconAtLocation(canvas, image, image_offset, dst_x, dst_y, icon_width,
172 icon_height, filter, paint);
175 chrome::HostDesktopType GetHostDesktopType(views::View* view) {
176 // Widget is NULL when tabs are detached.
177 views::Widget* widget = view->GetWidget();
178 return chrome::GetHostDesktopTypeForNativeView(
179 widget ? widget->GetNativeView() : NULL);
182 // Stop()s |animation| and then deletes it. We do this rather than just deleting
183 // so that the delegate is notified before the destruction.
184 void StopAndDeleteAnimation(scoped_ptr<gfx::Animation> animation) {
191 ////////////////////////////////////////////////////////////////////////////////
192 // FaviconCrashAnimation
194 // A custom animation subclass to manage the favicon crash animation.
195 class Tab::FaviconCrashAnimation : public gfx::LinearAnimation,
196 public gfx::AnimationDelegate {
198 explicit FaviconCrashAnimation(Tab* target)
199 : gfx::LinearAnimation(1000, 25, this),
202 ~FaviconCrashAnimation() override {}
204 // gfx::Animation overrides:
205 void AnimateToState(double state) override {
206 const double kHidingOffset = 27;
209 target_->SetFaviconHidingOffset(
210 static_cast<int>(floor(kHidingOffset * 2.0 * state)));
212 target_->DisplayCrashedFavicon();
213 target_->SetFaviconHidingOffset(
215 floor(kHidingOffset - ((state - .5) * 2.0 * kHidingOffset))));
219 // gfx::AnimationDelegate overrides:
220 void AnimationCanceled(const gfx::Animation* animation) override {
221 target_->SetFaviconHidingOffset(0);
227 DISALLOW_COPY_AND_ASSIGN(FaviconCrashAnimation);
230 ////////////////////////////////////////////////////////////////////////////////
233 // This is a Button subclass that causes middle clicks to be forwarded to the
234 // parent View by explicitly not handling them in OnMousePressed.
235 class Tab::TabCloseButton : public views::ImageButton,
236 public views::MaskedTargeterDelegate {
238 explicit TabCloseButton(Tab* tab)
239 : views::ImageButton(tab),
242 scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this)));
245 ~TabCloseButton() override {}
248 View* GetTooltipHandlerForPoint(const gfx::Point& point) override {
249 // Tab close button has no children, so tooltip handler should be the same
250 // as the event handler.
251 // In addition, a hit test has to be performed for the point (as
252 // GetTooltipHandlerForPoint() is responsible for it).
253 if (!HitTestPoint(point))
255 return GetEventHandlerForPoint(point);
258 bool OnMousePressed(const ui::MouseEvent& event) override {
259 tab_->controller_->OnMouseEventInTab(this, event);
261 bool handled = ImageButton::OnMousePressed(event);
262 // Explicitly mark midle-mouse clicks as non-handled to ensure the tab
264 return event.IsOnlyMiddleMouseButton() ? false : handled;
267 void OnMouseMoved(const ui::MouseEvent& event) override {
268 tab_->controller_->OnMouseEventInTab(this, event);
269 CustomButton::OnMouseMoved(event);
272 void OnMouseReleased(const ui::MouseEvent& event) override {
273 tab_->controller_->OnMouseEventInTab(this, event);
274 CustomButton::OnMouseReleased(event);
277 void OnGestureEvent(ui::GestureEvent* event) override {
278 // Consume all gesture events here so that the parent (Tab) does not
279 // start consuming gestures.
280 ImageButton::OnGestureEvent(event);
284 const char* GetClassName() const override { return kTabCloseButtonName; }
287 // Returns the rectangular bounds of parent tab's visible region in the
288 // local coordinate space of |this|.
289 gfx::Rect GetTabBounds() const {
291 tab_->GetHitTestMask(&tab_mask);
293 gfx::RectF tab_bounds_f(gfx::SkRectToRectF(tab_mask.getBounds()));
294 views::View::ConvertRectToTarget(tab_, this, &tab_bounds_f);
295 return gfx::ToEnclosingRect(tab_bounds_f);
298 // Returns the rectangular bounds of the tab close button in the local
299 // coordinate space of |this|, not including clipped regions on the top
300 // or bottom of the button. |tab_bounds| is the rectangular bounds of
301 // the parent tab's visible region in the local coordinate space of |this|.
302 gfx::Rect GetTabCloseButtonBounds(const gfx::Rect& tab_bounds) const {
303 gfx::Rect button_bounds(GetContentsBounds());
304 button_bounds.set_x(GetMirroredXForRect(button_bounds));
306 int top_overflow = tab_bounds.y() - button_bounds.y();
307 int bottom_overflow = button_bounds.bottom() - tab_bounds.bottom();
308 if (top_overflow > 0)
309 button_bounds.set_y(tab_bounds.y());
310 else if (bottom_overflow > 0)
311 button_bounds.set_height(button_bounds.height() - bottom_overflow);
313 return button_bounds;
316 // views::ViewTargeterDelegate:
317 View* TargetForRect(View* root, const gfx::Rect& rect) override {
318 CHECK_EQ(root, this);
320 if (!views::UsePointBasedTargeting(rect))
321 return ViewTargeterDelegate::TargetForRect(root, rect);
323 // Ignore the padding set on the button.
324 gfx::Rect contents_bounds = GetContentsBounds();
325 contents_bounds.set_x(GetMirroredXForRect(contents_bounds));
327 // Include the padding in hit-test for touch events.
328 if (aura::Env::GetInstance()->is_touch_down())
329 contents_bounds = GetLocalBounds();
331 return contents_bounds.Intersects(rect) ? this : parent();
334 // views:MaskedTargeterDelegate:
335 bool GetHitTestMask(gfx::Path* mask) const override {
339 // The parent tab may be partially occluded by another tab if we are
340 // in stacked tab mode, which means that the tab close button may also
341 // be partially occluded. Define the hit test mask of the tab close
342 // button to be the intersection of the parent tab's visible bounds
343 // and the bounds of the tab close button.
344 gfx::Rect tab_bounds(GetTabBounds());
345 gfx::Rect button_bounds(GetTabCloseButtonBounds(tab_bounds));
346 gfx::Rect intersection(gfx::IntersectRects(tab_bounds, button_bounds));
348 if (!intersection.IsEmpty()) {
349 mask->addRect(RectToSkRect(intersection));
356 bool DoesIntersectRect(const View* target,
357 const gfx::Rect& rect) const override {
358 CHECK_EQ(target, this);
360 // If the request is not made in response to a gesture, use the
361 // default implementation.
362 if (views::UsePointBasedTargeting(rect))
363 return MaskedTargeterDelegate::DoesIntersectRect(target, rect);
365 // The hit test request is in response to a gesture. Return false if any
366 // part of the tab close button is hidden from the user.
367 // TODO(tdanderson): Consider always returning the intersection if the
368 // non-rectangular shape of the tab can be accounted for.
369 gfx::Rect tab_bounds(GetTabBounds());
370 gfx::Rect button_bounds(GetTabCloseButtonBounds(tab_bounds));
371 if (!tab_bounds.Contains(button_bounds))
374 return MaskedTargeterDelegate::DoesIntersectRect(target, rect);
379 DISALLOW_COPY_AND_ASSIGN(TabCloseButton);
382 ////////////////////////////////////////////////////////////////////////////////
385 Tab::ImageCacheEntry::ImageCacheEntry()
387 scale_factor(ui::SCALE_FACTOR_NONE) {
390 Tab::ImageCacheEntry::~ImageCacheEntry() {}
392 ////////////////////////////////////////////////////////////////////////////////
396 const char Tab::kViewClassName[] = "Tab";
397 Tab::TabImage Tab::tab_active_ = {0};
398 Tab::TabImage Tab::tab_inactive_ = {0};
399 Tab::TabImage Tab::tab_alpha_ = {0};
400 Tab::ImageCache* Tab::image_cache_ = NULL;
402 ////////////////////////////////////////////////////////////////////////////////
405 Tab::Tab(TabController* controller)
406 : controller_(controller),
410 favicon_hiding_offset_(0),
411 loading_animation_frame_(0),
412 immersive_loading_step_(0),
413 should_display_crashed_favicon_(false),
415 media_indicator_button_(NULL),
416 title_(new views::Label()),
417 tab_activated_with_last_tap_down_(false),
418 hover_controller_(this),
419 showing_icon_(false),
420 showing_media_indicator_(false),
421 showing_close_button_(false),
422 close_button_color_(0) {
426 // So we get don't get enter/exit on children and don't prematurely stop the
428 set_notify_enter_exit_on_child(true);
432 title_->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD);
433 title_->SetElideBehavior(gfx::FADE_TAIL);
434 title_->SetHandlesTooltips(false);
435 title_->SetAutoColorReadabilityEnabled(false);
436 title_->SetText(CoreTabHelper::GetDefaultTitle());
437 AddChildView(title_);
440 scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this)));
442 // Add the Close Button.
443 close_button_ = new TabCloseButton(this);
444 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
445 close_button_->SetImage(views::CustomButton::STATE_NORMAL,
446 rb.GetImageSkiaNamed(IDR_CLOSE_1));
447 close_button_->SetImage(views::CustomButton::STATE_HOVERED,
448 rb.GetImageSkiaNamed(IDR_CLOSE_1_H));
449 close_button_->SetImage(views::CustomButton::STATE_PRESSED,
450 rb.GetImageSkiaNamed(IDR_CLOSE_1_P));
451 close_button_->SetAccessibleName(
452 l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
453 // Disable animation so that the red danger sign shows up immediately
454 // to help avoid mis-clicks.
455 close_button_->SetAnimationDuration(0);
456 AddChildView(close_button_);
458 set_context_menu_controller(this);
464 void Tab::set_animation_container(gfx::AnimationContainer* container) {
465 animation_container_ = container;
466 hover_controller_.SetAnimationContainer(container);
469 bool Tab::IsActive() const {
470 return controller_->IsActiveTab(this);
473 bool Tab::IsSelected() const {
474 return controller_->IsTabSelected(this);
477 void Tab::SetData(const TabRendererData& data) {
478 if (data_.Equals(data))
481 TabRendererData old(data_);
484 base::string16 title = data_.title;
486 title = data_.loading ?
487 l10n_util::GetStringUTF16(IDS_TAB_LOADING_TITLE) :
488 CoreTabHelper::GetDefaultTitle();
490 Browser::FormatTitleForDisplay(&title);
492 title_->SetText(title);
494 if (data_.IsCrashed()) {
495 if (!should_display_crashed_favicon_ && !IsPerformingCrashAnimation()) {
496 data_.media_state = TAB_MEDIA_STATE_NONE;
497 #if defined(OS_CHROMEOS)
498 // On Chrome OS, we reload killed tabs automatically when the user
499 // switches to them. Don't display animations for these unless they're
500 // selected (i.e. in the foreground) -- we won't reload these
501 // automatically since we don't want to get into a crash loop.
503 data_.crashed_status != base::TERMINATION_STATUS_PROCESS_WAS_KILLED)
504 StartCrashAnimation();
506 StartCrashAnimation();
510 if (IsPerformingCrashAnimation())
511 StopCrashAnimation();
512 ResetCrashedFavicon();
515 if (data_.media_state != old.media_state)
516 GetMediaIndicatorButton()->TransitionToMediaState(data_.media_state);
518 if (old.mini != data_.mini) {
519 StopAndDeleteAnimation(mini_title_change_animation_.Pass());
528 void Tab::UpdateLoadingAnimation(TabRendererData::NetworkState state) {
529 if (state == data_.network_state &&
530 state == TabRendererData::NETWORK_STATE_NONE) {
531 // If the network state is none and hasn't changed, do nothing. Otherwise we
532 // need to advance the animation frame.
536 TabRendererData::NetworkState old_state = data_.network_state;
537 data_.network_state = state;
538 AdvanceLoadingAnimation(old_state, state);
541 void Tab::StartPulse() {
542 pulse_animation_.reset(new gfx::ThrobAnimation(this));
543 pulse_animation_->SetSlideDuration(kPulseDurationMs);
544 if (animation_container_.get())
545 pulse_animation_->SetContainer(animation_container_.get());
546 pulse_animation_->StartThrobbing(std::numeric_limits<int>::max());
549 void Tab::StopPulse() {
550 StopAndDeleteAnimation(pulse_animation_.Pass());
553 void Tab::StartMiniTabTitleAnimation() {
556 if (!mini_title_change_animation_) {
557 gfx::MultiAnimation::Parts parts;
559 gfx::MultiAnimation::Part(kMiniTitleChangeAnimationDuration1MS,
560 gfx::Tween::EASE_OUT));
562 gfx::MultiAnimation::Part(kMiniTitleChangeAnimationDuration2MS,
565 gfx::MultiAnimation::Part(kMiniTitleChangeAnimationDuration3MS,
566 gfx::Tween::EASE_IN));
567 parts[0].start_time_ms = kMiniTitleChangeAnimationStart1MS;
568 parts[0].end_time_ms = kMiniTitleChangeAnimationEnd1MS;
569 parts[2].start_time_ms = kMiniTitleChangeAnimationStart3MS;
570 parts[2].end_time_ms = kMiniTitleChangeAnimationEnd3MS;
571 base::TimeDelta timeout =
572 base::TimeDelta::FromMilliseconds(kMiniTitleChangeAnimationIntervalMS);
573 mini_title_change_animation_.reset(new gfx::MultiAnimation(parts, timeout));
574 if (animation_container_.get())
575 mini_title_change_animation_->SetContainer(animation_container_.get());
576 mini_title_change_animation_->set_delegate(this);
578 mini_title_change_animation_->Start();
581 void Tab::StopMiniTabTitleAnimation() {
582 StopAndDeleteAnimation(mini_title_change_animation_.Pass());
586 gfx::Size Tab::GetBasicMinimumUnselectedSize() {
589 gfx::Size minimum_size;
590 minimum_size.set_width(kLeftPadding + kRightPadding);
591 // Since we use image images, the real minimum height of the image is
592 // defined most accurately by the height of the end cap images.
593 minimum_size.set_height(tab_active_.image_l->height());
597 gfx::Size Tab::GetMinimumUnselectedSize() {
598 return GetBasicMinimumUnselectedSize();
602 gfx::Size Tab::GetMinimumSelectedSize() {
603 gfx::Size minimum_size = GetBasicMinimumUnselectedSize();
604 minimum_size.set_width(
605 kLeftPadding + gfx::kFaviconSize + kRightPadding);
610 gfx::Size Tab::GetStandardSize() {
611 gfx::Size standard_size = GetBasicMinimumUnselectedSize();
612 standard_size.set_width(
613 standard_size.width() + kFaviconTitleSpacing + kStandardTitleWidth);
614 return standard_size;
618 int Tab::GetTouchWidth() {
623 int Tab::GetMiniWidth() {
624 return browser_defaults::kMiniTabWidth;
628 int Tab::GetImmersiveHeight() {
629 return kImmersiveTabHeight;
632 ////////////////////////////////////////////////////////////////////////////////
633 // Tab, AnimationDelegate overrides:
635 void Tab::AnimationProgressed(const gfx::Animation* animation) {
636 // Ignore if the pulse animation is being performed on active tab because
637 // it repaints the same image. See |Tab::PaintTabBackground()|.
638 if (animation == pulse_animation_.get() && IsActive())
643 void Tab::AnimationCanceled(const gfx::Animation* animation) {
647 void Tab::AnimationEnded(const gfx::Animation* animation) {
651 ////////////////////////////////////////////////////////////////////////////////
652 // Tab, views::ButtonListener overrides:
654 void Tab::ButtonPressed(views::Button* sender, const ui::Event& event) {
655 if (media_indicator_button_ && media_indicator_button_->visible()) {
656 if (media_indicator_button_->enabled())
657 content::RecordAction(UserMetricsAction("CloseTab_MuteToggleAvailable"));
658 else if (data_.media_state == TAB_MEDIA_STATE_AUDIO_PLAYING)
659 content::RecordAction(UserMetricsAction("CloseTab_AudioIndicator"));
661 content::RecordAction(UserMetricsAction("CloseTab_RecordingIndicator"));
663 content::RecordAction(UserMetricsAction("CloseTab_NoMediaIndicator"));
666 const CloseTabSource source =
667 (event.type() == ui::ET_MOUSE_RELEASED &&
668 (event.flags() & ui::EF_FROM_TOUCH) == 0) ? CLOSE_TAB_FROM_MOUSE :
669 CLOSE_TAB_FROM_TOUCH;
670 DCHECK_EQ(close_button_, sender);
671 controller_->CloseTab(this, source);
672 if (event.type() == ui::ET_GESTURE_TAP)
673 TouchUMA::RecordGestureAction(TouchUMA::GESTURE_TABCLOSE_TAP);
676 ////////////////////////////////////////////////////////////////////////////////
677 // Tab, views::ContextMenuController overrides:
679 void Tab::ShowContextMenuForView(views::View* source,
680 const gfx::Point& point,
681 ui::MenuSourceType source_type) {
683 controller_->ShowContextMenuForTab(this, point, source_type);
686 ////////////////////////////////////////////////////////////////////////////////
687 // Tab, views::MaskedTargeterDelegate overrides:
689 bool Tab::GetHitTestMask(gfx::Path* mask) const {
692 // When the window is maximized we don't want to shave off the edges or top
693 // shadow of the tab, such that the user can click anywhere along the top
694 // edge of the screen to select a tab. Ditto for immersive fullscreen.
695 const views::Widget* widget = GetWidget();
696 bool include_top_shadow =
697 widget && (widget->IsMaximized() || widget->IsFullscreen());
698 TabResources::GetHitTestMask(width(), height(), include_top_shadow, mask);
700 // It is possible for a portion of the tab to be occluded if tabs are
701 // stacked, so modify the hit test mask to only include the visible
702 // region of the tab.
704 controller_->ShouldPaintTab(this, &clip);
705 if (clip.size().GetArea()) {
706 SkRect intersection(mask->getBounds());
707 intersection.intersect(RectToSkRect(clip));
709 mask->addRect(intersection);
715 ////////////////////////////////////////////////////////////////////////////////
716 // Tab, views::View overrides:
718 void Tab::OnPaint(gfx::Canvas* canvas) {
719 // Don't paint if we're narrower than we can render correctly. (This should
720 // only happen during animations).
721 if (width() < GetMinimumUnselectedSize().width() && !data().mini)
725 if (!controller_->ShouldPaintTab(this, &clip))
727 if (!clip.IsEmpty()) {
729 canvas->ClipRect(clip);
732 if (controller_->IsImmersiveStyle())
733 PaintImmersiveTab(canvas);
742 gfx::Rect lb = GetContentsBounds();
746 lb.Inset(kLeftPadding, kTopPadding, kRightPadding, kBottomPadding);
747 showing_icon_ = ShouldShowIcon();
748 favicon_bounds_.SetRect(lb.x(), lb.y(), 0, 0);
750 favicon_bounds_.set_size(gfx::Size(gfx::kFaviconSize, gfx::kFaviconSize));
751 favicon_bounds_.set_y(lb.y() + (lb.height() - gfx::kFaviconSize + 1) / 2);
752 MaybeAdjustLeftForMiniTab(&favicon_bounds_);
755 showing_close_button_ = ShouldShowCloseBox();
756 if (showing_close_button_) {
757 // If the ratio of the close button size to tab width exceeds the maximum.
758 // The close button should be as large as possible so that there is a larger
759 // hit-target for touch events. So the close button bounds extends to the
760 // edges of the tab. However, the larger hit-target should be active only
761 // for mouse events, and the close-image should show up in the right place.
762 // So a border is added to the button with necessary padding. The close
763 // button (BaseTab::TabCloseButton) makes sure the padding is a hit-target
764 // only for touch events.
765 close_button_->SetBorder(views::Border::NullBorder());
766 const gfx::Size close_button_size(close_button_->GetPreferredSize());
767 const int top = lb.y() + (lb.height() - close_button_size.height() + 1) / 2;
768 const int bottom = height() - (close_button_size.height() + top);
769 const int left = kViewSpacing;
770 const int right = width() - (lb.width() + close_button_size.width() + left);
771 close_button_->SetBorder(
772 views::Border::CreateEmptyBorder(top, left, bottom, right));
773 close_button_->SetPosition(gfx::Point(lb.width(), 0));
774 close_button_->SizeToPreferredSize();
776 close_button_->SetVisible(showing_close_button_);
778 showing_media_indicator_ = ShouldShowMediaIndicator();
779 if (showing_media_indicator_) {
780 views::ImageButton* const button = GetMediaIndicatorButton();
781 const gfx::Size image_size(button->GetPreferredSize());
782 const int right = showing_close_button_ ?
783 close_button_->x() + close_button_->GetInsets().left() : lb.right();
785 std::max(lb.x(), right - image_size.width()),
786 lb.y() + (lb.height() - image_size.height() + 1) / 2,
788 image_size.height());
789 MaybeAdjustLeftForMiniTab(&bounds);
790 button->SetBoundsRect(bounds);
791 button->SetVisible(true);
792 } else if (media_indicator_button_) {
793 media_indicator_button_->SetVisible(false);
796 // Size the title to fill the remaining width and use all available height.
797 bool show_title = !data().mini || width() >= kMiniTabRendererAsNormalTabWidth;
799 int title_left = favicon_bounds_.right() + kFaviconTitleSpacing;
800 int title_width = lb.width() - title_left;
801 if (showing_media_indicator_) {
802 title_width = media_indicator_button_->x() - kViewSpacing - title_left;
803 } else if (close_button_->visible()) {
804 // Allow the title to overlay the close button's empty border padding.
805 title_width = close_button_->x() + close_button_->GetInsets().left() -
806 kViewSpacing - title_left;
808 gfx::Rect rect(title_left, lb.y(), std::max(title_width, 0), lb.height());
809 const int title_height = title_->GetPreferredSize().height();
810 if (title_height > rect.height()) {
811 rect.set_y(lb.y() - (title_height - rect.height()) / 2);
812 rect.set_height(title_height);
814 title_->SetBoundsRect(rect);
816 title_->SetVisible(show_title);
819 void Tab::OnThemeChanged() {
823 const char* Tab::GetClassName() const {
824 return kViewClassName;
827 bool Tab::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
828 // Note: Anything that affects the tooltip text should be accounted for when
829 // calling TooltipTextChanged() from Tab::DataChanged().
830 *tooltip = chrome::AssembleTabTooltipText(data_.title, data_.media_state);
831 return !tooltip->empty();
834 bool Tab::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* origin) const {
835 origin->set_x(title_->x() + 10);
836 origin->set_y(-views::TooltipManager::GetTooltipHeight() - 4);
840 bool Tab::OnMousePressed(const ui::MouseEvent& event) {
841 controller_->OnMouseEventInTab(this, event);
843 // Allow a right click from touch to drag, which corresponds to a long click.
844 if (event.IsOnlyLeftMouseButton() ||
845 (event.IsOnlyRightMouseButton() && event.flags() & ui::EF_FROM_TOUCH)) {
846 ui::ListSelectionModel original_selection;
847 original_selection.Copy(controller_->GetSelectionModel());
848 // Changing the selection may cause our bounds to change. If that happens
849 // the location of the event may no longer be valid. Create a copy of the
850 // event in the parents coordinate, which won't change, and recreate an
851 // event after changing so the coordinates are correct.
852 ui::MouseEvent event_in_parent(event, static_cast<View*>(this), parent());
853 if (controller_->SupportsMultipleSelection()) {
854 if (event.IsShiftDown() && event.IsControlDown()) {
855 controller_->AddSelectionFromAnchorTo(this);
856 } else if (event.IsShiftDown()) {
857 controller_->ExtendSelectionTo(this);
858 } else if (event.IsControlDown()) {
859 controller_->ToggleSelected(this);
861 // Don't allow dragging non-selected tabs.
864 } else if (!IsSelected()) {
865 controller_->SelectTab(this);
867 } else if (!IsSelected()) {
868 controller_->SelectTab(this);
870 ui::MouseEvent cloned_event(event_in_parent, parent(),
871 static_cast<View*>(this));
872 controller_->MaybeStartDrag(this, cloned_event, original_selection);
877 bool Tab::OnMouseDragged(const ui::MouseEvent& event) {
878 controller_->ContinueDrag(this, event);
882 void Tab::OnMouseReleased(const ui::MouseEvent& event) {
883 controller_->OnMouseEventInTab(this, event);
885 // Notify the drag helper that we're done with any potential drag operations.
886 // Clean up the drag helper, which is re-created on the next mouse press.
887 // In some cases, ending the drag will schedule the tab for destruction; if
888 // so, bail immediately, since our members are already dead and we shouldn't
889 // do anything else except drop the tab where it is.
890 if (controller_->EndDrag(END_DRAG_COMPLETE))
893 // Close tab on middle click, but only if the button is released over the tab
894 // (normal windows behavior is to discard presses of a UI element where the
895 // releases happen off the element).
896 if (event.IsMiddleMouseButton()) {
897 if (HitTestPoint(event.location())) {
898 controller_->CloseTab(this, CLOSE_TAB_FROM_MOUSE);
899 } else if (closing_) {
900 // We're animating closed and a middle mouse button was pushed on us but
901 // we don't contain the mouse anymore. We assume the user is clicking
902 // quicker than the animation and we should close the tab that falls under
904 Tab* closest_tab = controller_->GetTabAt(this, event.location());
906 controller_->CloseTab(closest_tab, CLOSE_TAB_FROM_MOUSE);
908 } else if (event.IsOnlyLeftMouseButton() && !event.IsShiftDown() &&
909 !event.IsControlDown()) {
910 // If the tab was already selected mouse pressed doesn't change the
911 // selection. Reset it now to handle the case where multiple tabs were
913 controller_->SelectTab(this);
915 if (media_indicator_button_ && media_indicator_button_->visible() &&
916 media_indicator_button_->bounds().Contains(event.location())) {
917 content::RecordAction(UserMetricsAction("TabMediaIndicator_Clicked"));
922 void Tab::OnMouseCaptureLost() {
923 controller_->EndDrag(END_DRAG_CAPTURE_LOST);
926 void Tab::OnMouseEntered(const ui::MouseEvent& event) {
927 hover_controller_.Show(views::GlowHoverController::SUBTLE);
930 void Tab::OnMouseMoved(const ui::MouseEvent& event) {
931 hover_controller_.SetLocation(event.location());
932 controller_->OnMouseEventInTab(this, event);
935 void Tab::OnMouseExited(const ui::MouseEvent& event) {
936 hover_controller_.Hide();
939 void Tab::OnGestureEvent(ui::GestureEvent* event) {
940 switch (event->type()) {
941 case ui::ET_GESTURE_TAP_DOWN: {
942 // TAP_DOWN is only dispatched for the first touch point.
943 DCHECK_EQ(1, event->details().touch_points());
945 // See comment in OnMousePressed() as to why we copy the event.
946 ui::GestureEvent event_in_parent(*event, static_cast<View*>(this),
948 ui::ListSelectionModel original_selection;
949 original_selection.Copy(controller_->GetSelectionModel());
950 tab_activated_with_last_tap_down_ = !IsActive();
952 controller_->SelectTab(this);
953 gfx::Point loc(event->location());
954 views::View::ConvertPointToScreen(this, &loc);
955 ui::GestureEvent cloned_event(event_in_parent, parent(),
956 static_cast<View*>(this));
957 controller_->MaybeStartDrag(this, cloned_event, original_selection);
961 case ui::ET_GESTURE_END:
962 controller_->EndDrag(END_DRAG_COMPLETE);
965 case ui::ET_GESTURE_SCROLL_UPDATE:
966 controller_->ContinueDrag(this, *event);
975 void Tab::GetAccessibleState(ui::AXViewState* state) {
976 state->role = ui::AX_ROLE_TAB;
977 state->name = data_.title;
978 state->AddStateFlag(ui::AX_STATE_MULTISELECTABLE);
979 state->AddStateFlag(ui::AX_STATE_SELECTABLE);
980 controller_->UpdateTabAccessibilityState(this, state);
982 state->AddStateFlag(ui::AX_STATE_SELECTED);
985 ////////////////////////////////////////////////////////////////////////////////
988 void Tab::MaybeAdjustLeftForMiniTab(gfx::Rect* bounds) const {
989 if (!data().mini || width() >= kMiniTabRendererAsNormalTabWidth)
991 const int mini_delta = kMiniTabRendererAsNormalTabWidth - GetMiniWidth();
992 const int ideal_delta = width() - GetMiniWidth();
993 const int ideal_x = (GetMiniWidth() - bounds->width()) / 2;
994 bounds->set_x(bounds->x() + static_cast<int>(
995 (1 - static_cast<float>(ideal_delta) / static_cast<float>(mini_delta)) *
996 (ideal_x - bounds->x())));
999 void Tab::DataChanged(const TabRendererData& old) {
1000 if (data().media_state != old.media_state || data().title != old.title)
1001 TooltipTextChanged();
1003 if (data().blocked == old.blocked)
1012 void Tab::PaintTab(gfx::Canvas* canvas) {
1013 // See if the model changes whether the icons should be painted.
1014 const bool show_icon = ShouldShowIcon();
1015 const bool show_media_indicator = ShouldShowMediaIndicator();
1016 const bool show_close_button = ShouldShowCloseBox();
1017 if (show_icon != showing_icon_ ||
1018 show_media_indicator != showing_media_indicator_ ||
1019 show_close_button != showing_close_button_) {
1023 PaintTabBackground(canvas);
1025 const SkColor title_color = GetThemeProvider()->GetColor(IsSelected() ?
1026 ThemeProperties::COLOR_TAB_TEXT :
1027 ThemeProperties::COLOR_BACKGROUND_TAB_TEXT);
1028 title_->SetVisible(!data().mini ||
1029 width() > kMiniTabRendererAsNormalTabWidth);
1030 title_->SetEnabledColor(title_color);
1035 // If the close button color has changed, generate a new one.
1036 if (!close_button_color_ || title_color != close_button_color_) {
1037 close_button_color_ = title_color;
1038 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1039 close_button_->SetBackground(close_button_color_,
1040 rb.GetImageSkiaNamed(IDR_CLOSE_1),
1041 rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));
1045 void Tab::PaintImmersiveTab(gfx::Canvas* canvas) {
1046 // Use transparency for the draw-attention animation.
1048 if (pulse_animation_ && pulse_animation_->is_animating() && !data().mini) {
1049 alpha = pulse_animation_->CurrentValueBetween(
1050 255, static_cast<int>(255 * kImmersiveTabMinThrobOpacity));
1053 // Draw a gray rectangle to represent the tab. This works for mini-tabs as
1054 // well as regular ones. The active tab has a brigher bar.
1056 IsActive() ? kImmersiveActiveTabColor : kImmersiveInactiveTabColor;
1057 gfx::Rect bar_rect = GetImmersiveBarRect();
1058 canvas->FillRect(bar_rect, SkColorSetA(color, alpha));
1060 // Paint network activity indicator.
1061 // TODO(jamescook): Replace this placeholder animation with a real one.
1062 // For now, let's go with a Cylon eye effect, but in blue.
1063 if (data().network_state != TabRendererData::NETWORK_STATE_NONE) {
1064 const SkColor kEyeColor = SkColorSetARGB(alpha, 71, 138, 217);
1065 int eye_width = bar_rect.width() / 3;
1066 int eye_offset = bar_rect.width() * immersive_loading_step_ /
1067 kImmersiveLoadingStepCount;
1068 if (eye_offset + eye_width < bar_rect.width()) {
1069 // Draw a single indicator strip because it fits inside |bar_rect|.
1071 bar_rect.x() + eye_offset, 0, eye_width, kImmersiveBarHeight);
1072 canvas->FillRect(eye_rect, kEyeColor);
1074 // Draw two indicators to simulate the eye "wrapping around" to the left
1075 // side. The first part fills the remainder of the bar.
1076 int right_eye_width = bar_rect.width() - eye_offset;
1077 gfx::Rect right_eye_rect(
1078 bar_rect.x() + eye_offset, 0, right_eye_width, kImmersiveBarHeight);
1079 canvas->FillRect(right_eye_rect, kEyeColor);
1080 // The second part parts the remaining |eye_width| on the left.
1081 int left_eye_width = eye_offset + eye_width - bar_rect.width();
1082 gfx::Rect left_eye_rect(
1083 bar_rect.x(), 0, left_eye_width, kImmersiveBarHeight);
1084 canvas->FillRect(left_eye_rect, kEyeColor);
1089 void Tab::PaintTabBackground(gfx::Canvas* canvas) {
1091 PaintActiveTabBackground(canvas);
1093 if (mini_title_change_animation_ &&
1094 mini_title_change_animation_->is_animating()) {
1095 PaintInactiveTabBackgroundWithTitleChange(canvas);
1097 PaintInactiveTabBackground(canvas);
1100 double throb_value = GetThrobValue();
1101 if (throb_value > 0) {
1102 canvas->SaveLayerAlpha(static_cast<int>(throb_value * 0xff),
1104 PaintActiveTabBackground(canvas);
1110 void Tab::PaintInactiveTabBackgroundWithTitleChange(gfx::Canvas* canvas) {
1111 // Render the inactive tab background. We'll use this for clipping.
1112 gfx::Canvas background_canvas(size(), canvas->image_scale(), false);
1113 PaintInactiveTabBackground(&background_canvas);
1115 gfx::ImageSkia background_image(background_canvas.ExtractImageRep());
1117 // Draw a radial gradient to hover_canvas.
1118 gfx::Canvas hover_canvas(size(), canvas->image_scale(), false);
1119 int radius = kMiniTitleChangeGradientRadius;
1120 int x0 = width() + radius - kMiniTitleChangeInitialXOffset;
1124 if (mini_title_change_animation_->current_part_index() == 0) {
1125 x = mini_title_change_animation_->CurrentValueBetween(x0, x1);
1126 } else if (mini_title_change_animation_->current_part_index() == 1) {
1129 x = mini_title_change_animation_->CurrentValueBetween(x1, x2);
1131 SkPoint center_point;
1132 center_point.iset(x, 0);
1133 SkColor colors[2] = { kMiniTitleChangeGradientColor1,
1134 kMiniTitleChangeGradientColor2 };
1135 skia::RefPtr<SkShader> shader = skia::AdoptRef(
1136 SkGradientShader::CreateRadial(
1137 center_point, SkIntToScalar(radius), colors, NULL, 2,
1138 SkShader::kClamp_TileMode));
1140 paint.setShader(shader.get());
1141 hover_canvas.DrawRect(gfx::Rect(x - radius, -radius, radius * 2, radius * 2),
1144 // Draw the radial gradient clipped to the background into hover_image.
1145 gfx::ImageSkia hover_image = gfx::ImageSkiaOperations::CreateMaskedImage(
1146 gfx::ImageSkia(hover_canvas.ExtractImageRep()), background_image);
1148 // Draw the tab background to the canvas.
1149 canvas->DrawImageInt(background_image, 0, 0);
1151 // And then the gradient on top of that.
1152 if (mini_title_change_animation_->current_part_index() == 2) {
1153 uint8 alpha = mini_title_change_animation_->CurrentValueBetween(255, 0);
1154 canvas->DrawImageInt(hover_image, 0, 0, alpha);
1156 canvas->DrawImageInt(hover_image, 0, 0);
1160 void Tab::PaintInactiveTabBackground(gfx::Canvas* canvas) {
1163 views::Widget* widget = GetWidget();
1164 GetTabIdAndFrameId(widget, &tab_id, &frame_id);
1166 // Explicitly map the id so we cache correctly.
1167 const chrome::HostDesktopType host_desktop_type = GetHostDesktopType(this);
1168 tab_id = chrome::MapThemeImage(host_desktop_type, tab_id);
1170 // HasCustomImage() is only true if the theme provides the image. However,
1171 // even if the theme does not provide a tab background, the theme machinery
1172 // will make one if given a frame image.
1173 ui::ThemeProvider* theme_provider = GetThemeProvider();
1174 const bool theme_provided_image = theme_provider->HasCustomImage(tab_id) ||
1175 (frame_id != 0 && theme_provider->HasCustomImage(frame_id));
1177 const bool can_cache = !theme_provided_image &&
1178 !hover_controller_.ShouldDraw();
1181 ui::ScaleFactor scale_factor =
1182 ui::GetSupportedScaleFactor(canvas->image_scale());
1183 gfx::ImageSkia cached_image(GetCachedImage(tab_id, size(), scale_factor));
1184 if (cached_image.width() == 0) {
1185 gfx::Canvas tmp_canvas(size(), canvas->image_scale(), false);
1186 PaintInactiveTabBackgroundUsingResourceId(&tmp_canvas, tab_id);
1187 cached_image = gfx::ImageSkia(tmp_canvas.ExtractImageRep());
1188 SetCachedImage(tab_id, scale_factor, cached_image);
1190 canvas->DrawImageInt(cached_image, 0, 0);
1192 PaintInactiveTabBackgroundUsingResourceId(canvas, tab_id);
1196 void Tab::PaintInactiveTabBackgroundUsingResourceId(gfx::Canvas* canvas,
1198 // WARNING: the inactive tab background may be cached. If you change what it
1199 // is drawn from you may need to update whether it can be cached.
1201 // The tab image needs to be lined up with the background image
1202 // so that it feels partially transparent. These offsets represent the tab
1203 // position within the frame background image.
1204 int offset = GetMirroredX() + background_offset_.x();
1206 gfx::ImageSkia* tab_bg = GetThemeProvider()->GetImageSkiaNamed(tab_id);
1208 TabImage* tab_image = &tab_active_;
1209 TabImage* tab_inactive_image = &tab_inactive_;
1210 TabImage* alpha = &tab_alpha_;
1212 // If the theme is providing a custom background image, then its top edge
1213 // should be at the top of the tab. Otherwise, we assume that the background
1214 // image is a composited foreground + frame image.
1215 int bg_offset_y = GetThemeProvider()->HasCustomImage(tab_id) ?
1216 0 : background_offset_.y();
1218 // We need a gfx::Canvas object to be able to extract the image from.
1219 // We draw everything to this canvas and then output it to the canvas
1220 // parameter in addition to using it to mask the hover glow if needed.
1221 gfx::Canvas background_canvas(size(), canvas->image_scale(), false);
1223 // Draw left edge. Don't draw over the toolbar, as we're not the foreground
1225 gfx::ImageSkia tab_l = gfx::ImageSkiaOperations::CreateTiledImage(
1226 *tab_bg, offset, bg_offset_y, tab_image->l_width, height());
1227 gfx::ImageSkia theme_l =
1228 gfx::ImageSkiaOperations::CreateMaskedImage(tab_l, *alpha->image_l);
1229 background_canvas.DrawImageInt(theme_l,
1230 0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
1231 0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
1234 // Draw right edge. Again, don't draw over the toolbar.
1235 gfx::ImageSkia tab_r = gfx::ImageSkiaOperations::CreateTiledImage(*tab_bg,
1236 offset + width() - tab_image->r_width, bg_offset_y,
1237 tab_image->r_width, height());
1238 gfx::ImageSkia theme_r =
1239 gfx::ImageSkiaOperations::CreateMaskedImage(tab_r, *alpha->image_r);
1240 background_canvas.DrawImageInt(theme_r,
1241 0, 0, theme_r.width(), theme_r.height() - kToolbarOverlap,
1242 width() - theme_r.width(), 0, theme_r.width(),
1243 theme_r.height() - kToolbarOverlap, false);
1245 // Draw center. Instead of masking out the top portion we simply skip over
1246 // it by incrementing by GetDropShadowHeight(), since it's a simple
1247 // rectangle. And again, don't draw over the toolbar.
1248 background_canvas.TileImageInt(*tab_bg,
1249 offset + tab_image->l_width,
1250 bg_offset_y + kDropShadowHeight,
1253 width() - tab_image->l_width - tab_image->r_width,
1254 height() - kDropShadowHeight - kToolbarOverlap);
1256 canvas->DrawImageInt(
1257 gfx::ImageSkia(background_canvas.ExtractImageRep()), 0, 0);
1259 if (!GetThemeProvider()->HasCustomImage(tab_id) &&
1260 hover_controller_.ShouldDraw()) {
1261 hover_controller_.Draw(canvas, gfx::ImageSkia(
1262 background_canvas.ExtractImageRep()));
1265 // Now draw the highlights/shadows around the tab edge.
1266 canvas->DrawImageInt(*tab_inactive_image->image_l, 0, 0);
1267 canvas->TileImageInt(*tab_inactive_image->image_c,
1268 tab_inactive_image->l_width, 0,
1269 width() - tab_inactive_image->l_width -
1270 tab_inactive_image->r_width,
1272 canvas->DrawImageInt(*tab_inactive_image->image_r,
1273 width() - tab_inactive_image->r_width, 0);
1276 void Tab::PaintActiveTabBackground(gfx::Canvas* canvas) {
1277 gfx::ImageSkia* tab_background =
1278 GetThemeProvider()->GetImageSkiaNamed(IDR_THEME_TOOLBAR);
1279 int offset = GetMirroredX() + background_offset_.x();
1281 TabImage* tab_image = &tab_active_;
1282 TabImage* alpha = &tab_alpha_;
1285 gfx::ImageSkia tab_l = gfx::ImageSkiaOperations::CreateTiledImage(
1286 *tab_background, offset, 0, tab_image->l_width, height());
1287 gfx::ImageSkia theme_l =
1288 gfx::ImageSkiaOperations::CreateMaskedImage(tab_l, *alpha->image_l);
1289 canvas->DrawImageInt(theme_l, 0, 0);
1292 gfx::ImageSkia tab_r = gfx::ImageSkiaOperations::CreateTiledImage(
1294 offset + width() - tab_image->r_width, 0, tab_image->r_width, height());
1295 gfx::ImageSkia theme_r =
1296 gfx::ImageSkiaOperations::CreateMaskedImage(tab_r, *alpha->image_r);
1297 canvas->DrawImageInt(theme_r, width() - tab_image->r_width, 0);
1299 // Draw center. Instead of masking out the top portion we simply skip over it
1300 // by incrementing by GetDropShadowHeight(), since it's a simple rectangle.
1301 canvas->TileImageInt(*tab_background,
1302 offset + tab_image->l_width,
1306 width() - tab_image->l_width - tab_image->r_width,
1307 height() - kDropShadowHeight);
1309 // Now draw the highlights/shadows around the tab edge.
1310 canvas->DrawImageInt(*tab_image->image_l, 0, 0);
1311 canvas->TileImageInt(*tab_image->image_c, tab_image->l_width, 0,
1312 width() - tab_image->l_width - tab_image->r_width, height());
1313 canvas->DrawImageInt(*tab_image->image_r, width() - tab_image->r_width, 0);
1316 void Tab::PaintIcon(gfx::Canvas* canvas) {
1317 gfx::Rect bounds = favicon_bounds_;
1318 if (bounds.IsEmpty())
1321 bounds.set_x(GetMirroredXForRect(bounds));
1323 if (data().network_state != TabRendererData::NETWORK_STATE_NONE) {
1324 // Paint network activity (aka throbber) animation frame.
1325 ui::ThemeProvider* tp = GetThemeProvider();
1326 gfx::ImageSkia frames(*tp->GetImageSkiaNamed(
1327 (data().network_state == TabRendererData::NETWORK_STATE_WAITING) ?
1328 IDR_THROBBER_WAITING : IDR_THROBBER));
1330 int icon_size = frames.height();
1331 int image_offset = loading_animation_frame_ * icon_size;
1332 DrawIconCenter(canvas, frames, image_offset,
1333 icon_size, icon_size,
1334 bounds, false, SkPaint());
1335 } else if (should_display_crashed_favicon_) {
1336 // Paint crash favicon.
1337 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1338 gfx::ImageSkia crashed_favicon(*rb.GetImageSkiaNamed(IDR_SAD_FAVICON));
1339 bounds.set_y(bounds.y() + favicon_hiding_offset_);
1340 DrawIconCenter(canvas, crashed_favicon, 0,
1341 crashed_favicon.width(),
1342 crashed_favicon.height(),
1343 bounds, true, SkPaint());
1344 } else if (!data().favicon.isNull()) {
1345 // Paint the normal favicon.
1346 DrawIconCenter(canvas, data().favicon, 0,
1347 data().favicon.width(),
1348 data().favicon.height(),
1349 bounds, true, SkPaint());
1353 void Tab::AdvanceLoadingAnimation(TabRendererData::NetworkState old_state,
1354 TabRendererData::NetworkState state) {
1355 static bool initialized = false;
1356 static int loading_animation_frame_count = 0;
1357 static int waiting_animation_frame_count = 0;
1358 static int waiting_to_loading_frame_count_ratio = 0;
1361 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1362 gfx::ImageSkia loading_animation(*rb.GetImageSkiaNamed(IDR_THROBBER));
1363 loading_animation_frame_count =
1364 loading_animation.width() / loading_animation.height();
1365 gfx::ImageSkia waiting_animation(*rb.GetImageSkiaNamed(
1366 IDR_THROBBER_WAITING));
1367 waiting_animation_frame_count =
1368 waiting_animation.width() / waiting_animation.height();
1369 waiting_to_loading_frame_count_ratio =
1370 waiting_animation_frame_count / loading_animation_frame_count;
1372 base::debug::Alias(&loading_animation_frame_count);
1373 base::debug::Alias(&waiting_animation_frame_count);
1374 CHECK_NE(0, waiting_to_loading_frame_count_ratio) <<
1375 "Number of frames in IDR_THROBBER must be equal to or greater " <<
1376 "than the number of frames in IDR_THROBBER_WAITING. Please " <<
1377 "investigate how this happened and update http://crbug.com/132590, " <<
1378 "this is causing crashes in the wild.";
1381 // The waiting animation is the reverse of the loading animation, but at a
1382 // different rate - the following reverses and scales the animation_frame_
1383 // so that the frame is at an equivalent position when going from one
1384 // animation to the other.
1385 if (state != old_state) {
1386 loading_animation_frame_ = loading_animation_frame_count -
1387 (loading_animation_frame_ / waiting_to_loading_frame_count_ratio);
1390 if (state == TabRendererData::NETWORK_STATE_WAITING) {
1391 loading_animation_frame_ = (loading_animation_frame_ + 1) %
1392 waiting_animation_frame_count;
1393 // Waiting steps backwards.
1394 immersive_loading_step_ =
1395 (immersive_loading_step_ - 1 + kImmersiveLoadingStepCount) %
1396 kImmersiveLoadingStepCount;
1397 } else if (state == TabRendererData::NETWORK_STATE_LOADING) {
1398 loading_animation_frame_ = (loading_animation_frame_ + 1) %
1399 loading_animation_frame_count;
1400 immersive_loading_step_ = (immersive_loading_step_ + 1) %
1401 kImmersiveLoadingStepCount;
1403 loading_animation_frame_ = 0;
1404 immersive_loading_step_ = 0;
1406 if (controller_->IsImmersiveStyle())
1407 SchedulePaintInRect(GetImmersiveBarRect());
1409 ScheduleIconPaint();
1412 int Tab::IconCapacity() const {
1413 if (height() < GetMinimumUnselectedSize().height())
1415 const int available_width =
1416 std::max(0, width() - kLeftPadding - kRightPadding);
1417 const int width_per_icon = gfx::kFaviconSize;
1418 const int kPaddingBetweenIcons = 2;
1419 if (available_width >= width_per_icon &&
1420 available_width < (width_per_icon + kPaddingBetweenIcons)) {
1423 return available_width / (width_per_icon + kPaddingBetweenIcons);
1426 bool Tab::ShouldShowIcon() const {
1427 return chrome::ShouldTabShowFavicon(
1428 IconCapacity(), data().mini, IsActive(), data().show_icon,
1429 media_indicator_button_ ? media_indicator_button_->showing_media_state() :
1433 bool Tab::ShouldShowMediaIndicator() const {
1434 return chrome::ShouldTabShowMediaIndicator(
1435 IconCapacity(), data().mini, IsActive(), data().show_icon,
1436 media_indicator_button_ ? media_indicator_button_->showing_media_state() :
1440 bool Tab::ShouldShowCloseBox() const {
1441 return chrome::ShouldTabShowCloseButton(
1442 IconCapacity(), data().mini, IsActive());
1445 double Tab::GetThrobValue() {
1446 const bool is_selected = IsSelected();
1447 const double min = is_selected ? kSelectedTabOpacity : 0;
1448 const double scale = is_selected ? kSelectedTabThrobScale : 1;
1450 // Showing both the pulse and title change animation at the same time is too
1452 if (pulse_animation_ && pulse_animation_->is_animating() &&
1453 (!mini_title_change_animation_ ||
1454 !mini_title_change_animation_->is_animating())) {
1455 return pulse_animation_->GetCurrentValue() * kHoverOpacity * scale + min;
1458 if (hover_controller_.ShouldDraw()) {
1459 return kHoverOpacity * hover_controller_.GetAnimationValue() * scale +
1463 return is_selected ? kSelectedTabOpacity : 0;
1466 void Tab::SetFaviconHidingOffset(int offset) {
1467 favicon_hiding_offset_ = offset;
1468 ScheduleIconPaint();
1471 void Tab::DisplayCrashedFavicon() {
1472 should_display_crashed_favicon_ = true;
1475 void Tab::ResetCrashedFavicon() {
1476 should_display_crashed_favicon_ = false;
1479 void Tab::StopCrashAnimation() {
1480 crash_icon_animation_.reset();
1483 void Tab::StartCrashAnimation() {
1484 crash_icon_animation_.reset(new FaviconCrashAnimation(this));
1485 crash_icon_animation_->Start();
1488 bool Tab::IsPerformingCrashAnimation() const {
1489 return crash_icon_animation_.get() && data_.IsCrashed();
1492 void Tab::ScheduleIconPaint() {
1493 gfx::Rect bounds = favicon_bounds_;
1494 if (bounds.IsEmpty())
1497 // Extends the area to the bottom when sad_favicon is animating.
1498 if (IsPerformingCrashAnimation())
1499 bounds.set_height(height() - bounds.y());
1500 bounds.set_x(GetMirroredXForRect(bounds));
1501 SchedulePaintInRect(bounds);
1504 gfx::Rect Tab::GetImmersiveBarRect() const {
1505 // The main bar is as wide as the normal tab's horizontal top line.
1506 // This top line of the tab extends a few pixels left and right of the
1507 // center image due to pixels in the rounded corner images.
1508 const int kBarPadding = 1;
1509 int main_bar_left = tab_active_.l_width - kBarPadding;
1510 int main_bar_right = width() - tab_active_.r_width + kBarPadding;
1512 main_bar_left, 0, main_bar_right - main_bar_left, kImmersiveBarHeight);
1515 void Tab::GetTabIdAndFrameId(views::Widget* widget,
1517 int* frame_id) const {
1519 widget->GetTopLevelWidget()->ShouldWindowContentsBeTransparent()) {
1520 *tab_id = IDR_THEME_TAB_BACKGROUND_V;
1522 } else if (data().incognito) {
1523 *tab_id = IDR_THEME_TAB_BACKGROUND_INCOGNITO;
1524 *frame_id = IDR_THEME_FRAME_INCOGNITO;
1526 *tab_id = IDR_THEME_TAB_BACKGROUND;
1527 *frame_id = IDR_THEME_FRAME;
1531 MediaIndicatorButton* Tab::GetMediaIndicatorButton() {
1532 if (!media_indicator_button_) {
1533 media_indicator_button_ = new MediaIndicatorButton();
1534 AddChildView(media_indicator_button_); // Takes ownership.
1536 return media_indicator_button_;
1539 ////////////////////////////////////////////////////////////////////////////////
1540 // Tab, private static:
1543 void Tab::InitTabResources() {
1544 static bool initialized = false;
1549 image_cache_ = new ImageCache();
1551 // Load the tab images once now, and maybe again later if the theme changes.
1556 void Tab::LoadTabImages() {
1557 // We're not letting people override tab images just yet.
1558 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1560 tab_alpha_.image_l = rb.GetImageSkiaNamed(IDR_TAB_ALPHA_LEFT);
1561 tab_alpha_.image_r = rb.GetImageSkiaNamed(IDR_TAB_ALPHA_RIGHT);
1563 tab_active_.image_l = rb.GetImageSkiaNamed(IDR_TAB_ACTIVE_LEFT);
1564 tab_active_.image_c = rb.GetImageSkiaNamed(IDR_TAB_ACTIVE_CENTER);
1565 tab_active_.image_r = rb.GetImageSkiaNamed(IDR_TAB_ACTIVE_RIGHT);
1566 tab_active_.l_width = tab_active_.image_l->width();
1567 tab_active_.r_width = tab_active_.image_r->width();
1569 tab_inactive_.image_l = rb.GetImageSkiaNamed(IDR_TAB_INACTIVE_LEFT);
1570 tab_inactive_.image_c = rb.GetImageSkiaNamed(IDR_TAB_INACTIVE_CENTER);
1571 tab_inactive_.image_r = rb.GetImageSkiaNamed(IDR_TAB_INACTIVE_RIGHT);
1572 tab_inactive_.l_width = tab_inactive_.image_l->width();
1573 tab_inactive_.r_width = tab_inactive_.image_r->width();
1577 gfx::ImageSkia Tab::GetCachedImage(int resource_id,
1578 const gfx::Size& size,
1579 ui::ScaleFactor scale_factor) {
1580 for (ImageCache::const_iterator i = image_cache_->begin();
1581 i != image_cache_->end(); ++i) {
1582 if (i->resource_id == resource_id && i->scale_factor == scale_factor &&
1583 i->image.size() == size) {
1587 return gfx::ImageSkia();
1591 void Tab::SetCachedImage(int resource_id,
1592 ui::ScaleFactor scale_factor,
1593 const gfx::ImageSkia& image) {
1594 DCHECK_NE(scale_factor, ui::SCALE_FACTOR_NONE);
1595 ImageCacheEntry entry;
1596 entry.resource_id = resource_id;
1597 entry.scale_factor = scale_factor;
1598 entry.image = image;
1599 image_cache_->push_front(entry);
1600 if (image_cache_->size() > kMaxImageCacheSize)
1601 image_cache_->pop_back();