Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / chrome / browser / ui / views / tabs / tab_strip.cc
blob169d128faa2f31c7f85a841676eabcd731c45ef0
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_strip.h"
7 #if defined(OS_WIN)
8 #include <windowsx.h>
9 #endif
11 #include <algorithm>
12 #include <iterator>
13 #include <string>
14 #include <vector>
16 #include "base/compiler_specific.h"
17 #include "base/metrics/histogram.h"
18 #include "base/stl_util.h"
19 #include "base/strings/utf_string_conversions.h"
20 #include "chrome/browser/defaults.h"
21 #include "chrome/browser/ui/host_desktop.h"
22 #include "chrome/browser/ui/tabs/tab_strip_model.h"
23 #include "chrome/browser/ui/view_ids.h"
24 #include "chrome/browser/ui/views/tabs/stacked_tab_strip_layout.h"
25 #include "chrome/browser/ui/views/tabs/tab.h"
26 #include "chrome/browser/ui/views/tabs/tab_drag_controller.h"
27 #include "chrome/browser/ui/views/tabs/tab_strip_controller.h"
28 #include "chrome/browser/ui/views/tabs/tab_strip_observer.h"
29 #include "chrome/browser/ui/views/touch_uma/touch_uma.h"
30 #include "content/public/browser/user_metrics.h"
31 #include "grit/generated_resources.h"
32 #include "grit/theme_resources.h"
33 #include "ui/accessibility/ax_view_state.h"
34 #include "ui/base/default_theme_provider.h"
35 #include "ui/base/dragdrop/drag_drop_types.h"
36 #include "ui/base/l10n/l10n_util.h"
37 #include "ui/base/models/list_selection_model.h"
38 #include "ui/base/resource/resource_bundle.h"
39 #include "ui/gfx/animation/animation_container.h"
40 #include "ui/gfx/animation/throb_animation.h"
41 #include "ui/gfx/canvas.h"
42 #include "ui/gfx/display.h"
43 #include "ui/gfx/image/image_skia.h"
44 #include "ui/gfx/image/image_skia_operations.h"
45 #include "ui/gfx/path.h"
46 #include "ui/gfx/rect_conversions.h"
47 #include "ui/gfx/screen.h"
48 #include "ui/gfx/size.h"
49 #include "ui/views/controls/image_view.h"
50 #include "ui/views/mouse_watcher_view_host.h"
51 #include "ui/views/rect_based_targeting_utils.h"
52 #include "ui/views/view_model_utils.h"
53 #include "ui/views/widget/root_view.h"
54 #include "ui/views/widget/widget.h"
55 #include "ui/views/window/non_client_view.h"
57 #if defined(OS_WIN)
58 #include "ui/gfx/win/hwnd_util.h"
59 #include "ui/views/widget/monitor_win.h"
60 #include "ui/views/win/hwnd_util.h"
61 #endif
63 using base::UserMetricsAction;
64 using ui::DropTargetEvent;
66 namespace {
68 static const int kTabStripAnimationVSlop = 40;
69 // Inactive tabs in a native frame are slightly transparent.
70 static const int kGlassFrameInactiveTabAlpha = 200;
71 // If there are multiple tabs selected then make non-selected inactive tabs
72 // even more transparent.
73 static const int kGlassFrameInactiveTabAlphaMultiSelection = 150;
75 // Alpha applied to all elements save the selected tabs.
76 static const int kInactiveTabAndNewTabButtonAlphaAsh = 230;
77 static const int kInactiveTabAndNewTabButtonAlpha = 255;
79 // Inverse ratio of the width of a tab edge to the width of the tab. When
80 // hovering over the left or right edge of a tab, the drop indicator will
81 // point between tabs.
82 static const int kTabEdgeRatioInverse = 4;
84 // Size of the drop indicator.
85 static int drop_indicator_width;
86 static int drop_indicator_height;
88 static inline int Round(double x) {
89 // Why oh why is this not in a standard header?
90 return static_cast<int>(floor(x + 0.5));
93 // Max number of stacked tabs.
94 static const int kMaxStackedCount = 4;
96 // Padding between stacked tabs.
97 static const int kStackedPadding = 6;
99 // See UpdateLayoutTypeFromMouseEvent() for a description of these.
100 #if !defined(USE_ASH)
101 const int kMouseMoveTimeMS = 200;
102 const int kMouseMoveCountBeforeConsiderReal = 3;
103 #endif
105 // Amount of time we delay before resizing after a close from a touch.
106 const int kTouchResizeLayoutTimeMS = 2000;
108 // Horizontal offset for the new tab button to bring it closer to the
109 // rightmost tab.
110 const int kNewTabButtonHorizontalOffset = -11;
112 // Vertical offset for the new tab button to bring it closer to the
113 // rightmost tab.
114 const int kNewTabButtonVerticalOffset = 7;
116 // Amount the left edge of a tab is offset from the rectangle of the tab's
117 // favicon/title/close box. Related to the width of IDR_TAB_ACTIVE_LEFT.
118 // Affects the size of the "V" between adjacent tabs.
119 const int kTabHorizontalOffset = -26;
121 // The size of the new tab button must be hardcoded because we need to be
122 // able to lay it out before we are able to get its image from the
123 // ui::ThemeProvider. It also makes sense to do this, because the size of the
124 // new tab button should not need to be calculated dynamically.
125 const int kNewTabButtonAssetWidth = 34;
126 const int kNewTabButtonAssetHeight = 18;
128 // Amount to adjust the clip by when the tab is stacked before the active index.
129 const int kStackedTabLeftClip = 20;
131 // Amount to adjust the clip by when the tab is stacked after the active index.
132 const int kStackedTabRightClip = 20;
134 base::string16 GetClipboardText() {
135 if (!ui::Clipboard::IsSupportedClipboardType(ui::CLIPBOARD_TYPE_SELECTION))
136 return base::string16();
137 ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
138 CHECK(clipboard);
139 base::string16 clipboard_text;
140 clipboard->ReadText(ui::CLIPBOARD_TYPE_SELECTION, &clipboard_text);
141 return clipboard_text;
144 // Animation delegate used when a dragged tab is released. When done sets the
145 // dragging state to false.
146 class ResetDraggingStateDelegate
147 : public views::BoundsAnimator::OwnedAnimationDelegate {
148 public:
149 explicit ResetDraggingStateDelegate(Tab* tab) : tab_(tab) {
152 virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE {
153 tab_->set_dragging(false);
156 virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE {
157 tab_->set_dragging(false);
160 private:
161 Tab* tab_;
163 DISALLOW_COPY_AND_ASSIGN(ResetDraggingStateDelegate);
166 // If |dest| contains the point |point_in_source| the event handler from |dest|
167 // is returned. Otherwise NULL is returned.
168 views::View* ConvertPointToViewAndGetEventHandler(
169 views::View* source,
170 views::View* dest,
171 const gfx::Point& point_in_source) {
172 gfx::Point dest_point(point_in_source);
173 views::View::ConvertPointToTarget(source, dest, &dest_point);
174 return dest->HitTestPoint(dest_point) ?
175 dest->GetEventHandlerForPoint(dest_point) : NULL;
178 // Gets a tooltip handler for |point_in_source| from |dest|. Note that |dest|
179 // should return NULL if it does not contain the point.
180 views::View* ConvertPointToViewAndGetTooltipHandler(
181 views::View* source,
182 views::View* dest,
183 const gfx::Point& point_in_source) {
184 gfx::Point dest_point(point_in_source);
185 views::View::ConvertPointToTarget(source, dest, &dest_point);
186 return dest->GetTooltipHandlerForPoint(dest_point);
189 TabDragController::EventSource EventSourceFromEvent(
190 const ui::LocatedEvent& event) {
191 return event.IsGestureEvent() ? TabDragController::EVENT_SOURCE_TOUCH :
192 TabDragController::EVENT_SOURCE_MOUSE;
195 } // namespace
197 ///////////////////////////////////////////////////////////////////////////////
198 // NewTabButton
200 // A subclass of button that hit-tests to the shape of the new tab button and
201 // does custom drawing.
203 class NewTabButton : public views::ImageButton {
204 public:
205 NewTabButton(TabStrip* tab_strip, views::ButtonListener* listener);
206 virtual ~NewTabButton();
208 // Set the background offset used to match the background image to the frame
209 // image.
210 void set_background_offset(const gfx::Point& offset) {
211 background_offset_ = offset;
214 protected:
215 // Overridden from views::View:
216 virtual bool HasHitTestMask() const OVERRIDE;
217 virtual void GetHitTestMask(HitTestSource source,
218 gfx::Path* path) const OVERRIDE;
219 #if defined(OS_WIN)
220 virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE;
221 #endif
222 virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;
224 // Overridden from ui::EventHandler:
225 virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
227 private:
228 bool ShouldWindowContentsBeTransparent() const;
229 gfx::ImageSkia GetBackgroundImage(views::CustomButton::ButtonState state,
230 ui::ScaleFactor scale_factor) const;
231 gfx::ImageSkia GetImageForState(views::CustomButton::ButtonState state,
232 ui::ScaleFactor scale_factor) const;
233 gfx::ImageSkia GetImageForScale(ui::ScaleFactor scale_factor) const;
235 // Tab strip that contains this button.
236 TabStrip* tab_strip_;
238 // The offset used to paint the background image.
239 gfx::Point background_offset_;
241 // were we destroyed?
242 bool* destroyed_;
244 DISALLOW_COPY_AND_ASSIGN(NewTabButton);
247 NewTabButton::NewTabButton(TabStrip* tab_strip, views::ButtonListener* listener)
248 : views::ImageButton(listener),
249 tab_strip_(tab_strip),
250 destroyed_(NULL) {
251 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
252 set_triggerable_event_flags(triggerable_event_flags() |
253 ui::EF_MIDDLE_MOUSE_BUTTON);
254 #endif
257 NewTabButton::~NewTabButton() {
258 if (destroyed_)
259 *destroyed_ = true;
262 bool NewTabButton::HasHitTestMask() const {
263 // When the button is sized to the top of the tab strip we want the user to
264 // be able to click on complete bounds, and so don't return a custom hit
265 // mask.
266 return !tab_strip_->SizeTabButtonToTopOfTabStrip();
269 void NewTabButton::GetHitTestMask(HitTestSource source, gfx::Path* path) const {
270 DCHECK(path);
272 SkScalar w = SkIntToScalar(width());
273 SkScalar v_offset = SkIntToScalar(kNewTabButtonVerticalOffset);
275 // These values are defined by the shape of the new tab image. Should that
276 // image ever change, these values will need to be updated. They're so
277 // custom it's not really worth defining constants for.
278 // These values are correct for regular and USE_ASH versions of the image.
279 path->moveTo(0, v_offset + 1);
280 path->lineTo(w - 7, v_offset + 1);
281 path->lineTo(w - 4, v_offset + 4);
282 path->lineTo(w, v_offset + 16);
283 path->lineTo(w - 1, v_offset + 17);
284 path->lineTo(7, v_offset + 17);
285 path->lineTo(4, v_offset + 13);
286 path->lineTo(0, v_offset + 1);
287 path->close();
290 #if defined(OS_WIN)
291 void NewTabButton::OnMouseReleased(const ui::MouseEvent& event) {
292 if (event.IsOnlyRightMouseButton()) {
293 gfx::Point point = event.location();
294 views::View::ConvertPointToScreen(this, &point);
295 bool destroyed = false;
296 destroyed_ = &destroyed;
297 gfx::ShowSystemMenuAtPoint(views::HWNDForView(this), point);
298 if (destroyed)
299 return;
301 destroyed_ = NULL;
302 SetState(views::CustomButton::STATE_NORMAL);
303 return;
305 views::ImageButton::OnMouseReleased(event);
307 #endif
309 void NewTabButton::OnPaint(gfx::Canvas* canvas) {
310 gfx::ImageSkia image =
311 GetImageForScale(ui::GetSupportedScaleFactor(canvas->image_scale()));
312 canvas->DrawImageInt(image, 0, height() - image.height());
315 void NewTabButton::OnGestureEvent(ui::GestureEvent* event) {
316 // Consume all gesture events here so that the parent (Tab) does not
317 // start consuming gestures.
318 views::ImageButton::OnGestureEvent(event);
319 event->SetHandled();
322 bool NewTabButton::ShouldWindowContentsBeTransparent() const {
323 return GetWidget() &&
324 GetWidget()->GetTopLevelWidget()->ShouldWindowContentsBeTransparent();
327 gfx::ImageSkia NewTabButton::GetBackgroundImage(
328 views::CustomButton::ButtonState state,
329 ui::ScaleFactor scale_factor) const {
330 int background_id = 0;
331 if (ShouldWindowContentsBeTransparent()) {
332 background_id = IDR_THEME_TAB_BACKGROUND_V;
333 } else if (tab_strip_->controller()->IsIncognito()) {
334 background_id = IDR_THEME_TAB_BACKGROUND_INCOGNITO;
335 } else {
336 background_id = IDR_THEME_TAB_BACKGROUND;
339 int alpha = 0;
340 switch (state) {
341 case views::CustomButton::STATE_NORMAL:
342 case views::CustomButton::STATE_HOVERED:
343 alpha = ShouldWindowContentsBeTransparent() ? kGlassFrameInactiveTabAlpha
344 : 255;
345 break;
346 case views::CustomButton::STATE_PRESSED:
347 alpha = 145;
348 break;
349 default:
350 NOTREACHED();
351 break;
354 gfx::ImageSkia* mask =
355 GetThemeProvider()->GetImageSkiaNamed(IDR_NEWTAB_BUTTON_MASK);
356 int height = mask->height();
357 int width = mask->width();
358 float scale = ui::GetImageScale(scale_factor);
359 // The canvas and mask has to use the same scale factor.
360 if (!mask->HasRepresentation(scale))
361 scale_factor = ui::SCALE_FACTOR_100P;
363 gfx::Canvas canvas(gfx::Size(width, height), scale, false);
365 // For custom images the background starts at the top of the tab strip.
366 // Otherwise the background starts at the top of the frame.
367 gfx::ImageSkia* background =
368 GetThemeProvider()->GetImageSkiaNamed(background_id);
369 int offset_y = GetThemeProvider()->HasCustomImage(background_id) ?
370 0 : background_offset_.y();
372 // The new tab background is mirrored in RTL mode, but the theme background
373 // should never be mirrored. Mirror it here to compensate.
374 float x_scale = 1.0f;
375 int x = GetMirroredX() + background_offset_.x();
376 if (base::i18n::IsRTL()) {
377 x_scale = -1.0f;
378 // Offset by |width| such that the same region is painted as if there was no
379 // flip.
380 x += width;
382 canvas.TileImageInt(*background, x, kNewTabButtonVerticalOffset + offset_y,
383 x_scale, 1.0f, 0, 0, width, height);
385 if (alpha != 255) {
386 SkPaint paint;
387 paint.setColor(SkColorSetARGB(alpha, 255, 255, 255));
388 paint.setXfermodeMode(SkXfermode::kDstIn_Mode);
389 paint.setStyle(SkPaint::kFill_Style);
390 canvas.DrawRect(gfx::Rect(0, 0, width, height), paint);
393 // White highlight on hover.
394 if (state == views::CustomButton::STATE_HOVERED)
395 canvas.FillRect(GetLocalBounds(), SkColorSetARGB(64, 255, 255, 255));
397 return gfx::ImageSkiaOperations::CreateMaskedImage(
398 gfx::ImageSkia(canvas.ExtractImageRep()), *mask);
401 gfx::ImageSkia NewTabButton::GetImageForState(
402 views::CustomButton::ButtonState state,
403 ui::ScaleFactor scale_factor) const {
404 const int overlay_id = state == views::CustomButton::STATE_PRESSED ?
405 IDR_NEWTAB_BUTTON_P : IDR_NEWTAB_BUTTON;
406 gfx::ImageSkia* overlay = GetThemeProvider()->GetImageSkiaNamed(overlay_id);
408 gfx::Canvas canvas(
409 gfx::Size(overlay->width(), overlay->height()),
410 ui::GetImageScale(scale_factor),
411 false);
412 canvas.DrawImageInt(GetBackgroundImage(state, scale_factor), 0, 0);
414 // Draw the button border with a slight alpha.
415 const int kGlassFrameOverlayAlpha = 178;
416 const int kOpaqueFrameOverlayAlpha = 230;
417 uint8 alpha = ShouldWindowContentsBeTransparent() ?
418 kGlassFrameOverlayAlpha : kOpaqueFrameOverlayAlpha;
419 canvas.DrawImageInt(*overlay, 0, 0, alpha);
421 return gfx::ImageSkia(canvas.ExtractImageRep());
424 gfx::ImageSkia NewTabButton::GetImageForScale(
425 ui::ScaleFactor scale_factor) const {
426 if (!hover_animation_->is_animating())
427 return GetImageForState(state(), scale_factor);
428 return gfx::ImageSkiaOperations::CreateBlendedImage(
429 GetImageForState(views::CustomButton::STATE_NORMAL, scale_factor),
430 GetImageForState(views::CustomButton::STATE_HOVERED, scale_factor),
431 hover_animation_->GetCurrentValue());
434 ///////////////////////////////////////////////////////////////////////////////
435 // TabStrip::RemoveTabDelegate
437 // AnimationDelegate used when removing a tab. Does the necessary cleanup when
438 // done.
439 class TabStrip::RemoveTabDelegate
440 : public views::BoundsAnimator::OwnedAnimationDelegate {
441 public:
442 RemoveTabDelegate(TabStrip* tab_strip, Tab* tab);
444 virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE;
445 virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE;
447 private:
448 void CompleteRemove();
450 // When the animation completes, we send the Container a message to simulate
451 // a mouse moved event at the current mouse position. This tickles the Tab
452 // the mouse is currently over to show the "hot" state of the close button.
453 void HighlightCloseButton();
455 TabStrip* tabstrip_;
456 Tab* tab_;
458 DISALLOW_COPY_AND_ASSIGN(RemoveTabDelegate);
461 TabStrip::RemoveTabDelegate::RemoveTabDelegate(TabStrip* tab_strip,
462 Tab* tab)
463 : tabstrip_(tab_strip),
464 tab_(tab) {
467 void TabStrip::RemoveTabDelegate::AnimationEnded(
468 const gfx::Animation* animation) {
469 CompleteRemove();
472 void TabStrip::RemoveTabDelegate::AnimationCanceled(
473 const gfx::Animation* animation) {
474 CompleteRemove();
477 void TabStrip::RemoveTabDelegate::CompleteRemove() {
478 DCHECK(tab_->closing());
479 tabstrip_->RemoveAndDeleteTab(tab_);
480 HighlightCloseButton();
483 void TabStrip::RemoveTabDelegate::HighlightCloseButton() {
484 if (tabstrip_->IsDragSessionActive() ||
485 !tabstrip_->ShouldHighlightCloseButtonAfterRemove()) {
486 // This function is not required (and indeed may crash!) for removes
487 // spawned by non-mouse closes and drag-detaches.
488 return;
491 views::Widget* widget = tabstrip_->GetWidget();
492 // This can be null during shutdown. See http://crbug.com/42737.
493 if (!widget)
494 return;
496 widget->SynthesizeMouseMoveEvent();
499 ///////////////////////////////////////////////////////////////////////////////
500 // TabStrip, public:
502 // static
503 const char TabStrip::kViewClassName[] = "TabStrip";
505 // static
506 const int TabStrip::kMiniToNonMiniGap = 3;
508 TabStrip::TabStrip(TabStripController* controller)
509 : controller_(controller),
510 newtab_button_(NULL),
511 current_unselected_width_(Tab::GetStandardSize().width()),
512 current_selected_width_(Tab::GetStandardSize().width()),
513 available_width_for_tabs_(-1),
514 in_tab_close_(false),
515 animation_container_(new gfx::AnimationContainer()),
516 bounds_animator_(this),
517 layout_type_(TAB_STRIP_LAYOUT_SHRINK),
518 adjust_layout_(false),
519 reset_to_shrink_on_exit_(false),
520 mouse_move_count_(0),
521 immersive_style_(false) {
522 Init();
525 TabStrip::~TabStrip() {
526 FOR_EACH_OBSERVER(TabStripObserver, observers_,
527 TabStripDeleted(this));
529 // The animations may reference the tabs. Shut down the animation before we
530 // delete the tabs.
531 StopAnimating(false);
533 DestroyDragController();
535 // Make sure we unhook ourselves as a message loop observer so that we don't
536 // crash in the case where the user closes the window after closing a tab
537 // but before moving the mouse.
538 RemoveMessageLoopObserver();
540 // The children (tabs) may callback to us from their destructor. Delete them
541 // so that if they call back we aren't in a weird state.
542 RemoveAllChildViews(true);
545 void TabStrip::AddObserver(TabStripObserver* observer) {
546 observers_.AddObserver(observer);
549 void TabStrip::RemoveObserver(TabStripObserver* observer) {
550 observers_.RemoveObserver(observer);
553 void TabStrip::SetLayoutType(TabStripLayoutType layout_type,
554 bool adjust_layout) {
555 adjust_layout_ = adjust_layout;
556 if (layout_type == layout_type_)
557 return;
559 const int active_index = controller_->GetActiveIndex();
560 int active_center = 0;
561 if (active_index != -1) {
562 active_center = ideal_bounds(active_index).x() +
563 ideal_bounds(active_index).width() / 2;
565 layout_type_ = layout_type;
566 SetResetToShrinkOnExit(false);
567 SwapLayoutIfNecessary();
568 // When transitioning to stacked try to keep the active tab centered.
569 if (touch_layout_.get() && active_index != -1) {
570 touch_layout_->SetActiveTabLocation(
571 active_center - ideal_bounds(active_index).width() / 2);
572 AnimateToIdealBounds();
576 gfx::Rect TabStrip::GetNewTabButtonBounds() {
577 return newtab_button_->bounds();
580 bool TabStrip::SizeTabButtonToTopOfTabStrip() {
581 // Extend the button to the screen edge in maximized and immersive fullscreen.
582 views::Widget* widget = GetWidget();
583 return browser_defaults::kSizeTabButtonToTopOfTabStrip ||
584 (widget && (widget->IsMaximized() || widget->IsFullscreen()));
587 void TabStrip::StartHighlight(int model_index) {
588 tab_at(model_index)->StartPulse();
591 void TabStrip::StopAllHighlighting() {
592 for (int i = 0; i < tab_count(); ++i)
593 tab_at(i)->StopPulse();
596 void TabStrip::AddTabAt(int model_index,
597 const TabRendererData& data,
598 bool is_active) {
599 // Stop dragging when a new tab is added and dragging a window. Doing
600 // otherwise results in a confusing state if the user attempts to reattach. We
601 // could allow this and make TabDragController update itself during the add,
602 // but this comes up infrequently enough that it's not work the complexity.
603 if (drag_controller_.get() && !drag_controller_->is_mutating() &&
604 drag_controller_->is_dragging_window()) {
605 EndDrag(END_DRAG_COMPLETE);
607 Tab* tab = CreateTab();
608 tab->SetData(data);
609 UpdateTabsClosingMap(model_index, 1);
610 tabs_.Add(tab, model_index);
611 AddChildView(tab);
613 if (touch_layout_.get()) {
614 GenerateIdealBoundsForMiniTabs(NULL);
615 int add_types = 0;
616 if (data.mini)
617 add_types |= StackedTabStripLayout::kAddTypeMini;
618 if (is_active)
619 add_types |= StackedTabStripLayout::kAddTypeActive;
620 touch_layout_->AddTab(model_index, add_types, GetStartXForNormalTabs());
623 // Don't animate the first tab, it looks weird, and don't animate anything
624 // if the containing window isn't visible yet.
625 if (tab_count() > 1 && GetWidget() && GetWidget()->IsVisible())
626 StartInsertTabAnimation(model_index);
627 else
628 DoLayout();
630 SwapLayoutIfNecessary();
632 FOR_EACH_OBSERVER(TabStripObserver, observers_,
633 TabStripAddedTabAt(this, model_index));
636 void TabStrip::MoveTab(int from_model_index,
637 int to_model_index,
638 const TabRendererData& data) {
639 DCHECK_GT(tabs_.view_size(), 0);
640 Tab* last_tab = tab_at(tab_count() - 1);
641 tab_at(from_model_index)->SetData(data);
642 if (touch_layout_.get()) {
643 tabs_.MoveViewOnly(from_model_index, to_model_index);
644 int mini_count = 0;
645 GenerateIdealBoundsForMiniTabs(&mini_count);
646 touch_layout_->MoveTab(
647 from_model_index, to_model_index, controller_->GetActiveIndex(),
648 GetStartXForNormalTabs(), mini_count);
649 } else {
650 tabs_.Move(from_model_index, to_model_index);
652 StartMoveTabAnimation();
653 if (TabDragController::IsAttachedTo(this) &&
654 (last_tab != tab_at(tab_count() - 1) || last_tab->dragging())) {
655 newtab_button_->SetVisible(false);
657 SwapLayoutIfNecessary();
659 FOR_EACH_OBSERVER(TabStripObserver, observers_,
660 TabStripMovedTab(this, from_model_index, to_model_index));
663 void TabStrip::RemoveTabAt(int model_index) {
664 if (touch_layout_.get()) {
665 Tab* tab = tab_at(model_index);
666 tab->set_closing(true);
667 int old_x = tabs_.ideal_bounds(model_index).x();
668 // We still need to paint the tab until we actually remove it. Put it in
669 // tabs_closing_map_ so we can find it.
670 RemoveTabFromViewModel(model_index);
671 touch_layout_->RemoveTab(model_index, GenerateIdealBoundsForMiniTabs(NULL),
672 old_x);
673 ScheduleRemoveTabAnimation(tab);
674 } else if (in_tab_close_ && model_index != GetModelCount()) {
675 StartMouseInitiatedRemoveTabAnimation(model_index);
676 } else {
677 StartRemoveTabAnimation(model_index);
679 SwapLayoutIfNecessary();
681 FOR_EACH_OBSERVER(TabStripObserver, observers_,
682 TabStripRemovedTabAt(this, model_index));
685 void TabStrip::SetTabData(int model_index, const TabRendererData& data) {
686 Tab* tab = tab_at(model_index);
687 bool mini_state_changed = tab->data().mini != data.mini;
688 tab->SetData(data);
690 if (mini_state_changed) {
691 if (touch_layout_.get()) {
692 int mini_tab_count = 0;
693 int start_x = GenerateIdealBoundsForMiniTabs(&mini_tab_count);
694 touch_layout_->SetXAndMiniCount(start_x, mini_tab_count);
696 if (GetWidget() && GetWidget()->IsVisible())
697 StartMiniTabAnimation();
698 else
699 DoLayout();
701 SwapLayoutIfNecessary();
704 void TabStrip::PrepareForCloseAt(int model_index, CloseTabSource source) {
705 if (!in_tab_close_ && IsAnimating()) {
706 // Cancel any current animations. We do this as remove uses the current
707 // ideal bounds and we need to know ideal bounds is in a good state.
708 StopAnimating(true);
711 if (!GetWidget())
712 return;
714 int model_count = GetModelCount();
715 if (model_index + 1 != model_count && model_count > 1) {
716 // The user is about to close a tab other than the last tab. Set
717 // available_width_for_tabs_ so that if we do a layout we don't position a
718 // tab past the end of the second to last tab. We do this so that as the
719 // user closes tabs with the mouse a tab continues to fall under the mouse.
720 Tab* last_tab = tab_at(model_count - 1);
721 Tab* tab_being_removed = tab_at(model_index);
722 available_width_for_tabs_ = last_tab->x() + last_tab->width() -
723 tab_being_removed->width() - kTabHorizontalOffset;
724 if (model_index == 0 && tab_being_removed->data().mini &&
725 !tab_at(1)->data().mini) {
726 available_width_for_tabs_ -= kMiniToNonMiniGap;
730 in_tab_close_ = true;
731 resize_layout_timer_.Stop();
732 if (source == CLOSE_TAB_FROM_TOUCH) {
733 StartResizeLayoutTabsFromTouchTimer();
734 } else {
735 AddMessageLoopObserver();
739 void TabStrip::SetSelection(const ui::ListSelectionModel& old_selection,
740 const ui::ListSelectionModel& new_selection) {
741 if (touch_layout_.get()) {
742 touch_layout_->SetActiveIndex(new_selection.active());
743 // Only start an animation if we need to. Otherwise clicking on an
744 // unselected tab and dragging won't work because dragging is only allowed
745 // if not animating.
746 if (!views::ViewModelUtils::IsAtIdealBounds(tabs_))
747 AnimateToIdealBounds();
748 SchedulePaint();
749 } else {
750 // We have "tiny tabs" if the tabs are so tiny that the unselected ones are
751 // a different size to the selected ones.
752 bool tiny_tabs = current_unselected_width_ != current_selected_width_;
753 if (!IsAnimating() && (!in_tab_close_ || tiny_tabs)) {
754 DoLayout();
755 } else {
756 SchedulePaint();
760 ui::ListSelectionModel::SelectedIndices no_longer_selected =
761 base::STLSetDifference<ui::ListSelectionModel::SelectedIndices>(
762 old_selection.selected_indices(),
763 new_selection.selected_indices());
764 for (size_t i = 0; i < no_longer_selected.size(); ++i)
765 tab_at(no_longer_selected[i])->StopMiniTabTitleAnimation();
768 void TabStrip::TabTitleChangedNotLoading(int model_index) {
769 Tab* tab = tab_at(model_index);
770 if (tab->data().mini && !tab->IsActive())
771 tab->StartMiniTabTitleAnimation();
774 Tab* TabStrip::tab_at(int index) const {
775 return static_cast<Tab*>(tabs_.view_at(index));
778 int TabStrip::GetModelIndexOfTab(const Tab* tab) const {
779 return tabs_.GetIndexOfView(tab);
782 int TabStrip::GetModelCount() const {
783 return controller_->GetCount();
786 bool TabStrip::IsValidModelIndex(int model_index) const {
787 return controller_->IsValidIndex(model_index);
790 bool TabStrip::IsDragSessionActive() const {
791 return drag_controller_.get() != NULL;
794 bool TabStrip::IsActiveDropTarget() const {
795 for (int i = 0; i < tab_count(); ++i) {
796 Tab* tab = tab_at(i);
797 if (tab->dragging())
798 return true;
800 return false;
803 bool TabStrip::IsTabStripEditable() const {
804 return !IsDragSessionActive() && !IsActiveDropTarget();
807 bool TabStrip::IsTabStripCloseable() const {
808 return !IsDragSessionActive();
811 void TabStrip::UpdateLoadingAnimations() {
812 controller_->UpdateLoadingAnimations();
815 bool TabStrip::IsPositionInWindowCaption(const gfx::Point& point) {
816 return IsRectInWindowCaption(gfx::Rect(point, gfx::Size(1, 1)));
819 bool TabStrip::IsRectInWindowCaption(const gfx::Rect& rect) {
820 views::View* v = GetEventHandlerForRect(rect);
822 // If there is no control at this location, claim the hit was in the title
823 // bar to get a move action.
824 if (v == this)
825 return true;
827 // Check to see if the rect intersects the non-button parts of the new tab
828 // button. The button has a non-rectangular shape, so if it's not in the
829 // visual portions of the button we treat it as a click to the caption.
830 gfx::RectF rect_in_newtab_coords_f(rect);
831 View::ConvertRectToTarget(this, newtab_button_, &rect_in_newtab_coords_f);
832 gfx::Rect rect_in_newtab_coords = gfx::ToEnclosingRect(
833 rect_in_newtab_coords_f);
834 if (newtab_button_->GetLocalBounds().Intersects(rect_in_newtab_coords) &&
835 !newtab_button_->HitTestRect(rect_in_newtab_coords))
836 return true;
838 // All other regions, including the new Tab button, should be considered part
839 // of the containing Window's client area so that regular events can be
840 // processed for them.
841 return false;
844 void TabStrip::SetBackgroundOffset(const gfx::Point& offset) {
845 for (int i = 0; i < tab_count(); ++i)
846 tab_at(i)->set_background_offset(offset);
847 newtab_button_->set_background_offset(offset);
850 views::View* TabStrip::newtab_button() {
851 return newtab_button_;
854 void TabStrip::SetImmersiveStyle(bool enable) {
855 if (immersive_style_ == enable)
856 return;
857 immersive_style_ = enable;
860 bool TabStrip::IsAnimating() const {
861 return bounds_animator_.IsAnimating();
864 void TabStrip::StopAnimating(bool layout) {
865 if (!IsAnimating())
866 return;
868 bounds_animator_.Cancel();
870 if (layout)
871 DoLayout();
874 void TabStrip::FileSupported(const GURL& url, bool supported) {
875 if (drop_info_.get() && drop_info_->url == url)
876 drop_info_->file_supported = supported;
879 const ui::ListSelectionModel& TabStrip::GetSelectionModel() {
880 return controller_->GetSelectionModel();
883 bool TabStrip::SupportsMultipleSelection() {
884 // TODO: currently only allow single selection in touch layout mode.
885 return touch_layout_.get() == NULL;
888 void TabStrip::SelectTab(Tab* tab) {
889 int model_index = GetModelIndexOfTab(tab);
890 if (IsValidModelIndex(model_index))
891 controller_->SelectTab(model_index);
894 void TabStrip::ExtendSelectionTo(Tab* tab) {
895 int model_index = GetModelIndexOfTab(tab);
896 if (IsValidModelIndex(model_index))
897 controller_->ExtendSelectionTo(model_index);
900 void TabStrip::ToggleSelected(Tab* tab) {
901 int model_index = GetModelIndexOfTab(tab);
902 if (IsValidModelIndex(model_index))
903 controller_->ToggleSelected(model_index);
906 void TabStrip::AddSelectionFromAnchorTo(Tab* tab) {
907 int model_index = GetModelIndexOfTab(tab);
908 if (IsValidModelIndex(model_index))
909 controller_->AddSelectionFromAnchorTo(model_index);
912 void TabStrip::CloseTab(Tab* tab, CloseTabSource source) {
913 if (tab->closing()) {
914 // If the tab is already closing, close the next tab. We do this so that the
915 // user can rapidly close tabs by clicking the close button and not have
916 // the animations interfere with that.
917 for (TabsClosingMap::const_iterator i(tabs_closing_map_.begin());
918 i != tabs_closing_map_.end(); ++i) {
919 std::vector<Tab*>::const_iterator j =
920 std::find(i->second.begin(), i->second.end(), tab);
921 if (j != i->second.end()) {
922 if (i->first + 1 < GetModelCount())
923 controller_->CloseTab(i->first + 1, source);
924 return;
927 // If we get here, it means a tab has been marked as closing but isn't in
928 // the set of known closing tabs.
929 NOTREACHED();
930 return;
932 int model_index = GetModelIndexOfTab(tab);
933 if (IsValidModelIndex(model_index))
934 controller_->CloseTab(model_index, source);
937 void TabStrip::ShowContextMenuForTab(Tab* tab,
938 const gfx::Point& p,
939 ui::MenuSourceType source_type) {
940 controller_->ShowContextMenuForTab(tab, p, source_type);
943 bool TabStrip::IsActiveTab(const Tab* tab) const {
944 int model_index = GetModelIndexOfTab(tab);
945 return IsValidModelIndex(model_index) &&
946 controller_->IsActiveTab(model_index);
949 bool TabStrip::IsTabSelected(const Tab* tab) const {
950 int model_index = GetModelIndexOfTab(tab);
951 return IsValidModelIndex(model_index) &&
952 controller_->IsTabSelected(model_index);
955 bool TabStrip::IsTabPinned(const Tab* tab) const {
956 if (tab->closing())
957 return false;
959 int model_index = GetModelIndexOfTab(tab);
960 return IsValidModelIndex(model_index) &&
961 controller_->IsTabPinned(model_index);
964 void TabStrip::MaybeStartDrag(
965 Tab* tab,
966 const ui::LocatedEvent& event,
967 const ui::ListSelectionModel& original_selection) {
968 // Don't accidentally start any drag operations during animations if the
969 // mouse is down... during an animation tabs are being resized automatically,
970 // so the View system can misinterpret this easily if the mouse is down that
971 // the user is dragging.
972 if (IsAnimating() || tab->closing() ||
973 controller_->HasAvailableDragActions() == 0) {
974 return;
977 // Do not do any dragging of tabs when using the super short immersive style.
978 if (IsImmersiveStyle())
979 return;
981 int model_index = GetModelIndexOfTab(tab);
982 if (!IsValidModelIndex(model_index)) {
983 CHECK(false);
984 return;
986 std::vector<Tab*> tabs;
987 int size_to_selected = 0;
988 int x = tab->GetMirroredXInView(event.x());
989 int y = event.y();
990 // Build the set of selected tabs to drag and calculate the offset from the
991 // first selected tab.
992 for (int i = 0; i < tab_count(); ++i) {
993 Tab* other_tab = tab_at(i);
994 if (IsTabSelected(other_tab)) {
995 tabs.push_back(other_tab);
996 if (other_tab == tab) {
997 size_to_selected = GetSizeNeededForTabs(tabs);
998 x = size_to_selected - tab->width() + x;
1002 DCHECK(!tabs.empty());
1003 DCHECK(std::find(tabs.begin(), tabs.end(), tab) != tabs.end());
1004 ui::ListSelectionModel selection_model;
1005 if (!original_selection.IsSelected(model_index))
1006 selection_model.Copy(original_selection);
1007 // Delete the existing DragController before creating a new one. We do this as
1008 // creating the DragController remembers the WebContents delegates and we need
1009 // to make sure the existing DragController isn't still a delegate.
1010 drag_controller_.reset();
1011 TabDragController::DetachBehavior detach_behavior =
1012 TabDragController::DETACHABLE;
1013 TabDragController::MoveBehavior move_behavior =
1014 TabDragController::REORDER;
1015 // Use MOVE_VISIBILE_TABS in the following conditions:
1016 // . Mouse event generated from touch and the left button is down (the right
1017 // button corresponds to a long press, which we want to reorder).
1018 // . Gesture begin and control key isn't down.
1019 // . Real mouse event and control is down. This is mostly for testing.
1020 DCHECK(event.type() == ui::ET_MOUSE_PRESSED ||
1021 event.type() == ui::ET_GESTURE_BEGIN);
1022 if (touch_layout_.get() &&
1023 ((event.type() == ui::ET_MOUSE_PRESSED &&
1024 (((event.flags() & ui::EF_FROM_TOUCH) &&
1025 static_cast<const ui::MouseEvent&>(event).IsLeftMouseButton()) ||
1026 (!(event.flags() & ui::EF_FROM_TOUCH) &&
1027 static_cast<const ui::MouseEvent&>(event).IsControlDown()))) ||
1028 (event.type() == ui::ET_GESTURE_BEGIN && !event.IsControlDown()))) {
1029 move_behavior = TabDragController::MOVE_VISIBILE_TABS;
1032 drag_controller_.reset(new TabDragController);
1033 drag_controller_->Init(
1034 this, tab, tabs, gfx::Point(x, y), event.x(), selection_model,
1035 detach_behavior, move_behavior, EventSourceFromEvent(event));
1038 void TabStrip::ContinueDrag(views::View* view, const ui::LocatedEvent& event) {
1039 if (drag_controller_.get() &&
1040 drag_controller_->event_source() == EventSourceFromEvent(event)) {
1041 gfx::Point screen_location(event.location());
1042 views::View::ConvertPointToScreen(view, &screen_location);
1043 drag_controller_->Drag(screen_location);
1047 bool TabStrip::EndDrag(EndDragReason reason) {
1048 if (!drag_controller_.get())
1049 return false;
1050 bool started_drag = drag_controller_->started_drag();
1051 drag_controller_->EndDrag(reason);
1052 return started_drag;
1055 Tab* TabStrip::GetTabAt(Tab* tab, const gfx::Point& tab_in_tab_coordinates) {
1056 gfx::Point local_point = tab_in_tab_coordinates;
1057 ConvertPointToTarget(tab, this, &local_point);
1059 views::View* view = GetEventHandlerForPoint(local_point);
1060 if (!view)
1061 return NULL; // No tab contains the point.
1063 // Walk up the view hierarchy until we find a tab, or the TabStrip.
1064 while (view && view != this && view->id() != VIEW_ID_TAB)
1065 view = view->parent();
1067 return view && view->id() == VIEW_ID_TAB ? static_cast<Tab*>(view) : NULL;
1070 void TabStrip::OnMouseEventInTab(views::View* source,
1071 const ui::MouseEvent& event) {
1072 UpdateLayoutTypeFromMouseEvent(source, event);
1075 bool TabStrip::ShouldPaintTab(const Tab* tab, gfx::Rect* clip) {
1076 // Only touch layout needs to restrict the clip.
1077 if (!(touch_layout_.get() || IsStackingDraggedTabs()))
1078 return true;
1080 int index = GetModelIndexOfTab(tab);
1081 if (index == -1)
1082 return true; // Tab is closing, paint it all.
1084 int active_index = IsStackingDraggedTabs() ?
1085 controller_->GetActiveIndex() : touch_layout_->active_index();
1086 if (active_index == tab_count())
1087 active_index--;
1089 if (index < active_index) {
1090 if (tab_at(index)->x() == tab_at(index + 1)->x())
1091 return false;
1093 if (tab_at(index)->x() > tab_at(index + 1)->x())
1094 return true; // Can happen during dragging.
1096 clip->SetRect(0, 0, tab_at(index + 1)->x() - tab_at(index)->x() +
1097 kStackedTabLeftClip,
1098 tab_at(index)->height());
1099 } else if (index > active_index && index > 0) {
1100 const gfx::Rect& tab_bounds(tab_at(index)->bounds());
1101 const gfx::Rect& previous_tab_bounds(tab_at(index - 1)->bounds());
1102 if (tab_bounds.x() == previous_tab_bounds.x())
1103 return false;
1105 if (tab_bounds.x() < previous_tab_bounds.x())
1106 return true; // Can happen during dragging.
1108 if (previous_tab_bounds.right() + kTabHorizontalOffset != tab_bounds.x()) {
1109 int x = previous_tab_bounds.right() - tab_bounds.x() -
1110 kStackedTabRightClip;
1111 clip->SetRect(x, 0, tab_bounds.width() - x, tab_bounds.height());
1114 return true;
1117 bool TabStrip::IsImmersiveStyle() const {
1118 return immersive_style_;
1121 void TabStrip::MouseMovedOutOfHost() {
1122 ResizeLayoutTabs();
1123 if (reset_to_shrink_on_exit_) {
1124 reset_to_shrink_on_exit_ = false;
1125 SetLayoutType(TAB_STRIP_LAYOUT_SHRINK, true);
1126 controller_->LayoutTypeMaybeChanged();
1130 ///////////////////////////////////////////////////////////////////////////////
1131 // TabStrip, views::View overrides:
1133 void TabStrip::Layout() {
1134 // Only do a layout if our size changed.
1135 if (last_layout_size_ == size())
1136 return;
1137 if (IsDragSessionActive())
1138 return;
1139 DoLayout();
1142 void TabStrip::PaintChildren(gfx::Canvas* canvas) {
1143 // The view order doesn't match the paint order (tabs_ contains the tab
1144 // ordering). Additionally we need to paint the tabs that are closing in
1145 // |tabs_closing_map_|.
1146 Tab* active_tab = NULL;
1147 std::vector<Tab*> tabs_dragging;
1148 std::vector<Tab*> selected_tabs;
1149 int selected_tab_count = 0;
1150 bool is_dragging = false;
1151 int active_tab_index = -1;
1152 // Since |touch_layout_| is created based on number of tabs and width we use
1153 // the ideal state to determine if we should paint stacked. This minimizes
1154 // painting changes as we switch between the two.
1155 const bool stacking = (layout_type_ == TAB_STRIP_LAYOUT_STACKED) ||
1156 IsStackingDraggedTabs();
1158 const chrome::HostDesktopType host_desktop_type =
1159 chrome::GetHostDesktopTypeForNativeView(GetWidget()->GetNativeView());
1160 const int inactive_tab_alpha =
1161 host_desktop_type == chrome::HOST_DESKTOP_TYPE_ASH ?
1162 kInactiveTabAndNewTabButtonAlphaAsh :
1163 kInactiveTabAndNewTabButtonAlpha;
1165 if (inactive_tab_alpha < 255)
1166 canvas->SaveLayerAlpha(inactive_tab_alpha);
1168 PaintClosingTabs(canvas, tab_count());
1170 for (int i = tab_count() - 1; i >= 0; --i) {
1171 Tab* tab = tab_at(i);
1172 if (tab->IsSelected())
1173 selected_tab_count++;
1174 if (tab->dragging() && !stacking) {
1175 is_dragging = true;
1176 if (tab->IsActive()) {
1177 active_tab = tab;
1178 active_tab_index = i;
1179 } else {
1180 tabs_dragging.push_back(tab);
1182 } else if (!tab->IsActive()) {
1183 if (!tab->IsSelected()) {
1184 if (!stacking)
1185 tab->Paint(canvas);
1186 } else {
1187 selected_tabs.push_back(tab);
1189 } else {
1190 active_tab = tab;
1191 active_tab_index = i;
1193 PaintClosingTabs(canvas, i);
1196 // Draw from the left and then the right if we're in touch mode.
1197 if (stacking && active_tab_index >= 0) {
1198 for (int i = 0; i < active_tab_index; ++i) {
1199 Tab* tab = tab_at(i);
1200 tab->Paint(canvas);
1203 for (int i = tab_count() - 1; i > active_tab_index; --i) {
1204 Tab* tab = tab_at(i);
1205 tab->Paint(canvas);
1208 if (inactive_tab_alpha < 255)
1209 canvas->Restore();
1211 if (GetWidget()->ShouldWindowContentsBeTransparent()) {
1212 // Make sure non-active tabs are somewhat transparent.
1213 SkPaint paint;
1214 // If there are multiple tabs selected, fade non-selected tabs more to make
1215 // the selected tabs more noticable.
1216 int alpha = selected_tab_count > 1 ?
1217 kGlassFrameInactiveTabAlphaMultiSelection :
1218 kGlassFrameInactiveTabAlpha;
1219 paint.setColor(SkColorSetARGB(alpha, 255, 255, 255));
1220 paint.setXfermodeMode(SkXfermode::kDstIn_Mode);
1221 paint.setStyle(SkPaint::kFill_Style);
1222 // The tabstrip area overlaps the toolbar area by 2 px.
1223 canvas->DrawRect(gfx::Rect(0, 0, width(), height() - 2), paint);
1226 // Now selected but not active. We don't want these dimmed if using native
1227 // frame, so they're painted after initial pass.
1228 for (size_t i = 0; i < selected_tabs.size(); ++i)
1229 selected_tabs[i]->Paint(canvas);
1231 // Next comes the active tab.
1232 if (active_tab && !is_dragging)
1233 active_tab->Paint(canvas);
1235 // Paint the New Tab button.
1236 if (inactive_tab_alpha < 255)
1237 canvas->SaveLayerAlpha(inactive_tab_alpha);
1238 newtab_button_->Paint(canvas);
1239 if (inactive_tab_alpha < 255)
1240 canvas->Restore();
1242 // And the dragged tabs.
1243 for (size_t i = 0; i < tabs_dragging.size(); ++i)
1244 tabs_dragging[i]->Paint(canvas);
1246 // If the active tab is being dragged, it goes last.
1247 if (active_tab && is_dragging)
1248 active_tab->Paint(canvas);
1251 const char* TabStrip::GetClassName() const {
1252 return kViewClassName;
1255 gfx::Size TabStrip::GetPreferredSize() {
1256 // For stacked tabs the minimum size is calculated as the size needed to
1257 // handle showing any number of tabs. Otherwise report the minimum width as
1258 // the size required for a single selected tab plus the new tab button. Don't
1259 // base it on the actual number of tabs because it's undesirable to have the
1260 // minimum window size change when a new tab is opened.
1261 int needed_width;
1262 if (touch_layout_.get() || adjust_layout_) {
1263 needed_width = Tab::GetTouchWidth() +
1264 (2 * kStackedPadding * kMaxStackedCount);
1265 } else {
1266 needed_width = Tab::GetMinimumSelectedSize().width();
1268 needed_width += new_tab_button_width();
1269 if (immersive_style_)
1270 return gfx::Size(needed_width, Tab::GetImmersiveHeight());
1271 return gfx::Size(needed_width, Tab::GetMinimumUnselectedSize().height());
1274 void TabStrip::OnDragEntered(const DropTargetEvent& event) {
1275 // Force animations to stop, otherwise it makes the index calculation tricky.
1276 StopAnimating(true);
1278 UpdateDropIndex(event);
1280 GURL url;
1281 base::string16 title;
1283 // Check whether the event data includes supported drop data.
1284 if (event.data().GetURLAndTitle(
1285 ui::OSExchangeData::CONVERT_FILENAMES, &url, &title) &&
1286 url.is_valid()) {
1287 drop_info_->url = url;
1289 // For file:// URLs, kick off a MIME type request in case they're dropped.
1290 if (url.SchemeIsFile())
1291 controller()->CheckFileSupported(url);
1295 int TabStrip::OnDragUpdated(const DropTargetEvent& event) {
1296 // Update the drop index even if the file is unsupported, to allow
1297 // dragging a file to the contents of another tab.
1298 UpdateDropIndex(event);
1300 if (!drop_info_->file_supported)
1301 return ui::DragDropTypes::DRAG_NONE;
1303 return GetDropEffect(event);
1306 void TabStrip::OnDragExited() {
1307 SetDropIndex(-1, false);
1310 int TabStrip::OnPerformDrop(const DropTargetEvent& event) {
1311 if (!drop_info_.get())
1312 return ui::DragDropTypes::DRAG_NONE;
1314 const int drop_index = drop_info_->drop_index;
1315 const bool drop_before = drop_info_->drop_before;
1316 const bool file_supported = drop_info_->file_supported;
1318 // Hide the drop indicator.
1319 SetDropIndex(-1, false);
1321 // Do nothing if the file was unsupported or the URL is invalid. The URL may
1322 // have been changed after |drop_info_| was created.
1323 GURL url;
1324 base::string16 title;
1325 if (!file_supported ||
1326 !event.data().GetURLAndTitle(
1327 ui::OSExchangeData::CONVERT_FILENAMES, &url, &title) ||
1328 !url.is_valid())
1329 return ui::DragDropTypes::DRAG_NONE;
1331 controller()->PerformDrop(drop_before, drop_index, url);
1333 return GetDropEffect(event);
1336 void TabStrip::GetAccessibleState(ui::AXViewState* state) {
1337 state->role = ui::AX_ROLE_TAB_LIST;
1340 views::View* TabStrip::GetEventHandlerForRect(const gfx::Rect& rect) {
1341 if (!views::UsePointBasedTargeting(rect))
1342 return View::GetEventHandlerForRect(rect);
1343 const gfx::Point point(rect.CenterPoint());
1345 if (!touch_layout_.get()) {
1346 // Return any view that isn't a Tab or this TabStrip immediately. We don't
1347 // want to interfere.
1348 views::View* v = View::GetEventHandlerForRect(rect);
1349 if (v && v != this && strcmp(v->GetClassName(), Tab::kViewClassName))
1350 return v;
1352 views::View* tab = FindTabHitByPoint(point);
1353 if (tab)
1354 return tab;
1355 } else {
1356 if (newtab_button_->visible()) {
1357 views::View* view =
1358 ConvertPointToViewAndGetEventHandler(this, newtab_button_, point);
1359 if (view)
1360 return view;
1362 Tab* tab = FindTabForEvent(point);
1363 if (tab)
1364 return ConvertPointToViewAndGetEventHandler(this, tab, point);
1366 return this;
1369 views::View* TabStrip::GetTooltipHandlerForPoint(const gfx::Point& point) {
1370 if (!HitTestPoint(point))
1371 return NULL;
1373 if (!touch_layout_.get()) {
1374 // Return any view that isn't a Tab or this TabStrip immediately. We don't
1375 // want to interfere.
1376 views::View* v = View::GetTooltipHandlerForPoint(point);
1377 if (v && v != this && strcmp(v->GetClassName(), Tab::kViewClassName))
1378 return v;
1380 views::View* tab = FindTabHitByPoint(point);
1381 if (tab)
1382 return tab;
1383 } else {
1384 if (newtab_button_->visible()) {
1385 views::View* view =
1386 ConvertPointToViewAndGetTooltipHandler(this, newtab_button_, point);
1387 if (view)
1388 return view;
1390 Tab* tab = FindTabForEvent(point);
1391 if (tab)
1392 return ConvertPointToViewAndGetTooltipHandler(this, tab, point);
1394 return this;
1397 // static
1398 int TabStrip::GetImmersiveHeight() {
1399 return Tab::GetImmersiveHeight();
1402 int TabStrip::GetMiniTabCount() const {
1403 int mini_count = 0;
1404 while (mini_count < tab_count() && tab_at(mini_count)->data().mini)
1405 mini_count++;
1406 return mini_count;
1409 ///////////////////////////////////////////////////////////////////////////////
1410 // TabStrip, views::ButtonListener implementation:
1412 void TabStrip::ButtonPressed(views::Button* sender, const ui::Event& event) {
1413 if (sender == newtab_button_) {
1414 content::RecordAction(UserMetricsAction("NewTab_Button"));
1415 UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", TabStripModel::NEW_TAB_BUTTON,
1416 TabStripModel::NEW_TAB_ENUM_COUNT);
1417 if (event.IsMouseEvent()) {
1418 const ui::MouseEvent& mouse = static_cast<const ui::MouseEvent&>(event);
1419 if (mouse.IsOnlyMiddleMouseButton()) {
1420 base::string16 clipboard_text = GetClipboardText();
1421 if (!clipboard_text.empty())
1422 controller()->CreateNewTabWithLocation(clipboard_text);
1423 return;
1427 controller()->CreateNewTab();
1428 if (event.type() == ui::ET_GESTURE_TAP)
1429 TouchUMA::RecordGestureAction(TouchUMA::GESTURE_NEWTAB_TAP);
1433 ///////////////////////////////////////////////////////////////////////////////
1434 // TabStrip, protected:
1436 // Overridden to support automation. See automation_proxy_uitest.cc.
1437 const views::View* TabStrip::GetViewByID(int view_id) const {
1438 if (tab_count() > 0) {
1439 if (view_id == VIEW_ID_TAB_LAST) {
1440 return tab_at(tab_count() - 1);
1441 } else if ((view_id >= VIEW_ID_TAB_0) && (view_id < VIEW_ID_TAB_LAST)) {
1442 int index = view_id - VIEW_ID_TAB_0;
1443 if (index >= 0 && index < tab_count()) {
1444 return tab_at(index);
1445 } else {
1446 return NULL;
1451 return View::GetViewByID(view_id);
1454 bool TabStrip::OnMousePressed(const ui::MouseEvent& event) {
1455 UpdateLayoutTypeFromMouseEvent(this, event);
1456 // We can't return true here, else clicking in an empty area won't drag the
1457 // window.
1458 return false;
1461 bool TabStrip::OnMouseDragged(const ui::MouseEvent& event) {
1462 ContinueDrag(this, event);
1463 return true;
1466 void TabStrip::OnMouseReleased(const ui::MouseEvent& event) {
1467 EndDrag(END_DRAG_COMPLETE);
1468 UpdateLayoutTypeFromMouseEvent(this, event);
1471 void TabStrip::OnMouseCaptureLost() {
1472 EndDrag(END_DRAG_CAPTURE_LOST);
1475 void TabStrip::OnMouseMoved(const ui::MouseEvent& event) {
1476 UpdateLayoutTypeFromMouseEvent(this, event);
1479 void TabStrip::OnMouseEntered(const ui::MouseEvent& event) {
1480 SetResetToShrinkOnExit(true);
1483 void TabStrip::OnGestureEvent(ui::GestureEvent* event) {
1484 SetResetToShrinkOnExit(false);
1485 switch (event->type()) {
1486 case ui::ET_GESTURE_SCROLL_END:
1487 case ui::ET_SCROLL_FLING_START:
1488 case ui::ET_GESTURE_END:
1489 EndDrag(END_DRAG_COMPLETE);
1490 if (adjust_layout_) {
1491 SetLayoutType(TAB_STRIP_LAYOUT_STACKED, true);
1492 controller_->LayoutTypeMaybeChanged();
1494 break;
1496 case ui::ET_GESTURE_LONG_PRESS:
1497 if (drag_controller_.get())
1498 drag_controller_->SetMoveBehavior(TabDragController::REORDER);
1499 break;
1501 case ui::ET_GESTURE_LONG_TAP: {
1502 EndDrag(END_DRAG_CANCEL);
1503 gfx::Point local_point = event->location();
1504 Tab* tab = FindTabForEvent(local_point);
1505 if (tab) {
1506 ConvertPointToScreen(this, &local_point);
1507 ShowContextMenuForTab(tab, local_point, ui::MENU_SOURCE_TOUCH);
1509 break;
1512 case ui::ET_GESTURE_SCROLL_UPDATE:
1513 ContinueDrag(this, *event);
1514 break;
1516 case ui::ET_GESTURE_BEGIN:
1517 EndDrag(END_DRAG_CANCEL);
1518 break;
1520 case ui::ET_GESTURE_TAP: {
1521 const int active_index = controller_->GetActiveIndex();
1522 DCHECK_NE(-1, active_index);
1523 Tab* active_tab = tab_at(active_index);
1524 TouchUMA::GestureActionType action = TouchUMA::GESTURE_TABNOSWITCH_TAP;
1525 if (active_tab->tab_activated_with_last_gesture_begin())
1526 action = TouchUMA::GESTURE_TABSWITCH_TAP;
1527 TouchUMA::RecordGestureAction(action);
1528 break;
1531 default:
1532 break;
1534 event->SetHandled();
1537 ///////////////////////////////////////////////////////////////////////////////
1538 // TabStrip, private:
1540 void TabStrip::Init() {
1541 set_id(VIEW_ID_TAB_STRIP);
1542 // So we get enter/exit on children to switch layout type.
1543 set_notify_enter_exit_on_child(true);
1544 newtab_button_bounds_.SetRect(0,
1546 kNewTabButtonAssetWidth,
1547 kNewTabButtonAssetHeight +
1548 kNewTabButtonVerticalOffset);
1549 newtab_button_ = new NewTabButton(this, this);
1550 newtab_button_->SetTooltipText(
1551 l10n_util::GetStringUTF16(IDS_TOOLTIP_NEW_TAB));
1552 newtab_button_->SetAccessibleName(
1553 l10n_util::GetStringUTF16(IDS_ACCNAME_NEWTAB));
1554 newtab_button_->SetImageAlignment(views::ImageButton::ALIGN_LEFT,
1555 views::ImageButton::ALIGN_BOTTOM);
1556 AddChildView(newtab_button_);
1557 if (drop_indicator_width == 0) {
1558 // Direction doesn't matter, both images are the same size.
1559 gfx::ImageSkia* drop_image = GetDropArrowImage(true);
1560 drop_indicator_width = drop_image->width();
1561 drop_indicator_height = drop_image->height();
1565 Tab* TabStrip::CreateTab() {
1566 Tab* tab = new Tab(this);
1567 tab->set_animation_container(animation_container_.get());
1568 return tab;
1571 void TabStrip::StartInsertTabAnimation(int model_index) {
1572 PrepareForAnimation();
1574 // The TabStrip can now use its entire width to lay out Tabs.
1575 in_tab_close_ = false;
1576 available_width_for_tabs_ = -1;
1578 GenerateIdealBounds();
1580 Tab* tab = tab_at(model_index);
1581 if (model_index == 0) {
1582 tab->SetBounds(0, ideal_bounds(model_index).y(), 0,
1583 ideal_bounds(model_index).height());
1584 } else {
1585 Tab* last_tab = tab_at(model_index - 1);
1586 tab->SetBounds(last_tab->bounds().right() + kTabHorizontalOffset,
1587 ideal_bounds(model_index).y(), 0,
1588 ideal_bounds(model_index).height());
1591 AnimateToIdealBounds();
1594 void TabStrip::StartMoveTabAnimation() {
1595 PrepareForAnimation();
1596 GenerateIdealBounds();
1597 AnimateToIdealBounds();
1600 void TabStrip::StartRemoveTabAnimation(int model_index) {
1601 PrepareForAnimation();
1603 // Mark the tab as closing.
1604 Tab* tab = tab_at(model_index);
1605 tab->set_closing(true);
1607 RemoveTabFromViewModel(model_index);
1609 ScheduleRemoveTabAnimation(tab);
1612 void TabStrip::ScheduleRemoveTabAnimation(Tab* tab) {
1613 // Start an animation for the tabs.
1614 GenerateIdealBounds();
1615 AnimateToIdealBounds();
1617 // Animate the tab being closed to 0x0.
1618 gfx::Rect tab_bounds = tab->bounds();
1619 tab_bounds.set_width(0);
1620 bounds_animator_.AnimateViewTo(tab, tab_bounds);
1622 // Register delegate to do cleanup when done, BoundsAnimator takes
1623 // ownership of RemoveTabDelegate.
1624 bounds_animator_.SetAnimationDelegate(tab, new RemoveTabDelegate(this, tab),
1625 true);
1627 // Don't animate the new tab button when dragging tabs. Otherwise it looks
1628 // like the new tab button magically appears from beyond the end of the tab
1629 // strip.
1630 if (TabDragController::IsAttachedTo(this)) {
1631 bounds_animator_.StopAnimatingView(newtab_button_);
1632 newtab_button_->SetBoundsRect(newtab_button_bounds_);
1636 void TabStrip::AnimateToIdealBounds() {
1637 for (int i = 0; i < tab_count(); ++i) {
1638 Tab* tab = tab_at(i);
1639 if (!tab->dragging())
1640 bounds_animator_.AnimateViewTo(tab, ideal_bounds(i));
1643 bounds_animator_.AnimateViewTo(newtab_button_, newtab_button_bounds_);
1646 bool TabStrip::ShouldHighlightCloseButtonAfterRemove() {
1647 return in_tab_close_;
1650 void TabStrip::DoLayout() {
1651 last_layout_size_ = size();
1653 StopAnimating(false);
1655 SwapLayoutIfNecessary();
1657 if (touch_layout_.get())
1658 touch_layout_->SetWidth(size().width() - new_tab_button_width());
1660 GenerateIdealBounds();
1662 views::ViewModelUtils::SetViewBoundsToIdealBounds(tabs_);
1664 SchedulePaint();
1666 bounds_animator_.StopAnimatingView(newtab_button_);
1667 newtab_button_->SetBoundsRect(newtab_button_bounds_);
1670 void TabStrip::DragActiveTab(const std::vector<int>& initial_positions,
1671 int delta) {
1672 DCHECK_EQ(tab_count(), static_cast<int>(initial_positions.size()));
1673 if (!touch_layout_.get()) {
1674 StackDraggedTabs(delta);
1675 return;
1677 SetIdealBoundsFromPositions(initial_positions);
1678 touch_layout_->DragActiveTab(delta);
1679 DoLayout();
1682 void TabStrip::SetIdealBoundsFromPositions(const std::vector<int>& positions) {
1683 if (static_cast<size_t>(tab_count()) != positions.size())
1684 return;
1686 for (int i = 0; i < tab_count(); ++i) {
1687 gfx::Rect bounds(ideal_bounds(i));
1688 bounds.set_x(positions[i]);
1689 set_ideal_bounds(i, bounds);
1693 void TabStrip::StackDraggedTabs(int delta) {
1694 DCHECK(!touch_layout_.get());
1695 GenerateIdealBounds();
1696 const int active_index = controller_->GetActiveIndex();
1697 DCHECK_NE(-1, active_index);
1698 if (delta < 0) {
1699 // Drag the tabs to the left, stacking tabs before the active tab.
1700 const int adjusted_delta =
1701 std::min(ideal_bounds(active_index).x() -
1702 kStackedPadding * std::min(active_index, kMaxStackedCount),
1703 -delta);
1704 for (int i = 0; i <= active_index; ++i) {
1705 const int min_x = std::min(i, kMaxStackedCount) * kStackedPadding;
1706 gfx::Rect new_bounds(ideal_bounds(i));
1707 new_bounds.set_x(std::max(min_x, new_bounds.x() - adjusted_delta));
1708 set_ideal_bounds(i, new_bounds);
1710 const bool is_active_mini = tab_at(active_index)->data().mini;
1711 const int active_width = ideal_bounds(active_index).width();
1712 for (int i = active_index + 1; i < tab_count(); ++i) {
1713 const int max_x = ideal_bounds(active_index).x() +
1714 (kStackedPadding * std::min(i - active_index, kMaxStackedCount));
1715 gfx::Rect new_bounds(ideal_bounds(i));
1716 int new_x = std::max(new_bounds.x() + delta, max_x);
1717 if (new_x == max_x && !tab_at(i)->data().mini && !is_active_mini &&
1718 new_bounds.width() != active_width)
1719 new_x += (active_width - new_bounds.width());
1720 new_bounds.set_x(new_x);
1721 set_ideal_bounds(i, new_bounds);
1723 } else {
1724 // Drag the tabs to the right, stacking tabs after the active tab.
1725 const int last_tab_width = ideal_bounds(tab_count() - 1).width();
1726 const int last_tab_x = width() - new_tab_button_width() - last_tab_width;
1727 if (active_index == tab_count() - 1 &&
1728 ideal_bounds(tab_count() - 1).x() == last_tab_x)
1729 return;
1730 const int adjusted_delta =
1731 std::min(last_tab_x -
1732 kStackedPadding * std::min(tab_count() - active_index - 1,
1733 kMaxStackedCount) -
1734 ideal_bounds(active_index).x(),
1735 delta);
1736 for (int last_index = tab_count() - 1, i = last_index; i >= active_index;
1737 --i) {
1738 const int max_x = last_tab_x -
1739 std::min(tab_count() - i - 1, kMaxStackedCount) * kStackedPadding;
1740 gfx::Rect new_bounds(ideal_bounds(i));
1741 int new_x = std::min(max_x, new_bounds.x() + adjusted_delta);
1742 // Because of rounding not all tabs are the same width. Adjust the
1743 // position to accommodate this, otherwise the stacking is off.
1744 if (new_x == max_x && !tab_at(i)->data().mini &&
1745 new_bounds.width() != last_tab_width)
1746 new_x += (last_tab_width - new_bounds.width());
1747 new_bounds.set_x(new_x);
1748 set_ideal_bounds(i, new_bounds);
1750 for (int i = active_index - 1; i >= 0; --i) {
1751 const int min_x = ideal_bounds(active_index).x() -
1752 std::min(active_index - i, kMaxStackedCount) * kStackedPadding;
1753 gfx::Rect new_bounds(ideal_bounds(i));
1754 new_bounds.set_x(std::min(min_x, new_bounds.x() + delta));
1755 set_ideal_bounds(i, new_bounds);
1757 if (ideal_bounds(tab_count() - 1).right() >= newtab_button_->x())
1758 newtab_button_->SetVisible(false);
1760 views::ViewModelUtils::SetViewBoundsToIdealBounds(tabs_);
1761 SchedulePaint();
1764 bool TabStrip::IsStackingDraggedTabs() const {
1765 return drag_controller_.get() && drag_controller_->started_drag() &&
1766 (drag_controller_->move_behavior() ==
1767 TabDragController::MOVE_VISIBILE_TABS);
1770 void TabStrip::LayoutDraggedTabsAt(const std::vector<Tab*>& tabs,
1771 Tab* active_tab,
1772 const gfx::Point& location,
1773 bool initial_drag) {
1774 // Immediately hide the new tab button if the last tab is being dragged.
1775 if (tab_at(tab_count() - 1)->dragging())
1776 newtab_button_->SetVisible(false);
1777 std::vector<gfx::Rect> bounds;
1778 CalculateBoundsForDraggedTabs(tabs, &bounds);
1779 DCHECK_EQ(tabs.size(), bounds.size());
1780 int active_tab_model_index = GetModelIndexOfTab(active_tab);
1781 int active_tab_index = static_cast<int>(
1782 std::find(tabs.begin(), tabs.end(), active_tab) - tabs.begin());
1783 for (size_t i = 0; i < tabs.size(); ++i) {
1784 Tab* tab = tabs[i];
1785 gfx::Rect new_bounds = bounds[i];
1786 new_bounds.Offset(location.x(), location.y());
1787 int consecutive_index =
1788 active_tab_model_index - (active_tab_index - static_cast<int>(i));
1789 // If this is the initial layout during a drag and the tabs aren't
1790 // consecutive animate the view into position. Do the same if the tab is
1791 // already animating (which means we previously caused it to animate).
1792 if ((initial_drag &&
1793 GetModelIndexOfTab(tabs[i]) != consecutive_index) ||
1794 bounds_animator_.IsAnimating(tabs[i])) {
1795 bounds_animator_.SetTargetBounds(tabs[i], new_bounds);
1796 } else {
1797 tab->SetBoundsRect(new_bounds);
1802 void TabStrip::CalculateBoundsForDraggedTabs(const std::vector<Tab*>& tabs,
1803 std::vector<gfx::Rect>* bounds) {
1804 int x = 0;
1805 for (size_t i = 0; i < tabs.size(); ++i) {
1806 Tab* tab = tabs[i];
1807 if (i > 0 && tab->data().mini != tabs[i - 1]->data().mini)
1808 x += kMiniToNonMiniGap;
1809 gfx::Rect new_bounds = tab->bounds();
1810 new_bounds.set_origin(gfx::Point(x, 0));
1811 bounds->push_back(new_bounds);
1812 x += tab->width() + kTabHorizontalOffset;
1816 int TabStrip::GetSizeNeededForTabs(const std::vector<Tab*>& tabs) {
1817 int width = 0;
1818 for (size_t i = 0; i < tabs.size(); ++i) {
1819 Tab* tab = tabs[i];
1820 width += tab->width();
1821 if (i > 0 && tab->data().mini != tabs[i - 1]->data().mini)
1822 width += kMiniToNonMiniGap;
1824 if (tabs.size() > 0)
1825 width += kTabHorizontalOffset * static_cast<int>(tabs.size() - 1);
1826 return width;
1829 void TabStrip::RemoveTabFromViewModel(int index) {
1830 // We still need to paint the tab until we actually remove it. Put it
1831 // in tabs_closing_map_ so we can find it.
1832 tabs_closing_map_[index].push_back(tab_at(index));
1833 UpdateTabsClosingMap(index + 1, -1);
1834 tabs_.Remove(index);
1837 void TabStrip::RemoveAndDeleteTab(Tab* tab) {
1838 scoped_ptr<Tab> deleter(tab);
1839 for (TabsClosingMap::iterator i(tabs_closing_map_.begin());
1840 i != tabs_closing_map_.end(); ++i) {
1841 std::vector<Tab*>::iterator j =
1842 std::find(i->second.begin(), i->second.end(), tab);
1843 if (j != i->second.end()) {
1844 i->second.erase(j);
1845 if (i->second.empty())
1846 tabs_closing_map_.erase(i);
1847 return;
1850 NOTREACHED();
1853 void TabStrip::UpdateTabsClosingMap(int index, int delta) {
1854 if (tabs_closing_map_.empty())
1855 return;
1857 if (delta == -1 &&
1858 tabs_closing_map_.find(index - 1) != tabs_closing_map_.end() &&
1859 tabs_closing_map_.find(index) != tabs_closing_map_.end()) {
1860 const std::vector<Tab*>& tabs(tabs_closing_map_[index]);
1861 tabs_closing_map_[index - 1].insert(
1862 tabs_closing_map_[index - 1].end(), tabs.begin(), tabs.end());
1864 TabsClosingMap updated_map;
1865 for (TabsClosingMap::iterator i(tabs_closing_map_.begin());
1866 i != tabs_closing_map_.end(); ++i) {
1867 if (i->first > index)
1868 updated_map[i->first + delta] = i->second;
1869 else if (i->first < index)
1870 updated_map[i->first] = i->second;
1872 if (delta > 0 && tabs_closing_map_.find(index) != tabs_closing_map_.end())
1873 updated_map[index + delta] = tabs_closing_map_[index];
1874 tabs_closing_map_.swap(updated_map);
1877 void TabStrip::StartedDraggingTabs(const std::vector<Tab*>& tabs) {
1878 // Let the controller know that the user started dragging tabs.
1879 controller()->OnStartedDraggingTabs();
1881 // Hide the new tab button immediately if we didn't originate the drag.
1882 if (!drag_controller_.get())
1883 newtab_button_->SetVisible(false);
1885 PrepareForAnimation();
1887 // Reset dragging state of existing tabs.
1888 for (int i = 0; i < tab_count(); ++i)
1889 tab_at(i)->set_dragging(false);
1891 for (size_t i = 0; i < tabs.size(); ++i) {
1892 tabs[i]->set_dragging(true);
1893 bounds_animator_.StopAnimatingView(tabs[i]);
1896 // Move the dragged tabs to their ideal bounds.
1897 GenerateIdealBounds();
1899 // Sets the bounds of the dragged tabs.
1900 for (size_t i = 0; i < tabs.size(); ++i) {
1901 int tab_data_index = GetModelIndexOfTab(tabs[i]);
1902 DCHECK_NE(-1, tab_data_index);
1903 tabs[i]->SetBoundsRect(ideal_bounds(tab_data_index));
1905 SchedulePaint();
1908 void TabStrip::DraggedTabsDetached() {
1909 // Let the controller know that the user is not dragging this tabstrip's tabs
1910 // anymore.
1911 controller()->OnStoppedDraggingTabs();
1912 newtab_button_->SetVisible(true);
1915 void TabStrip::StoppedDraggingTabs(const std::vector<Tab*>& tabs,
1916 const std::vector<int>& initial_positions,
1917 bool move_only,
1918 bool completed) {
1919 // Let the controller know that the user stopped dragging tabs.
1920 controller()->OnStoppedDraggingTabs();
1922 newtab_button_->SetVisible(true);
1923 if (move_only && touch_layout_.get()) {
1924 if (completed) {
1925 touch_layout_->SizeToFit();
1926 } else {
1927 SetIdealBoundsFromPositions(initial_positions);
1930 bool is_first_tab = true;
1931 for (size_t i = 0; i < tabs.size(); ++i)
1932 StoppedDraggingTab(tabs[i], &is_first_tab);
1935 void TabStrip::StoppedDraggingTab(Tab* tab, bool* is_first_tab) {
1936 int tab_data_index = GetModelIndexOfTab(tab);
1937 if (tab_data_index == -1) {
1938 // The tab was removed before the drag completed. Don't do anything.
1939 return;
1942 if (*is_first_tab) {
1943 *is_first_tab = false;
1944 PrepareForAnimation();
1946 // Animate the view back to its correct position.
1947 GenerateIdealBounds();
1948 AnimateToIdealBounds();
1950 bounds_animator_.AnimateViewTo(tab, ideal_bounds(tab_data_index));
1951 // Install a delegate to reset the dragging state when done. We have to leave
1952 // dragging true for the tab otherwise it'll draw beneath the new tab button.
1953 bounds_animator_.SetAnimationDelegate(
1954 tab, new ResetDraggingStateDelegate(tab), true);
1957 void TabStrip::OwnDragController(TabDragController* controller) {
1958 // Typically, ReleaseDragController() and OwnDragController() calls are paired
1959 // via corresponding calls to TabDragController::Detach() and
1960 // TabDragController::Attach(). There is one exception to that rule: when a
1961 // drag might start, we create a TabDragController that is owned by the
1962 // potential source tabstrip in MaybeStartDrag(). If a drag actually starts,
1963 // we then call Attach() on the source tabstrip, but since the source tabstrip
1964 // already owns the TabDragController, so we don't need to do anything.
1965 if (controller != drag_controller_.get())
1966 drag_controller_.reset(controller);
1969 void TabStrip::DestroyDragController() {
1970 newtab_button_->SetVisible(true);
1971 drag_controller_.reset();
1974 TabDragController* TabStrip::ReleaseDragController() {
1975 return drag_controller_.release();
1978 void TabStrip::PaintClosingTabs(gfx::Canvas* canvas, int index) {
1979 if (tabs_closing_map_.find(index) == tabs_closing_map_.end())
1980 return;
1982 const std::vector<Tab*>& tabs = tabs_closing_map_[index];
1983 for (std::vector<Tab*>::const_reverse_iterator i(tabs.rbegin());
1984 i != tabs.rend(); ++i) {
1985 (*i)->Paint(canvas);
1989 void TabStrip::UpdateLayoutTypeFromMouseEvent(views::View* source,
1990 const ui::MouseEvent& event) {
1991 if (!GetAdjustLayout())
1992 return;
1994 // The following code attempts to switch to TAB_STRIP_LAYOUT_SHRINK when the
1995 // mouse exits the tabstrip (or the mouse is pressed on a stacked tab) and
1996 // TAB_STRIP_LAYOUT_STACKED when a touch device is used. This is made
1997 // problematic by windows generating mouse move events that do not clearly
1998 // indicate the move is the result of a touch device. This assumes a real
1999 // mouse is used if |kMouseMoveCountBeforeConsiderReal| mouse move events are
2000 // received within the time window |kMouseMoveTimeMS|. At the time we get a
2001 // mouse press we know whether its from a touch device or not, but we don't
2002 // layout then else everything shifts. Instead we wait for the release.
2004 // TODO(sky): revisit this when touch events are really plumbed through.
2006 switch (event.type()) {
2007 case ui::ET_MOUSE_PRESSED:
2008 mouse_move_count_ = 0;
2009 last_mouse_move_time_ = base::TimeTicks();
2010 SetResetToShrinkOnExit((event.flags() & ui::EF_FROM_TOUCH) == 0);
2011 if (reset_to_shrink_on_exit_ && touch_layout_.get()) {
2012 gfx::Point tab_strip_point(event.location());
2013 views::View::ConvertPointToTarget(source, this, &tab_strip_point);
2014 Tab* tab = FindTabForEvent(tab_strip_point);
2015 if (tab && touch_layout_->IsStacked(GetModelIndexOfTab(tab))) {
2016 SetLayoutType(TAB_STRIP_LAYOUT_SHRINK, true);
2017 controller_->LayoutTypeMaybeChanged();
2020 break;
2022 case ui::ET_MOUSE_MOVED: {
2023 #if defined(USE_ASH)
2024 // Ash does not synthesize mouse events from touch events.
2025 SetResetToShrinkOnExit(true);
2026 #else
2027 gfx::Point location(event.location());
2028 ConvertPointToTarget(source, this, &location);
2029 if (location == last_mouse_move_location_)
2030 return; // Ignore spurious moves.
2031 last_mouse_move_location_ = location;
2032 if ((event.flags() & ui::EF_FROM_TOUCH) == 0 &&
2033 (event.flags() & ui::EF_IS_SYNTHESIZED) == 0) {
2034 if ((base::TimeTicks::Now() - last_mouse_move_time_).InMilliseconds() <
2035 kMouseMoveTimeMS) {
2036 if (mouse_move_count_++ == kMouseMoveCountBeforeConsiderReal)
2037 SetResetToShrinkOnExit(true);
2038 } else {
2039 mouse_move_count_ = 1;
2040 last_mouse_move_time_ = base::TimeTicks::Now();
2042 } else {
2043 last_mouse_move_time_ = base::TimeTicks();
2045 #endif
2046 break;
2049 case ui::ET_MOUSE_RELEASED: {
2050 gfx::Point location(event.location());
2051 ConvertPointToTarget(source, this, &location);
2052 last_mouse_move_location_ = location;
2053 mouse_move_count_ = 0;
2054 last_mouse_move_time_ = base::TimeTicks();
2055 if ((event.flags() & ui::EF_FROM_TOUCH) == ui::EF_FROM_TOUCH) {
2056 SetLayoutType(TAB_STRIP_LAYOUT_STACKED, true);
2057 controller_->LayoutTypeMaybeChanged();
2059 break;
2062 default:
2063 break;
2067 void TabStrip::GetCurrentTabWidths(double* unselected_width,
2068 double* selected_width) const {
2069 *unselected_width = current_unselected_width_;
2070 *selected_width = current_selected_width_;
2073 void TabStrip::GetDesiredTabWidths(int tab_count,
2074 int mini_tab_count,
2075 double* unselected_width,
2076 double* selected_width) const {
2077 DCHECK(tab_count >= 0 && mini_tab_count >= 0 && mini_tab_count <= tab_count);
2078 const double min_unselected_width = Tab::GetMinimumUnselectedSize().width();
2079 const double min_selected_width = Tab::GetMinimumSelectedSize().width();
2081 *unselected_width = min_unselected_width;
2082 *selected_width = min_selected_width;
2084 if (tab_count == 0) {
2085 // Return immediately to avoid divide-by-zero below.
2086 return;
2089 // Determine how much space we can actually allocate to tabs.
2090 int available_width;
2091 if (available_width_for_tabs_ < 0) {
2092 available_width = width() - new_tab_button_width();
2093 } else {
2094 // Interesting corner case: if |available_width_for_tabs_| > the result
2095 // of the calculation in the conditional arm above, the strip is in
2096 // overflow. We can either use the specified width or the true available
2097 // width here; the first preserves the consistent "leave the last tab under
2098 // the user's mouse so they can close many tabs" behavior at the cost of
2099 // prolonging the glitchy appearance of the overflow state, while the second
2100 // gets us out of overflow as soon as possible but forces the user to move
2101 // their mouse for a few tabs' worth of closing. We choose visual
2102 // imperfection over behavioral imperfection and select the first option.
2103 available_width = available_width_for_tabs_;
2106 if (mini_tab_count > 0) {
2107 available_width -=
2108 mini_tab_count * (Tab::GetMiniWidth() + kTabHorizontalOffset);
2109 tab_count -= mini_tab_count;
2110 if (tab_count == 0) {
2111 *selected_width = *unselected_width = Tab::GetStandardSize().width();
2112 return;
2114 // Account for gap between the last mini-tab and first non-mini-tab.
2115 available_width -= kMiniToNonMiniGap;
2118 // Calculate the desired tab widths by dividing the available space into equal
2119 // portions. Don't let tabs get larger than the "standard width" or smaller
2120 // than the minimum width for each type, respectively.
2121 const int total_offset = kTabHorizontalOffset * (tab_count - 1);
2122 const double desired_tab_width = std::min((static_cast<double>(
2123 available_width - total_offset) / static_cast<double>(tab_count)),
2124 static_cast<double>(Tab::GetStandardSize().width()));
2125 *unselected_width = std::max(desired_tab_width, min_unselected_width);
2126 *selected_width = std::max(desired_tab_width, min_selected_width);
2128 // When there are multiple tabs, we'll have one selected and some unselected
2129 // tabs. If the desired width was between the minimum sizes of these types,
2130 // try to shrink the tabs with the smaller minimum. For example, if we have
2131 // a strip of width 10 with 4 tabs, the desired width per tab will be 2.5. If
2132 // selected tabs have a minimum width of 4 and unselected tabs have a minimum
2133 // width of 1, the above code would set *unselected_width = 2.5,
2134 // *selected_width = 4, which results in a total width of 11.5. Instead, we
2135 // want to set *unselected_width = 2, *selected_width = 4, for a total width
2136 // of 10.
2137 if (tab_count > 1) {
2138 if ((min_unselected_width < min_selected_width) &&
2139 (desired_tab_width < min_selected_width)) {
2140 // Unselected width = (total width - selected width) / (num_tabs - 1)
2141 *unselected_width = std::max(static_cast<double>(
2142 available_width - total_offset - min_selected_width) /
2143 static_cast<double>(tab_count - 1), min_unselected_width);
2144 } else if ((min_unselected_width > min_selected_width) &&
2145 (desired_tab_width < min_unselected_width)) {
2146 // Selected width = (total width - (unselected width * (num_tabs - 1)))
2147 *selected_width = std::max(available_width - total_offset -
2148 (min_unselected_width * (tab_count - 1)), min_selected_width);
2153 void TabStrip::ResizeLayoutTabs() {
2154 // We've been called back after the TabStrip has been emptied out (probably
2155 // just prior to the window being destroyed). We need to do nothing here or
2156 // else GetTabAt below will crash.
2157 if (tab_count() == 0)
2158 return;
2160 // It is critically important that this is unhooked here, otherwise we will
2161 // keep spying on messages forever.
2162 RemoveMessageLoopObserver();
2164 in_tab_close_ = false;
2165 available_width_for_tabs_ = -1;
2166 int mini_tab_count = GetMiniTabCount();
2167 if (mini_tab_count == tab_count()) {
2168 // Only mini-tabs, we know the tab widths won't have changed (all
2169 // mini-tabs have the same width), so there is nothing to do.
2170 return;
2172 // Don't try and avoid layout based on tab sizes. If tabs are small enough
2173 // then the width of the active tab may not change, but other widths may
2174 // have. This is particularly important if we've overflowed (all tabs are at
2175 // the min).
2176 StartResizeLayoutAnimation();
2179 void TabStrip::ResizeLayoutTabsFromTouch() {
2180 // Don't resize if the user is interacting with the tabstrip.
2181 if (!drag_controller_.get())
2182 ResizeLayoutTabs();
2183 else
2184 StartResizeLayoutTabsFromTouchTimer();
2187 void TabStrip::StartResizeLayoutTabsFromTouchTimer() {
2188 resize_layout_timer_.Stop();
2189 resize_layout_timer_.Start(
2190 FROM_HERE, base::TimeDelta::FromMilliseconds(kTouchResizeLayoutTimeMS),
2191 this, &TabStrip::ResizeLayoutTabsFromTouch);
2194 void TabStrip::SetTabBoundsForDrag(const std::vector<gfx::Rect>& tab_bounds) {
2195 StopAnimating(false);
2196 DCHECK_EQ(tab_count(), static_cast<int>(tab_bounds.size()));
2197 for (int i = 0; i < tab_count(); ++i)
2198 tab_at(i)->SetBoundsRect(tab_bounds[i]);
2199 // Reset the layout size as we've effectively layed out a different size.
2200 // This ensures a layout happens after the drag is done.
2201 last_layout_size_ = gfx::Size();
2204 void TabStrip::AddMessageLoopObserver() {
2205 if (!mouse_watcher_.get()) {
2206 mouse_watcher_.reset(
2207 new views::MouseWatcher(
2208 new views::MouseWatcherViewHost(
2209 this, gfx::Insets(0, 0, kTabStripAnimationVSlop, 0)),
2210 this));
2212 mouse_watcher_->Start();
2215 void TabStrip::RemoveMessageLoopObserver() {
2216 mouse_watcher_.reset(NULL);
2219 gfx::Rect TabStrip::GetDropBounds(int drop_index,
2220 bool drop_before,
2221 bool* is_beneath) {
2222 DCHECK_NE(drop_index, -1);
2223 int center_x;
2224 if (drop_index < tab_count()) {
2225 Tab* tab = tab_at(drop_index);
2226 if (drop_before)
2227 center_x = tab->x() - (kTabHorizontalOffset / 2);
2228 else
2229 center_x = tab->x() + (tab->width() / 2);
2230 } else {
2231 Tab* last_tab = tab_at(drop_index - 1);
2232 center_x = last_tab->x() + last_tab->width() + (kTabHorizontalOffset / 2);
2235 // Mirror the center point if necessary.
2236 center_x = GetMirroredXInView(center_x);
2238 // Determine the screen bounds.
2239 gfx::Point drop_loc(center_x - drop_indicator_width / 2,
2240 -drop_indicator_height);
2241 ConvertPointToScreen(this, &drop_loc);
2242 gfx::Rect drop_bounds(drop_loc.x(), drop_loc.y(), drop_indicator_width,
2243 drop_indicator_height);
2245 // If the rect doesn't fit on the monitor, push the arrow to the bottom.
2246 gfx::Screen* screen = gfx::Screen::GetScreenFor(GetWidget()->GetNativeView());
2247 gfx::Display display = screen->GetDisplayMatching(drop_bounds);
2248 *is_beneath = !display.bounds().Contains(drop_bounds);
2249 if (*is_beneath)
2250 drop_bounds.Offset(0, drop_bounds.height() + height());
2252 return drop_bounds;
2255 void TabStrip::UpdateDropIndex(const DropTargetEvent& event) {
2256 // If the UI layout is right-to-left, we need to mirror the mouse
2257 // coordinates since we calculate the drop index based on the
2258 // original (and therefore non-mirrored) positions of the tabs.
2259 const int x = GetMirroredXInView(event.x());
2260 // We don't allow replacing the urls of mini-tabs.
2261 for (int i = GetMiniTabCount(); i < tab_count(); ++i) {
2262 Tab* tab = tab_at(i);
2263 const int tab_max_x = tab->x() + tab->width();
2264 const int hot_width = tab->width() / kTabEdgeRatioInverse;
2265 if (x < tab_max_x) {
2266 if (x < tab->x() + hot_width)
2267 SetDropIndex(i, true);
2268 else if (x >= tab_max_x - hot_width)
2269 SetDropIndex(i + 1, true);
2270 else
2271 SetDropIndex(i, false);
2272 return;
2276 // The drop isn't over a tab, add it to the end.
2277 SetDropIndex(tab_count(), true);
2280 void TabStrip::SetDropIndex(int tab_data_index, bool drop_before) {
2281 // Let the controller know of the index update.
2282 controller()->OnDropIndexUpdate(tab_data_index, drop_before);
2284 if (tab_data_index == -1) {
2285 if (drop_info_.get())
2286 drop_info_.reset(NULL);
2287 return;
2290 if (drop_info_.get() && drop_info_->drop_index == tab_data_index &&
2291 drop_info_->drop_before == drop_before) {
2292 return;
2295 bool is_beneath;
2296 gfx::Rect drop_bounds = GetDropBounds(tab_data_index, drop_before,
2297 &is_beneath);
2299 if (!drop_info_.get()) {
2300 drop_info_.reset(
2301 new DropInfo(tab_data_index, drop_before, !is_beneath, GetWidget()));
2302 } else {
2303 drop_info_->drop_index = tab_data_index;
2304 drop_info_->drop_before = drop_before;
2305 if (is_beneath == drop_info_->point_down) {
2306 drop_info_->point_down = !is_beneath;
2307 drop_info_->arrow_view->SetImage(
2308 GetDropArrowImage(drop_info_->point_down));
2312 // Reposition the window. Need to show it too as the window is initially
2313 // hidden.
2314 drop_info_->arrow_window->SetBounds(drop_bounds);
2315 drop_info_->arrow_window->Show();
2318 int TabStrip::GetDropEffect(const ui::DropTargetEvent& event) {
2319 const int source_ops = event.source_operations();
2320 if (source_ops & ui::DragDropTypes::DRAG_COPY)
2321 return ui::DragDropTypes::DRAG_COPY;
2322 if (source_ops & ui::DragDropTypes::DRAG_LINK)
2323 return ui::DragDropTypes::DRAG_LINK;
2324 return ui::DragDropTypes::DRAG_MOVE;
2327 // static
2328 gfx::ImageSkia* TabStrip::GetDropArrowImage(bool is_down) {
2329 return ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
2330 is_down ? IDR_TAB_DROP_DOWN : IDR_TAB_DROP_UP);
2333 // TabStrip::DropInfo ----------------------------------------------------------
2335 TabStrip::DropInfo::DropInfo(int drop_index,
2336 bool drop_before,
2337 bool point_down,
2338 views::Widget* context)
2339 : drop_index(drop_index),
2340 drop_before(drop_before),
2341 point_down(point_down),
2342 file_supported(true) {
2343 arrow_view = new views::ImageView;
2344 arrow_view->SetImage(GetDropArrowImage(point_down));
2346 arrow_window = new views::Widget;
2347 views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
2348 params.keep_on_top = true;
2349 params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
2350 params.accept_events = false;
2351 params.can_activate = false;
2352 params.bounds = gfx::Rect(drop_indicator_width, drop_indicator_height);
2353 params.context = context->GetNativeView();
2354 arrow_window->Init(params);
2355 arrow_window->SetContentsView(arrow_view);
2358 TabStrip::DropInfo::~DropInfo() {
2359 // Close eventually deletes the window, which deletes arrow_view too.
2360 arrow_window->Close();
2363 ///////////////////////////////////////////////////////////////////////////////
2365 void TabStrip::PrepareForAnimation() {
2366 if (!IsDragSessionActive() && !TabDragController::IsAttachedTo(this)) {
2367 for (int i = 0; i < tab_count(); ++i)
2368 tab_at(i)->set_dragging(false);
2372 void TabStrip::GenerateIdealBounds() {
2373 int new_tab_y = 0;
2375 if (touch_layout_.get()) {
2376 if (tabs_.view_size() == 0)
2377 return;
2379 int new_tab_x = tabs_.ideal_bounds(tabs_.view_size() - 1).right() +
2380 kNewTabButtonHorizontalOffset;
2381 newtab_button_bounds_.set_origin(gfx::Point(new_tab_x, new_tab_y));
2382 return;
2385 double unselected, selected;
2386 GetDesiredTabWidths(tab_count(), GetMiniTabCount(), &unselected, &selected);
2387 current_unselected_width_ = unselected;
2388 current_selected_width_ = selected;
2390 // NOTE: This currently assumes a tab's height doesn't differ based on
2391 // selected state or the number of tabs in the strip!
2392 int tab_height = Tab::GetStandardSize().height();
2393 int first_non_mini_index = 0;
2394 double tab_x = GenerateIdealBoundsForMiniTabs(&first_non_mini_index);
2395 for (int i = first_non_mini_index; i < tab_count(); ++i) {
2396 Tab* tab = tab_at(i);
2397 DCHECK(!tab->data().mini);
2398 double tab_width = tab->IsActive() ? selected : unselected;
2399 double end_of_tab = tab_x + tab_width;
2400 int rounded_tab_x = Round(tab_x);
2401 set_ideal_bounds(
2403 gfx::Rect(rounded_tab_x, 0, Round(end_of_tab) - rounded_tab_x,
2404 tab_height));
2405 tab_x = end_of_tab + kTabHorizontalOffset;
2408 // Update bounds of new tab button.
2409 int new_tab_x;
2410 if (abs(Round(unselected) - Tab::GetStandardSize().width()) > 1 &&
2411 !in_tab_close_) {
2412 // We're shrinking tabs, so we need to anchor the New Tab button to the
2413 // right edge of the TabStrip's bounds, rather than the right edge of the
2414 // right-most Tab, otherwise it'll bounce when animating.
2415 new_tab_x = width() - newtab_button_bounds_.width();
2416 } else {
2417 new_tab_x = Round(tab_x - kTabHorizontalOffset) +
2418 kNewTabButtonHorizontalOffset;
2420 newtab_button_bounds_.set_origin(gfx::Point(new_tab_x, new_tab_y));
2423 int TabStrip::GenerateIdealBoundsForMiniTabs(int* first_non_mini_index) {
2424 int next_x = 0;
2425 int mini_width = Tab::GetMiniWidth();
2426 int tab_height = Tab::GetStandardSize().height();
2427 int index = 0;
2428 for (; index < tab_count() && tab_at(index)->data().mini; ++index) {
2429 set_ideal_bounds(index,
2430 gfx::Rect(next_x, 0, mini_width, tab_height));
2431 next_x += mini_width + kTabHorizontalOffset;
2433 if (index > 0 && index < tab_count())
2434 next_x += kMiniToNonMiniGap;
2435 if (first_non_mini_index)
2436 *first_non_mini_index = index;
2437 return next_x;
2440 // static
2441 int TabStrip::new_tab_button_width() {
2442 return kNewTabButtonAssetWidth + kNewTabButtonHorizontalOffset;
2445 // static
2446 int TabStrip::button_v_offset() {
2447 return kNewTabButtonVerticalOffset;
2450 int TabStrip::tab_area_width() const {
2451 return width() - new_tab_button_width();
2454 void TabStrip::StartResizeLayoutAnimation() {
2455 PrepareForAnimation();
2456 GenerateIdealBounds();
2457 AnimateToIdealBounds();
2460 void TabStrip::StartMiniTabAnimation() {
2461 in_tab_close_ = false;
2462 available_width_for_tabs_ = -1;
2464 PrepareForAnimation();
2466 GenerateIdealBounds();
2467 AnimateToIdealBounds();
2470 void TabStrip::StartMouseInitiatedRemoveTabAnimation(int model_index) {
2471 // The user initiated the close. We want to persist the bounds of all the
2472 // existing tabs, so we manually shift ideal_bounds then animate.
2473 Tab* tab_closing = tab_at(model_index);
2474 int delta = tab_closing->width() + kTabHorizontalOffset;
2475 // If the tab being closed is a mini-tab next to a non-mini-tab, be sure to
2476 // add the extra padding.
2477 DCHECK_NE(model_index + 1, tab_count());
2478 if (tab_closing->data().mini && model_index + 1 < tab_count() &&
2479 !tab_at(model_index + 1)->data().mini) {
2480 delta += kMiniToNonMiniGap;
2483 for (int i = model_index + 1; i < tab_count(); ++i) {
2484 gfx::Rect bounds = ideal_bounds(i);
2485 bounds.set_x(bounds.x() - delta);
2486 set_ideal_bounds(i, bounds);
2489 newtab_button_bounds_.set_x(newtab_button_bounds_.x() - delta);
2491 PrepareForAnimation();
2493 tab_closing->set_closing(true);
2495 // We still need to paint the tab until we actually remove it. Put it in
2496 // tabs_closing_map_ so we can find it.
2497 RemoveTabFromViewModel(model_index);
2499 AnimateToIdealBounds();
2501 gfx::Rect tab_bounds = tab_closing->bounds();
2502 tab_bounds.set_width(0);
2503 bounds_animator_.AnimateViewTo(tab_closing, tab_bounds);
2505 // Register delegate to do cleanup when done, BoundsAnimator takes
2506 // ownership of RemoveTabDelegate.
2507 bounds_animator_.SetAnimationDelegate(
2508 tab_closing,
2509 new RemoveTabDelegate(this, tab_closing),
2510 true);
2513 bool TabStrip::IsPointInTab(Tab* tab,
2514 const gfx::Point& point_in_tabstrip_coords) {
2515 gfx::Point point_in_tab_coords(point_in_tabstrip_coords);
2516 View::ConvertPointToTarget(this, tab, &point_in_tab_coords);
2517 return tab->HitTestPoint(point_in_tab_coords);
2520 int TabStrip::GetStartXForNormalTabs() const {
2521 int mini_tab_count = GetMiniTabCount();
2522 if (mini_tab_count == 0)
2523 return 0;
2524 return mini_tab_count * (Tab::GetMiniWidth() + kTabHorizontalOffset) +
2525 kMiniToNonMiniGap;
2528 Tab* TabStrip::FindTabForEvent(const gfx::Point& point) {
2529 if (touch_layout_.get()) {
2530 int active_tab_index = touch_layout_->active_index();
2531 if (active_tab_index != -1) {
2532 Tab* tab = FindTabForEventFrom(point, active_tab_index, -1);
2533 if (!tab)
2534 tab = FindTabForEventFrom(point, active_tab_index + 1, 1);
2535 return tab;
2536 } else if (tab_count()) {
2537 return FindTabForEventFrom(point, 0, 1);
2539 } else {
2540 for (int i = 0; i < tab_count(); ++i) {
2541 if (IsPointInTab(tab_at(i), point))
2542 return tab_at(i);
2545 return NULL;
2548 Tab* TabStrip::FindTabForEventFrom(const gfx::Point& point,
2549 int start,
2550 int delta) {
2551 // |start| equals tab_count() when there are only pinned tabs.
2552 if (start == tab_count())
2553 start += delta;
2554 for (int i = start; i >= 0 && i < tab_count(); i += delta) {
2555 if (IsPointInTab(tab_at(i), point))
2556 return tab_at(i);
2558 return NULL;
2561 views::View* TabStrip::FindTabHitByPoint(const gfx::Point& point) {
2562 // The display order doesn't necessarily match the child list order, so we
2563 // walk the display list hit-testing Tabs. Since the active tab always
2564 // renders on top of adjacent tabs, it needs to be hit-tested before any
2565 // left-adjacent Tab, so we look ahead for it as we walk.
2566 for (int i = 0; i < tab_count(); ++i) {
2567 Tab* next_tab = i < (tab_count() - 1) ? tab_at(i + 1) : NULL;
2568 if (next_tab && next_tab->IsActive() && IsPointInTab(next_tab, point))
2569 return next_tab;
2570 if (IsPointInTab(tab_at(i), point))
2571 return tab_at(i);
2574 return NULL;
2577 std::vector<int> TabStrip::GetTabXCoordinates() {
2578 std::vector<int> results;
2579 for (int i = 0; i < tab_count(); ++i)
2580 results.push_back(ideal_bounds(i).x());
2581 return results;
2584 void TabStrip::SwapLayoutIfNecessary() {
2585 bool needs_touch = NeedsTouchLayout();
2586 bool using_touch = touch_layout_.get() != NULL;
2587 if (needs_touch == using_touch)
2588 return;
2590 if (needs_touch) {
2591 gfx::Size tab_size(Tab::GetMinimumSelectedSize());
2592 tab_size.set_width(Tab::GetTouchWidth());
2593 touch_layout_.reset(new StackedTabStripLayout(
2594 tab_size,
2595 kTabHorizontalOffset,
2596 kStackedPadding,
2597 kMaxStackedCount,
2598 &tabs_));
2599 touch_layout_->SetWidth(width() - new_tab_button_width());
2600 // This has to be after SetWidth() as SetWidth() is going to reset the
2601 // bounds of the mini-tabs (since StackedTabStripLayout doesn't yet know how
2602 // many mini-tabs there are).
2603 GenerateIdealBoundsForMiniTabs(NULL);
2604 touch_layout_->SetXAndMiniCount(GetStartXForNormalTabs(),
2605 GetMiniTabCount());
2606 touch_layout_->SetActiveIndex(controller_->GetActiveIndex());
2607 } else {
2608 touch_layout_.reset();
2610 PrepareForAnimation();
2611 GenerateIdealBounds();
2612 AnimateToIdealBounds();
2615 bool TabStrip::NeedsTouchLayout() const {
2616 if (layout_type_ == TAB_STRIP_LAYOUT_SHRINK)
2617 return false;
2619 int mini_tab_count = GetMiniTabCount();
2620 int normal_count = tab_count() - mini_tab_count;
2621 if (normal_count <= 1 || normal_count == mini_tab_count)
2622 return false;
2623 int x = GetStartXForNormalTabs();
2624 int available_width = width() - x - new_tab_button_width();
2625 return (Tab::GetTouchWidth() * normal_count +
2626 kTabHorizontalOffset * (normal_count - 1)) > available_width;
2629 void TabStrip::SetResetToShrinkOnExit(bool value) {
2630 if (!GetAdjustLayout())
2631 return;
2633 if (value && layout_type_ == TAB_STRIP_LAYOUT_SHRINK)
2634 value = false; // We're already at TAB_STRIP_LAYOUT_SHRINK.
2636 if (value == reset_to_shrink_on_exit_)
2637 return;
2639 reset_to_shrink_on_exit_ = value;
2640 // Add an observer so we know when the mouse moves out of the tabstrip.
2641 if (reset_to_shrink_on_exit_)
2642 AddMessageLoopObserver();
2643 else
2644 RemoveMessageLoopObserver();
2647 bool TabStrip::GetAdjustLayout() const {
2648 if (!adjust_layout_)
2649 return false;
2650 return chrome::GetHostDesktopTypeForNativeView(
2651 GetWidget()->GetNativeView()) == chrome::HOST_DESKTOP_TYPE_ASH;