tab_strip.cc revision 5f1c94371a64b3196d4be9466099bb892df9b88e
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.
4
5#include "chrome/browser/ui/views/tabs/tab_strip.h"
6
7#if defined(OS_WIN)
8#include <windowsx.h>
9#endif
10
11#include <algorithm>
12#include <iterator>
13#include <string>
14#include <vector>
15
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/gfx/skia_util.h"
50#include "ui/views/controls/image_view.h"
51#include "ui/views/masked_targeter_delegate.h"
52#include "ui/views/mouse_watcher_view_host.h"
53#include "ui/views/rect_based_targeting_utils.h"
54#include "ui/views/view_model_utils.h"
55#include "ui/views/view_targeter.h"
56#include "ui/views/widget/root_view.h"
57#include "ui/views/widget/widget.h"
58#include "ui/views/window/non_client_view.h"
59
60#if defined(OS_WIN)
61#include "ui/gfx/win/hwnd_util.h"
62#include "ui/views/widget/monitor_win.h"
63#include "ui/views/win/hwnd_util.h"
64#endif
65
66using base::UserMetricsAction;
67using ui::DropTargetEvent;
68
69namespace {
70
71static const int kTabStripAnimationVSlop = 40;
72// Inactive tabs in a native frame are slightly transparent.
73static const int kGlassFrameInactiveTabAlpha = 200;
74// If there are multiple tabs selected then make non-selected inactive tabs
75// even more transparent.
76static const int kGlassFrameInactiveTabAlphaMultiSelection = 150;
77
78// Alpha applied to all elements save the selected tabs.
79static const int kInactiveTabAndNewTabButtonAlphaAsh = 230;
80static const int kInactiveTabAndNewTabButtonAlpha = 255;
81
82// Inverse ratio of the width of a tab edge to the width of the tab. When
83// hovering over the left or right edge of a tab, the drop indicator will
84// point between tabs.
85static const int kTabEdgeRatioInverse = 4;
86
87// Size of the drop indicator.
88static int drop_indicator_width;
89static int drop_indicator_height;
90
91static inline int Round(double x) {
92  // Why oh why is this not in a standard header?
93  return static_cast<int>(floor(x + 0.5));
94}
95
96// Max number of stacked tabs.
97static const int kMaxStackedCount = 4;
98
99// Padding between stacked tabs.
100static const int kStackedPadding = 6;
101
102// See UpdateLayoutTypeFromMouseEvent() for a description of these.
103#if !defined(USE_ASH)
104const int kMouseMoveTimeMS = 200;
105const int kMouseMoveCountBeforeConsiderReal = 3;
106#endif
107
108// Amount of time we delay before resizing after a close from a touch.
109const int kTouchResizeLayoutTimeMS = 2000;
110
111// Amount the left edge of a tab is offset from the rectangle of the tab's
112// favicon/title/close box.  Related to the width of IDR_TAB_ACTIVE_LEFT.
113// Affects the size of the "V" between adjacent tabs.
114const int kTabHorizontalOffset = -26;
115
116// Amount to adjust the clip by when the tab is stacked before the active index.
117const int kStackedTabLeftClip = 20;
118
119// Amount to adjust the clip by when the tab is stacked after the active index.
120const int kStackedTabRightClip = 20;
121
122base::string16 GetClipboardText() {
123  if (!ui::Clipboard::IsSupportedClipboardType(ui::CLIPBOARD_TYPE_SELECTION))
124    return base::string16();
125  ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
126  CHECK(clipboard);
127  base::string16 clipboard_text;
128  clipboard->ReadText(ui::CLIPBOARD_TYPE_SELECTION, &clipboard_text);
129  return clipboard_text;
130}
131
132// Animation delegate used for any automatic tab movement.  Hides the tab if it
133// is not fully visible within the tabstrip area, to prevent overflow clipping.
134class TabAnimationDelegate : public gfx::AnimationDelegate {
135 public:
136  TabAnimationDelegate(TabStrip* tab_strip, Tab* tab);
137  virtual ~TabAnimationDelegate();
138
139  virtual void AnimationProgressed(const gfx::Animation* animation) OVERRIDE;
140
141 protected:
142  TabStrip* tab_strip() { return tab_strip_; }
143  Tab* tab() { return tab_; }
144
145 private:
146  TabStrip* const tab_strip_;
147  Tab* const tab_;
148
149  DISALLOW_COPY_AND_ASSIGN(TabAnimationDelegate);
150};
151
152TabAnimationDelegate::TabAnimationDelegate(TabStrip* tab_strip, Tab* tab)
153    : tab_strip_(tab_strip),
154      tab_(tab) {
155}
156
157TabAnimationDelegate::~TabAnimationDelegate() {
158}
159
160void TabAnimationDelegate::AnimationProgressed(
161    const gfx::Animation* animation) {
162  tab_->SetVisible(tab_strip_->ShouldTabBeVisible(tab_));
163}
164
165// Animation delegate used when a dragged tab is released. When done sets the
166// dragging state to false.
167class ResetDraggingStateDelegate : public TabAnimationDelegate {
168 public:
169  ResetDraggingStateDelegate(TabStrip* tab_strip, Tab* tab);
170  virtual ~ResetDraggingStateDelegate();
171
172  virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE;
173  virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE;
174
175 private:
176  DISALLOW_COPY_AND_ASSIGN(ResetDraggingStateDelegate);
177};
178
179ResetDraggingStateDelegate::ResetDraggingStateDelegate(TabStrip* tab_strip,
180                                                       Tab* tab)
181    : TabAnimationDelegate(tab_strip, tab) {
182}
183
184ResetDraggingStateDelegate::~ResetDraggingStateDelegate() {
185}
186
187void ResetDraggingStateDelegate::AnimationEnded(
188    const gfx::Animation* animation) {
189  tab()->set_dragging(false);
190  AnimationProgressed(animation);  // Forces tab visibility to update.
191}
192
193void ResetDraggingStateDelegate::AnimationCanceled(
194    const gfx::Animation* animation) {
195  AnimationEnded(animation);
196}
197
198// If |dest| contains the point |point_in_source| the event handler from |dest|
199// is returned. Otherwise NULL is returned.
200views::View* ConvertPointToViewAndGetEventHandler(
201    views::View* source,
202    views::View* dest,
203    const gfx::Point& point_in_source) {
204  gfx::Point dest_point(point_in_source);
205  views::View::ConvertPointToTarget(source, dest, &dest_point);
206  return dest->HitTestPoint(dest_point) ?
207      dest->GetEventHandlerForPoint(dest_point) : NULL;
208}
209
210// Gets a tooltip handler for |point_in_source| from |dest|. Note that |dest|
211// should return NULL if it does not contain the point.
212views::View* ConvertPointToViewAndGetTooltipHandler(
213    views::View* source,
214    views::View* dest,
215    const gfx::Point& point_in_source) {
216  gfx::Point dest_point(point_in_source);
217  views::View::ConvertPointToTarget(source, dest, &dest_point);
218  return dest->GetTooltipHandlerForPoint(dest_point);
219}
220
221TabDragController::EventSource EventSourceFromEvent(
222    const ui::LocatedEvent& event) {
223  return event.IsGestureEvent() ? TabDragController::EVENT_SOURCE_TOUCH :
224      TabDragController::EVENT_SOURCE_MOUSE;
225}
226
227}  // namespace
228
229///////////////////////////////////////////////////////////////////////////////
230// NewTabButton
231//
232//  A subclass of button that hit-tests to the shape of the new tab button and
233//  does custom drawing.
234
235class NewTabButton : public views::ImageButton,
236                     public views::MaskedTargeterDelegate {
237 public:
238  NewTabButton(TabStrip* tab_strip, views::ButtonListener* listener);
239  virtual ~NewTabButton();
240
241  // Set the background offset used to match the background image to the frame
242  // image.
243  void set_background_offset(const gfx::Point& offset) {
244    background_offset_ = offset;
245  }
246
247 protected:
248  // views::View:
249#if defined(OS_WIN)
250  virtual void OnMouseReleased(const ui::MouseEvent& event) OVERRIDE;
251#endif
252  virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE;
253
254  // ui::EventHandler:
255  virtual void OnGestureEvent(ui::GestureEvent* event) OVERRIDE;
256
257 private:
258  // views::MaskedTargeterDelegate:
259  virtual bool GetHitTestMask(gfx::Path* mask) const OVERRIDE;
260
261  bool ShouldWindowContentsBeTransparent() const;
262  gfx::ImageSkia GetBackgroundImage(views::CustomButton::ButtonState state,
263                                    float scale) const;
264  gfx::ImageSkia GetImageForState(views::CustomButton::ButtonState state,
265                                  float scale) const;
266  gfx::ImageSkia GetImageForScale(float scale) const;
267
268  // Tab strip that contains this button.
269  TabStrip* tab_strip_;
270
271  // The offset used to paint the background image.
272  gfx::Point background_offset_;
273
274  // were we destroyed?
275  bool* destroyed_;
276
277  DISALLOW_COPY_AND_ASSIGN(NewTabButton);
278};
279
280NewTabButton::NewTabButton(TabStrip* tab_strip, views::ButtonListener* listener)
281    : views::ImageButton(listener),
282      tab_strip_(tab_strip),
283      destroyed_(NULL) {
284#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
285  set_triggerable_event_flags(triggerable_event_flags() |
286                              ui::EF_MIDDLE_MOUSE_BUTTON);
287#endif
288}
289
290NewTabButton::~NewTabButton() {
291  if (destroyed_)
292    *destroyed_ = true;
293}
294
295#if defined(OS_WIN)
296void NewTabButton::OnMouseReleased(const ui::MouseEvent& event) {
297  if (event.IsOnlyRightMouseButton()) {
298    gfx::Point point = event.location();
299    views::View::ConvertPointToScreen(this, &point);
300    bool destroyed = false;
301    destroyed_ = &destroyed;
302    gfx::ShowSystemMenuAtPoint(views::HWNDForView(this), point);
303    if (destroyed)
304      return;
305
306    destroyed_ = NULL;
307    SetState(views::CustomButton::STATE_NORMAL);
308    return;
309  }
310  views::ImageButton::OnMouseReleased(event);
311}
312#endif
313
314void NewTabButton::OnPaint(gfx::Canvas* canvas) {
315  gfx::ImageSkia image = GetImageForScale(canvas->image_scale());
316  canvas->DrawImageInt(image, 0, height() - image.height());
317}
318
319void NewTabButton::OnGestureEvent(ui::GestureEvent* event) {
320  // Consume all gesture events here so that the parent (Tab) does not
321  // start consuming gestures.
322  views::ImageButton::OnGestureEvent(event);
323  event->SetHandled();
324}
325
326bool NewTabButton::GetHitTestMask(gfx::Path* mask) const {
327  DCHECK(mask);
328
329  // When the button is sized to the top of the tab strip, we want the hit
330  // test mask to be defined as the complete (rectangular) bounds of the
331  // button.
332  if (tab_strip_->SizeTabButtonToTopOfTabStrip()) {
333    gfx::Rect button_bounds(GetContentsBounds());
334    button_bounds.set_x(GetMirroredXForRect(button_bounds));
335    mask->addRect(RectToSkRect(button_bounds));
336    return true;
337  }
338
339  SkScalar w = SkIntToScalar(width());
340  SkScalar v_offset = SkIntToScalar(TabStrip::kNewTabButtonVerticalOffset);
341
342  // These values are defined by the shape of the new tab image. Should that
343  // image ever change, these values will need to be updated. They're so
344  // custom it's not really worth defining constants for.
345  // These values are correct for regular and USE_ASH versions of the image.
346  mask->moveTo(0, v_offset + 1);
347  mask->lineTo(w - 7, v_offset + 1);
348  mask->lineTo(w - 4, v_offset + 4);
349  mask->lineTo(w, v_offset + 16);
350  mask->lineTo(w - 1, v_offset + 17);
351  mask->lineTo(7, v_offset + 17);
352  mask->lineTo(4, v_offset + 13);
353  mask->lineTo(0, v_offset + 1);
354  mask->close();
355
356  return true;
357}
358
359bool NewTabButton::ShouldWindowContentsBeTransparent() const {
360  return GetWidget() &&
361         GetWidget()->GetTopLevelWidget()->ShouldWindowContentsBeTransparent();
362}
363
364gfx::ImageSkia NewTabButton::GetBackgroundImage(
365    views::CustomButton::ButtonState state,
366    float scale) const {
367  int background_id = 0;
368  if (ShouldWindowContentsBeTransparent()) {
369    background_id = IDR_THEME_TAB_BACKGROUND_V;
370  } else if (tab_strip_->controller()->IsIncognito()) {
371    background_id = IDR_THEME_TAB_BACKGROUND_INCOGNITO;
372  } else {
373    background_id = IDR_THEME_TAB_BACKGROUND;
374  }
375
376  int alpha = 0;
377  switch (state) {
378    case views::CustomButton::STATE_NORMAL:
379    case views::CustomButton::STATE_HOVERED:
380      alpha = ShouldWindowContentsBeTransparent() ? kGlassFrameInactiveTabAlpha
381                                                  : 255;
382      break;
383    case views::CustomButton::STATE_PRESSED:
384      alpha = 145;
385      break;
386    default:
387      NOTREACHED();
388      break;
389  }
390
391  gfx::ImageSkia* mask =
392      GetThemeProvider()->GetImageSkiaNamed(IDR_NEWTAB_BUTTON_MASK);
393  int height = mask->height();
394  int width = mask->width();
395  // The canvas and mask has to use the same scale factor.
396  if (!mask->HasRepresentation(scale))
397    scale = ui::GetScaleForScaleFactor(ui::SCALE_FACTOR_100P);
398
399  gfx::Canvas canvas(gfx::Size(width, height), scale, false);
400
401  // For custom images the background starts at the top of the tab strip.
402  // Otherwise the background starts at the top of the frame.
403  gfx::ImageSkia* background =
404      GetThemeProvider()->GetImageSkiaNamed(background_id);
405  int offset_y = GetThemeProvider()->HasCustomImage(background_id) ?
406      0 : background_offset_.y();
407
408  // The new tab background is mirrored in RTL mode, but the theme background
409  // should never be mirrored. Mirror it here to compensate.
410  float x_scale = 1.0f;
411  int x = GetMirroredX() + background_offset_.x();
412  if (base::i18n::IsRTL()) {
413    x_scale = -1.0f;
414    // Offset by |width| such that the same region is painted as if there was no
415    // flip.
416    x += width;
417  }
418  canvas.TileImageInt(*background, x,
419                      TabStrip::kNewTabButtonVerticalOffset + offset_y,
420                      x_scale, 1.0f, 0, 0, width, height);
421
422  if (alpha != 255) {
423    SkPaint paint;
424    paint.setColor(SkColorSetARGB(alpha, 255, 255, 255));
425    paint.setXfermodeMode(SkXfermode::kDstIn_Mode);
426    paint.setStyle(SkPaint::kFill_Style);
427    canvas.DrawRect(gfx::Rect(0, 0, width, height), paint);
428  }
429
430  // White highlight on hover.
431  if (state == views::CustomButton::STATE_HOVERED)
432    canvas.FillRect(GetLocalBounds(), SkColorSetARGB(64, 255, 255, 255));
433
434  return gfx::ImageSkiaOperations::CreateMaskedImage(
435      gfx::ImageSkia(canvas.ExtractImageRep()), *mask);
436}
437
438gfx::ImageSkia NewTabButton::GetImageForState(
439    views::CustomButton::ButtonState state,
440    float scale) const {
441  const int overlay_id = state == views::CustomButton::STATE_PRESSED ?
442        IDR_NEWTAB_BUTTON_P : IDR_NEWTAB_BUTTON;
443  gfx::ImageSkia* overlay = GetThemeProvider()->GetImageSkiaNamed(overlay_id);
444
445  gfx::Canvas canvas(
446      gfx::Size(overlay->width(), overlay->height()),
447      scale,
448      false);
449  canvas.DrawImageInt(GetBackgroundImage(state, scale), 0, 0);
450
451  // Draw the button border with a slight alpha.
452  const int kGlassFrameOverlayAlpha = 178;
453  const int kOpaqueFrameOverlayAlpha = 230;
454  uint8 alpha = ShouldWindowContentsBeTransparent() ?
455      kGlassFrameOverlayAlpha : kOpaqueFrameOverlayAlpha;
456  canvas.DrawImageInt(*overlay, 0, 0, alpha);
457
458  return gfx::ImageSkia(canvas.ExtractImageRep());
459}
460
461gfx::ImageSkia NewTabButton::GetImageForScale(float scale) const {
462  if (!hover_animation_->is_animating())
463    return GetImageForState(state(), scale);
464  return gfx::ImageSkiaOperations::CreateBlendedImage(
465      GetImageForState(views::CustomButton::STATE_NORMAL, scale),
466      GetImageForState(views::CustomButton::STATE_HOVERED, scale),
467      hover_animation_->GetCurrentValue());
468}
469
470///////////////////////////////////////////////////////////////////////////////
471// TabStrip::RemoveTabDelegate
472//
473// AnimationDelegate used when removing a tab. Does the necessary cleanup when
474// done.
475class TabStrip::RemoveTabDelegate : public TabAnimationDelegate {
476 public:
477  RemoveTabDelegate(TabStrip* tab_strip, Tab* tab);
478
479  virtual void AnimationEnded(const gfx::Animation* animation) OVERRIDE;
480  virtual void AnimationCanceled(const gfx::Animation* animation) OVERRIDE;
481
482 private:
483  DISALLOW_COPY_AND_ASSIGN(RemoveTabDelegate);
484};
485
486TabStrip::RemoveTabDelegate::RemoveTabDelegate(TabStrip* tab_strip,
487                                               Tab* tab)
488    : TabAnimationDelegate(tab_strip, tab) {
489}
490
491void TabStrip::RemoveTabDelegate::AnimationEnded(
492    const gfx::Animation* animation) {
493  DCHECK(tab()->closing());
494  tab_strip()->RemoveAndDeleteTab(tab());
495
496  // Send the Container a message to simulate a mouse moved event at the current
497  // mouse position. This tickles the Tab the mouse is currently over to show
498  // the "hot" state of the close button.  Note that this is not required (and
499  // indeed may crash!) for removes spawned by non-mouse closes and
500  // drag-detaches.
501  if (!tab_strip()->IsDragSessionActive() &&
502      tab_strip()->ShouldHighlightCloseButtonAfterRemove()) {
503    // The widget can apparently be null during shutdown.
504    views::Widget* widget = tab_strip()->GetWidget();
505    if (widget)
506      widget->SynthesizeMouseMoveEvent();
507  }
508}
509
510void TabStrip::RemoveTabDelegate::AnimationCanceled(
511    const gfx::Animation* animation) {
512  AnimationEnded(animation);
513}
514
515///////////////////////////////////////////////////////////////////////////////
516// TabStrip, public:
517
518// static
519const char TabStrip::kViewClassName[] = "TabStrip";
520const int TabStrip::kNewTabButtonHorizontalOffset = -11;
521const int TabStrip::kNewTabButtonVerticalOffset = 7;
522const int TabStrip::kMiniToNonMiniGap = 3;
523const int TabStrip::kNewTabButtonAssetWidth = 34;
524const int TabStrip::kNewTabButtonAssetHeight = 18;
525
526TabStrip::TabStrip(TabStripController* controller)
527    : controller_(controller),
528      newtab_button_(NULL),
529      current_unselected_width_(Tab::GetStandardSize().width()),
530      current_selected_width_(Tab::GetStandardSize().width()),
531      available_width_for_tabs_(-1),
532      in_tab_close_(false),
533      animation_container_(new gfx::AnimationContainer()),
534      bounds_animator_(this),
535      stacked_layout_(false),
536      adjust_layout_(false),
537      reset_to_shrink_on_exit_(false),
538      mouse_move_count_(0),
539      immersive_style_(false) {
540  Init();
541  SetEventTargeter(
542      scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this)));
543}
544
545TabStrip::~TabStrip() {
546  FOR_EACH_OBSERVER(TabStripObserver, observers_,
547                    TabStripDeleted(this));
548
549  // The animations may reference the tabs. Shut down the animation before we
550  // delete the tabs.
551  StopAnimating(false);
552
553  DestroyDragController();
554
555  // Make sure we unhook ourselves as a message loop observer so that we don't
556  // crash in the case where the user closes the window after closing a tab
557  // but before moving the mouse.
558  RemoveMessageLoopObserver();
559
560  // The children (tabs) may callback to us from their destructor. Delete them
561  // so that if they call back we aren't in a weird state.
562  RemoveAllChildViews(true);
563}
564
565void TabStrip::AddObserver(TabStripObserver* observer) {
566  observers_.AddObserver(observer);
567}
568
569void TabStrip::RemoveObserver(TabStripObserver* observer) {
570  observers_.RemoveObserver(observer);
571}
572
573void TabStrip::SetStackedLayout(bool stacked_layout) {
574  if (stacked_layout == stacked_layout_)
575    return;
576
577  const int active_index = controller_->GetActiveIndex();
578  int active_center = 0;
579  if (active_index != -1) {
580    active_center = ideal_bounds(active_index).x() +
581        ideal_bounds(active_index).width() / 2;
582  }
583  stacked_layout_ = stacked_layout;
584  SetResetToShrinkOnExit(false);
585  SwapLayoutIfNecessary();
586  // When transitioning to stacked try to keep the active tab centered.
587  if (touch_layout_ && active_index != -1) {
588    touch_layout_->SetActiveTabLocation(
589        active_center - ideal_bounds(active_index).width() / 2);
590    AnimateToIdealBounds();
591  }
592}
593
594gfx::Rect TabStrip::GetNewTabButtonBounds() {
595  return newtab_button_->bounds();
596}
597
598bool TabStrip::SizeTabButtonToTopOfTabStrip() {
599  // Extend the button to the screen edge in maximized and immersive fullscreen.
600  views::Widget* widget = GetWidget();
601  return browser_defaults::kSizeTabButtonToTopOfTabStrip ||
602      (widget && (widget->IsMaximized() || widget->IsFullscreen()));
603}
604
605void TabStrip::StartHighlight(int model_index) {
606  tab_at(model_index)->StartPulse();
607}
608
609void TabStrip::StopAllHighlighting() {
610  for (int i = 0; i < tab_count(); ++i)
611    tab_at(i)->StopPulse();
612}
613
614void TabStrip::AddTabAt(int model_index,
615                        const TabRendererData& data,
616                        bool is_active) {
617  // Stop dragging when a new tab is added and dragging a window. Doing
618  // otherwise results in a confusing state if the user attempts to reattach. We
619  // could allow this and make TabDragController update itself during the add,
620  // but this comes up infrequently enough that it's not work the complexity.
621  if (drag_controller_.get() && !drag_controller_->is_mutating() &&
622      drag_controller_->is_dragging_window()) {
623    EndDrag(END_DRAG_COMPLETE);
624  }
625  Tab* tab = CreateTab();
626  tab->SetData(data);
627  UpdateTabsClosingMap(model_index, 1);
628  tabs_.Add(tab, model_index);
629  AddChildView(tab);
630
631  if (touch_layout_) {
632    GenerateIdealBoundsForMiniTabs(NULL);
633    int add_types = 0;
634    if (data.mini)
635      add_types |= StackedTabStripLayout::kAddTypeMini;
636    if (is_active)
637      add_types |= StackedTabStripLayout::kAddTypeActive;
638    touch_layout_->AddTab(model_index, add_types, GetStartXForNormalTabs());
639  }
640
641  // Don't animate the first tab, it looks weird, and don't animate anything
642  // if the containing window isn't visible yet.
643  if (tab_count() > 1 && GetWidget() && GetWidget()->IsVisible())
644    StartInsertTabAnimation(model_index);
645  else
646    DoLayout();
647
648  SwapLayoutIfNecessary();
649
650  FOR_EACH_OBSERVER(TabStripObserver, observers_,
651                    TabStripAddedTabAt(this, model_index));
652}
653
654void TabStrip::MoveTab(int from_model_index,
655                       int to_model_index,
656                       const TabRendererData& data) {
657  DCHECK_GT(tabs_.view_size(), 0);
658  const Tab* last_tab = GetLastVisibleTab();
659  tab_at(from_model_index)->SetData(data);
660  if (touch_layout_) {
661    tabs_.MoveViewOnly(from_model_index, to_model_index);
662    int mini_count = 0;
663    GenerateIdealBoundsForMiniTabs(&mini_count);
664    touch_layout_->MoveTab(
665        from_model_index, to_model_index, controller_->GetActiveIndex(),
666        GetStartXForNormalTabs(), mini_count);
667  } else {
668    tabs_.Move(from_model_index, to_model_index);
669  }
670  StartMoveTabAnimation();
671  if (TabDragController::IsAttachedTo(this) &&
672      (last_tab != GetLastVisibleTab() || last_tab->dragging())) {
673    newtab_button_->SetVisible(false);
674  }
675  SwapLayoutIfNecessary();
676
677  FOR_EACH_OBSERVER(TabStripObserver, observers_,
678                    TabStripMovedTab(this, from_model_index, to_model_index));
679}
680
681void TabStrip::RemoveTabAt(int model_index) {
682  if (touch_layout_) {
683    Tab* tab = tab_at(model_index);
684    tab->set_closing(true);
685    int old_x = tabs_.ideal_bounds(model_index).x();
686    // We still need to paint the tab until we actually remove it. Put it in
687    // tabs_closing_map_ so we can find it.
688    RemoveTabFromViewModel(model_index);
689    touch_layout_->RemoveTab(model_index, GenerateIdealBoundsForMiniTabs(NULL),
690                             old_x);
691    ScheduleRemoveTabAnimation(tab);
692  } else if (in_tab_close_ && model_index != GetModelCount()) {
693    StartMouseInitiatedRemoveTabAnimation(model_index);
694  } else {
695    StartRemoveTabAnimation(model_index);
696  }
697  SwapLayoutIfNecessary();
698
699  FOR_EACH_OBSERVER(TabStripObserver, observers_,
700                    TabStripRemovedTabAt(this, model_index));
701}
702
703void TabStrip::SetTabData(int model_index, const TabRendererData& data) {
704  Tab* tab = tab_at(model_index);
705  bool mini_state_changed = tab->data().mini != data.mini;
706  tab->SetData(data);
707
708  if (mini_state_changed) {
709    if (touch_layout_) {
710      int mini_tab_count = 0;
711      int start_x = GenerateIdealBoundsForMiniTabs(&mini_tab_count);
712      touch_layout_->SetXAndMiniCount(start_x, mini_tab_count);
713    }
714    if (GetWidget() && GetWidget()->IsVisible())
715      StartMiniTabAnimation();
716    else
717      DoLayout();
718  }
719  SwapLayoutIfNecessary();
720}
721
722bool TabStrip::ShouldTabBeVisible(const Tab* tab) const {
723  // Detached tabs should always be invisible (as they close).
724  if (tab->detached())
725    return false;
726
727  // When stacking tabs, all tabs should always be visible.
728  if (stacked_layout_)
729    return true;
730
731  // If the tab is currently clipped, it shouldn't be visible.  Note that we
732  // allow dragged tabs to draw over the "New Tab button" region as well,
733  // because either the New Tab button will be hidden, or the dragged tabs will
734  // be animating back to their normal positions and we don't want to hide them
735  // in the New Tab button region in case they re-appear after leaving it.
736  // (This prevents flickeriness.)  We never draw non-dragged tabs in New Tab
737  // button area, even when the button is invisible, so that they don't appear
738  // to "pop in" when the button disappears.
739  // TODO: Probably doesn't work for RTL
740  int right_edge = tab->bounds().right();
741  const int visible_width = tab->dragging() ? width() : tab_area_width();
742  if (right_edge > visible_width)
743    return false;
744
745  // Non-clipped dragging tabs should always be visible.
746  if (tab->dragging())
747    return true;
748
749  // Let all non-clipped closing tabs be visible.  These will probably finish
750  // closing before the user changes the active tab, so there's little reason to
751  // try and make the more complex logic below apply.
752  if (tab->closing())
753    return true;
754
755  // Now we need to check whether the tab isn't currently clipped, but could
756  // become clipped if we changed the active tab, widening either this tab or
757  // the tabstrip portion before it.
758
759  // Mini tabs don't change size when activated, so any tab in the mini tab
760  // region is safe.
761  if (tab->data().mini)
762    return true;
763
764  // If the active tab is on or before this tab, we're safe.
765  if (controller_->GetActiveIndex() <= GetModelIndexOfTab(tab))
766    return true;
767
768  // We need to check what would happen if the active tab were to move to this
769  // tab or before.
770  return (right_edge + current_selected_width_ - current_unselected_width_) <=
771      tab_area_width();
772}
773
774void TabStrip::PrepareForCloseAt(int model_index, CloseTabSource source) {
775  if (!in_tab_close_ && IsAnimating()) {
776    // Cancel any current animations. We do this as remove uses the current
777    // ideal bounds and we need to know ideal bounds is in a good state.
778    StopAnimating(true);
779  }
780
781  if (!GetWidget())
782    return;
783
784  int model_count = GetModelCount();
785  if (model_count > 1 && model_index != model_count - 1) {
786    // The user is about to close a tab other than the last tab. Set
787    // available_width_for_tabs_ so that if we do a layout we don't position a
788    // tab past the end of the second to last tab. We do this so that as the
789    // user closes tabs with the mouse a tab continues to fall under the mouse.
790    Tab* last_tab = tab_at(model_count - 1);
791    Tab* tab_being_removed = tab_at(model_index);
792    available_width_for_tabs_ = last_tab->x() + last_tab->width() -
793        tab_being_removed->width() - kTabHorizontalOffset;
794    if (model_index == 0 && tab_being_removed->data().mini &&
795        !tab_at(1)->data().mini) {
796      available_width_for_tabs_ -= kMiniToNonMiniGap;
797    }
798  }
799
800  in_tab_close_ = true;
801  resize_layout_timer_.Stop();
802  if (source == CLOSE_TAB_FROM_TOUCH) {
803    StartResizeLayoutTabsFromTouchTimer();
804  } else {
805    AddMessageLoopObserver();
806  }
807}
808
809void TabStrip::SetSelection(const ui::ListSelectionModel& old_selection,
810                            const ui::ListSelectionModel& new_selection) {
811  if (touch_layout_) {
812    touch_layout_->SetActiveIndex(new_selection.active());
813    // Only start an animation if we need to. Otherwise clicking on an
814    // unselected tab and dragging won't work because dragging is only allowed
815    // if not animating.
816    if (!views::ViewModelUtils::IsAtIdealBounds(tabs_))
817      AnimateToIdealBounds();
818    SchedulePaint();
819  } else {
820    // We have "tiny tabs" if the tabs are so tiny that the unselected ones are
821    // a different size to the selected ones.
822    bool tiny_tabs = current_unselected_width_ != current_selected_width_;
823    if (!IsAnimating() && (!in_tab_close_ || tiny_tabs)) {
824      DoLayout();
825    } else {
826      SchedulePaint();
827    }
828  }
829
830  // Use STLSetDifference to get the indices of elements newly selected
831  // and no longer selected, since selected_indices() is always sorted.
832  ui::ListSelectionModel::SelectedIndices no_longer_selected =
833      base::STLSetDifference<ui::ListSelectionModel::SelectedIndices>(
834          old_selection.selected_indices(),
835          new_selection.selected_indices());
836  ui::ListSelectionModel::SelectedIndices newly_selected =
837      base::STLSetDifference<ui::ListSelectionModel::SelectedIndices>(
838          new_selection.selected_indices(),
839          old_selection.selected_indices());
840
841  // Fire accessibility events that reflect the changes to selection, and
842  // stop the mini tab title animation on tabs no longer selected.
843  for (size_t i = 0; i < no_longer_selected.size(); ++i) {
844    tab_at(no_longer_selected[i])->StopMiniTabTitleAnimation();
845    tab_at(no_longer_selected[i])->NotifyAccessibilityEvent(
846        ui::AX_EVENT_SELECTION_REMOVE, true);
847  }
848  for (size_t i = 0; i < newly_selected.size(); ++i) {
849    tab_at(newly_selected[i])->NotifyAccessibilityEvent(
850        ui::AX_EVENT_SELECTION_ADD, true);
851  }
852  tab_at(new_selection.active())->NotifyAccessibilityEvent(
853      ui::AX_EVENT_SELECTION, true);
854}
855
856void TabStrip::TabTitleChangedNotLoading(int model_index) {
857  Tab* tab = tab_at(model_index);
858  if (tab->data().mini && !tab->IsActive())
859    tab->StartMiniTabTitleAnimation();
860}
861
862int TabStrip::GetModelIndexOfTab(const Tab* tab) const {
863  return tabs_.GetIndexOfView(tab);
864}
865
866int TabStrip::GetModelCount() const {
867  return controller_->GetCount();
868}
869
870bool TabStrip::IsValidModelIndex(int model_index) const {
871  return controller_->IsValidIndex(model_index);
872}
873
874bool TabStrip::IsDragSessionActive() const {
875  return drag_controller_.get() != NULL;
876}
877
878bool TabStrip::IsActiveDropTarget() const {
879  for (int i = 0; i < tab_count(); ++i) {
880    Tab* tab = tab_at(i);
881    if (tab->dragging())
882      return true;
883  }
884  return false;
885}
886
887bool TabStrip::IsTabStripEditable() const {
888  return !IsDragSessionActive() && !IsActiveDropTarget();
889}
890
891bool TabStrip::IsTabStripCloseable() const {
892  return !IsDragSessionActive();
893}
894
895void TabStrip::UpdateLoadingAnimations() {
896  controller_->UpdateLoadingAnimations();
897}
898
899bool TabStrip::IsPositionInWindowCaption(const gfx::Point& point) {
900  return IsRectInWindowCaption(gfx::Rect(point, gfx::Size(1, 1)));
901}
902
903bool TabStrip::IsRectInWindowCaption(const gfx::Rect& rect) {
904  views::View* v = GetEventHandlerForRect(rect);
905
906  // If there is no control at this location, claim the hit was in the title
907  // bar to get a move action.
908  if (v == this)
909    return true;
910
911  // Check to see if the rect intersects the non-button parts of the new tab
912  // button. The button has a non-rectangular shape, so if it's not in the
913  // visual portions of the button we treat it as a click to the caption.
914  gfx::RectF rect_in_newtab_coords_f(rect);
915  View::ConvertRectToTarget(this, newtab_button_, &rect_in_newtab_coords_f);
916  gfx::Rect rect_in_newtab_coords = gfx::ToEnclosingRect(
917      rect_in_newtab_coords_f);
918  if (newtab_button_->GetLocalBounds().Intersects(rect_in_newtab_coords) &&
919      !newtab_button_->HitTestRect(rect_in_newtab_coords))
920    return true;
921
922  // All other regions, including the new Tab button, should be considered part
923  // of the containing Window's client area so that regular events can be
924  // processed for them.
925  return false;
926}
927
928void TabStrip::SetBackgroundOffset(const gfx::Point& offset) {
929  for (int i = 0; i < tab_count(); ++i)
930    tab_at(i)->set_background_offset(offset);
931  newtab_button_->set_background_offset(offset);
932}
933
934void TabStrip::SetImmersiveStyle(bool enable) {
935  if (immersive_style_ == enable)
936    return;
937  immersive_style_ = enable;
938}
939
940bool TabStrip::IsAnimating() const {
941  return bounds_animator_.IsAnimating();
942}
943
944void TabStrip::StopAnimating(bool layout) {
945  if (!IsAnimating())
946    return;
947
948  bounds_animator_.Cancel();
949
950  if (layout)
951    DoLayout();
952}
953
954void TabStrip::FileSupported(const GURL& url, bool supported) {
955  if (drop_info_.get() && drop_info_->url == url)
956    drop_info_->file_supported = supported;
957}
958
959const ui::ListSelectionModel& TabStrip::GetSelectionModel() {
960  return controller_->GetSelectionModel();
961}
962
963bool TabStrip::SupportsMultipleSelection() {
964  // TODO: currently only allow single selection in touch layout mode.
965  return touch_layout_ == NULL;
966}
967
968void TabStrip::SelectTab(Tab* tab) {
969  int model_index = GetModelIndexOfTab(tab);
970  if (IsValidModelIndex(model_index))
971    controller_->SelectTab(model_index);
972}
973
974void TabStrip::ExtendSelectionTo(Tab* tab) {
975  int model_index = GetModelIndexOfTab(tab);
976  if (IsValidModelIndex(model_index))
977    controller_->ExtendSelectionTo(model_index);
978}
979
980void TabStrip::ToggleSelected(Tab* tab) {
981  int model_index = GetModelIndexOfTab(tab);
982  if (IsValidModelIndex(model_index))
983    controller_->ToggleSelected(model_index);
984}
985
986void TabStrip::AddSelectionFromAnchorTo(Tab* tab) {
987  int model_index = GetModelIndexOfTab(tab);
988  if (IsValidModelIndex(model_index))
989    controller_->AddSelectionFromAnchorTo(model_index);
990}
991
992void TabStrip::CloseTab(Tab* tab, CloseTabSource source) {
993  if (tab->closing()) {
994    // If the tab is already closing, close the next tab. We do this so that the
995    // user can rapidly close tabs by clicking the close button and not have
996    // the animations interfere with that.
997    const int closed_tab_index = FindClosingTab(tab).first->first;
998    if (closed_tab_index < GetModelCount())
999      controller_->CloseTab(closed_tab_index, source);
1000    return;
1001  }
1002  int model_index = GetModelIndexOfTab(tab);
1003  if (IsValidModelIndex(model_index))
1004    controller_->CloseTab(model_index, source);
1005}
1006
1007void TabStrip::ShowContextMenuForTab(Tab* tab,
1008                                     const gfx::Point& p,
1009                                     ui::MenuSourceType source_type) {
1010  controller_->ShowContextMenuForTab(tab, p, source_type);
1011}
1012
1013bool TabStrip::IsActiveTab(const Tab* tab) const {
1014  int model_index = GetModelIndexOfTab(tab);
1015  return IsValidModelIndex(model_index) &&
1016      controller_->IsActiveTab(model_index);
1017}
1018
1019bool TabStrip::IsTabSelected(const Tab* tab) const {
1020  int model_index = GetModelIndexOfTab(tab);
1021  return IsValidModelIndex(model_index) &&
1022      controller_->IsTabSelected(model_index);
1023}
1024
1025bool TabStrip::IsTabPinned(const Tab* tab) const {
1026  if (tab->closing())
1027    return false;
1028
1029  int model_index = GetModelIndexOfTab(tab);
1030  return IsValidModelIndex(model_index) &&
1031      controller_->IsTabPinned(model_index);
1032}
1033
1034void TabStrip::MaybeStartDrag(
1035    Tab* tab,
1036    const ui::LocatedEvent& event,
1037    const ui::ListSelectionModel& original_selection) {
1038  // Don't accidentally start any drag operations during animations if the
1039  // mouse is down... during an animation tabs are being resized automatically,
1040  // so the View system can misinterpret this easily if the mouse is down that
1041  // the user is dragging.
1042  if (IsAnimating() || tab->closing() ||
1043      controller_->HasAvailableDragActions() == 0) {
1044    return;
1045  }
1046
1047  // Do not do any dragging of tabs when using the super short immersive style.
1048  if (IsImmersiveStyle())
1049    return;
1050
1051  int model_index = GetModelIndexOfTab(tab);
1052  if (!IsValidModelIndex(model_index)) {
1053    CHECK(false);
1054    return;
1055  }
1056  Tabs tabs;
1057  int size_to_selected = 0;
1058  int x = tab->GetMirroredXInView(event.x());
1059  int y = event.y();
1060  // Build the set of selected tabs to drag and calculate the offset from the
1061  // first selected tab.
1062  for (int i = 0; i < tab_count(); ++i) {
1063    Tab* other_tab = tab_at(i);
1064    if (IsTabSelected(other_tab)) {
1065      tabs.push_back(other_tab);
1066      if (other_tab == tab) {
1067        size_to_selected = GetSizeNeededForTabs(tabs);
1068        x = size_to_selected - tab->width() + x;
1069      }
1070    }
1071  }
1072  DCHECK(!tabs.empty());
1073  DCHECK(std::find(tabs.begin(), tabs.end(), tab) != tabs.end());
1074  ui::ListSelectionModel selection_model;
1075  if (!original_selection.IsSelected(model_index))
1076    selection_model.Copy(original_selection);
1077  // Delete the existing DragController before creating a new one. We do this as
1078  // creating the DragController remembers the WebContents delegates and we need
1079  // to make sure the existing DragController isn't still a delegate.
1080  drag_controller_.reset();
1081  TabDragController::MoveBehavior move_behavior =
1082      TabDragController::REORDER;
1083  // Use MOVE_VISIBILE_TABS in the following conditions:
1084  // . Mouse event generated from touch and the left button is down (the right
1085  //   button corresponds to a long press, which we want to reorder).
1086  // . Gesture tap down and control key isn't down.
1087  // . Real mouse event and control is down. This is mostly for testing.
1088  DCHECK(event.type() == ui::ET_MOUSE_PRESSED ||
1089         event.type() == ui::ET_GESTURE_TAP_DOWN);
1090  if (touch_layout_ &&
1091      ((event.type() == ui::ET_MOUSE_PRESSED &&
1092        (((event.flags() & ui::EF_FROM_TOUCH) &&
1093          static_cast<const ui::MouseEvent&>(event).IsLeftMouseButton()) ||
1094         (!(event.flags() & ui::EF_FROM_TOUCH) &&
1095          static_cast<const ui::MouseEvent&>(event).IsControlDown()))) ||
1096       (event.type() == ui::ET_GESTURE_TAP_DOWN && !event.IsControlDown()))) {
1097    move_behavior = TabDragController::MOVE_VISIBILE_TABS;
1098  }
1099
1100  drag_controller_.reset(new TabDragController);
1101  drag_controller_->Init(
1102      this, tab, tabs, gfx::Point(x, y), event.x(), selection_model,
1103      move_behavior, EventSourceFromEvent(event));
1104}
1105
1106void TabStrip::ContinueDrag(views::View* view, const ui::LocatedEvent& event) {
1107  if (drag_controller_.get() &&
1108      drag_controller_->event_source() == EventSourceFromEvent(event)) {
1109    gfx::Point screen_location(event.location());
1110    views::View::ConvertPointToScreen(view, &screen_location);
1111    drag_controller_->Drag(screen_location);
1112  }
1113}
1114
1115bool TabStrip::EndDrag(EndDragReason reason) {
1116  if (!drag_controller_.get())
1117    return false;
1118  bool started_drag = drag_controller_->started_drag();
1119  drag_controller_->EndDrag(reason);
1120  return started_drag;
1121}
1122
1123Tab* TabStrip::GetTabAt(Tab* tab, const gfx::Point& tab_in_tab_coordinates) {
1124  gfx::Point local_point = tab_in_tab_coordinates;
1125  ConvertPointToTarget(tab, this, &local_point);
1126
1127  views::View* view = GetEventHandlerForPoint(local_point);
1128  if (!view)
1129    return NULL;  // No tab contains the point.
1130
1131  // Walk up the view hierarchy until we find a tab, or the TabStrip.
1132  while (view && view != this && view->id() != VIEW_ID_TAB)
1133    view = view->parent();
1134
1135  return view && view->id() == VIEW_ID_TAB ? static_cast<Tab*>(view) : NULL;
1136}
1137
1138void TabStrip::OnMouseEventInTab(views::View* source,
1139                                 const ui::MouseEvent& event) {
1140  UpdateStackedLayoutFromMouseEvent(source, event);
1141}
1142
1143bool TabStrip::ShouldPaintTab(const Tab* tab, gfx::Rect* clip) {
1144  // Only touch layout needs to restrict the clip.
1145  if (!touch_layout_ && !IsStackingDraggedTabs())
1146    return true;
1147
1148  int index = GetModelIndexOfTab(tab);
1149  if (index == -1)
1150    return true;  // Tab is closing, paint it all.
1151
1152  int active_index = IsStackingDraggedTabs() ?
1153      controller_->GetActiveIndex() : touch_layout_->active_index();
1154  if (active_index == tab_count())
1155    active_index--;
1156
1157  if (index < active_index) {
1158    if (tab_at(index)->x() == tab_at(index + 1)->x())
1159      return false;
1160
1161    if (tab_at(index)->x() > tab_at(index + 1)->x())
1162      return true;  // Can happen during dragging.
1163
1164    clip->SetRect(
1165        0, 0, tab_at(index + 1)->x() - tab_at(index)->x() + kStackedTabLeftClip,
1166        tab_at(index)->height());
1167  } else if (index > active_index && index > 0) {
1168    const gfx::Rect& tab_bounds(tab_at(index)->bounds());
1169    const gfx::Rect& previous_tab_bounds(tab_at(index - 1)->bounds());
1170    if (tab_bounds.x() == previous_tab_bounds.x())
1171      return false;
1172
1173    if (tab_bounds.x() < previous_tab_bounds.x())
1174      return true;  // Can happen during dragging.
1175
1176    if (previous_tab_bounds.right() + kTabHorizontalOffset != tab_bounds.x()) {
1177      int x = previous_tab_bounds.right() - tab_bounds.x() -
1178          kStackedTabRightClip;
1179      clip->SetRect(x, 0, tab_bounds.width() - x, tab_bounds.height());
1180    }
1181  }
1182  return true;
1183}
1184
1185bool TabStrip::IsImmersiveStyle() const {
1186  return immersive_style_;
1187}
1188
1189void TabStrip::UpdateTabAccessibilityState(const Tab* tab,
1190                                           ui::AXViewState* state) {
1191  state->count = tab_count();
1192  state->index = GetModelIndexOfTab(tab);
1193}
1194
1195void TabStrip::MouseMovedOutOfHost() {
1196  ResizeLayoutTabs();
1197  if (reset_to_shrink_on_exit_) {
1198    reset_to_shrink_on_exit_ = false;
1199    SetStackedLayout(false);
1200    controller_->StackedLayoutMaybeChanged();
1201  }
1202}
1203
1204///////////////////////////////////////////////////////////////////////////////
1205// TabStrip, views::View overrides:
1206
1207void TabStrip::Layout() {
1208  // Only do a layout if our size changed.
1209  if (last_layout_size_ == size())
1210    return;
1211  if (IsDragSessionActive())
1212    return;
1213  DoLayout();
1214}
1215
1216void TabStrip::PaintChildren(gfx::Canvas* canvas,
1217                             const views::CullSet& cull_set) {
1218  // The view order doesn't match the paint order (tabs_ contains the tab
1219  // ordering). Additionally we need to paint the tabs that are closing in
1220  // |tabs_closing_map_|.
1221  Tab* active_tab = NULL;
1222  Tabs tabs_dragging;
1223  Tabs selected_tabs;
1224  int selected_tab_count = 0;
1225  bool is_dragging = false;
1226  int active_tab_index = -1;
1227
1228  const chrome::HostDesktopType host_desktop_type =
1229      chrome::GetHostDesktopTypeForNativeView(GetWidget()->GetNativeView());
1230  const int inactive_tab_alpha =
1231      (host_desktop_type == chrome::HOST_DESKTOP_TYPE_ASH) ?
1232      kInactiveTabAndNewTabButtonAlphaAsh : kInactiveTabAndNewTabButtonAlpha;
1233
1234  if (inactive_tab_alpha < 255)
1235    canvas->SaveLayerAlpha(inactive_tab_alpha);
1236
1237  PaintClosingTabs(canvas, tab_count(), cull_set);
1238
1239  for (int i = tab_count() - 1; i >= 0; --i) {
1240    Tab* tab = tab_at(i);
1241    if (tab->IsSelected())
1242      selected_tab_count++;
1243    if (tab->dragging() && !stacked_layout_) {
1244      is_dragging = true;
1245      if (tab->IsActive()) {
1246        active_tab = tab;
1247        active_tab_index = i;
1248      } else {
1249        tabs_dragging.push_back(tab);
1250      }
1251    } else if (!tab->IsActive()) {
1252      if (!tab->IsSelected()) {
1253        if (!stacked_layout_)
1254          tab->Paint(canvas, cull_set);
1255      } else {
1256        selected_tabs.push_back(tab);
1257      }
1258    } else {
1259      active_tab = tab;
1260      active_tab_index = i;
1261    }
1262    PaintClosingTabs(canvas, i, cull_set);
1263  }
1264
1265  // Draw from the left and then the right if we're in touch mode.
1266  if (stacked_layout_ && active_tab_index >= 0) {
1267    for (int i = 0; i < active_tab_index; ++i) {
1268      Tab* tab = tab_at(i);
1269      tab->Paint(canvas, cull_set);
1270    }
1271
1272    for (int i = tab_count() - 1; i > active_tab_index; --i) {
1273      Tab* tab = tab_at(i);
1274      tab->Paint(canvas, cull_set);
1275    }
1276  }
1277  if (inactive_tab_alpha < 255)
1278    canvas->Restore();
1279
1280  if (GetWidget()->ShouldWindowContentsBeTransparent()) {
1281    // Make sure non-active tabs are somewhat transparent.
1282    SkPaint paint;
1283    // If there are multiple tabs selected, fade non-selected tabs more to make
1284    // the selected tabs more noticable.
1285    int alpha = selected_tab_count > 1 ?
1286        kGlassFrameInactiveTabAlphaMultiSelection :
1287        kGlassFrameInactiveTabAlpha;
1288    paint.setColor(SkColorSetARGB(alpha, 255, 255, 255));
1289    paint.setXfermodeMode(SkXfermode::kDstIn_Mode);
1290    paint.setStyle(SkPaint::kFill_Style);
1291    // The tabstrip area overlaps the toolbar area by 2 px.
1292    canvas->DrawRect(gfx::Rect(0, 0, width(), height() - 2), paint);
1293  }
1294
1295  // Now selected but not active. We don't want these dimmed if using native
1296  // frame, so they're painted after initial pass.
1297  for (size_t i = 0; i < selected_tabs.size(); ++i)
1298    selected_tabs[i]->Paint(canvas, cull_set);
1299
1300  // Next comes the active tab.
1301  if (active_tab && !is_dragging)
1302    active_tab->Paint(canvas, cull_set);
1303
1304  // Paint the New Tab button.
1305  if (inactive_tab_alpha < 255)
1306    canvas->SaveLayerAlpha(inactive_tab_alpha);
1307  newtab_button_->Paint(canvas, cull_set);
1308  if (inactive_tab_alpha < 255)
1309    canvas->Restore();
1310
1311  // And the dragged tabs.
1312  for (size_t i = 0; i < tabs_dragging.size(); ++i)
1313    tabs_dragging[i]->Paint(canvas, cull_set);
1314
1315  // If the active tab is being dragged, it goes last.
1316  if (active_tab && is_dragging)
1317    active_tab->Paint(canvas, cull_set);
1318}
1319
1320const char* TabStrip::GetClassName() const {
1321  return kViewClassName;
1322}
1323
1324gfx::Size TabStrip::GetPreferredSize() const {
1325  int needed_tab_width;
1326  if (touch_layout_ || adjust_layout_) {
1327    // For stacked tabs the minimum size is calculated as the size needed to
1328    // handle showing any number of tabs.
1329    needed_tab_width =
1330        Tab::GetTouchWidth() + (2 * kStackedPadding * kMaxStackedCount);
1331  } else {
1332    // Otherwise the minimum width is based on the actual number of tabs.
1333    const int mini_tab_count = GetMiniTabCount();
1334    needed_tab_width = mini_tab_count * Tab::GetMiniWidth();
1335    const int remaining_tab_count = tab_count() - mini_tab_count;
1336    const int min_selected_width = Tab::GetMinimumSelectedSize().width();
1337    const int min_unselected_width = Tab::GetMinimumUnselectedSize().width();
1338    if (remaining_tab_count > 0) {
1339      needed_tab_width += kMiniToNonMiniGap + min_selected_width +
1340          ((remaining_tab_count - 1) * min_unselected_width);
1341    }
1342    if (tab_count() > 1)
1343      needed_tab_width += (tab_count() - 1) * kTabHorizontalOffset;
1344
1345    // Don't let the tabstrip shrink smaller than is necessary to show one tab,
1346    // and don't force it to be larger than is necessary to show 20 tabs.
1347    const int largest_min_tab_width =
1348        min_selected_width + 19 * (min_unselected_width + kTabHorizontalOffset);
1349    needed_tab_width = std::min(
1350        std::max(needed_tab_width, min_selected_width), largest_min_tab_width);
1351  }
1352  return gfx::Size(
1353      needed_tab_width + new_tab_button_width(),
1354      immersive_style_ ?
1355          Tab::GetImmersiveHeight() : Tab::GetMinimumUnselectedSize().height());
1356}
1357
1358void TabStrip::OnDragEntered(const DropTargetEvent& event) {
1359  // Force animations to stop, otherwise it makes the index calculation tricky.
1360  StopAnimating(true);
1361
1362  UpdateDropIndex(event);
1363
1364  GURL url;
1365  base::string16 title;
1366
1367  // Check whether the event data includes supported drop data.
1368  if (event.data().GetURLAndTitle(
1369          ui::OSExchangeData::CONVERT_FILENAMES, &url, &title) &&
1370      url.is_valid()) {
1371    drop_info_->url = url;
1372
1373    // For file:// URLs, kick off a MIME type request in case they're dropped.
1374    if (url.SchemeIsFile())
1375      controller()->CheckFileSupported(url);
1376  }
1377}
1378
1379int TabStrip::OnDragUpdated(const DropTargetEvent& event) {
1380  // Update the drop index even if the file is unsupported, to allow
1381  // dragging a file to the contents of another tab.
1382  UpdateDropIndex(event);
1383
1384  if (!drop_info_->file_supported)
1385    return ui::DragDropTypes::DRAG_NONE;
1386
1387  return GetDropEffect(event);
1388}
1389
1390void TabStrip::OnDragExited() {
1391  SetDropIndex(-1, false);
1392}
1393
1394int TabStrip::OnPerformDrop(const DropTargetEvent& event) {
1395  if (!drop_info_.get())
1396    return ui::DragDropTypes::DRAG_NONE;
1397
1398  const int drop_index = drop_info_->drop_index;
1399  const bool drop_before = drop_info_->drop_before;
1400  const bool file_supported = drop_info_->file_supported;
1401
1402  // Hide the drop indicator.
1403  SetDropIndex(-1, false);
1404
1405  // Do nothing if the file was unsupported or the URL is invalid. The URL may
1406  // have been changed after |drop_info_| was created.
1407  GURL url;
1408  base::string16 title;
1409  if (!file_supported ||
1410      !event.data().GetURLAndTitle(
1411           ui::OSExchangeData::CONVERT_FILENAMES, &url, &title) ||
1412      !url.is_valid())
1413    return ui::DragDropTypes::DRAG_NONE;
1414
1415  controller()->PerformDrop(drop_before, drop_index, url);
1416
1417  return GetDropEffect(event);
1418}
1419
1420void TabStrip::GetAccessibleState(ui::AXViewState* state) {
1421  state->role = ui::AX_ROLE_TAB_LIST;
1422}
1423
1424views::View* TabStrip::GetTooltipHandlerForPoint(const gfx::Point& point) {
1425  if (!HitTestPoint(point))
1426    return NULL;
1427
1428  if (!touch_layout_) {
1429    // Return any view that isn't a Tab or this TabStrip immediately. We don't
1430    // want to interfere.
1431    views::View* v = View::GetTooltipHandlerForPoint(point);
1432    if (v && v != this && strcmp(v->GetClassName(), Tab::kViewClassName))
1433      return v;
1434
1435    views::View* tab = FindTabHitByPoint(point);
1436    if (tab)
1437      return tab;
1438  } else {
1439    if (newtab_button_->visible()) {
1440      views::View* view =
1441          ConvertPointToViewAndGetTooltipHandler(this, newtab_button_, point);
1442      if (view)
1443        return view;
1444    }
1445    Tab* tab = FindTabForEvent(point);
1446    if (tab)
1447      return ConvertPointToViewAndGetTooltipHandler(this, tab, point);
1448  }
1449  return this;
1450}
1451
1452// static
1453int TabStrip::GetImmersiveHeight() {
1454  return Tab::GetImmersiveHeight();
1455}
1456
1457///////////////////////////////////////////////////////////////////////////////
1458// TabStrip, private:
1459
1460void TabStrip::Init() {
1461  set_id(VIEW_ID_TAB_STRIP);
1462  // So we get enter/exit on children to switch stacked layout on and off.
1463  set_notify_enter_exit_on_child(true);
1464  newtab_button_bounds_.SetRect(0,
1465                                0,
1466                                kNewTabButtonAssetWidth,
1467                                kNewTabButtonAssetHeight +
1468                                    kNewTabButtonVerticalOffset);
1469  newtab_button_ = new NewTabButton(this, this);
1470  newtab_button_->SetTooltipText(
1471      l10n_util::GetStringUTF16(IDS_TOOLTIP_NEW_TAB));
1472  newtab_button_->SetAccessibleName(
1473      l10n_util::GetStringUTF16(IDS_ACCNAME_NEWTAB));
1474  newtab_button_->SetImageAlignment(views::ImageButton::ALIGN_LEFT,
1475                                    views::ImageButton::ALIGN_BOTTOM);
1476  newtab_button_->SetEventTargeter(
1477      scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(newtab_button_)));
1478  AddChildView(newtab_button_);
1479
1480  if (drop_indicator_width == 0) {
1481    // Direction doesn't matter, both images are the same size.
1482    gfx::ImageSkia* drop_image = GetDropArrowImage(true);
1483    drop_indicator_width = drop_image->width();
1484    drop_indicator_height = drop_image->height();
1485  }
1486}
1487
1488Tab* TabStrip::CreateTab() {
1489  Tab* tab = new Tab(this);
1490  tab->set_animation_container(animation_container_.get());
1491  return tab;
1492}
1493
1494void TabStrip::StartInsertTabAnimation(int model_index) {
1495  PrepareForAnimation();
1496
1497  // The TabStrip can now use its entire width to lay out Tabs.
1498  in_tab_close_ = false;
1499  available_width_for_tabs_ = -1;
1500
1501  GenerateIdealBounds();
1502
1503  Tab* tab = tab_at(model_index);
1504  if (model_index == 0) {
1505    tab->SetBounds(0, ideal_bounds(model_index).y(), 0,
1506                   ideal_bounds(model_index).height());
1507  } else {
1508    Tab* last_tab = tab_at(model_index - 1);
1509    tab->SetBounds(last_tab->bounds().right() + kTabHorizontalOffset,
1510                   ideal_bounds(model_index).y(), 0,
1511                   ideal_bounds(model_index).height());
1512  }
1513
1514  AnimateToIdealBounds();
1515}
1516
1517void TabStrip::StartMoveTabAnimation() {
1518  PrepareForAnimation();
1519  GenerateIdealBounds();
1520  AnimateToIdealBounds();
1521}
1522
1523void TabStrip::StartRemoveTabAnimation(int model_index) {
1524  PrepareForAnimation();
1525
1526  // Mark the tab as closing.
1527  Tab* tab = tab_at(model_index);
1528  tab->set_closing(true);
1529
1530  RemoveTabFromViewModel(model_index);
1531
1532  ScheduleRemoveTabAnimation(tab);
1533}
1534
1535void TabStrip::ScheduleRemoveTabAnimation(Tab* tab) {
1536  // Start an animation for the tabs.
1537  GenerateIdealBounds();
1538  AnimateToIdealBounds();
1539
1540  // Animate the tab being closed to zero width.
1541  gfx::Rect tab_bounds = tab->bounds();
1542  tab_bounds.set_width(0);
1543  bounds_animator_.AnimateViewTo(tab, tab_bounds);
1544  bounds_animator_.SetAnimationDelegate(
1545      tab,
1546      scoped_ptr<gfx::AnimationDelegate>(new RemoveTabDelegate(this, tab)));
1547
1548  // Don't animate the new tab button when dragging tabs. Otherwise it looks
1549  // like the new tab button magically appears from beyond the end of the tab
1550  // strip.
1551  if (TabDragController::IsAttachedTo(this)) {
1552    bounds_animator_.StopAnimatingView(newtab_button_);
1553    newtab_button_->SetBoundsRect(newtab_button_bounds_);
1554  }
1555}
1556
1557void TabStrip::AnimateToIdealBounds() {
1558  for (int i = 0; i < tab_count(); ++i) {
1559    Tab* tab = tab_at(i);
1560    if (!tab->dragging()) {
1561      bounds_animator_.AnimateViewTo(tab, ideal_bounds(i));
1562      bounds_animator_.SetAnimationDelegate(
1563          tab,
1564          scoped_ptr<gfx::AnimationDelegate>(
1565              new TabAnimationDelegate(this, tab)));
1566    }
1567  }
1568
1569  bounds_animator_.AnimateViewTo(newtab_button_, newtab_button_bounds_);
1570}
1571
1572bool TabStrip::ShouldHighlightCloseButtonAfterRemove() {
1573  return in_tab_close_;
1574}
1575
1576void TabStrip::DoLayout() {
1577  last_layout_size_ = size();
1578
1579  StopAnimating(false);
1580
1581  SwapLayoutIfNecessary();
1582
1583  if (touch_layout_)
1584    touch_layout_->SetWidth(tab_area_width());
1585
1586  GenerateIdealBounds();
1587
1588  views::ViewModelUtils::SetViewBoundsToIdealBounds(tabs_);
1589  SetTabVisibility();
1590
1591  SchedulePaint();
1592
1593  bounds_animator_.StopAnimatingView(newtab_button_);
1594  newtab_button_->SetBoundsRect(newtab_button_bounds_);
1595}
1596
1597void TabStrip::SetTabVisibility() {
1598  // We could probably be more efficient here by making use of the fact that the
1599  // tabstrip will always have any visible tabs, and then any invisible tabs, so
1600  // we could e.g. binary-search for the changeover point.  But since we have to
1601  // iterate through all the tabs to call SetVisible() anyway, it doesn't seem
1602  // worth it.
1603  for (int i = 0; i < tab_count(); ++i) {
1604    Tab* tab = tab_at(i);
1605    tab->SetVisible(ShouldTabBeVisible(tab));
1606  }
1607  for (TabsClosingMap::const_iterator i(tabs_closing_map_.begin());
1608       i != tabs_closing_map_.end(); ++i) {
1609    for (Tabs::const_iterator j(i->second.begin()); j != i->second.end(); ++j) {
1610      Tab* tab = *j;
1611      tab->SetVisible(ShouldTabBeVisible(tab));
1612    }
1613  }
1614}
1615
1616void TabStrip::DragActiveTab(const std::vector<int>& initial_positions,
1617                             int delta) {
1618  DCHECK_EQ(tab_count(), static_cast<int>(initial_positions.size()));
1619  if (!touch_layout_) {
1620    StackDraggedTabs(delta);
1621    return;
1622  }
1623  SetIdealBoundsFromPositions(initial_positions);
1624  touch_layout_->DragActiveTab(delta);
1625  DoLayout();
1626}
1627
1628void TabStrip::SetIdealBoundsFromPositions(const std::vector<int>& positions) {
1629  if (static_cast<size_t>(tab_count()) != positions.size())
1630    return;
1631
1632  for (int i = 0; i < tab_count(); ++i) {
1633    gfx::Rect bounds(ideal_bounds(i));
1634    bounds.set_x(positions[i]);
1635    tabs_.set_ideal_bounds(i, bounds);
1636  }
1637}
1638
1639void TabStrip::StackDraggedTabs(int delta) {
1640  DCHECK(!touch_layout_);
1641  GenerateIdealBounds();
1642  const int active_index = controller_->GetActiveIndex();
1643  DCHECK_NE(-1, active_index);
1644  if (delta < 0) {
1645    // Drag the tabs to the left, stacking tabs before the active tab.
1646    const int adjusted_delta =
1647        std::min(ideal_bounds(active_index).x() -
1648                     kStackedPadding * std::min(active_index, kMaxStackedCount),
1649                 -delta);
1650    for (int i = 0; i <= active_index; ++i) {
1651      const int min_x = std::min(i, kMaxStackedCount) * kStackedPadding;
1652      gfx::Rect new_bounds(ideal_bounds(i));
1653      new_bounds.set_x(std::max(min_x, new_bounds.x() - adjusted_delta));
1654      tabs_.set_ideal_bounds(i, new_bounds);
1655    }
1656    const bool is_active_mini = tab_at(active_index)->data().mini;
1657    const int active_width = ideal_bounds(active_index).width();
1658    for (int i = active_index + 1; i < tab_count(); ++i) {
1659      const int max_x = ideal_bounds(active_index).x() +
1660          (kStackedPadding * std::min(i - active_index, kMaxStackedCount));
1661      gfx::Rect new_bounds(ideal_bounds(i));
1662      int new_x = std::max(new_bounds.x() + delta, max_x);
1663      if (new_x == max_x && !tab_at(i)->data().mini && !is_active_mini &&
1664          new_bounds.width() != active_width)
1665        new_x += (active_width - new_bounds.width());
1666      new_bounds.set_x(new_x);
1667      tabs_.set_ideal_bounds(i, new_bounds);
1668    }
1669  } else {
1670    // Drag the tabs to the right, stacking tabs after the active tab.
1671    const int last_tab_width = ideal_bounds(tab_count() - 1).width();
1672    const int last_tab_x = tab_area_width() - last_tab_width;
1673    if (active_index == tab_count() - 1 &&
1674        ideal_bounds(tab_count() - 1).x() == last_tab_x)
1675      return;
1676    const int adjusted_delta =
1677        std::min(last_tab_x -
1678                     kStackedPadding * std::min(tab_count() - active_index - 1,
1679                                                kMaxStackedCount) -
1680                     ideal_bounds(active_index).x(),
1681                 delta);
1682    for (int last_index = tab_count() - 1, i = last_index; i >= active_index;
1683         --i) {
1684      const int max_x = last_tab_x -
1685          std::min(tab_count() - i - 1, kMaxStackedCount) * kStackedPadding;
1686      gfx::Rect new_bounds(ideal_bounds(i));
1687      int new_x = std::min(max_x, new_bounds.x() + adjusted_delta);
1688      // Because of rounding not all tabs are the same width. Adjust the
1689      // position to accommodate this, otherwise the stacking is off.
1690      if (new_x == max_x && !tab_at(i)->data().mini &&
1691          new_bounds.width() != last_tab_width)
1692        new_x += (last_tab_width - new_bounds.width());
1693      new_bounds.set_x(new_x);
1694      tabs_.set_ideal_bounds(i, new_bounds);
1695    }
1696    for (int i = active_index - 1; i >= 0; --i) {
1697      const int min_x = ideal_bounds(active_index).x() -
1698          std::min(active_index - i, kMaxStackedCount) * kStackedPadding;
1699      gfx::Rect new_bounds(ideal_bounds(i));
1700      new_bounds.set_x(std::min(min_x, new_bounds.x() + delta));
1701      tabs_.set_ideal_bounds(i, new_bounds);
1702    }
1703    if (ideal_bounds(tab_count() - 1).right() >= newtab_button_->x())
1704      newtab_button_->SetVisible(false);
1705  }
1706  views::ViewModelUtils::SetViewBoundsToIdealBounds(tabs_);
1707  SchedulePaint();
1708}
1709
1710bool TabStrip::IsStackingDraggedTabs() const {
1711  return drag_controller_.get() && drag_controller_->started_drag() &&
1712      (drag_controller_->move_behavior() ==
1713       TabDragController::MOVE_VISIBILE_TABS);
1714}
1715
1716void TabStrip::LayoutDraggedTabsAt(const Tabs& tabs,
1717                                   Tab* active_tab,
1718                                   const gfx::Point& location,
1719                                   bool initial_drag) {
1720  // Immediately hide the new tab button if the last tab is being dragged.
1721  const Tab* last_visible_tab = GetLastVisibleTab();
1722  if (last_visible_tab && last_visible_tab->dragging())
1723    newtab_button_->SetVisible(false);
1724  std::vector<gfx::Rect> bounds;
1725  CalculateBoundsForDraggedTabs(tabs, &bounds);
1726  DCHECK_EQ(tabs.size(), bounds.size());
1727  int active_tab_model_index = GetModelIndexOfTab(active_tab);
1728  int active_tab_index = static_cast<int>(
1729      std::find(tabs.begin(), tabs.end(), active_tab) - tabs.begin());
1730  for (size_t i = 0; i < tabs.size(); ++i) {
1731    Tab* tab = tabs[i];
1732    gfx::Rect new_bounds = bounds[i];
1733    new_bounds.Offset(location.x(), location.y());
1734    int consecutive_index =
1735        active_tab_model_index - (active_tab_index - static_cast<int>(i));
1736    // If this is the initial layout during a drag and the tabs aren't
1737    // consecutive animate the view into position. Do the same if the tab is
1738    // already animating (which means we previously caused it to animate).
1739    if ((initial_drag &&
1740         GetModelIndexOfTab(tabs[i]) != consecutive_index) ||
1741        bounds_animator_.IsAnimating(tabs[i])) {
1742      bounds_animator_.SetTargetBounds(tabs[i], new_bounds);
1743    } else {
1744      tab->SetBoundsRect(new_bounds);
1745    }
1746  }
1747  SetTabVisibility();
1748}
1749
1750void TabStrip::CalculateBoundsForDraggedTabs(const Tabs& tabs,
1751                                             std::vector<gfx::Rect>* bounds) {
1752  int x = 0;
1753  for (size_t i = 0; i < tabs.size(); ++i) {
1754    Tab* tab = tabs[i];
1755    if (i > 0 && tab->data().mini != tabs[i - 1]->data().mini)
1756      x += kMiniToNonMiniGap;
1757    gfx::Rect new_bounds = tab->bounds();
1758    new_bounds.set_origin(gfx::Point(x, 0));
1759    bounds->push_back(new_bounds);
1760    x += tab->width() + kTabHorizontalOffset;
1761  }
1762}
1763
1764int TabStrip::GetSizeNeededForTabs(const Tabs& tabs) {
1765  int width = 0;
1766  for (size_t i = 0; i < tabs.size(); ++i) {
1767    Tab* tab = tabs[i];
1768    width += tab->width();
1769    if (i > 0 && tab->data().mini != tabs[i - 1]->data().mini)
1770      width += kMiniToNonMiniGap;
1771  }
1772  if (tabs.size() > 0)
1773    width += kTabHorizontalOffset * static_cast<int>(tabs.size() - 1);
1774  return width;
1775}
1776
1777int TabStrip::GetMiniTabCount() const {
1778  int mini_count = 0;
1779  while (mini_count < tab_count() && tab_at(mini_count)->data().mini)
1780    mini_count++;
1781  return mini_count;
1782}
1783
1784const Tab* TabStrip::GetLastVisibleTab() const {
1785  for (int i = tab_count() - 1; i >= 0; --i) {
1786    const Tab* tab = tab_at(i);
1787    if (tab->visible())
1788      return tab;
1789  }
1790  // While in normal use the tabstrip should always be wide enough to have at
1791  // least one visible tab, it can be zero-width in tests, meaning we get here.
1792  return NULL;
1793}
1794
1795void TabStrip::RemoveTabFromViewModel(int index) {
1796  // We still need to paint the tab until we actually remove it. Put it
1797  // in tabs_closing_map_ so we can find it.
1798  tabs_closing_map_[index].push_back(tab_at(index));
1799  UpdateTabsClosingMap(index + 1, -1);
1800  tabs_.Remove(index);
1801}
1802
1803void TabStrip::RemoveAndDeleteTab(Tab* tab) {
1804  scoped_ptr<Tab> deleter(tab);
1805  FindClosingTabResult res(FindClosingTab(tab));
1806  res.first->second.erase(res.second);
1807  if (res.first->second.empty())
1808    tabs_closing_map_.erase(res.first);
1809}
1810
1811void TabStrip::UpdateTabsClosingMap(int index, int delta) {
1812  if (tabs_closing_map_.empty())
1813    return;
1814
1815  if (delta == -1 &&
1816      tabs_closing_map_.find(index - 1) != tabs_closing_map_.end() &&
1817      tabs_closing_map_.find(index) != tabs_closing_map_.end()) {
1818    const Tabs& tabs(tabs_closing_map_[index]);
1819    tabs_closing_map_[index - 1].insert(
1820        tabs_closing_map_[index - 1].end(), tabs.begin(), tabs.end());
1821  }
1822  TabsClosingMap updated_map;
1823  for (TabsClosingMap::iterator i(tabs_closing_map_.begin());
1824       i != tabs_closing_map_.end(); ++i) {
1825    if (i->first > index)
1826      updated_map[i->first + delta] = i->second;
1827    else if (i->first < index)
1828      updated_map[i->first] = i->second;
1829  }
1830  if (delta > 0 && tabs_closing_map_.find(index) != tabs_closing_map_.end())
1831    updated_map[index + delta] = tabs_closing_map_[index];
1832  tabs_closing_map_.swap(updated_map);
1833}
1834
1835void TabStrip::StartedDraggingTabs(const Tabs& tabs) {
1836  // Let the controller know that the user started dragging tabs.
1837  controller()->OnStartedDraggingTabs();
1838
1839  // Hide the new tab button immediately if we didn't originate the drag.
1840  if (!drag_controller_.get())
1841    newtab_button_->SetVisible(false);
1842
1843  PrepareForAnimation();
1844
1845  // Reset dragging state of existing tabs.
1846  for (int i = 0; i < tab_count(); ++i)
1847    tab_at(i)->set_dragging(false);
1848
1849  for (size_t i = 0; i < tabs.size(); ++i) {
1850    tabs[i]->set_dragging(true);
1851    bounds_animator_.StopAnimatingView(tabs[i]);
1852  }
1853
1854  // Move the dragged tabs to their ideal bounds.
1855  GenerateIdealBounds();
1856
1857  // Sets the bounds of the dragged tabs.
1858  for (size_t i = 0; i < tabs.size(); ++i) {
1859    int tab_data_index = GetModelIndexOfTab(tabs[i]);
1860    DCHECK_NE(-1, tab_data_index);
1861    tabs[i]->SetBoundsRect(ideal_bounds(tab_data_index));
1862  }
1863  SetTabVisibility();
1864  SchedulePaint();
1865}
1866
1867void TabStrip::DraggedTabsDetached() {
1868  // Let the controller know that the user is not dragging this tabstrip's tabs
1869  // anymore.
1870  controller()->OnStoppedDraggingTabs();
1871  newtab_button_->SetVisible(true);
1872}
1873
1874void TabStrip::StoppedDraggingTabs(const Tabs& tabs,
1875                                   const std::vector<int>& initial_positions,
1876                                   bool move_only,
1877                                   bool completed) {
1878  // Let the controller know that the user stopped dragging tabs.
1879  controller()->OnStoppedDraggingTabs();
1880
1881  newtab_button_->SetVisible(true);
1882  if (move_only && touch_layout_) {
1883    if (completed)
1884      touch_layout_->SizeToFit();
1885    else
1886      SetIdealBoundsFromPositions(initial_positions);
1887  }
1888  bool is_first_tab = true;
1889  for (size_t i = 0; i < tabs.size(); ++i)
1890    StoppedDraggingTab(tabs[i], &is_first_tab);
1891}
1892
1893void TabStrip::StoppedDraggingTab(Tab* tab, bool* is_first_tab) {
1894  int tab_data_index = GetModelIndexOfTab(tab);
1895  if (tab_data_index == -1) {
1896    // The tab was removed before the drag completed. Don't do anything.
1897    return;
1898  }
1899
1900  if (*is_first_tab) {
1901    *is_first_tab = false;
1902    PrepareForAnimation();
1903
1904    // Animate the view back to its correct position.
1905    GenerateIdealBounds();
1906    AnimateToIdealBounds();
1907  }
1908  bounds_animator_.AnimateViewTo(tab, ideal_bounds(tab_data_index));
1909  // Install a delegate to reset the dragging state when done. We have to leave
1910  // dragging true for the tab otherwise it'll draw beneath the new tab button.
1911  bounds_animator_.SetAnimationDelegate(
1912      tab,
1913      scoped_ptr<gfx::AnimationDelegate>(
1914          new ResetDraggingStateDelegate(this, tab)));
1915}
1916
1917void TabStrip::OwnDragController(TabDragController* controller) {
1918  // Typically, ReleaseDragController() and OwnDragController() calls are paired
1919  // via corresponding calls to TabDragController::Detach() and
1920  // TabDragController::Attach(). There is one exception to that rule: when a
1921  // drag might start, we create a TabDragController that is owned by the
1922  // potential source tabstrip in MaybeStartDrag(). If a drag actually starts,
1923  // we then call Attach() on the source tabstrip, but since the source tabstrip
1924  // already owns the TabDragController, so we don't need to do anything.
1925  if (controller != drag_controller_.get())
1926    drag_controller_.reset(controller);
1927}
1928
1929void TabStrip::DestroyDragController() {
1930  newtab_button_->SetVisible(true);
1931  drag_controller_.reset();
1932}
1933
1934TabDragController* TabStrip::ReleaseDragController() {
1935  return drag_controller_.release();
1936}
1937
1938TabStrip::FindClosingTabResult TabStrip::FindClosingTab(const Tab* tab) {
1939  DCHECK(tab->closing());
1940  for (TabsClosingMap::iterator i(tabs_closing_map_.begin());
1941       i != tabs_closing_map_.end(); ++i) {
1942    Tabs::iterator j = std::find(i->second.begin(), i->second.end(), tab);
1943    if (j != i->second.end())
1944      return FindClosingTabResult(i, j);
1945  }
1946  NOTREACHED();
1947  return FindClosingTabResult(tabs_closing_map_.end(), Tabs::iterator());
1948}
1949
1950void TabStrip::PaintClosingTabs(gfx::Canvas* canvas,
1951                                int index,
1952                                const views::CullSet& cull_set) {
1953  if (tabs_closing_map_.find(index) == tabs_closing_map_.end())
1954    return;
1955
1956  const Tabs& tabs = tabs_closing_map_[index];
1957  for (Tabs::const_reverse_iterator i(tabs.rbegin()); i != tabs.rend(); ++i)
1958    (*i)->Paint(canvas, cull_set);
1959}
1960
1961void TabStrip::UpdateStackedLayoutFromMouseEvent(views::View* source,
1962                                                 const ui::MouseEvent& event) {
1963  if (!adjust_layout_)
1964    return;
1965
1966  // The following code attempts to switch to shrink (not stacked) layout when
1967  // the mouse exits the tabstrip (or the mouse is pressed on a stacked tab) and
1968  // to stacked layout when a touch device is used. This is made problematic by
1969  // windows generating mouse move events that do not clearly indicate the move
1970  // is the result of a touch device. This assumes a real mouse is used if
1971  // |kMouseMoveCountBeforeConsiderReal| mouse move events are received within
1972  // the time window |kMouseMoveTimeMS|.  At the time we get a mouse press we
1973  // know whether its from a touch device or not, but we don't layout then else
1974  // everything shifts. Instead we wait for the release.
1975  //
1976  // TODO(sky): revisit this when touch events are really plumbed through.
1977
1978  switch (event.type()) {
1979    case ui::ET_MOUSE_PRESSED:
1980      mouse_move_count_ = 0;
1981      last_mouse_move_time_ = base::TimeTicks();
1982      SetResetToShrinkOnExit((event.flags() & ui::EF_FROM_TOUCH) == 0);
1983      if (reset_to_shrink_on_exit_ && touch_layout_) {
1984        gfx::Point tab_strip_point(event.location());
1985        views::View::ConvertPointToTarget(source, this, &tab_strip_point);
1986        Tab* tab = FindTabForEvent(tab_strip_point);
1987        if (tab && touch_layout_->IsStacked(GetModelIndexOfTab(tab))) {
1988          SetStackedLayout(false);
1989          controller_->StackedLayoutMaybeChanged();
1990        }
1991      }
1992      break;
1993
1994    case ui::ET_MOUSE_MOVED: {
1995#if defined(USE_ASH)
1996      // Ash does not synthesize mouse events from touch events.
1997      SetResetToShrinkOnExit(true);
1998#else
1999      gfx::Point location(event.location());
2000      ConvertPointToTarget(source, this, &location);
2001      if (location == last_mouse_move_location_)
2002        return;  // Ignore spurious moves.
2003      last_mouse_move_location_ = location;
2004      if ((event.flags() & ui::EF_FROM_TOUCH) == 0 &&
2005          (event.flags() & ui::EF_IS_SYNTHESIZED) == 0) {
2006        if ((base::TimeTicks::Now() - last_mouse_move_time_).InMilliseconds() <
2007            kMouseMoveTimeMS) {
2008          if (mouse_move_count_++ == kMouseMoveCountBeforeConsiderReal)
2009            SetResetToShrinkOnExit(true);
2010        } else {
2011          mouse_move_count_ = 1;
2012          last_mouse_move_time_ = base::TimeTicks::Now();
2013        }
2014      } else {
2015        last_mouse_move_time_ = base::TimeTicks();
2016      }
2017#endif
2018      break;
2019    }
2020
2021    case ui::ET_MOUSE_RELEASED: {
2022      gfx::Point location(event.location());
2023      ConvertPointToTarget(source, this, &location);
2024      last_mouse_move_location_ = location;
2025      mouse_move_count_ = 0;
2026      last_mouse_move_time_ = base::TimeTicks();
2027      if ((event.flags() & ui::EF_FROM_TOUCH) == ui::EF_FROM_TOUCH) {
2028        SetStackedLayout(true);
2029        controller_->StackedLayoutMaybeChanged();
2030      }
2031      break;
2032    }
2033
2034    default:
2035      break;
2036  }
2037}
2038
2039void TabStrip::GetCurrentTabWidths(double* unselected_width,
2040                                   double* selected_width) const {
2041  *unselected_width = current_unselected_width_;
2042  *selected_width = current_selected_width_;
2043}
2044
2045void TabStrip::GetDesiredTabWidths(int tab_count,
2046                                   int mini_tab_count,
2047                                   double* unselected_width,
2048                                   double* selected_width) const {
2049  DCHECK(tab_count >= 0 && mini_tab_count >= 0 && mini_tab_count <= tab_count);
2050  const double min_unselected_width = Tab::GetMinimumUnselectedSize().width();
2051  const double min_selected_width = Tab::GetMinimumSelectedSize().width();
2052
2053  *unselected_width = min_unselected_width;
2054  *selected_width = min_selected_width;
2055
2056  if (tab_count == 0) {
2057    // Return immediately to avoid divide-by-zero below.
2058    return;
2059  }
2060
2061  // Determine how much space we can actually allocate to tabs.
2062  int available_width = (available_width_for_tabs_ < 0) ?
2063      tab_area_width() : available_width_for_tabs_;
2064  if (mini_tab_count > 0) {
2065    available_width -=
2066        mini_tab_count * (Tab::GetMiniWidth() + kTabHorizontalOffset);
2067    tab_count -= mini_tab_count;
2068    if (tab_count == 0) {
2069      *selected_width = *unselected_width = Tab::GetStandardSize().width();
2070      return;
2071    }
2072    // Account for gap between the last mini-tab and first non-mini-tab.
2073    available_width -= kMiniToNonMiniGap;
2074  }
2075
2076  // Calculate the desired tab widths by dividing the available space into equal
2077  // portions.  Don't let tabs get larger than the "standard width" or smaller
2078  // than the minimum width for each type, respectively.
2079  const int total_offset = kTabHorizontalOffset * (tab_count - 1);
2080  const double desired_tab_width = std::min((static_cast<double>(
2081      available_width - total_offset) / static_cast<double>(tab_count)),
2082      static_cast<double>(Tab::GetStandardSize().width()));
2083  *unselected_width = std::max(desired_tab_width, min_unselected_width);
2084  *selected_width = std::max(desired_tab_width, min_selected_width);
2085
2086  // When there are multiple tabs, we'll have one selected and some unselected
2087  // tabs.  If the desired width was between the minimum sizes of these types,
2088  // try to shrink the tabs with the smaller minimum.  For example, if we have
2089  // a strip of width 10 with 4 tabs, the desired width per tab will be 2.5.  If
2090  // selected tabs have a minimum width of 4 and unselected tabs have a minimum
2091  // width of 1, the above code would set *unselected_width = 2.5,
2092  // *selected_width = 4, which results in a total width of 11.5.  Instead, we
2093  // want to set *unselected_width = 2, *selected_width = 4, for a total width
2094  // of 10.
2095  if (tab_count > 1) {
2096    if (desired_tab_width < min_selected_width) {
2097      // Unselected width = (total width - selected width) / (num_tabs - 1)
2098      *unselected_width = std::max(static_cast<double>(
2099          available_width - total_offset - min_selected_width) /
2100          static_cast<double>(tab_count - 1), min_unselected_width);
2101    }
2102  }
2103}
2104
2105void TabStrip::ResizeLayoutTabs() {
2106  // We've been called back after the TabStrip has been emptied out (probably
2107  // just prior to the window being destroyed). We need to do nothing here or
2108  // else GetTabAt below will crash.
2109  if (tab_count() == 0)
2110    return;
2111
2112  // It is critically important that this is unhooked here, otherwise we will
2113  // keep spying on messages forever.
2114  RemoveMessageLoopObserver();
2115
2116  in_tab_close_ = false;
2117  available_width_for_tabs_ = -1;
2118  int mini_tab_count = GetMiniTabCount();
2119  if (mini_tab_count == tab_count()) {
2120    // Only mini-tabs, we know the tab widths won't have changed (all
2121    // mini-tabs have the same width), so there is nothing to do.
2122    return;
2123  }
2124  // Don't try and avoid layout based on tab sizes. If tabs are small enough
2125  // then the width of the active tab may not change, but other widths may
2126  // have. This is particularly important if we've overflowed (all tabs are at
2127  // the min).
2128  StartResizeLayoutAnimation();
2129}
2130
2131void TabStrip::ResizeLayoutTabsFromTouch() {
2132  // Don't resize if the user is interacting with the tabstrip.
2133  if (!drag_controller_.get())
2134    ResizeLayoutTabs();
2135  else
2136    StartResizeLayoutTabsFromTouchTimer();
2137}
2138
2139void TabStrip::StartResizeLayoutTabsFromTouchTimer() {
2140  resize_layout_timer_.Stop();
2141  resize_layout_timer_.Start(
2142      FROM_HERE, base::TimeDelta::FromMilliseconds(kTouchResizeLayoutTimeMS),
2143      this, &TabStrip::ResizeLayoutTabsFromTouch);
2144}
2145
2146void TabStrip::SetTabBoundsForDrag(const std::vector<gfx::Rect>& tab_bounds) {
2147  StopAnimating(false);
2148  DCHECK_EQ(tab_count(), static_cast<int>(tab_bounds.size()));
2149  for (int i = 0; i < tab_count(); ++i)
2150    tab_at(i)->SetBoundsRect(tab_bounds[i]);
2151  // Reset the layout size as we've effectively layed out a different size.
2152  // This ensures a layout happens after the drag is done.
2153  last_layout_size_ = gfx::Size();
2154}
2155
2156void TabStrip::AddMessageLoopObserver() {
2157  if (!mouse_watcher_.get()) {
2158    mouse_watcher_.reset(
2159        new views::MouseWatcher(
2160            new views::MouseWatcherViewHost(
2161                this, gfx::Insets(0, 0, kTabStripAnimationVSlop, 0)),
2162            this));
2163  }
2164  mouse_watcher_->Start();
2165}
2166
2167void TabStrip::RemoveMessageLoopObserver() {
2168  mouse_watcher_.reset(NULL);
2169}
2170
2171gfx::Rect TabStrip::GetDropBounds(int drop_index,
2172                                  bool drop_before,
2173                                  bool* is_beneath) {
2174  DCHECK_NE(drop_index, -1);
2175  int center_x;
2176  if (drop_index < tab_count()) {
2177    Tab* tab = tab_at(drop_index);
2178    if (drop_before)
2179      center_x = tab->x() - (kTabHorizontalOffset / 2);
2180    else
2181      center_x = tab->x() + (tab->width() / 2);
2182  } else {
2183    Tab* last_tab = tab_at(drop_index - 1);
2184    center_x = last_tab->x() + last_tab->width() + (kTabHorizontalOffset / 2);
2185  }
2186
2187  // Mirror the center point if necessary.
2188  center_x = GetMirroredXInView(center_x);
2189
2190  // Determine the screen bounds.
2191  gfx::Point drop_loc(center_x - drop_indicator_width / 2,
2192                      -drop_indicator_height);
2193  ConvertPointToScreen(this, &drop_loc);
2194  gfx::Rect drop_bounds(drop_loc.x(), drop_loc.y(), drop_indicator_width,
2195                        drop_indicator_height);
2196
2197  // If the rect doesn't fit on the monitor, push the arrow to the bottom.
2198  gfx::Screen* screen = gfx::Screen::GetScreenFor(GetWidget()->GetNativeView());
2199  gfx::Display display = screen->GetDisplayMatching(drop_bounds);
2200  *is_beneath = !display.bounds().Contains(drop_bounds);
2201  if (*is_beneath)
2202    drop_bounds.Offset(0, drop_bounds.height() + height());
2203
2204  return drop_bounds;
2205}
2206
2207void TabStrip::UpdateDropIndex(const DropTargetEvent& event) {
2208  // If the UI layout is right-to-left, we need to mirror the mouse
2209  // coordinates since we calculate the drop index based on the
2210  // original (and therefore non-mirrored) positions of the tabs.
2211  const int x = GetMirroredXInView(event.x());
2212  // We don't allow replacing the urls of mini-tabs.
2213  for (int i = GetMiniTabCount(); i < tab_count(); ++i) {
2214    Tab* tab = tab_at(i);
2215    const int tab_max_x = tab->x() + tab->width();
2216    const int hot_width = tab->width() / kTabEdgeRatioInverse;
2217    if (x < tab_max_x) {
2218      if (x < tab->x() + hot_width)
2219        SetDropIndex(i, true);
2220      else if (x >= tab_max_x - hot_width)
2221        SetDropIndex(i + 1, true);
2222      else
2223        SetDropIndex(i, false);
2224      return;
2225    }
2226  }
2227
2228  // The drop isn't over a tab, add it to the end.
2229  SetDropIndex(tab_count(), true);
2230}
2231
2232void TabStrip::SetDropIndex(int tab_data_index, bool drop_before) {
2233  // Let the controller know of the index update.
2234  controller()->OnDropIndexUpdate(tab_data_index, drop_before);
2235
2236  if (tab_data_index == -1) {
2237    if (drop_info_.get())
2238      drop_info_.reset(NULL);
2239    return;
2240  }
2241
2242  if (drop_info_.get() && drop_info_->drop_index == tab_data_index &&
2243      drop_info_->drop_before == drop_before) {
2244    return;
2245  }
2246
2247  bool is_beneath;
2248  gfx::Rect drop_bounds = GetDropBounds(tab_data_index, drop_before,
2249                                        &is_beneath);
2250
2251  if (!drop_info_.get()) {
2252    drop_info_.reset(
2253        new DropInfo(tab_data_index, drop_before, !is_beneath, GetWidget()));
2254  } else {
2255    drop_info_->drop_index = tab_data_index;
2256    drop_info_->drop_before = drop_before;
2257    if (is_beneath == drop_info_->point_down) {
2258      drop_info_->point_down = !is_beneath;
2259      drop_info_->arrow_view->SetImage(
2260          GetDropArrowImage(drop_info_->point_down));
2261    }
2262  }
2263
2264  // Reposition the window. Need to show it too as the window is initially
2265  // hidden.
2266  drop_info_->arrow_window->SetBounds(drop_bounds);
2267  drop_info_->arrow_window->Show();
2268}
2269
2270int TabStrip::GetDropEffect(const ui::DropTargetEvent& event) {
2271  const int source_ops = event.source_operations();
2272  if (source_ops & ui::DragDropTypes::DRAG_COPY)
2273    return ui::DragDropTypes::DRAG_COPY;
2274  if (source_ops & ui::DragDropTypes::DRAG_LINK)
2275    return ui::DragDropTypes::DRAG_LINK;
2276  return ui::DragDropTypes::DRAG_MOVE;
2277}
2278
2279// static
2280gfx::ImageSkia* TabStrip::GetDropArrowImage(bool is_down) {
2281  return ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
2282      is_down ? IDR_TAB_DROP_DOWN : IDR_TAB_DROP_UP);
2283}
2284
2285// TabStrip::DropInfo ----------------------------------------------------------
2286
2287TabStrip::DropInfo::DropInfo(int drop_index,
2288                             bool drop_before,
2289                             bool point_down,
2290                             views::Widget* context)
2291    : drop_index(drop_index),
2292      drop_before(drop_before),
2293      point_down(point_down),
2294      file_supported(true) {
2295  arrow_view = new views::ImageView;
2296  arrow_view->SetImage(GetDropArrowImage(point_down));
2297
2298  arrow_window = new views::Widget;
2299  views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
2300  params.keep_on_top = true;
2301  params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW;
2302  params.accept_events = false;
2303  params.bounds = gfx::Rect(drop_indicator_width, drop_indicator_height);
2304  params.context = context->GetNativeWindow();
2305  arrow_window->Init(params);
2306  arrow_window->SetContentsView(arrow_view);
2307}
2308
2309TabStrip::DropInfo::~DropInfo() {
2310  // Close eventually deletes the window, which deletes arrow_view too.
2311  arrow_window->Close();
2312}
2313
2314///////////////////////////////////////////////////////////////////////////////
2315
2316void TabStrip::PrepareForAnimation() {
2317  if (!IsDragSessionActive() && !TabDragController::IsAttachedTo(this)) {
2318    for (int i = 0; i < tab_count(); ++i)
2319      tab_at(i)->set_dragging(false);
2320  }
2321}
2322
2323void TabStrip::GenerateIdealBounds() {
2324  int new_tab_y = 0;
2325
2326  if (touch_layout_) {
2327    if (tabs_.view_size() == 0)
2328      return;
2329
2330    int new_tab_x = tabs_.ideal_bounds(tabs_.view_size() - 1).right() +
2331        kNewTabButtonHorizontalOffset;
2332    newtab_button_bounds_.set_origin(gfx::Point(new_tab_x, new_tab_y));
2333    return;
2334  }
2335
2336  GetDesiredTabWidths(tab_count(), GetMiniTabCount(),
2337                      &current_unselected_width_, &current_selected_width_);
2338
2339  // NOTE: This currently assumes a tab's height doesn't differ based on
2340  // selected state or the number of tabs in the strip!
2341  int tab_height = Tab::GetStandardSize().height();
2342  int first_non_mini_index = 0;
2343  double tab_x = GenerateIdealBoundsForMiniTabs(&first_non_mini_index);
2344  for (int i = first_non_mini_index; i < tab_count(); ++i) {
2345    Tab* tab = tab_at(i);
2346    DCHECK(!tab->data().mini);
2347    double tab_width =
2348        tab->IsActive() ? current_selected_width_ : current_unselected_width_;
2349    double end_of_tab = tab_x + tab_width;
2350    int rounded_tab_x = Round(tab_x);
2351    tabs_.set_ideal_bounds(
2352        i,
2353        gfx::Rect(rounded_tab_x, 0, Round(end_of_tab) - rounded_tab_x,
2354                  tab_height));
2355    tab_x = end_of_tab + kTabHorizontalOffset;
2356  }
2357
2358  // Update bounds of new tab button.
2359  int new_tab_x;
2360  if ((Tab::GetStandardSize().width() - Round(current_unselected_width_)) > 1 &&
2361      !in_tab_close_) {
2362    // We're shrinking tabs, so we need to anchor the New Tab button to the
2363    // right edge of the TabStrip's bounds, rather than the right edge of the
2364    // right-most Tab, otherwise it'll bounce when animating.
2365    new_tab_x = width() - newtab_button_bounds_.width();
2366  } else {
2367    new_tab_x = Round(tab_x - kTabHorizontalOffset) +
2368        kNewTabButtonHorizontalOffset;
2369  }
2370  newtab_button_bounds_.set_origin(gfx::Point(new_tab_x, new_tab_y));
2371}
2372
2373int TabStrip::GenerateIdealBoundsForMiniTabs(int* first_non_mini_index) {
2374  int next_x = 0;
2375  int mini_width = Tab::GetMiniWidth();
2376  int tab_height = Tab::GetStandardSize().height();
2377  int index = 0;
2378  for (; index < tab_count() && tab_at(index)->data().mini; ++index) {
2379    tabs_.set_ideal_bounds(index, gfx::Rect(next_x, 0, mini_width, tab_height));
2380    next_x += mini_width + kTabHorizontalOffset;
2381  }
2382  if (index > 0 && index < tab_count())
2383    next_x += kMiniToNonMiniGap;
2384  if (first_non_mini_index)
2385    *first_non_mini_index = index;
2386  return next_x;
2387}
2388
2389void TabStrip::StartResizeLayoutAnimation() {
2390  PrepareForAnimation();
2391  GenerateIdealBounds();
2392  AnimateToIdealBounds();
2393}
2394
2395void TabStrip::StartMiniTabAnimation() {
2396  in_tab_close_ = false;
2397  available_width_for_tabs_ = -1;
2398
2399  PrepareForAnimation();
2400
2401  GenerateIdealBounds();
2402  AnimateToIdealBounds();
2403}
2404
2405void TabStrip::StartMouseInitiatedRemoveTabAnimation(int model_index) {
2406  // The user initiated the close. We want to persist the bounds of all the
2407  // existing tabs, so we manually shift ideal_bounds then animate.
2408  Tab* tab_closing = tab_at(model_index);
2409  int delta = tab_closing->width() + kTabHorizontalOffset;
2410  // If the tab being closed is a mini-tab next to a non-mini-tab, be sure to
2411  // add the extra padding.
2412  DCHECK_LT(model_index, tab_count() - 1);
2413  if (tab_closing->data().mini && !tab_at(model_index + 1)->data().mini)
2414    delta += kMiniToNonMiniGap;
2415
2416  for (int i = model_index + 1; i < tab_count(); ++i) {
2417    gfx::Rect bounds = ideal_bounds(i);
2418    bounds.set_x(bounds.x() - delta);
2419    tabs_.set_ideal_bounds(i, bounds);
2420  }
2421
2422  // Don't just subtract |delta| from the New Tab x-coordinate, as we might have
2423  // overflow tabs that will be able to animate into the strip, in which case
2424  // the new tab button should stay where it is.
2425  newtab_button_bounds_.set_x(std::min(
2426      width() - newtab_button_bounds_.width(),
2427      ideal_bounds(tab_count() - 1).right() + kNewTabButtonHorizontalOffset));
2428
2429  PrepareForAnimation();
2430
2431  tab_closing->set_closing(true);
2432
2433  // We still need to paint the tab until we actually remove it. Put it in
2434  // tabs_closing_map_ so we can find it.
2435  RemoveTabFromViewModel(model_index);
2436
2437  AnimateToIdealBounds();
2438
2439  gfx::Rect tab_bounds = tab_closing->bounds();
2440  tab_bounds.set_width(0);
2441  bounds_animator_.AnimateViewTo(tab_closing, tab_bounds);
2442
2443  // Register delegate to do cleanup when done, BoundsAnimator takes
2444  // ownership of RemoveTabDelegate.
2445  bounds_animator_.SetAnimationDelegate(
2446      tab_closing,
2447      scoped_ptr<gfx::AnimationDelegate>(
2448          new RemoveTabDelegate(this, tab_closing)));
2449}
2450
2451bool TabStrip::IsPointInTab(Tab* tab,
2452                            const gfx::Point& point_in_tabstrip_coords) {
2453  gfx::Point point_in_tab_coords(point_in_tabstrip_coords);
2454  View::ConvertPointToTarget(this, tab, &point_in_tab_coords);
2455  return tab->HitTestPoint(point_in_tab_coords);
2456}
2457
2458int TabStrip::GetStartXForNormalTabs() const {
2459  int mini_tab_count = GetMiniTabCount();
2460  if (mini_tab_count == 0)
2461    return 0;
2462  return mini_tab_count * (Tab::GetMiniWidth() + kTabHorizontalOffset) +
2463      kMiniToNonMiniGap;
2464}
2465
2466Tab* TabStrip::FindTabForEvent(const gfx::Point& point) {
2467  if (touch_layout_) {
2468    int active_tab_index = touch_layout_->active_index();
2469    if (active_tab_index != -1) {
2470      Tab* tab = FindTabForEventFrom(point, active_tab_index, -1);
2471      if (!tab)
2472        tab = FindTabForEventFrom(point, active_tab_index + 1, 1);
2473      return tab;
2474    }
2475    if (tab_count())
2476      return FindTabForEventFrom(point, 0, 1);
2477  } else {
2478    for (int i = 0; i < tab_count(); ++i) {
2479      if (IsPointInTab(tab_at(i), point))
2480        return tab_at(i);
2481    }
2482  }
2483  return NULL;
2484}
2485
2486Tab* TabStrip::FindTabForEventFrom(const gfx::Point& point,
2487                                   int start,
2488                                   int delta) {
2489  // |start| equals tab_count() when there are only pinned tabs.
2490  if (start == tab_count())
2491    start += delta;
2492  for (int i = start; i >= 0 && i < tab_count(); i += delta) {
2493    if (IsPointInTab(tab_at(i), point))
2494      return tab_at(i);
2495  }
2496  return NULL;
2497}
2498
2499views::View* TabStrip::FindTabHitByPoint(const gfx::Point& point) {
2500  // The display order doesn't necessarily match the child list order, so we
2501  // walk the display list hit-testing Tabs. Since the active tab always
2502  // renders on top of adjacent tabs, it needs to be hit-tested before any
2503  // left-adjacent Tab, so we look ahead for it as we walk.
2504  for (int i = 0; i < tab_count(); ++i) {
2505    Tab* next_tab = i < (tab_count() - 1) ? tab_at(i + 1) : NULL;
2506    if (next_tab && next_tab->IsActive() && IsPointInTab(next_tab, point))
2507      return next_tab;
2508    if (IsPointInTab(tab_at(i), point))
2509      return tab_at(i);
2510  }
2511
2512  return NULL;
2513}
2514
2515std::vector<int> TabStrip::GetTabXCoordinates() {
2516  std::vector<int> results;
2517  for (int i = 0; i < tab_count(); ++i)
2518    results.push_back(ideal_bounds(i).x());
2519  return results;
2520}
2521
2522void TabStrip::SwapLayoutIfNecessary() {
2523  bool needs_touch = NeedsTouchLayout();
2524  bool using_touch = touch_layout_ != NULL;
2525  if (needs_touch == using_touch)
2526    return;
2527
2528  if (needs_touch) {
2529    gfx::Size tab_size(Tab::GetMinimumSelectedSize());
2530    tab_size.set_width(Tab::GetTouchWidth());
2531    touch_layout_.reset(new StackedTabStripLayout(
2532                            tab_size,
2533                            kTabHorizontalOffset,
2534                            kStackedPadding,
2535                            kMaxStackedCount,
2536                            &tabs_));
2537    touch_layout_->SetWidth(tab_area_width());
2538    // This has to be after SetWidth() as SetWidth() is going to reset the
2539    // bounds of the mini-tabs (since StackedTabStripLayout doesn't yet know how
2540    // many mini-tabs there are).
2541    GenerateIdealBoundsForMiniTabs(NULL);
2542    touch_layout_->SetXAndMiniCount(GetStartXForNormalTabs(),
2543                                    GetMiniTabCount());
2544    touch_layout_->SetActiveIndex(controller_->GetActiveIndex());
2545  } else {
2546    touch_layout_.reset();
2547  }
2548  PrepareForAnimation();
2549  GenerateIdealBounds();
2550  SetTabVisibility();
2551  AnimateToIdealBounds();
2552}
2553
2554bool TabStrip::NeedsTouchLayout() const {
2555  if (!stacked_layout_)
2556    return false;
2557
2558  int mini_tab_count = GetMiniTabCount();
2559  int normal_count = tab_count() - mini_tab_count;
2560  if (normal_count <= 1 || normal_count == mini_tab_count)
2561    return false;
2562  int x = GetStartXForNormalTabs();
2563  int available_width = tab_area_width() - x;
2564  return (Tab::GetTouchWidth() * normal_count +
2565          kTabHorizontalOffset * (normal_count - 1)) > available_width;
2566}
2567
2568void TabStrip::SetResetToShrinkOnExit(bool value) {
2569  if (!adjust_layout_)
2570    return;
2571
2572  if (value && !stacked_layout_)
2573    value = false;  // We're already using shrink (not stacked) layout.
2574
2575  if (value == reset_to_shrink_on_exit_)
2576    return;
2577
2578  reset_to_shrink_on_exit_ = value;
2579  // Add an observer so we know when the mouse moves out of the tabstrip.
2580  if (reset_to_shrink_on_exit_)
2581    AddMessageLoopObserver();
2582  else
2583    RemoveMessageLoopObserver();
2584}
2585
2586void TabStrip::ButtonPressed(views::Button* sender, const ui::Event& event) {
2587  if (sender == newtab_button_) {
2588    content::RecordAction(UserMetricsAction("NewTab_Button"));
2589    UMA_HISTOGRAM_ENUMERATION("Tab.NewTab", TabStripModel::NEW_TAB_BUTTON,
2590                              TabStripModel::NEW_TAB_ENUM_COUNT);
2591    if (event.IsMouseEvent()) {
2592      const ui::MouseEvent& mouse = static_cast<const ui::MouseEvent&>(event);
2593      if (mouse.IsOnlyMiddleMouseButton()) {
2594        base::string16 clipboard_text = GetClipboardText();
2595        if (!clipboard_text.empty())
2596          controller()->CreateNewTabWithLocation(clipboard_text);
2597        return;
2598      }
2599    }
2600
2601    controller()->CreateNewTab();
2602    if (event.type() == ui::ET_GESTURE_TAP)
2603      TouchUMA::RecordGestureAction(TouchUMA::GESTURE_NEWTAB_TAP);
2604  }
2605}
2606
2607// Overridden to support automation. See automation_proxy_uitest.cc.
2608const views::View* TabStrip::GetViewByID(int view_id) const {
2609  if (tab_count() > 0) {
2610    if (view_id == VIEW_ID_TAB_LAST)
2611      return tab_at(tab_count() - 1);
2612    if ((view_id >= VIEW_ID_TAB_0) && (view_id < VIEW_ID_TAB_LAST)) {
2613      int index = view_id - VIEW_ID_TAB_0;
2614      return (index >= 0 && index < tab_count()) ? tab_at(index) : NULL;
2615    }
2616  }
2617
2618  return View::GetViewByID(view_id);
2619}
2620
2621bool TabStrip::OnMousePressed(const ui::MouseEvent& event) {
2622  UpdateStackedLayoutFromMouseEvent(this, event);
2623  // We can't return true here, else clicking in an empty area won't drag the
2624  // window.
2625  return false;
2626}
2627
2628bool TabStrip::OnMouseDragged(const ui::MouseEvent& event) {
2629  ContinueDrag(this, event);
2630  return true;
2631}
2632
2633void TabStrip::OnMouseReleased(const ui::MouseEvent& event) {
2634  EndDrag(END_DRAG_COMPLETE);
2635  UpdateStackedLayoutFromMouseEvent(this, event);
2636}
2637
2638void TabStrip::OnMouseCaptureLost() {
2639  EndDrag(END_DRAG_CAPTURE_LOST);
2640}
2641
2642void TabStrip::OnMouseMoved(const ui::MouseEvent& event) {
2643  UpdateStackedLayoutFromMouseEvent(this, event);
2644}
2645
2646void TabStrip::OnMouseEntered(const ui::MouseEvent& event) {
2647  SetResetToShrinkOnExit(true);
2648}
2649
2650void TabStrip::OnGestureEvent(ui::GestureEvent* event) {
2651  SetResetToShrinkOnExit(false);
2652  switch (event->type()) {
2653    case ui::ET_GESTURE_SCROLL_END:
2654    case ui::ET_SCROLL_FLING_START:
2655    case ui::ET_GESTURE_END:
2656      EndDrag(END_DRAG_COMPLETE);
2657      if (adjust_layout_) {
2658        SetStackedLayout(true);
2659        controller_->StackedLayoutMaybeChanged();
2660      }
2661      break;
2662
2663    case ui::ET_GESTURE_LONG_PRESS:
2664      if (drag_controller_.get())
2665        drag_controller_->SetMoveBehavior(TabDragController::REORDER);
2666      break;
2667
2668    case ui::ET_GESTURE_LONG_TAP: {
2669      EndDrag(END_DRAG_CANCEL);
2670      gfx::Point local_point = event->location();
2671      Tab* tab = FindTabForEvent(local_point);
2672      if (tab) {
2673        ConvertPointToScreen(this, &local_point);
2674        ShowContextMenuForTab(tab, local_point, ui::MENU_SOURCE_TOUCH);
2675      }
2676      break;
2677    }
2678
2679    case ui::ET_GESTURE_SCROLL_UPDATE:
2680      ContinueDrag(this, *event);
2681      break;
2682
2683    case ui::ET_GESTURE_TAP_DOWN:
2684      EndDrag(END_DRAG_CANCEL);
2685      break;
2686
2687    case ui::ET_GESTURE_TAP: {
2688      const int active_index = controller_->GetActiveIndex();
2689      DCHECK_NE(-1, active_index);
2690      Tab* active_tab = tab_at(active_index);
2691      TouchUMA::GestureActionType action = TouchUMA::GESTURE_TABNOSWITCH_TAP;
2692      if (active_tab->tab_activated_with_last_tap_down())
2693        action = TouchUMA::GESTURE_TABSWITCH_TAP;
2694      TouchUMA::RecordGestureAction(action);
2695      break;
2696    }
2697
2698    default:
2699      break;
2700  }
2701  event->SetHandled();
2702}
2703
2704views::View* TabStrip::TargetForRect(views::View* root, const gfx::Rect& rect) {
2705  CHECK_EQ(root, this);
2706
2707  if (!views::UsePointBasedTargeting(rect))
2708    return views::ViewTargeterDelegate::TargetForRect(root, rect);
2709  const gfx::Point point(rect.CenterPoint());
2710
2711  if (!touch_layout_) {
2712    // Return any view that isn't a Tab or this TabStrip immediately. We don't
2713    // want to interfere.
2714    views::View* v = views::ViewTargeterDelegate::TargetForRect(root, rect);
2715    if (v && v != this && strcmp(v->GetClassName(), Tab::kViewClassName))
2716      return v;
2717
2718    views::View* tab = FindTabHitByPoint(point);
2719    if (tab)
2720      return tab;
2721  } else {
2722    if (newtab_button_->visible()) {
2723      views::View* view =
2724          ConvertPointToViewAndGetEventHandler(this, newtab_button_, point);
2725      if (view)
2726        return view;
2727    }
2728    Tab* tab = FindTabForEvent(point);
2729    if (tab)
2730      return ConvertPointToViewAndGetEventHandler(this, tab, point);
2731  }
2732  return this;
2733}
2734