Disable TabDragController tests that fail with a real compositor.
[chromium-blink-merge.git] / chrome / browser / ui / views / tabs / tab.cc
blob41d524b37d0359ad0e9374e4b8431e4f348249ab
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"
7 #include <limits>
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/tab_controller.h"
20 #include "chrome/browser/ui/views/theme_image_mapper.h"
21 #include "chrome/browser/ui/views/touch_uma/touch_uma.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "grit/generated_resources.h"
24 #include "grit/theme_resources.h"
25 #include "grit/ui_resources.h"
26 #include "third_party/skia/include/effects/SkGradientShader.h"
27 #include "ui/base/accessibility/accessible_view_state.h"
28 #include "ui/base/l10n/l10n_util.h"
29 #include "ui/base/layout.h"
30 #include "ui/base/models/list_selection_model.h"
31 #include "ui/base/resource/resource_bundle.h"
32 #include "ui/base/theme_provider.h"
33 #include "ui/gfx/animation/animation_container.h"
34 #include "ui/gfx/animation/multi_animation.h"
35 #include "ui/gfx/animation/throb_animation.h"
36 #include "ui/gfx/canvas.h"
37 #include "ui/gfx/color_analysis.h"
38 #include "ui/gfx/favicon_size.h"
39 #include "ui/gfx/font.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/gfx/text_elider.h"
45 #include "ui/views/border.h"
46 #include "ui/views/controls/button/image_button.h"
47 #include "ui/views/rect_based_targeting_utils.h"
48 #include "ui/views/widget/tooltip_manager.h"
49 #include "ui/views/widget/widget.h"
50 #include "ui/views/window/non_client_view.h"
52 #if defined(OS_WIN)
53 #include "win8/util/win8_util.h"
54 #endif
56 #if defined(USE_ASH)
57 #include "ui/aura/env.h"
58 #endif
60 namespace {
62 // Padding around the "content" of a tab, occupied by the tab border graphics.
64 int left_padding() {
65 static int value = -1;
66 if (value == -1) {
67 switch (ui::GetDisplayLayout()) {
68 case ui::LAYOUT_DESKTOP:
69 value = 22;
70 break;
71 case ui::LAYOUT_TOUCH:
72 value = 30;
73 break;
74 default:
75 NOTREACHED();
78 return value;
81 int top_padding() {
82 static int value = -1;
83 if (value == -1) {
84 switch (ui::GetDisplayLayout()) {
85 case ui::LAYOUT_DESKTOP:
86 value = 7;
87 break;
88 case ui::LAYOUT_TOUCH:
89 value = 10;
90 break;
91 default:
92 NOTREACHED();
95 return value;
98 int right_padding() {
99 static int value = -1;
100 if (value == -1) {
101 switch (ui::GetDisplayLayout()) {
102 case ui::LAYOUT_DESKTOP:
103 value = 17;
104 break;
105 case ui::LAYOUT_TOUCH:
106 value = 21;
107 break;
108 default:
109 NOTREACHED();
112 return value;
115 int bottom_padding() {
116 static int value = -1;
117 if (value == -1) {
118 switch (ui::GetDisplayLayout()) {
119 case ui::LAYOUT_DESKTOP:
120 value = 5;
121 break;
122 case ui::LAYOUT_TOUCH:
123 value = 7;
124 break;
125 default:
126 NOTREACHED();
129 return value;
132 // Height of the shadow at the top of the tab image assets.
133 int drop_shadow_height() {
134 static int value = -1;
135 if (value == -1) {
136 switch (ui::GetDisplayLayout()) {
137 case ui::LAYOUT_DESKTOP:
138 value = 4;
139 break;
140 case ui::LAYOUT_TOUCH:
141 value = 5;
142 break;
143 default:
144 NOTREACHED();
147 return value;
150 // Size of icon used for throbber and favicon next to tab title.
151 int tab_icon_size() {
152 static int value = -1;
153 if (value == -1) {
154 switch (ui::GetDisplayLayout()) {
155 case ui::LAYOUT_DESKTOP:
156 value = gfx::kFaviconSize;
157 break;
158 case ui::LAYOUT_TOUCH:
159 value = 20;
160 break;
161 default:
162 NOTREACHED();
165 return value;
168 // How long the pulse throb takes.
169 const int kPulseDurationMs = 200;
171 // Width of touch tabs.
172 static const int kTouchWidth = 120;
174 static const int kToolbarOverlap = 1;
175 static const int kFaviconTitleSpacing = 4;
176 // Additional vertical offset for title text relative to top of tab.
177 // Ash text rendering may be different than Windows.
178 static const int kTitleTextOffsetYAsh = 1;
179 static const int kTitleTextOffsetY = 0;
180 static const int kTitleCloseButtonSpacing = 3;
181 static const int kStandardTitleWidth = 175;
182 // Additional vertical offset for close button relative to top of tab.
183 // Ash needs this to match the text vertical position.
184 static const int kCloseButtonVertFuzzAsh = 1;
185 static const int kCloseButtonVertFuzz = 0;
186 // Additional horizontal offset for close button relative to title text.
187 static const int kCloseButtonHorzFuzz = 3;
189 // When a non-mini-tab becomes a mini-tab the width of the tab animates. If
190 // the width of a mini-tab is >= kMiniTabRendererAsNormalTabWidth then the tab
191 // is rendered as a normal tab. This is done to avoid having the title
192 // immediately disappear when transitioning a tab from normal to mini-tab.
193 static const int kMiniTabRendererAsNormalTabWidth =
194 browser_defaults::kMiniTabWidth + 30;
196 // How opaque to make the hover state (out of 1).
197 static const double kHoverOpacity = 0.33;
199 // Opacity for non-active selected tabs.
200 static const double kSelectedTabOpacity = .45;
202 // Selected (but not active) tabs have their throb value scaled down by this.
203 static const double kSelectedTabThrobScale = .5;
205 // Durations for the various parts of the mini tab title animation.
206 static const int kMiniTitleChangeAnimationDuration1MS = 1600;
207 static const int kMiniTitleChangeAnimationStart1MS = 0;
208 static const int kMiniTitleChangeAnimationEnd1MS = 1900;
209 static const int kMiniTitleChangeAnimationDuration2MS = 0;
210 static const int kMiniTitleChangeAnimationDuration3MS = 550;
211 static const int kMiniTitleChangeAnimationStart3MS = 150;
212 static const int kMiniTitleChangeAnimationEnd3MS = 800;
213 static const int kMiniTitleChangeAnimationIntervalMS = 40;
215 // Offset from the right edge for the start of the mini title change animation.
216 static const int kMiniTitleChangeInitialXOffset = 6;
218 // Radius of the radial gradient used for mini title change animation.
219 static const int kMiniTitleChangeGradientRadius = 20;
221 // Colors of the gradient used during the mini title change animation.
222 static const SkColor kMiniTitleChangeGradientColor1 = SK_ColorWHITE;
223 static const SkColor kMiniTitleChangeGradientColor2 =
224 SkColorSetARGB(0, 255, 255, 255);
226 // Max number of images to cache. This has to be at least two since rounding
227 // errors may lead to tabs in the same tabstrip having different sizes.
228 const size_t kMaxImageCacheSize = 4;
230 // Height of the miniature tab strip in immersive mode.
231 const int kImmersiveTabHeight = 3;
233 // Height of the small tab indicator rectangles in immersive mode.
234 const int kImmersiveBarHeight = 2;
236 // Color for active and inactive tabs in the immersive mode light strip. These
237 // should be a little brighter than the color of the normal art assets for tabs,
238 // which for active tabs is 230, 230, 230 and for inactive is 184, 184, 184.
239 const SkColor kImmersiveActiveTabColor = SkColorSetRGB(235, 235, 235);
240 const SkColor kImmersiveInactiveTabColor = SkColorSetRGB(190, 190, 190);
242 // The minimum opacity (out of 1) when a tab (either active or inactive) is
243 // throbbing in the immersive mode light strip.
244 const double kImmersiveTabMinThrobOpacity = 0.66;
246 // Number of steps in the immersive mode loading animation.
247 const int kImmersiveLoadingStepCount = 32;
249 const char kTabCloseButtonName[] = "TabCloseButton";
251 void DrawIconAtLocation(gfx::Canvas* canvas,
252 const gfx::ImageSkia& image,
253 int image_offset,
254 int dst_x,
255 int dst_y,
256 int icon_width,
257 int icon_height,
258 bool filter,
259 const SkPaint& paint) {
260 // NOTE: the clipping is a work around for 69528, it shouldn't be necessary.
261 canvas->Save();
262 canvas->ClipRect(gfx::Rect(dst_x, dst_y, icon_width, icon_height));
263 canvas->DrawImageInt(image,
264 image_offset, 0, icon_width, icon_height,
265 dst_x, dst_y, icon_width, icon_height,
266 filter, paint);
267 canvas->Restore();
270 // Draws the icon image at the center of |bounds|.
271 void DrawIconCenter(gfx::Canvas* canvas,
272 const gfx::ImageSkia& image,
273 int image_offset,
274 int icon_width,
275 int icon_height,
276 const gfx::Rect& bounds,
277 bool filter,
278 const SkPaint& paint) {
279 // Center the image within bounds.
280 int dst_x = bounds.x() - (icon_width - bounds.width()) / 2;
281 int dst_y = bounds.y() - (icon_height - bounds.height()) / 2;
282 DrawIconAtLocation(canvas, image, image_offset, dst_x, dst_y, icon_width,
283 icon_height, filter, paint);
286 chrome::HostDesktopType GetHostDesktopType(views::View* view) {
287 // Widget is NULL when tabs are detached.
288 views::Widget* widget = view->GetWidget();
289 return chrome::GetHostDesktopTypeForNativeView(
290 widget ? widget->GetNativeView() : NULL);
293 } // namespace
295 ////////////////////////////////////////////////////////////////////////////////
296 // FaviconCrashAnimation
298 // A custom animation subclass to manage the favicon crash animation.
299 class Tab::FaviconCrashAnimation : public gfx::LinearAnimation,
300 public gfx::AnimationDelegate {
301 public:
302 explicit FaviconCrashAnimation(Tab* target)
303 : gfx::LinearAnimation(1000, 25, this),
304 target_(target) {
306 virtual ~FaviconCrashAnimation() {}
308 // gfx::Animation overrides:
309 virtual void AnimateToState(double state) OVERRIDE {
310 const double kHidingOffset = 27;
312 if (state < .5) {
313 target_->SetFaviconHidingOffset(
314 static_cast<int>(floor(kHidingOffset * 2.0 * state)));
315 } else {
316 target_->DisplayCrashedFavicon();
317 target_->SetFaviconHidingOffset(
318 static_cast<int>(
319 floor(kHidingOffset - ((state - .5) * 2.0 * kHidingOffset))));
323 // gfx::AnimationDelegate overrides:
324 virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
325 target_->SetFaviconHidingOffset(0);
328 private:
329 Tab* target_;
331 DISALLOW_COPY_AND_ASSIGN(FaviconCrashAnimation);
334 ////////////////////////////////////////////////////////////////////////////////
335 // TabCloseButton
337 // This is a Button subclass that causes middle clicks to be forwarded to the
338 // parent View by explicitly not handling them in OnMousePressed.
339 class Tab::TabCloseButton : public views::ImageButton {
340 public:
341 explicit TabCloseButton(Tab* tab) : views::ImageButton(tab), tab_(tab) {}
342 virtual ~TabCloseButton() {}
344 // Overridden from views::View.
345 virtual View* GetEventHandlerForRect(const gfx::Rect& rect) OVERRIDE {
346 if (!views::UsePointBasedTargeting(rect))
347 return View::GetEventHandlerForRect(rect);
349 // Ignore the padding set on the button.
350 gfx::Rect contents_bounds = GetContentsBounds();
351 contents_bounds.set_x(GetMirroredXForRect(contents_bounds));
353 // TODO(tdanderson): Remove this ifdef if rect-based targeting
354 // is turned on by default.
355 #if defined(USE_ASH)
356 // Include the padding in hit-test for touch events.
357 if (aura::Env::GetInstance()->is_touch_down())
358 contents_bounds = GetLocalBounds();
359 #elif defined(OS_WIN)
360 // TODO(sky): Use local-bounds if a touch-point is active.
361 // http://crbug.com/145258
362 #endif
364 return contents_bounds.Intersects(rect) ? this : parent();
367 // Overridden from views::View.
368 virtual View* GetTooltipHandlerForPoint(const gfx::Point& point) OVERRIDE {
369 // Tab close button has no children, so tooltip handler should be the same
370 // as the event handler.
371 // In addition, a hit test has to be performed for the point (as
372 // GetTooltipHandlerForPoint() is responsible for it).
373 if (!HitTestPoint(point))
374 return NULL;
375 return GetEventHandlerForPoint(point);
378 virtual bool OnMousePressed(const ui::MouseEvent& event) OVERRIDE {
379 if (tab_->controller())
380 tab_->controller()->OnMouseEventInTab(this, event);
382 bool handled = ImageButton::OnMousePressed(event);
383 // Explicitly mark midle-mouse clicks as non-handled to ensure the tab
384 // sees them.
385 return event.IsOnlyMiddleMouseButton() ? false : handled;
388 virtual void OnMouseMoved(const ui::MouseEvent& event) OVERRIDE {
389 if (tab_->controller())
390 tab_->controller()->OnMouseEventInTab(this, event);
391 CustomButton::OnMouseMoved(event);
394 virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE {
395 if (tab_->controller())
396 tab_->controller()->OnMouseEventInTab(this, event);
397 CustomButton::OnMouseReleased(event);
400 virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE {
401 // Consume all gesture events here so that the parent (Tab) does not
402 // start consuming gestures.
403 ImageButton::OnGestureEvent(event);
404 event->SetHandled();
407 virtual bool HasHitTestMask() const OVERRIDE {
408 return true;
411 virtual void GetHitTestMask(HitTestSource source,
412 gfx::Path* path) const OVERRIDE {
413 // Use the button's contents bounds (which does not include padding)
414 // and the hit test mask of our parent |tab_| to determine if the
415 // button is hidden behind another tab.
416 gfx::Path tab_mask;
417 tab_->GetHitTestMask(source, &tab_mask);
419 gfx::Rect button_bounds(GetContentsBounds());
420 button_bounds.set_x(GetMirroredXForRect(button_bounds));
421 gfx::RectF tab_bounds_f(gfx::SkRectToRectF(tab_mask.getBounds()));
422 views::View::ConvertRectToTarget(tab_, this, &tab_bounds_f);
423 gfx::Rect tab_bounds = gfx::ToEnclosingRect(tab_bounds_f);
425 // If the button is hidden behind another tab, the hit test mask is empty.
426 // Otherwise set the hit test mask to be the contents bounds.
427 path->reset();
428 if (tab_bounds.Contains(button_bounds)) {
429 // Include the padding in the hit test mask for touch events.
430 if (source == HIT_TEST_SOURCE_TOUCH)
431 button_bounds = GetLocalBounds();
433 path->addRect(RectToSkRect(button_bounds));
437 virtual const char* GetClassName() const OVERRIDE {
438 return kTabCloseButtonName;
441 private:
442 Tab* tab_;
444 DISALLOW_COPY_AND_ASSIGN(TabCloseButton);
447 ////////////////////////////////////////////////////////////////////////////////
448 // ImageCacheEntry
450 Tab::ImageCacheEntry::ImageCacheEntry()
451 : resource_id(-1),
452 scale_factor(ui::SCALE_FACTOR_NONE) {
455 Tab::ImageCacheEntry::~ImageCacheEntry() {}
457 ////////////////////////////////////////////////////////////////////////////////
458 // Tab, statics:
460 // static
461 const char Tab::kViewClassName[] = "Tab";
463 // static
464 Tab::TabImage Tab::tab_alpha_ = {0};
465 Tab::TabImage Tab::tab_active_ = {0};
466 Tab::TabImage Tab::tab_inactive_ = {0};
467 // static
468 gfx::Font* Tab::font_ = NULL;
469 // static
470 int Tab::font_height_ = 0;
471 // static
472 Tab::ImageCache* Tab::image_cache_ = NULL;
474 ////////////////////////////////////////////////////////////////////////////////
475 // Tab, public:
477 Tab::Tab(TabController* controller)
478 : controller_(controller),
479 closing_(false),
480 dragging_(false),
481 favicon_hiding_offset_(0),
482 loading_animation_frame_(0),
483 immersive_loading_step_(0),
484 should_display_crashed_favicon_(false),
485 animating_media_state_(TAB_MEDIA_STATE_NONE),
486 theme_provider_(NULL),
487 tab_activated_with_last_gesture_begin_(false),
488 hover_controller_(this),
489 showing_icon_(false),
490 showing_media_indicator_(false),
491 showing_close_button_(false),
492 close_button_color_(0) {
493 InitTabResources();
495 // So we get don't get enter/exit on children and don't prematurely stop the
496 // hover.
497 set_notify_enter_exit_on_child(true);
499 set_id(VIEW_ID_TAB);
501 // Add the Close Button.
502 close_button_ = new TabCloseButton(this);
503 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
504 close_button_->SetImage(views::CustomButton::STATE_NORMAL,
505 rb.GetImageSkiaNamed(IDR_CLOSE_1));
506 close_button_->SetImage(views::CustomButton::STATE_HOVERED,
507 rb.GetImageSkiaNamed(IDR_CLOSE_1_H));
508 close_button_->SetImage(views::CustomButton::STATE_PRESSED,
509 rb.GetImageSkiaNamed(IDR_CLOSE_1_P));
510 close_button_->SetAccessibleName(
511 l10n_util::GetStringUTF16(IDS_ACCNAME_CLOSE));
512 // Disable animation so that the red danger sign shows up immediately
513 // to help avoid mis-clicks.
514 close_button_->SetAnimationDuration(0);
515 AddChildView(close_button_);
517 set_context_menu_controller(this);
520 Tab::~Tab() {
523 void Tab::set_animation_container(gfx::AnimationContainer* container) {
524 animation_container_ = container;
525 hover_controller_.SetAnimationContainer(container);
528 bool Tab::IsActive() const {
529 return controller() ? controller()->IsActiveTab(this) : true;
532 bool Tab::IsSelected() const {
533 return controller() ? controller()->IsTabSelected(this) : true;
536 void Tab::SetData(const TabRendererData& data) {
537 if (data_.Equals(data))
538 return;
540 TabRendererData old(data_);
541 data_ = data;
543 if (data_.IsCrashed()) {
544 if (!should_display_crashed_favicon_ && !IsPerformingCrashAnimation()) {
545 data_.media_state = TAB_MEDIA_STATE_NONE;
546 #if defined(OS_CHROMEOS)
547 // On Chrome OS, we reload killed tabs automatically when the user
548 // switches to them. Don't display animations for these unless they're
549 // selected (i.e. in the foreground) -- we won't reload these
550 // automatically since we don't want to get into a crash loop.
551 if (IsSelected() ||
552 data_.crashed_status != base::TERMINATION_STATUS_PROCESS_WAS_KILLED)
553 StartCrashAnimation();
554 #else
555 StartCrashAnimation();
556 #endif
558 } else {
559 if (IsPerformingCrashAnimation())
560 StopCrashAnimation();
561 ResetCrashedFavicon();
564 if (data_.media_state != old.media_state) {
565 if (data_.media_state != TAB_MEDIA_STATE_NONE)
566 animating_media_state_ = data_.media_state;
567 StartMediaIndicatorAnimation();
570 if (old.mini != data_.mini) {
571 if (tab_animation_.get() && tab_animation_->is_animating()) {
572 tab_animation_->Stop();
573 tab_animation_.reset(NULL);
577 DataChanged(old);
579 Layout();
580 SchedulePaint();
583 void Tab::UpdateLoadingAnimation(TabRendererData::NetworkState state) {
584 if (state == data_.network_state &&
585 state == TabRendererData::NETWORK_STATE_NONE) {
586 // If the network state is none and hasn't changed, do nothing. Otherwise we
587 // need to advance the animation frame.
588 return;
591 TabRendererData::NetworkState old_state = data_.network_state;
592 data_.network_state = state;
593 AdvanceLoadingAnimation(old_state, state);
596 void Tab::StartPulse() {
597 gfx::ThrobAnimation* animation = new gfx::ThrobAnimation(this);
598 animation->SetSlideDuration(kPulseDurationMs);
599 if (animation_container_.get())
600 animation->SetContainer(animation_container_.get());
601 animation->StartThrobbing(std::numeric_limits<int>::max());
602 tab_animation_.reset(animation);
605 void Tab::StopPulse() {
606 if (!tab_animation_.get())
607 return;
608 tab_animation_->Stop();
609 tab_animation_.reset(NULL);
612 void Tab::StartMiniTabTitleAnimation() {
613 // We can only do this animation if the tab is mini because we will
614 // upcast tab_animation back to MultiAnimation when we draw.
615 if (!data().mini)
616 return;
617 if (!tab_animation_.get()) {
618 gfx::MultiAnimation::Parts parts;
619 parts.push_back(
620 gfx::MultiAnimation::Part(kMiniTitleChangeAnimationDuration1MS,
621 gfx::Tween::EASE_OUT));
622 parts.push_back(
623 gfx::MultiAnimation::Part(kMiniTitleChangeAnimationDuration2MS,
624 gfx::Tween::ZERO));
625 parts.push_back(
626 gfx::MultiAnimation::Part(kMiniTitleChangeAnimationDuration3MS,
627 gfx::Tween::EASE_IN));
628 parts[0].start_time_ms = kMiniTitleChangeAnimationStart1MS;
629 parts[0].end_time_ms = kMiniTitleChangeAnimationEnd1MS;
630 parts[2].start_time_ms = kMiniTitleChangeAnimationStart3MS;
631 parts[2].end_time_ms = kMiniTitleChangeAnimationEnd3MS;
632 base::TimeDelta timeout =
633 base::TimeDelta::FromMilliseconds(kMiniTitleChangeAnimationIntervalMS);
634 gfx::MultiAnimation* animation = new gfx::MultiAnimation(parts, timeout);
635 if (animation_container_.get())
636 animation->SetContainer(animation_container_.get());
637 animation->set_delegate(this);
638 tab_animation_.reset(animation);
640 tab_animation_->Start();
643 void Tab::StopMiniTabTitleAnimation() {
644 if (!tab_animation_.get())
645 return;
646 tab_animation_->Stop();
647 tab_animation_.reset(NULL);
650 // static
651 gfx::Size Tab::GetBasicMinimumUnselectedSize() {
652 InitTabResources();
654 gfx::Size minimum_size;
655 minimum_size.set_width(left_padding() + right_padding());
656 // Since we use image images, the real minimum height of the image is
657 // defined most accurately by the height of the end cap images.
658 minimum_size.set_height(tab_active_.image_l->height());
659 return minimum_size;
662 gfx::Size Tab::GetMinimumUnselectedSize() {
663 return GetBasicMinimumUnselectedSize();
666 // static
667 gfx::Size Tab::GetMinimumSelectedSize() {
668 gfx::Size minimum_size = GetBasicMinimumUnselectedSize();
669 minimum_size.set_width(
670 left_padding() + gfx::kFaviconSize + right_padding());
671 return minimum_size;
674 // static
675 gfx::Size Tab::GetStandardSize() {
676 gfx::Size standard_size = GetBasicMinimumUnselectedSize();
677 standard_size.set_width(
678 standard_size.width() + kFaviconTitleSpacing + kStandardTitleWidth);
679 return standard_size;
682 // static
683 int Tab::GetTouchWidth() {
684 return kTouchWidth;
687 // static
688 int Tab::GetMiniWidth() {
689 return browser_defaults::kMiniTabWidth;
692 // static
693 int Tab::GetImmersiveHeight() {
694 return kImmersiveTabHeight;
697 ////////////////////////////////////////////////////////////////////////////////
698 // Tab, AnimationDelegate overrides:
700 void Tab::AnimationProgressed(const gfx::Animation* animation) {
701 // Ignore if the pulse animation is being performed on active tab because
702 // it repaints the same image. See |Tab::PaintTabBackground()|.
703 if (animation == tab_animation_.get() && IsActive())
704 return;
705 SchedulePaint();
708 void Tab::AnimationCanceled(const gfx::Animation* animation) {
709 if (media_indicator_animation_ == animation)
710 animating_media_state_ = data_.media_state;
711 SchedulePaint();
714 void Tab::AnimationEnded(const gfx::Animation* animation) {
715 if (media_indicator_animation_ == animation)
716 animating_media_state_ = data_.media_state;
717 SchedulePaint();
720 ////////////////////////////////////////////////////////////////////////////////
721 // Tab, views::ButtonListener overrides:
723 void Tab::ButtonPressed(views::Button* sender, const ui::Event& event) {
724 const CloseTabSource source =
725 (event.type() == ui::ET_MOUSE_RELEASED &&
726 (event.flags() & ui::EF_FROM_TOUCH) == 0) ? CLOSE_TAB_FROM_MOUSE :
727 CLOSE_TAB_FROM_TOUCH;
728 DCHECK_EQ(close_button_, sender);
729 controller()->CloseTab(this, source);
730 if (event.type() == ui::ET_GESTURE_TAP)
731 TouchUMA::RecordGestureAction(TouchUMA::GESTURE_TABCLOSE_TAP);
734 ////////////////////////////////////////////////////////////////////////////////
735 // Tab, views::ContextMenuController overrides:
737 void Tab::ShowContextMenuForView(views::View* source,
738 const gfx::Point& point,
739 ui::MenuSourceType source_type) {
740 if (controller() && !closing())
741 controller()->ShowContextMenuForTab(this, point, source_type);
744 ////////////////////////////////////////////////////////////////////////////////
745 // Tab, views::View overrides:
747 void Tab::OnPaint(gfx::Canvas* canvas) {
748 // Don't paint if we're narrower than we can render correctly. (This should
749 // only happen during animations).
750 if (width() < GetMinimumUnselectedSize().width() && !data().mini)
751 return;
753 gfx::Rect clip;
754 if (controller()) {
755 if (!controller()->ShouldPaintTab(this, &clip))
756 return;
757 if (!clip.IsEmpty()) {
758 canvas->Save();
759 canvas->ClipRect(clip);
763 if (controller() && controller()->IsImmersiveStyle())
764 PaintImmersiveTab(canvas);
765 else
766 PaintTab(canvas);
768 if (!clip.IsEmpty())
769 canvas->Restore();
772 void Tab::Layout() {
773 gfx::Rect lb = GetContentsBounds();
774 if (lb.IsEmpty())
775 return;
776 lb.Inset(
777 left_padding(), top_padding(), right_padding(), bottom_padding());
779 // The height of the content of the Tab is the largest of the favicon,
780 // the title text and the close button graphic.
781 int content_height = std::max(tab_icon_size(), font_height_);
782 close_button_->set_border(NULL);
783 gfx::Size close_button_size(close_button_->GetPreferredSize());
784 content_height = std::max(content_height, close_button_size.height());
786 // Size the Favicon.
787 showing_icon_ = ShouldShowIcon();
788 if (showing_icon_) {
789 // Use the size of the favicon as apps use a bigger favicon size.
790 int favicon_top = top_padding() + content_height / 2 - tab_icon_size() / 2;
791 int favicon_left = lb.x();
792 favicon_bounds_.SetRect(favicon_left, favicon_top,
793 tab_icon_size(), tab_icon_size());
794 MaybeAdjustLeftForMiniTab(&favicon_bounds_);
795 } else {
796 favicon_bounds_.SetRect(lb.x(), lb.y(), 0, 0);
799 // Size the Close button.
800 showing_close_button_ = ShouldShowCloseBox();
801 const bool is_host_desktop_type_ash =
802 GetHostDesktopType(this) == chrome::HOST_DESKTOP_TYPE_ASH;
803 if (showing_close_button_) {
804 const int close_button_vert_fuzz = is_host_desktop_type_ash ?
805 kCloseButtonVertFuzzAsh : kCloseButtonVertFuzz;
806 int close_button_top = top_padding() + close_button_vert_fuzz +
807 (content_height - close_button_size.height()) / 2;
808 // If the ratio of the close button size to tab width exceeds the maximum.
809 // The close button should be as large as possible so that there is a larger
810 // hit-target for touch events. So the close button bounds extends to the
811 // edges of the tab. However, the larger hit-target should be active only
812 // for mouse events, and the close-image should show up in the right place.
813 // So a border is added to the button with necessary padding. The close
814 // button (BaseTab::TabCloseButton) makes sure the padding is a hit-target
815 // only for touch events.
816 int top_border = close_button_top;
817 int bottom_border = height() - (close_button_size.height() + top_border);
818 int left_border = kCloseButtonHorzFuzz;
819 int right_border = width() - (lb.width() + close_button_size.width() +
820 left_border);
821 close_button_->set_border(views::Border::CreateEmptyBorder(top_border,
822 left_border, bottom_border, right_border));
823 close_button_->SetPosition(gfx::Point(lb.width(), 0));
824 close_button_->SizeToPreferredSize();
825 close_button_->SetVisible(true);
826 } else {
827 close_button_->SetBounds(0, 0, 0, 0);
828 close_button_->SetVisible(false);
831 showing_media_indicator_ = ShouldShowMediaIndicator();
832 if (showing_media_indicator_) {
833 const gfx::Image& media_indicator_image =
834 chrome::GetTabMediaIndicatorImage(animating_media_state_);
835 media_indicator_bounds_.set_width(media_indicator_image.Width());
836 media_indicator_bounds_.set_height(media_indicator_image.Height());
837 media_indicator_bounds_.set_y(
838 top_padding() +
839 (content_height - media_indicator_bounds_.height()) / 2);
840 const int right = showing_close_button_ ?
841 close_button_->x() + close_button_->GetInsets().left() : lb.right();
842 media_indicator_bounds_.set_x(
843 std::max(lb.x(), right - media_indicator_bounds_.width()));
844 MaybeAdjustLeftForMiniTab(&media_indicator_bounds_);
845 } else {
846 media_indicator_bounds_.SetRect(lb.x(), lb.y(), 0, 0);
849 const int title_text_offset = is_host_desktop_type_ash ?
850 kTitleTextOffsetYAsh : kTitleTextOffsetY;
851 int title_left = favicon_bounds_.right() + kFaviconTitleSpacing;
852 int title_top = top_padding() + title_text_offset +
853 (content_height - font_height_) / 2;
854 // Size the Title text to fill the remaining space.
855 if (!data().mini || width() >= kMiniTabRendererAsNormalTabWidth) {
856 // If the user has big fonts, the title will appear rendered too far down
857 // on the y-axis if we use the regular top padding, so we need to adjust it
858 // so that the text appears centered.
859 gfx::Size minimum_size = GetMinimumUnselectedSize();
860 int text_height = title_top + font_height_ + bottom_padding();
861 if (text_height > minimum_size.height())
862 title_top -= (text_height - minimum_size.height()) / 2;
864 int title_width;
865 if (showing_media_indicator_) {
866 title_width = media_indicator_bounds_.x() - kTitleCloseButtonSpacing -
867 title_left;
868 } else if (close_button_->visible()) {
869 // The close button has an empty border with some padding (see details
870 // above where the close-button's bounds is set). Allow the title to
871 // overlap the empty padding.
872 title_width = close_button_->x() + close_button_->GetInsets().left() -
873 kTitleCloseButtonSpacing - title_left;
874 } else {
875 title_width = lb.width() - title_left;
877 title_width = std::max(title_width, 0);
878 title_bounds_.SetRect(title_left, title_top, title_width, font_height_);
879 } else {
880 title_bounds_.SetRect(title_left, title_top, 0, 0);
883 // Certain UI elements within the Tab (the favicon, etc.) are not represented
884 // as child Views (which is the preferred method). Instead, these UI elements
885 // are drawn directly on the canvas from within Tab::OnPaint(). The Tab's
886 // child Views (for example, the Tab's close button which is a views::Button
887 // instance) are automatically mirrored by the mirroring infrastructure in
888 // views. The elements Tab draws directly on the canvas need to be manually
889 // mirrored if the View's layout is right-to-left.
890 title_bounds_.set_x(GetMirroredXForRect(title_bounds_));
893 void Tab::OnThemeChanged() {
894 LoadTabImages();
897 const char* Tab::GetClassName() const {
898 return kViewClassName;
901 bool Tab::HasHitTestMask() const {
902 return true;
905 void Tab::GetHitTestMask(HitTestSource source, gfx::Path* path) const {
906 // When the window is maximized we don't want to shave off the edges or top
907 // shadow of the tab, such that the user can click anywhere along the top
908 // edge of the screen to select a tab. Ditto for immersive fullscreen.
909 const views::Widget* widget = GetWidget();
910 bool include_top_shadow =
911 widget && (widget->IsMaximized() || widget->IsFullscreen());
912 TabResources::GetHitTestMask(width(), height(), include_top_shadow, path);
914 // It is possible for a portion of the tab to be occluded if tabs are
915 // stacked, so modify the hit test mask to only include the visible
916 // region of the tab.
917 if (controller()) {
918 gfx::Rect clip;
919 controller()->ShouldPaintTab(this, &clip);
920 if (clip.size().GetArea()) {
921 SkRect intersection(path->getBounds());
922 intersection.intersect(RectToSkRect(clip));
923 path->reset();
924 path->addRect(intersection);
929 bool Tab::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const {
930 // Note: Anything that affects the tooltip text should be accounted for when
931 // calling TooltipTextChanged() from Tab::DataChanged().
932 *tooltip = chrome::AssembleTabTooltipText(data_.title, data_.media_state);
933 return !tooltip->empty();
936 bool Tab::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* origin) const {
937 origin->set_x(title_bounds_.x() + 10);
938 origin->set_y(-views::TooltipManager::GetTooltipHeight() - 4);
939 return true;
942 ui::ThemeProvider* Tab::GetThemeProvider() const {
943 ui::ThemeProvider* tp = View::GetThemeProvider();
944 return tp ? tp : theme_provider_;
947 bool Tab::OnMousePressed(const ui::MouseEvent& event) {
948 if (!controller())
949 return false;
951 controller()->OnMouseEventInTab(this, event);
953 // Allow a right click from touch to drag, which corresponds to a long click.
954 if (event.IsOnlyLeftMouseButton() ||
955 (event.IsOnlyRightMouseButton() && event.flags() & ui::EF_FROM_TOUCH)) {
956 ui::ListSelectionModel original_selection;
957 original_selection.Copy(controller()->GetSelectionModel());
958 // Changing the selection may cause our bounds to change. If that happens
959 // the location of the event may no longer be valid. Create a copy of the
960 // event in the parents coordinate, which won't change, and recreate an
961 // event after changing so the coordinates are correct.
962 ui::MouseEvent event_in_parent(event, static_cast<View*>(this), parent());
963 if (controller()->SupportsMultipleSelection()) {
964 if (event.IsShiftDown() && event.IsControlDown()) {
965 controller()->AddSelectionFromAnchorTo(this);
966 } else if (event.IsShiftDown()) {
967 controller()->ExtendSelectionTo(this);
968 } else if (event.IsControlDown()) {
969 controller()->ToggleSelected(this);
970 if (!IsSelected()) {
971 // Don't allow dragging non-selected tabs.
972 return false;
974 } else if (!IsSelected()) {
975 controller()->SelectTab(this);
977 } else if (!IsSelected()) {
978 controller()->SelectTab(this);
980 ui::MouseEvent cloned_event(event_in_parent, parent(),
981 static_cast<View*>(this));
982 controller()->MaybeStartDrag(this, cloned_event, original_selection);
984 return true;
987 bool Tab::OnMouseDragged(const ui::MouseEvent& event) {
988 if (controller())
989 controller()->ContinueDrag(this, event);
990 return true;
993 void Tab::OnMouseReleased(const ui::MouseEvent& event) {
994 if (!controller())
995 return;
997 controller()->OnMouseEventInTab(this, event);
999 // Notify the drag helper that we're done with any potential drag operations.
1000 // Clean up the drag helper, which is re-created on the next mouse press.
1001 // In some cases, ending the drag will schedule the tab for destruction; if
1002 // so, bail immediately, since our members are already dead and we shouldn't
1003 // do anything else except drop the tab where it is.
1004 if (controller()->EndDrag(END_DRAG_COMPLETE))
1005 return;
1007 // Close tab on middle click, but only if the button is released over the tab
1008 // (normal windows behavior is to discard presses of a UI element where the
1009 // releases happen off the element).
1010 if (event.IsMiddleMouseButton()) {
1011 if (HitTestPoint(event.location())) {
1012 controller()->CloseTab(this, CLOSE_TAB_FROM_MOUSE);
1013 } else if (closing_) {
1014 // We're animating closed and a middle mouse button was pushed on us but
1015 // we don't contain the mouse anymore. We assume the user is clicking
1016 // quicker than the animation and we should close the tab that falls under
1017 // the mouse.
1018 Tab* closest_tab = controller()->GetTabAt(this, event.location());
1019 if (closest_tab)
1020 controller()->CloseTab(closest_tab, CLOSE_TAB_FROM_MOUSE);
1022 } else if (event.IsOnlyLeftMouseButton() && !event.IsShiftDown() &&
1023 !event.IsControlDown()) {
1024 // If the tab was already selected mouse pressed doesn't change the
1025 // selection. Reset it now to handle the case where multiple tabs were
1026 // selected.
1027 controller()->SelectTab(this);
1031 void Tab::OnMouseCaptureLost() {
1032 if (controller())
1033 controller()->EndDrag(END_DRAG_CAPTURE_LOST);
1036 void Tab::OnMouseEntered(const ui::MouseEvent& event) {
1037 hover_controller_.Show(views::GlowHoverController::SUBTLE);
1040 void Tab::OnMouseMoved(const ui::MouseEvent& event) {
1041 hover_controller_.SetLocation(event.location());
1042 if (controller())
1043 controller()->OnMouseEventInTab(this, event);
1046 void Tab::OnMouseExited(const ui::MouseEvent& event) {
1047 hover_controller_.Hide();
1050 void Tab::OnGestureEvent(ui::GestureEvent* event) {
1051 if (!controller()) {
1052 event->SetHandled();
1053 return;
1056 switch (event->type()) {
1057 case ui::ET_GESTURE_BEGIN: {
1058 if (event->details().touch_points() != 1)
1059 return;
1061 // See comment in OnMousePressed() as to why we copy the event.
1062 ui::GestureEvent event_in_parent(*event, static_cast<View*>(this),
1063 parent());
1064 ui::ListSelectionModel original_selection;
1065 original_selection.Copy(controller()->GetSelectionModel());
1066 tab_activated_with_last_gesture_begin_ = !IsActive();
1067 if (!IsSelected())
1068 controller()->SelectTab(this);
1069 gfx::Point loc(event->location());
1070 views::View::ConvertPointToScreen(this, &loc);
1071 ui::GestureEvent cloned_event(event_in_parent, parent(),
1072 static_cast<View*>(this));
1073 controller()->MaybeStartDrag(this, cloned_event, original_selection);
1074 break;
1077 case ui::ET_GESTURE_END:
1078 controller()->EndDrag(END_DRAG_COMPLETE);
1079 break;
1081 case ui::ET_GESTURE_SCROLL_UPDATE:
1082 controller()->ContinueDrag(this, *event);
1083 break;
1085 default:
1086 break;
1088 event->SetHandled();
1091 void Tab::GetAccessibleState(ui::AccessibleViewState* state) {
1092 state->role = ui::AccessibilityTypes::ROLE_PAGETAB;
1093 state->name = data_.title;
1096 ////////////////////////////////////////////////////////////////////////////////
1097 // Tab, private
1099 const gfx::Rect& Tab::GetTitleBounds() const {
1100 return title_bounds_;
1103 const gfx::Rect& Tab::GetIconBounds() const {
1104 return favicon_bounds_;
1107 void Tab::MaybeAdjustLeftForMiniTab(gfx::Rect* bounds) const {
1108 if (!data().mini || width() >= kMiniTabRendererAsNormalTabWidth)
1109 return;
1110 const int mini_delta = kMiniTabRendererAsNormalTabWidth - GetMiniWidth();
1111 const int ideal_delta = width() - GetMiniWidth();
1112 const int ideal_x = (GetMiniWidth() - bounds->width()) / 2;
1113 bounds->set_x(bounds->x() + static_cast<int>(
1114 (1 - static_cast<float>(ideal_delta) / static_cast<float>(mini_delta)) *
1115 (ideal_x - bounds->x())));
1118 void Tab::DataChanged(const TabRendererData& old) {
1119 if (data().media_state != old.media_state || data().title != old.title)
1120 TooltipTextChanged();
1122 if (data().blocked == old.blocked)
1123 return;
1125 if (data().blocked)
1126 StartPulse();
1127 else
1128 StopPulse();
1131 void Tab::PaintTab(gfx::Canvas* canvas) {
1132 // See if the model changes whether the icons should be painted.
1133 const bool show_icon = ShouldShowIcon();
1134 const bool show_media_indicator = ShouldShowMediaIndicator();
1135 const bool show_close_button = ShouldShowCloseBox();
1136 if (show_icon != showing_icon_ ||
1137 show_media_indicator != showing_media_indicator_ ||
1138 show_close_button != showing_close_button_) {
1139 Layout();
1142 PaintTabBackground(canvas);
1144 SkColor title_color = GetThemeProvider()->
1145 GetColor(IsSelected() ?
1146 ThemeProperties::COLOR_TAB_TEXT :
1147 ThemeProperties::COLOR_BACKGROUND_TAB_TEXT);
1149 if (!data().mini || width() > kMiniTabRendererAsNormalTabWidth)
1150 PaintTitle(canvas, title_color);
1152 if (show_icon)
1153 PaintIcon(canvas);
1155 if (show_media_indicator)
1156 PaintMediaIndicator(canvas);
1158 // If the close button color has changed, generate a new one.
1159 if (!close_button_color_ || title_color != close_button_color_) {
1160 close_button_color_ = title_color;
1161 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1162 close_button_->SetBackground(close_button_color_,
1163 rb.GetImageSkiaNamed(IDR_CLOSE_1),
1164 rb.GetImageSkiaNamed(IDR_CLOSE_1_MASK));
1168 void Tab::PaintImmersiveTab(gfx::Canvas* canvas) {
1169 // Use transparency for the draw-attention animation.
1170 int alpha = 255;
1171 if (tab_animation_ &&
1172 tab_animation_->is_animating() &&
1173 !data().mini) {
1174 alpha = tab_animation_->CurrentValueBetween(
1175 255, static_cast<int>(255 * kImmersiveTabMinThrobOpacity));
1178 // Draw a gray rectangle to represent the tab. This works for mini-tabs as
1179 // well as regular ones. The active tab has a brigher bar.
1180 SkColor color =
1181 IsActive() ? kImmersiveActiveTabColor : kImmersiveInactiveTabColor;
1182 gfx::Rect bar_rect = GetImmersiveBarRect();
1183 canvas->FillRect(bar_rect, SkColorSetA(color, alpha));
1185 // Paint network activity indicator.
1186 // TODO(jamescook): Replace this placeholder animation with a real one.
1187 // For now, let's go with a Cylon eye effect, but in blue.
1188 if (data().network_state != TabRendererData::NETWORK_STATE_NONE) {
1189 const SkColor kEyeColor = SkColorSetARGB(alpha, 71, 138, 217);
1190 int eye_width = bar_rect.width() / 3;
1191 int eye_offset = bar_rect.width() * immersive_loading_step_ /
1192 kImmersiveLoadingStepCount;
1193 if (eye_offset + eye_width < bar_rect.width()) {
1194 // Draw a single indicator strip because it fits inside |bar_rect|.
1195 gfx::Rect eye_rect(
1196 bar_rect.x() + eye_offset, 0, eye_width, kImmersiveBarHeight);
1197 canvas->FillRect(eye_rect, kEyeColor);
1198 } else {
1199 // Draw two indicators to simulate the eye "wrapping around" to the left
1200 // side. The first part fills the remainder of the bar.
1201 int right_eye_width = bar_rect.width() - eye_offset;
1202 gfx::Rect right_eye_rect(
1203 bar_rect.x() + eye_offset, 0, right_eye_width, kImmersiveBarHeight);
1204 canvas->FillRect(right_eye_rect, kEyeColor);
1205 // The second part parts the remaining |eye_width| on the left.
1206 int left_eye_width = eye_offset + eye_width - bar_rect.width();
1207 gfx::Rect left_eye_rect(
1208 bar_rect.x(), 0, left_eye_width, kImmersiveBarHeight);
1209 canvas->FillRect(left_eye_rect, kEyeColor);
1214 void Tab::PaintTabBackground(gfx::Canvas* canvas) {
1215 if (IsActive()) {
1216 PaintActiveTabBackground(canvas);
1217 } else {
1218 if (tab_animation_.get() &&
1219 tab_animation_->is_animating() &&
1220 data().mini) {
1221 gfx::MultiAnimation* animation =
1222 static_cast<gfx::MultiAnimation*>(tab_animation_.get());
1223 PaintInactiveTabBackgroundWithTitleChange(canvas, animation);
1224 } else {
1225 PaintInactiveTabBackground(canvas);
1228 double throb_value = GetThrobValue();
1229 if (throb_value > 0) {
1230 canvas->SaveLayerAlpha(static_cast<int>(throb_value * 0xff),
1231 GetLocalBounds());
1232 PaintActiveTabBackground(canvas);
1233 canvas->Restore();
1238 void Tab::PaintInactiveTabBackgroundWithTitleChange(
1239 gfx::Canvas* canvas,
1240 gfx::MultiAnimation* animation) {
1241 // Render the inactive tab background. We'll use this for clipping.
1242 gfx::Canvas background_canvas(size(), canvas->image_scale(), false);
1243 PaintInactiveTabBackground(&background_canvas);
1245 gfx::ImageSkia background_image(background_canvas.ExtractImageRep());
1247 // Draw a radial gradient to hover_canvas.
1248 gfx::Canvas hover_canvas(size(), canvas->image_scale(), false);
1249 int radius = kMiniTitleChangeGradientRadius;
1250 int x0 = width() + radius - kMiniTitleChangeInitialXOffset;
1251 int x1 = radius;
1252 int x2 = -radius;
1253 int x;
1254 if (animation->current_part_index() == 0) {
1255 x = animation->CurrentValueBetween(x0, x1);
1256 } else if (animation->current_part_index() == 1) {
1257 x = x1;
1258 } else {
1259 x = animation->CurrentValueBetween(x1, x2);
1261 SkPoint center_point;
1262 center_point.iset(x, 0);
1263 SkColor colors[2] = { kMiniTitleChangeGradientColor1,
1264 kMiniTitleChangeGradientColor2 };
1265 skia::RefPtr<SkShader> shader = skia::AdoptRef(
1266 SkGradientShader::CreateRadial(
1267 center_point, SkIntToScalar(radius), colors, NULL, 2,
1268 SkShader::kClamp_TileMode));
1269 SkPaint paint;
1270 paint.setShader(shader.get());
1271 hover_canvas.DrawRect(gfx::Rect(x - radius, -radius, radius * 2, radius * 2),
1272 paint);
1274 // Draw the radial gradient clipped to the background into hover_image.
1275 gfx::ImageSkia hover_image = gfx::ImageSkiaOperations::CreateMaskedImage(
1276 gfx::ImageSkia(hover_canvas.ExtractImageRep()), background_image);
1278 // Draw the tab background to the canvas.
1279 canvas->DrawImageInt(background_image, 0, 0);
1281 // And then the gradient on top of that.
1282 if (animation->current_part_index() == 2) {
1283 uint8 alpha = animation->CurrentValueBetween(255, 0);
1284 canvas->DrawImageInt(hover_image, 0, 0, alpha);
1285 } else {
1286 canvas->DrawImageInt(hover_image, 0, 0);
1290 void Tab::PaintInactiveTabBackground(gfx::Canvas* canvas) {
1291 int tab_id;
1292 int frame_id;
1293 views::Widget* widget = GetWidget();
1294 GetTabIdAndFrameId(widget, &tab_id, &frame_id);
1296 // Explicitly map the id so we cache correctly.
1297 const chrome::HostDesktopType host_desktop_type = GetHostDesktopType(this);
1298 tab_id = chrome::MapThemeImage(host_desktop_type, tab_id);
1300 // HasCustomImage() is only true if the theme provides the image. However,
1301 // even if the theme does not provide a tab background, the theme machinery
1302 // will make one if given a frame image.
1303 ui::ThemeProvider* theme_provider = GetThemeProvider();
1304 const bool theme_provided_image = theme_provider->HasCustomImage(tab_id) ||
1305 (frame_id != 0 && theme_provider->HasCustomImage(frame_id));
1307 const bool can_cache = !theme_provided_image &&
1308 !hover_controller_.ShouldDraw();
1310 if (can_cache) {
1311 ui::ScaleFactor scale_factor =
1312 ui::GetSupportedScaleFactor(canvas->image_scale());
1313 gfx::ImageSkia cached_image(GetCachedImage(tab_id, size(), scale_factor));
1314 if (cached_image.width() == 0) {
1315 gfx::Canvas tmp_canvas(size(), canvas->image_scale(), false);
1316 PaintInactiveTabBackgroundUsingResourceId(&tmp_canvas, tab_id);
1317 cached_image = gfx::ImageSkia(tmp_canvas.ExtractImageRep());
1318 SetCachedImage(tab_id, scale_factor, cached_image);
1320 canvas->DrawImageInt(cached_image, 0, 0);
1321 } else {
1322 PaintInactiveTabBackgroundUsingResourceId(canvas, tab_id);
1326 void Tab::PaintInactiveTabBackgroundUsingResourceId(gfx::Canvas* canvas,
1327 int tab_id) {
1328 // WARNING: the inactive tab background may be cached. If you change what it
1329 // is drawn from you may need to update whether it can be cached.
1331 // The tab image needs to be lined up with the background image
1332 // so that it feels partially transparent. These offsets represent the tab
1333 // position within the frame background image.
1334 int offset = GetMirroredX() + background_offset_.x();
1336 gfx::ImageSkia* tab_bg = GetThemeProvider()->GetImageSkiaNamed(tab_id);
1338 TabImage* tab_image = &tab_active_;
1339 TabImage* tab_inactive_image = &tab_inactive_;
1340 TabImage* alpha = &tab_alpha_;
1342 // If the theme is providing a custom background image, then its top edge
1343 // should be at the top of the tab. Otherwise, we assume that the background
1344 // image is a composited foreground + frame image.
1345 int bg_offset_y = GetThemeProvider()->HasCustomImage(tab_id) ?
1346 0 : background_offset_.y();
1348 // We need a gfx::Canvas object to be able to extract the image from.
1349 // We draw everything to this canvas and then output it to the canvas
1350 // parameter in addition to using it to mask the hover glow if needed.
1351 gfx::Canvas background_canvas(size(), canvas->image_scale(), false);
1353 // Draw left edge. Don't draw over the toolbar, as we're not the foreground
1354 // tab.
1355 gfx::ImageSkia tab_l = gfx::ImageSkiaOperations::CreateTiledImage(
1356 *tab_bg, offset, bg_offset_y, tab_image->l_width, height());
1357 gfx::ImageSkia theme_l =
1358 gfx::ImageSkiaOperations::CreateMaskedImage(tab_l, *alpha->image_l);
1359 background_canvas.DrawImageInt(theme_l,
1360 0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
1361 0, 0, theme_l.width(), theme_l.height() - kToolbarOverlap,
1362 false);
1364 // Draw right edge. Again, don't draw over the toolbar.
1365 gfx::ImageSkia tab_r = gfx::ImageSkiaOperations::CreateTiledImage(*tab_bg,
1366 offset + width() - tab_image->r_width, bg_offset_y,
1367 tab_image->r_width, height());
1368 gfx::ImageSkia theme_r =
1369 gfx::ImageSkiaOperations::CreateMaskedImage(tab_r, *alpha->image_r);
1370 background_canvas.DrawImageInt(theme_r,
1371 0, 0, theme_r.width(), theme_r.height() - kToolbarOverlap,
1372 width() - theme_r.width(), 0, theme_r.width(),
1373 theme_r.height() - kToolbarOverlap, false);
1375 // Draw center. Instead of masking out the top portion we simply skip over
1376 // it by incrementing by GetDropShadowHeight(), since it's a simple
1377 // rectangle. And again, don't draw over the toolbar.
1378 background_canvas.TileImageInt(*tab_bg,
1379 offset + tab_image->l_width,
1380 bg_offset_y + drop_shadow_height(),
1381 tab_image->l_width,
1382 drop_shadow_height(),
1383 width() - tab_image->l_width - tab_image->r_width,
1384 height() - drop_shadow_height() - kToolbarOverlap);
1386 canvas->DrawImageInt(
1387 gfx::ImageSkia(background_canvas.ExtractImageRep()), 0, 0);
1389 if (!GetThemeProvider()->HasCustomImage(tab_id) &&
1390 hover_controller_.ShouldDraw()) {
1391 hover_controller_.Draw(canvas, gfx::ImageSkia(
1392 background_canvas.ExtractImageRep()));
1395 // Now draw the highlights/shadows around the tab edge.
1396 canvas->DrawImageInt(*tab_inactive_image->image_l, 0, 0);
1397 canvas->TileImageInt(*tab_inactive_image->image_c,
1398 tab_inactive_image->l_width, 0,
1399 width() - tab_inactive_image->l_width -
1400 tab_inactive_image->r_width,
1401 height());
1402 canvas->DrawImageInt(*tab_inactive_image->image_r,
1403 width() - tab_inactive_image->r_width, 0);
1406 void Tab::PaintActiveTabBackground(gfx::Canvas* canvas) {
1407 gfx::ImageSkia* tab_background =
1408 GetThemeProvider()->GetImageSkiaNamed(IDR_THEME_TOOLBAR);
1409 int offset = GetMirroredX() + background_offset_.x();
1411 TabImage* tab_image = &tab_active_;
1412 TabImage* alpha = &tab_alpha_;
1414 // Draw left edge.
1415 gfx::ImageSkia tab_l = gfx::ImageSkiaOperations::CreateTiledImage(
1416 *tab_background, offset, 0, tab_image->l_width, height());
1417 gfx::ImageSkia theme_l =
1418 gfx::ImageSkiaOperations::CreateMaskedImage(tab_l, *alpha->image_l);
1419 canvas->DrawImageInt(theme_l, 0, 0);
1421 // Draw right edge.
1422 gfx::ImageSkia tab_r = gfx::ImageSkiaOperations::CreateTiledImage(
1423 *tab_background,
1424 offset + width() - tab_image->r_width, 0, tab_image->r_width, height());
1425 gfx::ImageSkia theme_r =
1426 gfx::ImageSkiaOperations::CreateMaskedImage(tab_r, *alpha->image_r);
1427 canvas->DrawImageInt(theme_r, width() - tab_image->r_width, 0);
1429 // Draw center. Instead of masking out the top portion we simply skip over it
1430 // by incrementing by GetDropShadowHeight(), since it's a simple rectangle.
1431 canvas->TileImageInt(*tab_background,
1432 offset + tab_image->l_width,
1433 drop_shadow_height(),
1434 tab_image->l_width,
1435 drop_shadow_height(),
1436 width() - tab_image->l_width - tab_image->r_width,
1437 height() - drop_shadow_height());
1439 // Now draw the highlights/shadows around the tab edge.
1440 canvas->DrawImageInt(*tab_image->image_l, 0, 0);
1441 canvas->TileImageInt(*tab_image->image_c, tab_image->l_width, 0,
1442 width() - tab_image->l_width - tab_image->r_width, height());
1443 canvas->DrawImageInt(*tab_image->image_r, width() - tab_image->r_width, 0);
1446 void Tab::PaintIcon(gfx::Canvas* canvas) {
1447 gfx::Rect bounds = GetIconBounds();
1448 if (bounds.IsEmpty())
1449 return;
1451 bounds.set_x(GetMirroredXForRect(bounds));
1453 if (data().network_state != TabRendererData::NETWORK_STATE_NONE) {
1454 // Paint network activity (aka throbber) animation frame.
1455 ui::ThemeProvider* tp = GetThemeProvider();
1456 gfx::ImageSkia frames(*tp->GetImageSkiaNamed(
1457 (data().network_state == TabRendererData::NETWORK_STATE_WAITING) ?
1458 IDR_THROBBER_WAITING : IDR_THROBBER));
1460 int icon_size = frames.height();
1461 int image_offset = loading_animation_frame_ * icon_size;
1462 DrawIconCenter(canvas, frames, image_offset,
1463 icon_size, icon_size,
1464 bounds, false, SkPaint());
1465 } else if (should_display_crashed_favicon_) {
1466 // Paint crash favicon.
1467 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1468 gfx::ImageSkia crashed_favicon(*rb.GetImageSkiaNamed(IDR_SAD_FAVICON));
1469 bounds.set_y(bounds.y() + favicon_hiding_offset_);
1470 DrawIconCenter(canvas, crashed_favicon, 0,
1471 crashed_favicon.width(),
1472 crashed_favicon.height(),
1473 bounds, true, SkPaint());
1474 } else if (!data().favicon.isNull()) {
1475 // Paint the normal favicon.
1476 DrawIconCenter(canvas, data().favicon, 0,
1477 data().favicon.width(),
1478 data().favicon.height(),
1479 bounds, true, SkPaint());
1483 void Tab::PaintMediaIndicator(gfx::Canvas* canvas) {
1484 if (media_indicator_bounds_.IsEmpty() || !media_indicator_animation_)
1485 return;
1487 gfx::Rect bounds = media_indicator_bounds_;
1488 bounds.set_x(GetMirroredXForRect(bounds));
1490 SkPaint paint;
1491 paint.setAntiAlias(true);
1492 double opaqueness = media_indicator_animation_->GetCurrentValue();
1493 if (data_.media_state == TAB_MEDIA_STATE_NONE)
1494 opaqueness = 1.0 - opaqueness; // Fading out, not in.
1495 paint.setAlpha(opaqueness * SK_AlphaOPAQUE);
1497 const gfx::ImageSkia& media_indicator_image =
1498 *(chrome::GetTabMediaIndicatorImage(animating_media_state_).
1499 ToImageSkia());
1500 DrawIconAtLocation(canvas, media_indicator_image, 0,
1501 bounds.x(), bounds.y(), media_indicator_image.width(),
1502 media_indicator_image.height(), true, paint);
1505 void Tab::PaintTitle(gfx::Canvas* canvas, SkColor title_color) {
1506 // Paint the Title.
1507 base::string16 title = data().title;
1508 if (title.empty()) {
1509 title = data().loading ?
1510 l10n_util::GetStringUTF16(IDS_TAB_LOADING_TITLE) :
1511 CoreTabHelper::GetDefaultTitle();
1512 } else {
1513 Browser::FormatTitleForDisplay(&title);
1516 canvas->DrawFadeTruncatingStringRect(title, gfx::Canvas::TruncateFadeTail,
1517 gfx::FontList(*font_), title_color, GetTitleBounds());
1520 void Tab::AdvanceLoadingAnimation(TabRendererData::NetworkState old_state,
1521 TabRendererData::NetworkState state) {
1522 static bool initialized = false;
1523 static int loading_animation_frame_count = 0;
1524 static int waiting_animation_frame_count = 0;
1525 static int waiting_to_loading_frame_count_ratio = 0;
1526 if (!initialized) {
1527 initialized = true;
1528 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1529 gfx::ImageSkia loading_animation(*rb.GetImageSkiaNamed(IDR_THROBBER));
1530 loading_animation_frame_count =
1531 loading_animation.width() / loading_animation.height();
1532 gfx::ImageSkia waiting_animation(*rb.GetImageSkiaNamed(
1533 IDR_THROBBER_WAITING));
1534 waiting_animation_frame_count =
1535 waiting_animation.width() / waiting_animation.height();
1536 waiting_to_loading_frame_count_ratio =
1537 waiting_animation_frame_count / loading_animation_frame_count;
1539 base::debug::Alias(&loading_animation_frame_count);
1540 base::debug::Alias(&waiting_animation_frame_count);
1541 CHECK_NE(0, waiting_to_loading_frame_count_ratio) <<
1542 "Number of frames in IDR_THROBBER must be equal to or greater " <<
1543 "than the number of frames in IDR_THROBBER_WAITING. Please " <<
1544 "investigate how this happened and update http://crbug.com/132590, " <<
1545 "this is causing crashes in the wild.";
1548 // The waiting animation is the reverse of the loading animation, but at a
1549 // different rate - the following reverses and scales the animation_frame_
1550 // so that the frame is at an equivalent position when going from one
1551 // animation to the other.
1552 if (state != old_state) {
1553 loading_animation_frame_ = loading_animation_frame_count -
1554 (loading_animation_frame_ / waiting_to_loading_frame_count_ratio);
1557 if (state == TabRendererData::NETWORK_STATE_WAITING) {
1558 loading_animation_frame_ = (loading_animation_frame_ + 1) %
1559 waiting_animation_frame_count;
1560 // Waiting steps backwards.
1561 immersive_loading_step_ =
1562 (immersive_loading_step_ - 1 + kImmersiveLoadingStepCount) %
1563 kImmersiveLoadingStepCount;
1564 } else if (state == TabRendererData::NETWORK_STATE_LOADING) {
1565 loading_animation_frame_ = (loading_animation_frame_ + 1) %
1566 loading_animation_frame_count;
1567 immersive_loading_step_ = (immersive_loading_step_ + 1) %
1568 kImmersiveLoadingStepCount;
1569 } else {
1570 loading_animation_frame_ = 0;
1571 immersive_loading_step_ = 0;
1573 if (controller() && controller()->IsImmersiveStyle())
1574 SchedulePaintInRect(GetImmersiveBarRect());
1575 else
1576 ScheduleIconPaint();
1579 int Tab::IconCapacity() const {
1580 if (height() < GetMinimumUnselectedSize().height())
1581 return 0;
1582 const int available_width =
1583 std::max(0, width() - left_padding() - right_padding());
1584 const int width_per_icon = tab_icon_size();
1585 const int kPaddingBetweenIcons = 2;
1586 if (available_width >= width_per_icon &&
1587 available_width < (width_per_icon + kPaddingBetweenIcons)) {
1588 return 1;
1590 return available_width / (width_per_icon + kPaddingBetweenIcons);
1593 bool Tab::ShouldShowIcon() const {
1594 return chrome::ShouldTabShowFavicon(
1595 IconCapacity(), data().mini, IsActive(), data().show_icon,
1596 animating_media_state_);
1599 bool Tab::ShouldShowMediaIndicator() const {
1600 return chrome::ShouldTabShowMediaIndicator(
1601 IconCapacity(), data().mini, IsActive(), data().show_icon,
1602 animating_media_state_);
1605 bool Tab::ShouldShowCloseBox() const {
1606 return chrome::ShouldTabShowCloseButton(
1607 IconCapacity(), data().mini, IsActive());
1610 double Tab::GetThrobValue() {
1611 bool is_selected = IsSelected();
1612 double min = is_selected ? kSelectedTabOpacity : 0;
1613 double scale = is_selected ? kSelectedTabThrobScale : 1;
1615 if (!data().mini) {
1616 if (tab_animation_.get() && tab_animation_->is_animating())
1617 return tab_animation_->GetCurrentValue() * kHoverOpacity * scale + min;
1620 if (hover_controller_.ShouldDraw()) {
1621 return kHoverOpacity * hover_controller_.GetAnimationValue() * scale +
1622 min;
1625 return is_selected ? kSelectedTabOpacity : 0;
1628 void Tab::SetFaviconHidingOffset(int offset) {
1629 favicon_hiding_offset_ = offset;
1630 ScheduleIconPaint();
1633 void Tab::DisplayCrashedFavicon() {
1634 should_display_crashed_favicon_ = true;
1637 void Tab::ResetCrashedFavicon() {
1638 should_display_crashed_favicon_ = false;
1641 void Tab::StopCrashAnimation() {
1642 crash_icon_animation_.reset();
1645 void Tab::StartCrashAnimation() {
1646 crash_icon_animation_.reset(new FaviconCrashAnimation(this));
1647 crash_icon_animation_->Start();
1650 bool Tab::IsPerformingCrashAnimation() const {
1651 return crash_icon_animation_.get() && data_.IsCrashed();
1654 void Tab::StartMediaIndicatorAnimation() {
1655 media_indicator_animation_ =
1656 chrome::CreateTabMediaIndicatorFadeAnimation(data_.media_state);
1657 media_indicator_animation_->set_delegate(this);
1658 media_indicator_animation_->Start();
1661 void Tab::ScheduleIconPaint() {
1662 gfx::Rect bounds = GetIconBounds();
1663 if (bounds.IsEmpty())
1664 return;
1666 // Extends the area to the bottom when sad_favicon is
1667 // animating.
1668 if (IsPerformingCrashAnimation())
1669 bounds.set_height(height() - bounds.y());
1670 bounds.set_x(GetMirroredXForRect(bounds));
1671 SchedulePaintInRect(bounds);
1674 gfx::Rect Tab::GetImmersiveBarRect() const {
1675 // The main bar is as wide as the normal tab's horizontal top line.
1676 // This top line of the tab extends a few pixels left and right of the
1677 // center image due to pixels in the rounded corner images.
1678 const int kBarPadding = 1;
1679 int main_bar_left = tab_active_.l_width - kBarPadding;
1680 int main_bar_right = width() - tab_active_.r_width + kBarPadding;
1681 return gfx::Rect(
1682 main_bar_left, 0, main_bar_right - main_bar_left, kImmersiveBarHeight);
1685 void Tab::GetTabIdAndFrameId(views::Widget* widget,
1686 int* tab_id,
1687 int* frame_id) const {
1688 if (widget && widget->GetTopLevelWidget()->ShouldUseNativeFrame()) {
1689 *tab_id = IDR_THEME_TAB_BACKGROUND_V;
1690 *frame_id = 0;
1691 } else if (data().incognito) {
1692 *tab_id = IDR_THEME_TAB_BACKGROUND_INCOGNITO;
1693 *frame_id = IDR_THEME_FRAME_INCOGNITO;
1694 #if defined(OS_WIN)
1695 } else if (win8::IsSingleWindowMetroMode()) {
1696 *tab_id = IDR_THEME_TAB_BACKGROUND_V;
1697 *frame_id = 0;
1698 #endif
1699 } else {
1700 *tab_id = IDR_THEME_TAB_BACKGROUND;
1701 *frame_id = IDR_THEME_FRAME;
1705 ////////////////////////////////////////////////////////////////////////////////
1706 // Tab, private static:
1708 // static
1709 void Tab::InitTabResources() {
1710 static bool initialized = false;
1711 if (initialized)
1712 return;
1714 initialized = true;
1716 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1717 font_ = new gfx::Font(rb.GetFont(ui::ResourceBundle::BaseFont));
1718 font_height_ = font_->GetHeight();
1720 image_cache_ = new ImageCache();
1722 // Load the tab images once now, and maybe again later if the theme changes.
1723 LoadTabImages();
1726 // static
1727 void Tab::LoadTabImages() {
1728 // We're not letting people override tab images just yet.
1729 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
1731 tab_alpha_.image_l = rb.GetImageSkiaNamed(IDR_TAB_ALPHA_LEFT);
1732 tab_alpha_.image_r = rb.GetImageSkiaNamed(IDR_TAB_ALPHA_RIGHT);
1734 tab_active_.image_l = rb.GetImageSkiaNamed(IDR_TAB_ACTIVE_LEFT);
1735 tab_active_.image_c = rb.GetImageSkiaNamed(IDR_TAB_ACTIVE_CENTER);
1736 tab_active_.image_r = rb.GetImageSkiaNamed(IDR_TAB_ACTIVE_RIGHT);
1737 tab_active_.l_width = tab_active_.image_l->width();
1738 tab_active_.r_width = tab_active_.image_r->width();
1740 tab_inactive_.image_l = rb.GetImageSkiaNamed(IDR_TAB_INACTIVE_LEFT);
1741 tab_inactive_.image_c = rb.GetImageSkiaNamed(IDR_TAB_INACTIVE_CENTER);
1742 tab_inactive_.image_r = rb.GetImageSkiaNamed(IDR_TAB_INACTIVE_RIGHT);
1743 tab_inactive_.l_width = tab_inactive_.image_l->width();
1744 tab_inactive_.r_width = tab_inactive_.image_r->width();
1747 // static
1748 gfx::ImageSkia Tab::GetCachedImage(int resource_id,
1749 const gfx::Size& size,
1750 ui::ScaleFactor scale_factor) {
1751 for (ImageCache::const_iterator i = image_cache_->begin();
1752 i != image_cache_->end(); ++i) {
1753 if (i->resource_id == resource_id && i->scale_factor == scale_factor &&
1754 i->image.size() == size) {
1755 return i->image;
1758 return gfx::ImageSkia();
1761 // static
1762 void Tab::SetCachedImage(int resource_id,
1763 ui::ScaleFactor scale_factor,
1764 const gfx::ImageSkia& image) {
1765 DCHECK_NE(scale_factor, ui::SCALE_FACTOR_NONE);
1766 ImageCacheEntry entry;
1767 entry.resource_id = resource_id;
1768 entry.scale_factor = scale_factor;
1769 entry.image = image;
1770 image_cache_->push_front(entry);
1771 if (image_cache_->size() > kMaxImageCacheSize)
1772 image_cache_->pop_back();