tab_drag_controller.cc revision 2a99a7e74a7f215066514fe81d2bfa6639d9eddd
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_drag_controller.h"
6
7#include <math.h>
8#include <set>
9
10#include "base/auto_reset.h"
11#include "base/callback.h"
12#include "base/command_line.h"
13#include "base/i18n/rtl.h"
14#include "chrome/browser/extensions/extension_function_dispatcher.h"
15#include "chrome/browser/profiles/profile.h"
16#include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
17#include "chrome/browser/ui/browser_window.h"
18#include "chrome/browser/ui/tabs/tab_strip_model.h"
19#include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
20#include "chrome/browser/ui/views/frame/browser_view.h"
21#include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
22#include "chrome/browser/ui/views/tabs/dragged_tab_view.h"
23#include "chrome/browser/ui/views/tabs/native_view_photobooth.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_strip.h"
27#include "chrome/common/chrome_notification_types.h"
28#include "chrome/common/chrome_switches.h"
29#include "content/public/browser/notification_details.h"
30#include "content/public/browser/notification_service.h"
31#include "content/public/browser/notification_source.h"
32#include "content/public/browser/notification_types.h"
33#include "content/public/browser/user_metrics.h"
34#include "content/public/browser/web_contents.h"
35#include "content/public/browser/web_contents_view.h"
36#include "grit/theme_resources.h"
37#include "ui/base/animation/animation.h"
38#include "ui/base/animation/animation_delegate.h"
39#include "ui/base/animation/slide_animation.h"
40#include "ui/base/events/event_constants.h"
41#include "ui/base/events/event_utils.h"
42#include "ui/base/resource/resource_bundle.h"
43#include "ui/gfx/canvas.h"
44#include "ui/gfx/image/image_skia.h"
45#include "ui/gfx/screen.h"
46#include "ui/views/widget/root_view.h"
47#include "ui/views/widget/widget.h"
48
49#if defined(USE_ASH)
50#include "ash/shell.h"
51#include "ash/wm/property_util.h"
52#include "ash/wm/window_util.h"
53#include "ui/aura/env.h"
54#include "ui/aura/root_window.h"
55#include "ui/base/gestures/gesture_recognizer.h"
56#endif
57
58using content::OpenURLParams;
59using content::UserMetricsAction;
60using content::WebContents;
61
62static const int kHorizontalMoveThreshold = 16;  // Pixels.
63
64// Distance from the next/previous stacked before before we consider the tab
65// close enough to trigger moving.
66static const int kStackedDistance = 36;
67
68// If non-null there is a drag underway.
69static TabDragController* instance_ = NULL;
70
71namespace {
72
73// Delay, in ms, during dragging before we bring a window to front.
74const int kBringToFrontDelay = 750;
75
76// Initial delay before moving tabs when the dragged tab is close to the edge of
77// the stacked tabs.
78const int kMoveAttachedInitialDelay = 600;
79
80// Delay for moving tabs after the initial delay has passed.
81const int kMoveAttachedSubsequentDelay = 300;
82
83// Radius of the rect drawn by DockView.
84const int kRoundedRectRadius = 4;
85
86// Spacing between tab icons when DockView is showing a docking location that
87// contains more than one tab.
88const int kTabSpacing = 4;
89
90// DockView is the view responsible for giving a visual indicator of where a
91// dock is going to occur.
92
93class DockView : public views::View {
94 public:
95  explicit DockView(DockInfo::Type type) : type_(type) {}
96
97  virtual gfx::Size GetPreferredSize() OVERRIDE {
98    return gfx::Size(DockInfo::popup_width(), DockInfo::popup_height());
99  }
100
101  virtual void OnPaintBackground(gfx::Canvas* canvas) OVERRIDE {
102    // Fill the background rect.
103    SkPaint paint;
104    paint.setColor(SkColorSetRGB(108, 108, 108));
105    paint.setStyle(SkPaint::kFill_Style);
106    canvas->DrawRoundRect(GetLocalBounds(), kRoundedRectRadius, paint);
107
108    ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
109
110    gfx::ImageSkia* high_icon = rb.GetImageSkiaNamed(IDR_DOCK_HIGH);
111    gfx::ImageSkia* wide_icon = rb.GetImageSkiaNamed(IDR_DOCK_WIDE);
112
113    canvas->Save();
114    bool rtl_ui = base::i18n::IsRTL();
115    if (rtl_ui) {
116      // Flip canvas to draw the mirrored tab images for RTL UI.
117      canvas->Translate(gfx::Vector2d(width(), 0));
118      canvas->Scale(-1, 1);
119    }
120    int x_of_active_tab = width() / 2 + kTabSpacing / 2;
121    int x_of_inactive_tab = width() / 2 - high_icon->width() - kTabSpacing / 2;
122    switch (type_) {
123      case DockInfo::LEFT_OF_WINDOW:
124      case DockInfo::LEFT_HALF:
125        if (!rtl_ui)
126          std::swap(x_of_active_tab, x_of_inactive_tab);
127        canvas->DrawImageInt(*high_icon, x_of_active_tab,
128                             (height() - high_icon->height()) / 2);
129        if (type_ == DockInfo::LEFT_OF_WINDOW) {
130          DrawImageWithAlpha(canvas, *high_icon, x_of_inactive_tab,
131                             (height() - high_icon->height()) / 2);
132        }
133        break;
134
135
136      case DockInfo::RIGHT_OF_WINDOW:
137      case DockInfo::RIGHT_HALF:
138        if (rtl_ui)
139          std::swap(x_of_active_tab, x_of_inactive_tab);
140        canvas->DrawImageInt(*high_icon, x_of_active_tab,
141                             (height() - high_icon->height()) / 2);
142        if (type_ == DockInfo::RIGHT_OF_WINDOW) {
143         DrawImageWithAlpha(canvas, *high_icon, x_of_inactive_tab,
144                           (height() - high_icon->height()) / 2);
145        }
146        break;
147
148      case DockInfo::TOP_OF_WINDOW:
149        canvas->DrawImageInt(*wide_icon, (width() - wide_icon->width()) / 2,
150                             height() / 2 - high_icon->height());
151        break;
152
153      case DockInfo::MAXIMIZE: {
154        gfx::ImageSkia* max_icon = rb.GetImageSkiaNamed(IDR_DOCK_MAX);
155        canvas->DrawImageInt(*max_icon, (width() - max_icon->width()) / 2,
156                             (height() - max_icon->height()) / 2);
157        break;
158      }
159
160      case DockInfo::BOTTOM_HALF:
161      case DockInfo::BOTTOM_OF_WINDOW:
162        canvas->DrawImageInt(*wide_icon, (width() - wide_icon->width()) / 2,
163                             height() / 2 + kTabSpacing / 2);
164        if (type_ == DockInfo::BOTTOM_OF_WINDOW) {
165          DrawImageWithAlpha(canvas, *wide_icon,
166              (width() - wide_icon->width()) / 2,
167              height() / 2 - kTabSpacing / 2 - wide_icon->height());
168        }
169        break;
170
171      default:
172        NOTREACHED();
173        break;
174    }
175    canvas->Restore();
176  }
177
178 private:
179  void DrawImageWithAlpha(gfx::Canvas* canvas, const gfx::ImageSkia& image,
180                          int x, int y) {
181    SkPaint paint;
182    paint.setAlpha(128);
183    canvas->DrawImageInt(image, x, y, paint);
184  }
185
186  DockInfo::Type type_;
187
188  DISALLOW_COPY_AND_ASSIGN(DockView);
189};
190
191void SetTrackedByWorkspace(gfx::NativeWindow window, bool value) {
192#if defined(USE_ASH)
193  ash::SetTrackedByWorkspace(window, value);
194#endif
195}
196
197void SetWindowPositionManaged(gfx::NativeWindow window, bool value) {
198#if defined(USE_ASH)
199  ash::wm::SetWindowPositionManaged(window, value);
200#endif
201}
202
203bool ShouldDetachIntoNewBrowser() {
204#if defined(USE_AURA)
205  return true;
206#else
207  return CommandLine::ForCurrentProcess()->HasSwitch(
208      switches::kTabBrowserDragging);
209#endif
210}
211
212// Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
213// of |bounds| is adjusted by |vertical_adjustment|.
214bool DoesRectContainVerticalPointExpanded(
215    const gfx::Rect& bounds,
216    int vertical_adjustment,
217    int y) {
218  int upper_threshold = bounds.bottom() + vertical_adjustment;
219  int lower_threshold = bounds.y() - vertical_adjustment;
220  return y >= lower_threshold && y <= upper_threshold;
221}
222
223// WidgetObserver implementation that resets the window position managed
224// property on Show.
225// We're forced to do this here since BrowserFrameAura resets the 'window
226// position managed' property during a show and we need the property set to
227// false before WorkspaceLayoutManager2 sees the visibility change.
228class WindowPositionManagedUpdater : public views::WidgetObserver {
229 public:
230  virtual void OnWidgetVisibilityChanged(views::Widget* widget,
231                                         bool visible) OVERRIDE {
232    SetWindowPositionManaged(widget->GetNativeView(), false);
233  }
234};
235
236}  // namespace
237
238///////////////////////////////////////////////////////////////////////////////
239// DockDisplayer
240
241// DockDisplayer is responsible for giving the user a visual indication of a
242// possible dock position (as represented by DockInfo). DockDisplayer shows
243// a window with a DockView in it. Two animations are used that correspond to
244// the state of DockInfo::in_enable_area.
245class TabDragController::DockDisplayer : public ui::AnimationDelegate {
246 public:
247  DockDisplayer(TabDragController* controller, const DockInfo& info)
248      : controller_(controller),
249        popup_(NULL),
250        popup_view_(NULL),
251        ALLOW_THIS_IN_INITIALIZER_LIST(animation_(this)),
252        hidden_(false),
253        in_enable_area_(info.in_enable_area()) {
254    popup_ = new views::Widget;
255    views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
256    params.transparent = true;
257    params.keep_on_top = true;
258    params.bounds = info.GetPopupRect();
259    popup_->Init(params);
260    popup_->SetContentsView(new DockView(info.type()));
261    popup_->SetOpacity(0x00);
262    if (info.in_enable_area())
263      animation_.Reset(1);
264    else
265      animation_.Show();
266    popup_->Show();
267    popup_view_ = popup_->GetNativeView();
268  }
269
270  virtual ~DockDisplayer() {
271    if (controller_)
272      controller_->DockDisplayerDestroyed(this);
273  }
274
275  // Updates the state based on |in_enable_area|.
276  void UpdateInEnabledArea(bool in_enable_area) {
277    if (in_enable_area != in_enable_area_) {
278      in_enable_area_ = in_enable_area;
279      UpdateLayeredAlpha();
280    }
281  }
282
283  // Resets the reference to the hosting TabDragController. This is
284  // invoked when the TabDragController is destroyed.
285  void clear_controller() { controller_ = NULL; }
286
287  // NativeView of the window we create.
288  gfx::NativeView popup_view() { return popup_view_; }
289
290  // Starts the hide animation. When the window is closed the
291  // TabDragController is notified by way of the DockDisplayerDestroyed
292  // method
293  void Hide() {
294    if (hidden_)
295      return;
296
297    if (!popup_) {
298      delete this;
299      return;
300    }
301    hidden_ = true;
302    animation_.Hide();
303  }
304
305  virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE {
306    UpdateLayeredAlpha();
307  }
308
309  virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE {
310    if (!hidden_)
311      return;
312    popup_->Close();
313    delete this;
314  }
315
316 private:
317  void UpdateLayeredAlpha() {
318    double scale = in_enable_area_ ? 1 : .5;
319    popup_->SetOpacity(static_cast<unsigned char>(animation_.GetCurrentValue() *
320        scale * 255.0));
321  }
322
323  // TabDragController that created us.
324  TabDragController* controller_;
325
326  // Window we're showing.
327  views::Widget* popup_;
328
329  // NativeView of |popup_|. We cache this to avoid the possibility of
330  // invoking a method on popup_ after we close it.
331  gfx::NativeView popup_view_;
332
333  // Animation for when first made visible.
334  ui::SlideAnimation animation_;
335
336  // Have we been hidden?
337  bool hidden_;
338
339  // Value of DockInfo::in_enable_area.
340  bool in_enable_area_;
341};
342
343TabDragController::TabDragData::TabDragData()
344    : contents(NULL),
345      original_delegate(NULL),
346      source_model_index(-1),
347      attached_tab(NULL),
348      pinned(false) {
349}
350
351TabDragController::TabDragData::~TabDragData() {
352}
353
354///////////////////////////////////////////////////////////////////////////////
355// TabDragController, public:
356
357// static
358const int TabDragController::kTouchVerticalDetachMagnetism = 50;
359
360// static
361const int TabDragController::kVerticalDetachMagnetism = 15;
362
363TabDragController::TabDragController()
364    : detach_into_browser_(ShouldDetachIntoNewBrowser()),
365      event_source_(EVENT_SOURCE_MOUSE),
366      source_tabstrip_(NULL),
367      attached_tabstrip_(NULL),
368      screen_(NULL),
369      host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE),
370      offset_to_width_ratio_(0),
371      old_focused_view_(NULL),
372      last_move_screen_loc_(0),
373      started_drag_(false),
374      active_(true),
375      source_tab_index_(std::numeric_limits<size_t>::max()),
376      initial_move_(true),
377      detach_behavior_(DETACHABLE),
378      move_behavior_(REORDER),
379      mouse_move_direction_(0),
380      is_dragging_window_(false),
381      end_run_loop_behavior_(END_RUN_LOOP_STOP_DRAGGING),
382      waiting_for_run_loop_to_exit_(false),
383      tab_strip_to_attach_to_after_exit_(NULL),
384      move_loop_widget_(NULL),
385      destroyed_(NULL),
386      is_mutating_(false) {
387  instance_ = this;
388}
389
390TabDragController::~TabDragController() {
391  if (instance_ == this)
392    instance_ = NULL;
393
394  if (destroyed_)
395    *destroyed_ = true;
396
397  if (move_loop_widget_) {
398    move_loop_widget_->RemoveObserver(this);
399    SetTrackedByWorkspace(move_loop_widget_->GetNativeView(), true);
400    SetWindowPositionManaged(move_loop_widget_->GetNativeView(), true);
401  }
402
403  if (source_tabstrip_ && detach_into_browser_)
404    GetModel(source_tabstrip_)->RemoveObserver(this);
405
406  MessageLoopForUI::current()->RemoveObserver(this);
407
408  // Need to delete the view here manually _before_ we reset the dragged
409  // contents to NULL, otherwise if the view is animating to its destination
410  // bounds, it won't be able to clean up properly since its cleanup routine
411  // uses GetIndexForDraggedContents, which will be invalid.
412  view_.reset(NULL);
413
414  // Reset the delegate of the dragged WebContents. This ends up doing nothing
415  // if the drag was completed.
416  if (!detach_into_browser_)
417    ResetDelegates();
418}
419
420void TabDragController::Init(
421    TabStrip* source_tabstrip,
422    Tab* source_tab,
423    const std::vector<Tab*>& tabs,
424    const gfx::Point& mouse_offset,
425    int source_tab_offset,
426    const ui::ListSelectionModel& initial_selection_model,
427    DetachBehavior detach_behavior,
428    MoveBehavior move_behavior,
429    EventSource event_source) {
430  DCHECK(!tabs.empty());
431  DCHECK(std::find(tabs.begin(), tabs.end(), source_tab) != tabs.end());
432  source_tabstrip_ = source_tabstrip;
433  screen_ = gfx::Screen::GetScreenFor(
434      source_tabstrip->GetWidget()->GetNativeView());
435  host_desktop_type_ = chrome::GetHostDesktopTypeForNativeView(
436      source_tabstrip->GetWidget()->GetNativeView());
437  start_point_in_screen_ = gfx::Point(source_tab_offset, mouse_offset.y());
438  views::View::ConvertPointToScreen(source_tab, &start_point_in_screen_);
439  event_source_ = event_source;
440  mouse_offset_ = mouse_offset;
441  detach_behavior_ = detach_behavior;
442  move_behavior_ = move_behavior;
443  last_point_in_screen_ = start_point_in_screen_;
444  last_move_screen_loc_ = start_point_in_screen_.x();
445  initial_tab_positions_ = source_tabstrip->GetTabXCoordinates();
446  if (detach_behavior == NOT_DETACHABLE)
447    detach_into_browser_ = false;
448
449  if (detach_into_browser_)
450    GetModel(source_tabstrip_)->AddObserver(this);
451
452  drag_data_.resize(tabs.size());
453  for (size_t i = 0; i < tabs.size(); ++i)
454    InitTabDragData(tabs[i], &(drag_data_[i]));
455  source_tab_index_ =
456      std::find(tabs.begin(), tabs.end(), source_tab) - tabs.begin();
457
458  // Listen for Esc key presses.
459  MessageLoopForUI::current()->AddObserver(this);
460
461  if (source_tab->width() > 0) {
462    offset_to_width_ratio_ = static_cast<float>(
463        source_tab->GetMirroredXInView(source_tab_offset)) /
464        static_cast<float>(source_tab->width());
465  }
466  InitWindowCreatePoint();
467  initial_selection_model_.Copy(initial_selection_model);
468}
469
470// static
471bool TabDragController::IsAttachedTo(TabStrip* tab_strip) {
472  return (instance_ && instance_->active() &&
473          instance_->attached_tabstrip() == tab_strip);
474}
475
476// static
477bool TabDragController::IsActive() {
478  return instance_ && instance_->active();
479}
480
481void TabDragController::SetMoveBehavior(MoveBehavior behavior) {
482  if (started_drag())
483    return;
484
485  move_behavior_ = behavior;
486}
487
488void TabDragController::Drag(const gfx::Point& point_in_screen) {
489  bring_to_front_timer_.Stop();
490  move_stacked_timer_.Stop();
491
492  if (waiting_for_run_loop_to_exit_)
493    return;
494
495  if (!started_drag_) {
496    if (!CanStartDrag(point_in_screen))
497      return;  // User hasn't dragged far enough yet.
498
499    started_drag_ = true;
500    SaveFocus();
501    Attach(source_tabstrip_, gfx::Point());
502    if (detach_into_browser_ && static_cast<int>(drag_data_.size()) ==
503        GetModel(source_tabstrip_)->count()) {
504      RunMoveLoop(GetWindowOffset(point_in_screen));
505      return;
506    }
507  }
508
509  ContinueDragging(point_in_screen);
510}
511
512void TabDragController::EndDrag(EndDragReason reason) {
513  // If we're dragging a window ignore capture lost since it'll ultimately
514  // trigger the move loop to end and we'll revert the drag when RunMoveLoop()
515  // finishes.
516  if (reason == END_DRAG_CAPTURE_LOST && is_dragging_window_)
517    return;
518  EndDragImpl(reason != END_DRAG_COMPLETE && source_tabstrip_ ?
519              CANCELED : NORMAL);
520}
521
522void TabDragController::InitTabDragData(Tab* tab,
523                                        TabDragData* drag_data) {
524  drag_data->source_model_index =
525      source_tabstrip_->GetModelIndexOfTab(tab);
526  drag_data->contents = GetModel(source_tabstrip_)->GetWebContentsAt(
527      drag_data->source_model_index);
528  drag_data->pinned = source_tabstrip_->IsTabPinned(tab);
529  registrar_.Add(
530      this,
531      content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
532      content::Source<WebContents>(drag_data->contents));
533
534  if (!detach_into_browser_) {
535    drag_data->original_delegate = drag_data->contents->GetDelegate();
536    drag_data->contents->SetDelegate(this);
537  }
538}
539
540///////////////////////////////////////////////////////////////////////////////
541// TabDragController, PageNavigator implementation:
542
543WebContents* TabDragController::OpenURLFromTab(
544    WebContents* source,
545    const OpenURLParams& params) {
546  if (source_tab_drag_data()->original_delegate) {
547    OpenURLParams forward_params = params;
548    if (params.disposition == CURRENT_TAB)
549      forward_params.disposition = NEW_WINDOW;
550
551    return source_tab_drag_data()->original_delegate->OpenURLFromTab(
552        source, forward_params);
553  }
554  return NULL;
555}
556
557///////////////////////////////////////////////////////////////////////////////
558// TabDragController, content::WebContentsDelegate implementation:
559
560void TabDragController::NavigationStateChanged(const WebContents* source,
561                                               unsigned changed_flags) {
562  if (attached_tabstrip_) {
563    for (size_t i = 0; i < drag_data_.size(); ++i) {
564      if (drag_data_[i].contents == source) {
565        // Pass the NavigationStateChanged call to the original delegate so
566        // that the title is updated. Do this only when we are attached as
567        // otherwise the Tab isn't in the TabStrip.
568        drag_data_[i].original_delegate->NavigationStateChanged(source,
569                                                                changed_flags);
570        break;
571      }
572    }
573  }
574  if (view_.get())
575    view_->Update();
576}
577
578void TabDragController::AddNewContents(WebContents* source,
579                                       WebContents* new_contents,
580                                       WindowOpenDisposition disposition,
581                                       const gfx::Rect& initial_pos,
582                                       bool user_gesture,
583                                       bool* was_blocked) {
584  DCHECK_NE(CURRENT_TAB, disposition);
585
586  // Theoretically could be called while dragging if the page tries to
587  // spawn a window. Route this message back to the browser in most cases.
588  if (source_tab_drag_data()->original_delegate) {
589    source_tab_drag_data()->original_delegate->AddNewContents(
590        source, new_contents, disposition, initial_pos, user_gesture,
591        was_blocked);
592  }
593}
594
595void TabDragController::LoadingStateChanged(WebContents* source) {
596  // It would be nice to respond to this message by changing the
597  // screen shot in the dragged tab.
598  if (view_.get())
599    view_->Update();
600}
601
602bool TabDragController::ShouldSuppressDialogs() {
603  // When a dialog is about to be shown we revert the drag. Otherwise a modal
604  // dialog might appear and attempt to parent itself to a hidden tabcontents.
605  EndDragImpl(CANCELED);
606  return false;
607}
608
609content::JavaScriptDialogManager*
610TabDragController::GetJavaScriptDialogManager() {
611  return GetJavaScriptDialogManagerInstance();
612}
613
614///////////////////////////////////////////////////////////////////////////////
615// TabDragController, content::NotificationObserver implementation:
616
617void TabDragController::Observe(
618    int type,
619    const content::NotificationSource& source,
620    const content::NotificationDetails& details) {
621  DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED, type);
622  WebContents* destroyed_web_contents =
623      content::Source<WebContents>(source).ptr();
624  for (size_t i = 0; i < drag_data_.size(); ++i) {
625    if (drag_data_[i].contents == destroyed_web_contents) {
626      // One of the tabs we're dragging has been destroyed. Cancel the drag.
627      if (destroyed_web_contents->GetDelegate() == this)
628        destroyed_web_contents->SetDelegate(NULL);
629      drag_data_[i].contents = NULL;
630      drag_data_[i].original_delegate = NULL;
631      EndDragImpl(TAB_DESTROYED);
632      return;
633    }
634  }
635  // If we get here it means we got notification for a tab we don't know about.
636  NOTREACHED();
637}
638
639///////////////////////////////////////////////////////////////////////////////
640// TabDragController, MessageLoop::Observer implementation:
641
642base::EventStatus TabDragController::WillProcessEvent(
643    const base::NativeEvent& event) {
644  return base::EVENT_CONTINUE;
645}
646
647void TabDragController::DidProcessEvent(const base::NativeEvent& event) {
648  // If the user presses ESC during a drag, we need to abort and revert things
649  // to the way they were. This is the most reliable way to do this since no
650  // single view or window reliably receives events throughout all the various
651  // kinds of tab dragging.
652  if (ui::EventTypeFromNative(event) == ui::ET_KEY_PRESSED &&
653      ui::KeyboardCodeFromNative(event) == ui::VKEY_ESCAPE) {
654    EndDrag(END_DRAG_CANCEL);
655  }
656}
657
658void TabDragController::OnWidgetBoundsChanged(views::Widget* widget,
659                                              const gfx::Rect& new_bounds) {
660  Drag(GetCursorScreenPoint());
661}
662
663void TabDragController::TabStripEmpty() {
664  DCHECK(detach_into_browser_);
665  GetModel(source_tabstrip_)->RemoveObserver(this);
666  // NULL out source_tabstrip_ so that we don't attempt to add back to it (in
667  // the case of a revert).
668  source_tabstrip_ = NULL;
669}
670
671///////////////////////////////////////////////////////////////////////////////
672// TabDragController, private:
673
674void TabDragController::InitWindowCreatePoint() {
675  // window_create_point_ is only used in CompleteDrag() (through
676  // GetWindowCreatePoint() to get the start point of the docked window) when
677  // the attached_tabstrip_ is NULL and all the window's related bound
678  // information are obtained from source_tabstrip_. So, we need to get the
679  // first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise,
680  // the window_create_point_ is not in the correct coordinate system. Please
681  // refer to http://crbug.com/6223 comment #15 for detailed information.
682  views::View* first_tab = source_tabstrip_->tab_at(0);
683  views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_);
684  window_create_point_ = first_source_tab_point_;
685  window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y());
686}
687
688gfx::Point TabDragController::GetWindowCreatePoint(
689    const gfx::Point& origin) const {
690  if (dock_info_.type() != DockInfo::NONE && dock_info_.in_enable_area()) {
691    // If we're going to dock, we need to return the exact coordinate,
692    // otherwise we may attempt to maximize on the wrong monitor.
693    return origin;
694  }
695
696  // If the cursor is outside the monitor area, move it inside. For example,
697  // dropping a tab onto the task bar on Windows produces this situation.
698  gfx::Rect work_area = screen_->GetDisplayNearestPoint(origin).work_area();
699  gfx::Point create_point(origin);
700  if (!work_area.IsEmpty()) {
701    if (create_point.x() < work_area.x())
702      create_point.set_x(work_area.x());
703    else if (create_point.x() > work_area.right())
704      create_point.set_x(work_area.right());
705    if (create_point.y() < work_area.y())
706      create_point.set_y(work_area.y());
707    else if (create_point.y() > work_area.bottom())
708      create_point.set_y(work_area.bottom());
709  }
710  return gfx::Point(create_point.x() - window_create_point_.x(),
711                    create_point.y() - window_create_point_.y());
712}
713
714void TabDragController::UpdateDockInfo(const gfx::Point& point_in_screen) {
715  // Update the DockInfo for the current mouse coordinates.
716  DockInfo dock_info = GetDockInfoAtPoint(point_in_screen);
717  if (!dock_info.equals(dock_info_)) {
718    // DockInfo for current position differs.
719    if (dock_info_.type() != DockInfo::NONE &&
720        !dock_controllers_.empty()) {
721      // Hide old visual indicator.
722      dock_controllers_.back()->Hide();
723    }
724    dock_info_ = dock_info;
725    if (dock_info_.type() != DockInfo::NONE) {
726      // Show new docking position.
727      DockDisplayer* controller = new DockDisplayer(this, dock_info_);
728      if (controller->popup_view()) {
729        dock_controllers_.push_back(controller);
730        dock_windows_.insert(controller->popup_view());
731      } else {
732        delete controller;
733      }
734    }
735  } else if (dock_info_.type() != DockInfo::NONE &&
736             !dock_controllers_.empty()) {
737    // Current dock position is the same as last, update the controller's
738    // in_enable_area state as it may have changed.
739    dock_controllers_.back()->UpdateInEnabledArea(dock_info_.in_enable_area());
740  }
741}
742
743void TabDragController::SaveFocus() {
744  DCHECK(!old_focused_view_);  // This should only be invoked once.
745  DCHECK(source_tabstrip_);
746  old_focused_view_ = source_tabstrip_->GetFocusManager()->GetFocusedView();
747  source_tabstrip_->GetFocusManager()->SetFocusedView(source_tabstrip_);
748}
749
750void TabDragController::RestoreFocus() {
751  if (old_focused_view_ && attached_tabstrip_ == source_tabstrip_)
752    old_focused_view_->GetFocusManager()->SetFocusedView(old_focused_view_);
753  old_focused_view_ = NULL;
754}
755
756bool TabDragController::CanStartDrag(const gfx::Point& point_in_screen) const {
757  // Determine if the mouse has moved beyond a minimum elasticity distance in
758  // any direction from the starting point.
759  static const int kMinimumDragDistance = 10;
760  int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x());
761  int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y());
762  return sqrt(pow(static_cast<float>(x_offset), 2) +
763              pow(static_cast<float>(y_offset), 2)) > kMinimumDragDistance;
764}
765
766void TabDragController::ContinueDragging(const gfx::Point& point_in_screen) {
767  DCHECK(!detach_into_browser_ || attached_tabstrip_);
768
769  TabStrip* target_tabstrip = detach_behavior_ == DETACHABLE ?
770      GetTargetTabStripForPoint(point_in_screen) : source_tabstrip_;
771  bool tab_strip_changed = (target_tabstrip != attached_tabstrip_);
772
773  if (attached_tabstrip_) {
774    int move_delta = point_in_screen.x() - last_point_in_screen_.x();
775    if (move_delta > 0)
776      mouse_move_direction_ |= kMovedMouseRight;
777    else if (move_delta < 0)
778      mouse_move_direction_ |= kMovedMouseLeft;
779  }
780  last_point_in_screen_ = point_in_screen;
781
782  if (tab_strip_changed) {
783    if (detach_into_browser_ &&
784        DragBrowserToNewTabStrip(target_tabstrip, point_in_screen) ==
785        DRAG_BROWSER_RESULT_STOP) {
786      return;
787    } else if (!detach_into_browser_) {
788      if (attached_tabstrip_)
789        Detach(RELEASE_CAPTURE);
790      if (target_tabstrip)
791        Attach(target_tabstrip, point_in_screen);
792    }
793  }
794  if (view_.get() || is_dragging_window_) {
795    static_cast<base::Timer*>(&bring_to_front_timer_)->Start(FROM_HERE,
796        base::TimeDelta::FromMilliseconds(kBringToFrontDelay),
797        base::Bind(&TabDragController::BringWindowUnderPointToFront,
798                   base::Unretained(this), point_in_screen));
799  }
800
801  UpdateDockInfo(point_in_screen);
802
803  if (!is_dragging_window_) {
804    if (attached_tabstrip_) {
805      if (move_only()) {
806        DragActiveTabStacked(point_in_screen);
807      } else {
808        MoveAttached(point_in_screen);
809        if (tab_strip_changed) {
810          // Move the corresponding window to the front. We do this after the
811          // move as on windows activate triggers a synchronous paint.
812          attached_tabstrip_->GetWidget()->Activate();
813        }
814      }
815    } else {
816      MoveDetached(point_in_screen);
817    }
818  }
819}
820
821TabDragController::DragBrowserResultType
822TabDragController::DragBrowserToNewTabStrip(
823    TabStrip* target_tabstrip,
824    const gfx::Point& point_in_screen) {
825  if (!target_tabstrip) {
826    DetachIntoNewBrowserAndRunMoveLoop(point_in_screen);
827    return DRAG_BROWSER_RESULT_STOP;
828  }
829  if (is_dragging_window_) {
830    // ReleaseCapture() is going to result in calling back to us (because it
831    // results in a move). That'll cause all sorts of problems.  Reset the
832    // observer so we don't get notified and process the event.
833    if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
834      move_loop_widget_->RemoveObserver(this);
835      move_loop_widget_ = NULL;
836    }
837    views::Widget* browser_widget = GetAttachedBrowserWidget();
838    // Need to release the drag controller before starting the move loop as it's
839    // going to trigger capture lost, which cancels drag.
840    attached_tabstrip_->ReleaseDragController();
841    target_tabstrip->OwnDragController(this);
842    // Disable animations so that we don't see a close animation on aero.
843    browser_widget->SetVisibilityChangedAnimationsEnabled(false);
844    // For aura we can't release capture, otherwise it'll cancel a gesture.
845    // Instead we have to directly change capture.
846    if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH)
847      target_tabstrip->GetWidget()->SetCapture(attached_tabstrip_);
848    else
849      browser_widget->ReleaseCapture();
850    // The window is going away. Since the drag is still on going we don't want
851    // that to effect the position of any windows.
852    SetWindowPositionManaged(browser_widget->GetNativeView(), false);
853
854    // EndMoveLoop is going to snap the window back to its original location.
855    // Hide it so users don't see this.
856    browser_widget->Hide();
857    browser_widget->EndMoveLoop();
858
859    // Ideally we would always swap the tabs now, but on non-ash it seems that
860    // running the move loop implicitly activates the window when done, leading
861    // to all sorts of flicker. So, on non-ash, instead we process the move
862    // after the loop completes. But on chromeos, we can do tab swapping now to
863    // avoid the tab flashing issue(crbug.com/116329).
864    if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
865      is_dragging_window_ = false;
866      Detach(DONT_RELEASE_CAPTURE);
867      Attach(target_tabstrip, point_in_screen);
868      // Move the tabs into position.
869      MoveAttached(point_in_screen);
870      attached_tabstrip_->GetWidget()->Activate();
871    } else {
872      tab_strip_to_attach_to_after_exit_ = target_tabstrip;
873    }
874
875    waiting_for_run_loop_to_exit_ = true;
876    end_run_loop_behavior_ = END_RUN_LOOP_CONTINUE_DRAGGING;
877    return DRAG_BROWSER_RESULT_STOP;
878  }
879  Detach(DONT_RELEASE_CAPTURE);
880  Attach(target_tabstrip, point_in_screen);
881  return DRAG_BROWSER_RESULT_CONTINUE;
882}
883
884void TabDragController::DragActiveTabStacked(
885    const gfx::Point& point_in_screen) {
886  if (attached_tabstrip_->tab_count() !=
887      static_cast<int>(initial_tab_positions_.size()))
888    return;  // TODO: should cancel drag if this happens.
889
890  int delta = point_in_screen.x() - start_point_in_screen_.x();
891  attached_tabstrip_->DragActiveTab(initial_tab_positions_, delta);
892}
893
894void TabDragController::MoveAttachedToNextStackedIndex(
895    const gfx::Point& point_in_screen) {
896  int index = attached_tabstrip_->touch_layout_->active_index();
897  if (index + 1 >= attached_tabstrip_->tab_count())
898    return;
899
900  GetModel(attached_tabstrip_)->MoveSelectedTabsTo(index + 1);
901  StartMoveStackedTimerIfNecessary(point_in_screen,
902                                   kMoveAttachedSubsequentDelay);
903}
904
905void TabDragController::MoveAttachedToPreviousStackedIndex(
906    const gfx::Point& point_in_screen) {
907  int index = attached_tabstrip_->touch_layout_->active_index();
908  if (index <= attached_tabstrip_->GetMiniTabCount())
909    return;
910
911  GetModel(attached_tabstrip_)->MoveSelectedTabsTo(index - 1);
912  StartMoveStackedTimerIfNecessary(point_in_screen,
913                                   kMoveAttachedSubsequentDelay);
914}
915
916void TabDragController::MoveAttached(const gfx::Point& point_in_screen) {
917  DCHECK(attached_tabstrip_);
918  DCHECK(!view_.get());
919  DCHECK(!is_dragging_window_);
920
921  gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
922
923  // Determine the horizontal move threshold. This is dependent on the width
924  // of tabs. The smaller the tabs compared to the standard size, the smaller
925  // the threshold.
926  int threshold = kHorizontalMoveThreshold;
927  if (!attached_tabstrip_->touch_layout_.get()) {
928    double unselected, selected;
929    attached_tabstrip_->GetCurrentTabWidths(&unselected, &selected);
930    double ratio = unselected / Tab::GetStandardSize().width();
931    threshold = static_cast<int>(ratio * kHorizontalMoveThreshold);
932  }
933  // else case: touch tabs never shrink.
934
935  std::vector<Tab*> tabs(drag_data_.size());
936  for (size_t i = 0; i < drag_data_.size(); ++i)
937    tabs[i] = drag_data_[i].attached_tab;
938
939  bool did_layout = false;
940  // Update the model, moving the WebContents from one index to another. Do this
941  // only if we have moved a minimum distance since the last reorder (to prevent
942  // jitter) or if this the first move and the tabs are not consecutive.
943  if ((abs(point_in_screen.x() - last_move_screen_loc_) > threshold ||
944        (initial_move_ && !AreTabsConsecutive()))) {
945    TabStripModel* attached_model = GetModel(attached_tabstrip_);
946    gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point);
947    int to_index = GetInsertionIndexForDraggedBounds(bounds);
948    WebContents* last_contents = drag_data_[drag_data_.size() - 1].contents;
949    int index_of_last_item =
950          attached_model->GetIndexOfWebContents(last_contents);
951    if (initial_move_) {
952      // TabStrip determines if the tabs needs to be animated based on model
953      // position. This means we need to invoke LayoutDraggedTabsAt before
954      // changing the model.
955      attached_tabstrip_->LayoutDraggedTabsAt(
956          tabs, source_tab_drag_data()->attached_tab, dragged_view_point,
957          initial_move_);
958      did_layout = true;
959    }
960    attached_model->MoveSelectedTabsTo(to_index);
961
962    // Move may do nothing in certain situations (such as when dragging pinned
963    // tabs). Make sure the tabstrip actually changed before updating
964    // last_move_screen_loc_.
965    if (index_of_last_item !=
966        attached_model->GetIndexOfWebContents(last_contents)) {
967      last_move_screen_loc_ = point_in_screen.x();
968    }
969  }
970
971  if (!did_layout) {
972    attached_tabstrip_->LayoutDraggedTabsAt(
973        tabs, source_tab_drag_data()->attached_tab, dragged_view_point,
974        initial_move_);
975  }
976
977  StartMoveStackedTimerIfNecessary(point_in_screen, kMoveAttachedInitialDelay);
978
979  initial_move_ = false;
980}
981
982void TabDragController::MoveDetached(const gfx::Point& point_in_screen) {
983  DCHECK(!attached_tabstrip_);
984  DCHECK(view_.get());
985  DCHECK(!is_dragging_window_);
986
987  // Move the View. There are no changes to the model if we're detached.
988  view_->MoveTo(point_in_screen);
989}
990
991void TabDragController::StartMoveStackedTimerIfNecessary(
992    const gfx::Point& point_in_screen,
993    int delay_ms) {
994  DCHECK(attached_tabstrip_);
995
996  StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get();
997  if (!touch_layout)
998    return;
999
1000  gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
1001  gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point);
1002  int index = touch_layout->active_index();
1003  if (ShouldDragToNextStackedTab(bounds, index)) {
1004    static_cast<base::Timer*>(&move_stacked_timer_)->Start(
1005        FROM_HERE,
1006        base::TimeDelta::FromMilliseconds(delay_ms),
1007        base::Bind(&TabDragController::MoveAttachedToNextStackedIndex,
1008                   base::Unretained(this), point_in_screen));
1009  } else if (ShouldDragToPreviousStackedTab(bounds, index)) {
1010    static_cast<base::Timer*>(&move_stacked_timer_)->Start(
1011        FROM_HERE,
1012        base::TimeDelta::FromMilliseconds(delay_ms),
1013        base::Bind(&TabDragController::MoveAttachedToPreviousStackedIndex,
1014                   base::Unretained(this), point_in_screen));
1015  }
1016}
1017
1018TabDragController::DetachPosition TabDragController::GetDetachPosition(
1019    const gfx::Point& point_in_screen) {
1020  DCHECK(attached_tabstrip_);
1021  gfx::Point attached_point(point_in_screen);
1022  views::View::ConvertPointToTarget(NULL, attached_tabstrip_, &attached_point);
1023  if (attached_point.x() < 0)
1024    return DETACH_BEFORE;
1025  if (attached_point.x() >= attached_tabstrip_->width())
1026    return DETACH_AFTER;
1027  return DETACH_ABOVE_OR_BELOW;
1028}
1029
1030DockInfo TabDragController::GetDockInfoAtPoint(
1031    const gfx::Point& point_in_screen) {
1032  // TODO: add support for dock info when |detach_into_browser_| is true.
1033  if (attached_tabstrip_ || detach_into_browser_) {
1034    // If the mouse is over a tab strip, don't offer a dock position.
1035    return DockInfo();
1036  }
1037
1038  if (dock_info_.IsValidForPoint(point_in_screen)) {
1039    // It's possible any given screen coordinate has multiple docking
1040    // positions. Check the current info first to avoid having the docking
1041    // position bounce around.
1042    return dock_info_;
1043  }
1044
1045  gfx::NativeView dragged_view = view_->GetWidget()->GetNativeView();
1046  dock_windows_.insert(dragged_view);
1047  DockInfo info = DockInfo::GetDockInfoAtPoint(
1048      host_desktop_type_,
1049      point_in_screen,
1050      dock_windows_);
1051  dock_windows_.erase(dragged_view);
1052  return info;
1053}
1054
1055TabStrip* TabDragController::GetTargetTabStripForPoint(
1056    const gfx::Point& point_in_screen) {
1057  if (move_only() && attached_tabstrip_) {
1058    DCHECK_EQ(DETACHABLE, detach_behavior_);
1059    // move_only() is intended for touch, in which case we only want to detach
1060    // if the touch point moves significantly in the vertical distance.
1061    gfx::Rect tabstrip_bounds = GetViewScreenBounds(attached_tabstrip_);
1062    if (DoesRectContainVerticalPointExpanded(tabstrip_bounds,
1063                                             kTouchVerticalDetachMagnetism,
1064                                             point_in_screen.y()))
1065      return attached_tabstrip_;
1066  }
1067  gfx::NativeView dragged_view = NULL;
1068  if (view_.get())
1069    dragged_view = view_->GetWidget()->GetNativeView();
1070  else if (is_dragging_window_)
1071    dragged_view = attached_tabstrip_->GetWidget()->GetNativeView();
1072  if (dragged_view)
1073    dock_windows_.insert(dragged_view);
1074  gfx::NativeWindow local_window =
1075      DockInfo::GetLocalProcessWindowAtPoint(
1076          host_desktop_type_,
1077          point_in_screen,
1078          dock_windows_);
1079  if (dragged_view)
1080    dock_windows_.erase(dragged_view);
1081  TabStrip* tab_strip = GetTabStripForWindow(local_window);
1082  if (tab_strip && DoesTabStripContain(tab_strip, point_in_screen))
1083    return tab_strip;
1084  return is_dragging_window_ ? attached_tabstrip_ : NULL;
1085}
1086
1087TabStrip* TabDragController::GetTabStripForWindow(gfx::NativeWindow window) {
1088  if (!window)
1089    return NULL;
1090  BrowserView* browser_view =
1091      BrowserView::GetBrowserViewForNativeWindow(window);
1092  // We don't allow drops on windows that don't have tabstrips.
1093  if (!browser_view ||
1094      !browser_view->browser()->SupportsWindowFeature(
1095          Browser::FEATURE_TABSTRIP))
1096    return NULL;
1097
1098  TabStrip* other_tabstrip = browser_view->tabstrip();
1099  TabStrip* tab_strip =
1100      attached_tabstrip_ ? attached_tabstrip_ : source_tabstrip_;
1101  DCHECK(tab_strip);
1102
1103  return other_tabstrip->controller()->IsCompatibleWith(tab_strip) ?
1104      other_tabstrip : NULL;
1105}
1106
1107bool TabDragController::DoesTabStripContain(
1108    TabStrip* tabstrip,
1109    const gfx::Point& point_in_screen) const {
1110  // Make sure the specified screen point is actually within the bounds of the
1111  // specified tabstrip...
1112  gfx::Rect tabstrip_bounds = GetViewScreenBounds(tabstrip);
1113  return point_in_screen.x() < tabstrip_bounds.right() &&
1114      point_in_screen.x() >= tabstrip_bounds.x() &&
1115      DoesRectContainVerticalPointExpanded(tabstrip_bounds,
1116                                           kVerticalDetachMagnetism,
1117                                           point_in_screen.y());
1118}
1119
1120void TabDragController::Attach(TabStrip* attached_tabstrip,
1121                               const gfx::Point& point_in_screen) {
1122  DCHECK(!attached_tabstrip_);  // We should already have detached by the time
1123                                // we get here.
1124
1125  attached_tabstrip_ = attached_tabstrip;
1126
1127  // And we don't need the dragged view.
1128  view_.reset();
1129
1130  std::vector<Tab*> tabs =
1131      GetTabsMatchingDraggedContents(attached_tabstrip_);
1132
1133  if (tabs.empty()) {
1134    // Transitioning from detached to attached to a new tabstrip. Add tabs to
1135    // the new model.
1136
1137    selection_model_before_attach_.Copy(attached_tabstrip->GetSelectionModel());
1138
1139    if (!detach_into_browser_) {
1140      // Remove ourselves as the delegate now that the dragged WebContents is
1141      // being inserted back into a Browser.
1142      for (size_t i = 0; i < drag_data_.size(); ++i) {
1143        drag_data_[i].contents->SetDelegate(NULL);
1144        drag_data_[i].original_delegate = NULL;
1145      }
1146
1147      // Return the WebContents to normalcy.
1148      source_dragged_contents()->DecrementCapturerCount();
1149    }
1150
1151    // Inserting counts as a move. We don't want the tabs to jitter when the
1152    // user moves the tab immediately after attaching it.
1153    last_move_screen_loc_ = point_in_screen.x();
1154
1155    // Figure out where to insert the tab based on the bounds of the dragged
1156    // representation and the ideal bounds of the other Tabs already in the
1157    // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
1158    // changing due to animation).
1159    gfx::Point tab_strip_point(point_in_screen);
1160    views::View::ConvertPointToTarget(NULL, attached_tabstrip_,
1161                                      &tab_strip_point);
1162    tab_strip_point.set_x(
1163        attached_tabstrip_->GetMirroredXInView(tab_strip_point.x()));
1164    tab_strip_point.Offset(-mouse_offset_.x(), -mouse_offset_.y());
1165    gfx::Rect bounds = GetDraggedViewTabStripBounds(tab_strip_point);
1166    int index = GetInsertionIndexForDraggedBounds(bounds);
1167    base::AutoReset<bool> setter(&is_mutating_, true);
1168    for (size_t i = 0; i < drag_data_.size(); ++i) {
1169      int add_types = TabStripModel::ADD_NONE;
1170      if (attached_tabstrip_->touch_layout_.get()) {
1171        // StackedTabStripLayout positions relative to the active tab, if we
1172        // don't add the tab as active things bounce around.
1173        DCHECK_EQ(1u, drag_data_.size());
1174        add_types |= TabStripModel::ADD_ACTIVE;
1175      }
1176      if (drag_data_[i].pinned)
1177        add_types |= TabStripModel::ADD_PINNED;
1178      GetModel(attached_tabstrip_)->InsertWebContentsAt(
1179          index + i, drag_data_[i].contents, add_types);
1180    }
1181
1182    tabs = GetTabsMatchingDraggedContents(attached_tabstrip_);
1183  }
1184  DCHECK_EQ(tabs.size(), drag_data_.size());
1185  for (size_t i = 0; i < drag_data_.size(); ++i)
1186    drag_data_[i].attached_tab = tabs[i];
1187
1188  attached_tabstrip_->StartedDraggingTabs(tabs);
1189
1190  ResetSelection(GetModel(attached_tabstrip_));
1191
1192  // The size of the dragged tab may have changed. Adjust the x offset so that
1193  // ratio of mouse_offset_ to original width is maintained.
1194  std::vector<Tab*> tabs_to_source(tabs);
1195  tabs_to_source.erase(tabs_to_source.begin() + source_tab_index_ + 1,
1196                       tabs_to_source.end());
1197  int new_x = attached_tabstrip_->GetSizeNeededForTabs(tabs_to_source) -
1198      tabs[source_tab_index_]->width() +
1199      static_cast<int>(offset_to_width_ratio_ *
1200                       tabs[source_tab_index_]->width());
1201  mouse_offset_.set_x(new_x);
1202
1203  // Transfer ownership of us to the new tabstrip as well as making sure the
1204  // window has capture. This is important so that if activation changes the
1205  // drag isn't prematurely canceled.
1206  if (detach_into_browser_) {
1207    attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_);
1208    attached_tabstrip_->OwnDragController(this);
1209  }
1210
1211  // Redirect all mouse events to the TabStrip so that the tab that originated
1212  // the drag can safely be deleted.
1213  if (detach_into_browser_ || attached_tabstrip_ == source_tabstrip_) {
1214    static_cast<views::internal::RootView*>(
1215        attached_tabstrip_->GetWidget()->GetRootView())->SetMouseHandler(
1216            attached_tabstrip_);
1217  }
1218}
1219
1220void TabDragController::Detach(ReleaseCapture release_capture) {
1221  // When the user detaches we assume they want to reorder.
1222  move_behavior_ = REORDER;
1223
1224  // Release ownership of the drag controller and mouse capture. When we
1225  // reattach ownership is transfered.
1226  if (detach_into_browser_) {
1227    attached_tabstrip_->ReleaseDragController();
1228    if (release_capture == RELEASE_CAPTURE)
1229      attached_tabstrip_->GetWidget()->ReleaseCapture();
1230  }
1231
1232  mouse_move_direction_ = kMovedMouseLeft | kMovedMouseRight;
1233
1234  // Prevent the WebContents HWND from being hidden by any of the model
1235  // operations performed during the drag.
1236  if (!detach_into_browser_)
1237    source_dragged_contents()->IncrementCapturerCount();
1238
1239  std::vector<gfx::Rect> drag_bounds = CalculateBoundsForDraggedTabs(0);
1240  TabStripModel* attached_model = GetModel(attached_tabstrip_);
1241  std::vector<TabRendererData> tab_data;
1242  for (size_t i = 0; i < drag_data_.size(); ++i) {
1243    tab_data.push_back(drag_data_[i].attached_tab->data());
1244    int index = attached_model->GetIndexOfWebContents(drag_data_[i].contents);
1245    DCHECK_NE(-1, index);
1246
1247    // Hide the tab so that the user doesn't see it animate closed.
1248    drag_data_[i].attached_tab->SetVisible(false);
1249
1250    attached_model->DetachWebContentsAt(index);
1251
1252    // Detaching resets the delegate, but we still want to be the delegate.
1253    if (!detach_into_browser_)
1254      drag_data_[i].contents->SetDelegate(this);
1255
1256    // Detaching may end up deleting the tab, drop references to it.
1257    drag_data_[i].attached_tab = NULL;
1258  }
1259
1260  // If we've removed the last Tab from the TabStrip, hide the frame now.
1261  if (!attached_model->empty()) {
1262    if (!selection_model_before_attach_.empty() &&
1263        selection_model_before_attach_.active() >= 0 &&
1264        selection_model_before_attach_.active() < attached_model->count()) {
1265      // Restore the selection.
1266      attached_model->SetSelectionFromModel(selection_model_before_attach_);
1267    } else if (attached_tabstrip_ == source_tabstrip_ &&
1268               !initial_selection_model_.empty()) {
1269      // First time detaching from the source tabstrip. Reset selection model to
1270      // initial_selection_model_. Before resetting though we have to remove all
1271      // the tabs from initial_selection_model_ as it was created with the tabs
1272      // still there.
1273      ui::ListSelectionModel selection_model;
1274      selection_model.Copy(initial_selection_model_);
1275      for (DragData::const_reverse_iterator i(drag_data_.rbegin());
1276           i != drag_data_.rend(); ++i) {
1277        selection_model.DecrementFrom(i->source_model_index);
1278      }
1279      // We may have cleared out the selection model. Only reset it if it
1280      // contains something.
1281      if (!selection_model.empty())
1282        attached_model->SetSelectionFromModel(selection_model);
1283    }
1284  } else if (!detach_into_browser_) {
1285    HideFrame();
1286  }
1287
1288  // Create the dragged view.
1289  if (!detach_into_browser_)
1290    CreateDraggedView(tab_data, drag_bounds);
1291
1292  attached_tabstrip_->DraggedTabsDetached();
1293  attached_tabstrip_ = NULL;
1294}
1295
1296void TabDragController::DetachIntoNewBrowserAndRunMoveLoop(
1297    const gfx::Point& point_in_screen) {
1298  if (GetModel(attached_tabstrip_)->count() ==
1299      static_cast<int>(drag_data_.size())) {
1300    // All the tabs in a browser are being dragged but all the tabs weren't
1301    // initially being dragged. For this to happen the user would have to
1302    // start dragging a set of tabs, the other tabs close, then detach.
1303    RunMoveLoop(GetWindowOffset(point_in_screen));
1304    return;
1305  }
1306
1307  // Create a new browser to house the dragged tabs and have the OS run a move
1308  // loop.
1309
1310  gfx::Point attached_point = GetAttachedDragPoint(point_in_screen);
1311
1312  // Calculate the bounds for the tabs from the attached_tab_strip. We do this
1313  // so that the tabs don't change size when detached.
1314  std::vector<gfx::Rect> drag_bounds =
1315      CalculateBoundsForDraggedTabs(attached_point.x());
1316
1317  gfx::Vector2d drag_offset;
1318  Browser* browser = CreateBrowserForDrag(
1319      attached_tabstrip_, point_in_screen, &drag_offset, &drag_bounds);
1320  Detach(DONT_RELEASE_CAPTURE);
1321  BrowserView* dragged_browser_view =
1322      BrowserView::GetBrowserViewForBrowser(browser);
1323  dragged_browser_view->GetWidget()->SetVisibilityChangedAnimationsEnabled(
1324      false);
1325  Attach(dragged_browser_view->tabstrip(), gfx::Point());
1326  // TODO: come up with a cleaner way to do this.
1327  attached_tabstrip_->SetTabBoundsForDrag(drag_bounds);
1328
1329  WindowPositionManagedUpdater updater;
1330  dragged_browser_view->GetWidget()->AddObserver(&updater);
1331  browser->window()->Show();
1332  dragged_browser_view->GetWidget()->RemoveObserver(&updater);
1333
1334  browser->window()->Activate();
1335  dragged_browser_view->GetWidget()->SetVisibilityChangedAnimationsEnabled(
1336      true);
1337  RunMoveLoop(drag_offset);
1338}
1339
1340void TabDragController::RunMoveLoop(const gfx::Vector2d& drag_offset) {
1341  // If the user drags the whole window we'll assume they are going to attach to
1342  // another window and therefor want to reorder.
1343  move_behavior_ = REORDER;
1344
1345  move_loop_widget_ = GetAttachedBrowserWidget();
1346  DCHECK(move_loop_widget_);
1347  SetTrackedByWorkspace(move_loop_widget_->GetNativeView(), false);
1348  move_loop_widget_->AddObserver(this);
1349  is_dragging_window_ = true;
1350  bool destroyed = false;
1351  destroyed_ = &destroyed;
1352  // Running the move loop releases mouse capture on non-ash, which triggers
1353  // destroying the drag loop. Release mouse capture ourself before this while
1354  // the DragController isn't owned by the TabStrip.
1355  if (host_desktop_type_ != chrome::HOST_DESKTOP_TYPE_ASH) {
1356    attached_tabstrip_->ReleaseDragController();
1357    attached_tabstrip_->GetWidget()->ReleaseCapture();
1358    attached_tabstrip_->OwnDragController(this);
1359  }
1360  const views::Widget::MoveLoopSource move_loop_source =
1361      event_source_ == EVENT_SOURCE_MOUSE ?
1362      views::Widget::MOVE_LOOP_SOURCE_MOUSE :
1363      views::Widget::MOVE_LOOP_SOURCE_TOUCH;
1364  views::Widget::MoveLoopResult result =
1365      move_loop_widget_->RunMoveLoop(drag_offset, move_loop_source);
1366  content::NotificationService::current()->Notify(
1367      chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE,
1368      content::NotificationService::AllBrowserContextsAndSources(),
1369      content::NotificationService::NoDetails());
1370
1371  if (destroyed)
1372    return;
1373  destroyed_ = NULL;
1374  // Under chromeos we immediately set the |move_loop_widget_| to NULL.
1375  if (move_loop_widget_) {
1376    move_loop_widget_->RemoveObserver(this);
1377    move_loop_widget_ = NULL;
1378  }
1379  is_dragging_window_ = false;
1380  waiting_for_run_loop_to_exit_ = false;
1381  if (end_run_loop_behavior_ == END_RUN_LOOP_CONTINUE_DRAGGING) {
1382    end_run_loop_behavior_ = END_RUN_LOOP_STOP_DRAGGING;
1383    if (tab_strip_to_attach_to_after_exit_) {
1384      gfx::Point point_in_screen(GetCursorScreenPoint());
1385      Detach(DONT_RELEASE_CAPTURE);
1386      Attach(tab_strip_to_attach_to_after_exit_, point_in_screen);
1387      // Move the tabs into position.
1388      MoveAttached(point_in_screen);
1389      attached_tabstrip_->GetWidget()->Activate();
1390      tab_strip_to_attach_to_after_exit_ = NULL;
1391    }
1392    DCHECK(attached_tabstrip_);
1393    attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_);
1394  } else if (active_) {
1395    EndDrag(result == views::Widget::MOVE_LOOP_CANCELED ?
1396            END_DRAG_CANCEL : END_DRAG_COMPLETE);
1397  }
1398}
1399
1400int TabDragController::GetInsertionIndexFrom(const gfx::Rect& dragged_bounds,
1401                                             int start,
1402                                             int delta) const {
1403  for (int i = start, tab_count = attached_tabstrip_->tab_count();
1404       i >= 0 && i < tab_count; i += delta) {
1405    const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i);
1406    gfx::Rect left_half, right_half;
1407    ideal_bounds.SplitVertically(&left_half, &right_half);
1408    if (dragged_bounds.x() >= right_half.x() &&
1409        dragged_bounds.x() < right_half.right()) {
1410      return i + 1;
1411    } else if (dragged_bounds.x() >= left_half.x() &&
1412               dragged_bounds.x() < left_half.right()) {
1413      return i;
1414    }
1415  }
1416  return -1;
1417}
1418
1419int TabDragController::GetInsertionIndexForDraggedBounds(
1420    const gfx::Rect& dragged_bounds) const {
1421  int index = -1;
1422  if (attached_tabstrip_->touch_layout_.get()) {
1423    index = GetInsertionIndexForDraggedBoundsStacked(dragged_bounds);
1424    if (index != -1) {
1425      // Only move the tab to the left/right if the user actually moved the
1426      // mouse that way. This is necessary as tabs with stacked tabs
1427      // before/after them have multiple drag positions.
1428      int active_index = attached_tabstrip_->touch_layout_->active_index();
1429      if ((index < active_index &&
1430           (mouse_move_direction_ & kMovedMouseLeft) == 0) ||
1431          (index > active_index &&
1432           (mouse_move_direction_ & kMovedMouseRight) == 0)) {
1433        index = active_index;
1434      }
1435    }
1436  } else {
1437    index = GetInsertionIndexFrom(dragged_bounds, 0, 1);
1438  }
1439  if (index == -1) {
1440    int tab_count = attached_tabstrip_->tab_count();
1441    int right_tab_x = tab_count == 0 ? 0 :
1442        attached_tabstrip_->ideal_bounds(tab_count - 1).right();
1443    if (dragged_bounds.right() > right_tab_x) {
1444      index = GetModel(attached_tabstrip_)->count();
1445    } else {
1446      index = 0;
1447    }
1448  }
1449
1450  if (!drag_data_[0].attached_tab) {
1451    // If 'attached_tab' is NULL, it means we're in the process of attaching and
1452    // don't need to constrain the index.
1453    return index;
1454  }
1455
1456  int max_index = GetModel(attached_tabstrip_)->count() -
1457      static_cast<int>(drag_data_.size());
1458  return std::max(0, std::min(max_index, index));
1459}
1460
1461bool TabDragController::ShouldDragToNextStackedTab(
1462    const gfx::Rect& dragged_bounds,
1463    int index) const {
1464  if (index + 1 >= attached_tabstrip_->tab_count() ||
1465      !attached_tabstrip_->touch_layout_->IsStacked(index + 1) ||
1466      (mouse_move_direction_ & kMovedMouseRight) == 0)
1467    return false;
1468
1469  int active_x = attached_tabstrip_->ideal_bounds(index).x();
1470  int next_x = attached_tabstrip_->ideal_bounds(index + 1).x();
1471  int mid_x = std::min(next_x - kStackedDistance,
1472                       active_x + (next_x - active_x) / 4);
1473  return dragged_bounds.x() >= mid_x;
1474}
1475
1476bool TabDragController::ShouldDragToPreviousStackedTab(
1477    const gfx::Rect& dragged_bounds,
1478    int index) const {
1479  if (index - 1 < attached_tabstrip_->GetMiniTabCount() ||
1480      !attached_tabstrip_->touch_layout_->IsStacked(index - 1) ||
1481      (mouse_move_direction_ & kMovedMouseLeft) == 0)
1482    return false;
1483
1484  int active_x = attached_tabstrip_->ideal_bounds(index).x();
1485  int previous_x = attached_tabstrip_->ideal_bounds(index - 1).x();
1486  int mid_x = std::max(previous_x + kStackedDistance,
1487                       active_x - (active_x - previous_x) / 4);
1488  return dragged_bounds.x() <= mid_x;
1489}
1490
1491int TabDragController::GetInsertionIndexForDraggedBoundsStacked(
1492    const gfx::Rect& dragged_bounds) const {
1493  StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get();
1494  int active_index = touch_layout->active_index();
1495  // Search from the active index to the front of the tabstrip. Do this as tabs
1496  // overlap each other from the active index.
1497  int index = GetInsertionIndexFrom(dragged_bounds, active_index, -1);
1498  if (index != active_index)
1499    return index;
1500  if (index == -1)
1501    return GetInsertionIndexFrom(dragged_bounds, active_index + 1, 1);
1502
1503  // The position to drag to corresponds to the active tab. If the next/previous
1504  // tab is stacked, then shorten the distance used to determine insertion
1505  // bounds. We do this as GetInsertionIndexFrom() uses the bounds of the
1506  // tabs. When tabs are stacked the next/previous tab is on top of the tab.
1507  if (active_index + 1 < attached_tabstrip_->tab_count() &&
1508      touch_layout->IsStacked(active_index + 1)) {
1509    index = GetInsertionIndexFrom(dragged_bounds, active_index + 1, 1);
1510    if (index == -1 && ShouldDragToNextStackedTab(dragged_bounds, active_index))
1511      index = active_index + 1;
1512    else if (index == -1)
1513      index = active_index;
1514  } else if (ShouldDragToPreviousStackedTab(dragged_bounds, active_index)) {
1515    index = active_index - 1;
1516  }
1517  return index;
1518}
1519
1520gfx::Rect TabDragController::GetDraggedViewTabStripBounds(
1521    const gfx::Point& tab_strip_point) {
1522  // attached_tab is NULL when inserting into a new tabstrip.
1523  if (source_tab_drag_data()->attached_tab) {
1524    return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1525                     source_tab_drag_data()->attached_tab->width(),
1526                     source_tab_drag_data()->attached_tab->height());
1527  }
1528
1529  double sel_width, unselected_width;
1530  attached_tabstrip_->GetCurrentTabWidths(&sel_width, &unselected_width);
1531  return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1532                   static_cast<int>(sel_width),
1533                   Tab::GetStandardSize().height());
1534}
1535
1536gfx::Point TabDragController::GetAttachedDragPoint(
1537    const gfx::Point& point_in_screen) {
1538  DCHECK(attached_tabstrip_);  // The tab must be attached.
1539
1540  gfx::Point tab_loc(point_in_screen);
1541  views::View::ConvertPointToTarget(NULL, attached_tabstrip_, &tab_loc);
1542  int x =
1543      attached_tabstrip_->GetMirroredXInView(tab_loc.x()) - mouse_offset_.x();
1544
1545  // TODO: consider caching this.
1546  std::vector<Tab*> attached_tabs;
1547  for (size_t i = 0; i < drag_data_.size(); ++i)
1548    attached_tabs.push_back(drag_data_[i].attached_tab);
1549  int size = attached_tabstrip_->GetSizeNeededForTabs(attached_tabs);
1550  int max_x = attached_tabstrip_->width() - size;
1551  return gfx::Point(std::min(std::max(x, 0), max_x), 0);
1552}
1553
1554std::vector<Tab*> TabDragController::GetTabsMatchingDraggedContents(
1555    TabStrip* tabstrip) {
1556  TabStripModel* model = GetModel(attached_tabstrip_);
1557  std::vector<Tab*> tabs;
1558  for (size_t i = 0; i < drag_data_.size(); ++i) {
1559    int model_index = model->GetIndexOfWebContents(drag_data_[i].contents);
1560    if (model_index == TabStripModel::kNoTab)
1561      return std::vector<Tab*>();
1562    tabs.push_back(tabstrip->tab_at(model_index));
1563  }
1564  return tabs;
1565}
1566
1567std::vector<gfx::Rect> TabDragController::CalculateBoundsForDraggedTabs(
1568    int x_offset) {
1569  std::vector<gfx::Rect> drag_bounds;
1570  std::vector<Tab*> attached_tabs;
1571  for (size_t i = 0; i < drag_data_.size(); ++i)
1572    attached_tabs.push_back(drag_data_[i].attached_tab);
1573  attached_tabstrip_->CalculateBoundsForDraggedTabs(attached_tabs,
1574                                                    &drag_bounds);
1575  if (x_offset != 0) {
1576    for (size_t i = 0; i < drag_bounds.size(); ++i)
1577      drag_bounds[i].set_x(drag_bounds[i].x() + x_offset);
1578  }
1579  return drag_bounds;
1580}
1581
1582void TabDragController::EndDragImpl(EndDragType type) {
1583  DCHECK(active_);
1584  active_ = false;
1585
1586  bring_to_front_timer_.Stop();
1587  move_stacked_timer_.Stop();
1588
1589  if (is_dragging_window_) {
1590    // SetTrackedByWorkspace() may call us back (by way of the window bounds
1591    // changing). Set |waiting_for_run_loop_to_exit_| here so that if that
1592    // happens we ignore it.
1593    waiting_for_run_loop_to_exit_ = true;
1594
1595    if (type == NORMAL || (type == TAB_DESTROYED && drag_data_.size() > 1)) {
1596      SetTrackedByWorkspace(GetAttachedBrowserWidget()->GetNativeView(), true);
1597      SetWindowPositionManaged(GetAttachedBrowserWidget()->GetNativeView(),
1598                               true);
1599    }
1600
1601    // End the nested drag loop.
1602    GetAttachedBrowserWidget()->EndMoveLoop();
1603  }
1604
1605  // Hide the current dock controllers.
1606  for (size_t i = 0; i < dock_controllers_.size(); ++i) {
1607    // Be sure and clear the controller first, that way if Hide ends up
1608    // deleting the controller it won't call us back.
1609    dock_controllers_[i]->clear_controller();
1610    dock_controllers_[i]->Hide();
1611  }
1612  dock_controllers_.clear();
1613  dock_windows_.clear();
1614
1615  if (type != TAB_DESTROYED) {
1616    // We only finish up the drag if we were actually dragging. If start_drag_
1617    // is false, the user just clicked and released and didn't move the mouse
1618    // enough to trigger a drag.
1619    if (started_drag_) {
1620      RestoreFocus();
1621      if (type == CANCELED)
1622        RevertDrag();
1623      else
1624        CompleteDrag();
1625    }
1626  } else if (drag_data_.size() > 1) {
1627    RevertDrag();
1628  }  // else case the only tab we were dragging was deleted. Nothing to do.
1629
1630  if (!detach_into_browser_)
1631    ResetDelegates();
1632
1633  // Clear out drag data so we don't attempt to do anything with it.
1634  drag_data_.clear();
1635
1636  TabStrip* owning_tabstrip = (attached_tabstrip_ && detach_into_browser_) ?
1637      attached_tabstrip_ : source_tabstrip_;
1638  owning_tabstrip->DestroyDragController();
1639}
1640
1641void TabDragController::RevertDrag() {
1642  std::vector<Tab*> tabs;
1643  for (size_t i = 0; i < drag_data_.size(); ++i) {
1644    if (drag_data_[i].contents) {
1645      // Contents is NULL if a tab was destroyed while the drag was under way.
1646      tabs.push_back(drag_data_[i].attached_tab);
1647      RevertDragAt(i);
1648    }
1649  }
1650
1651  bool restore_frame = !detach_into_browser_ &&
1652                       attached_tabstrip_ != source_tabstrip_;
1653  if (attached_tabstrip_) {
1654    if (attached_tabstrip_ == source_tabstrip_) {
1655      source_tabstrip_->StoppedDraggingTabs(
1656          tabs, initial_tab_positions_, move_behavior_ == MOVE_VISIBILE_TABS,
1657          false);
1658    } else {
1659      attached_tabstrip_->DraggedTabsDetached();
1660    }
1661  }
1662
1663  if (initial_selection_model_.empty())
1664    ResetSelection(GetModel(source_tabstrip_));
1665  else
1666    GetModel(source_tabstrip_)->SetSelectionFromModel(initial_selection_model_);
1667
1668  // If we're not attached to any TabStrip, or attached to some other TabStrip,
1669  // we need to restore the bounds of the original TabStrip's frame, in case
1670  // it has been hidden.
1671  if (restore_frame && !restore_bounds_.IsEmpty())
1672    source_tabstrip_->GetWidget()->SetBounds(restore_bounds_);
1673
1674  if (detach_into_browser_ && source_tabstrip_)
1675    source_tabstrip_->GetWidget()->Activate();
1676
1677  // Return the WebContents to normalcy.  If the tab was attached to a
1678  // TabStrip before the revert, the decrement has already occurred.
1679  // If the tab was destroyed, don't attempt to dereference the
1680  // WebContents pointer.
1681  if (!detach_into_browser_ && !attached_tabstrip_ && source_dragged_contents())
1682    source_dragged_contents()->DecrementCapturerCount();
1683}
1684
1685void TabDragController::ResetSelection(TabStripModel* model) {
1686  DCHECK(model);
1687  ui::ListSelectionModel selection_model;
1688  bool has_one_valid_tab = false;
1689  for (size_t i = 0; i < drag_data_.size(); ++i) {
1690    // |contents| is NULL if a tab was deleted out from under us.
1691    if (drag_data_[i].contents) {
1692      int index = model->GetIndexOfWebContents(drag_data_[i].contents);
1693      DCHECK_NE(-1, index);
1694      selection_model.AddIndexToSelection(index);
1695      if (!has_one_valid_tab || i == source_tab_index_) {
1696        // Reset the active/lead to the first tab. If the source tab is still
1697        // valid we'll reset these again later on.
1698        selection_model.set_active(index);
1699        selection_model.set_anchor(index);
1700        has_one_valid_tab = true;
1701      }
1702    }
1703  }
1704  if (!has_one_valid_tab)
1705    return;
1706
1707  model->SetSelectionFromModel(selection_model);
1708}
1709
1710void TabDragController::RevertDragAt(size_t drag_index) {
1711  DCHECK(started_drag_);
1712  DCHECK(source_tabstrip_);
1713
1714  base::AutoReset<bool> setter(&is_mutating_, true);
1715  TabDragData* data = &(drag_data_[drag_index]);
1716  if (attached_tabstrip_) {
1717    int index =
1718        GetModel(attached_tabstrip_)->GetIndexOfWebContents(data->contents);
1719    if (attached_tabstrip_ != source_tabstrip_) {
1720      // The Tab was inserted into another TabStrip. We need to put it back
1721      // into the original one.
1722      GetModel(attached_tabstrip_)->DetachWebContentsAt(index);
1723      // TODO(beng): (Cleanup) seems like we should use Attach() for this
1724      //             somehow.
1725      GetModel(source_tabstrip_)->InsertWebContentsAt(
1726          data->source_model_index, data->contents,
1727          (data->pinned ? TabStripModel::ADD_PINNED : 0));
1728    } else {
1729      // The Tab was moved within the TabStrip where the drag was initiated.
1730      // Move it back to the starting location.
1731      GetModel(source_tabstrip_)->MoveWebContentsAt(
1732          index, data->source_model_index, false);
1733    }
1734  } else {
1735    // The Tab was detached from the TabStrip where the drag began, and has not
1736    // been attached to any other TabStrip. We need to put it back into the
1737    // source TabStrip.
1738    GetModel(source_tabstrip_)->InsertWebContentsAt(
1739        data->source_model_index, data->contents,
1740        (data->pinned ? TabStripModel::ADD_PINNED : 0));
1741  }
1742}
1743
1744void TabDragController::CompleteDrag() {
1745  DCHECK(started_drag_);
1746
1747  if (attached_tabstrip_) {
1748    attached_tabstrip_->StoppedDraggingTabs(
1749        GetTabsMatchingDraggedContents(attached_tabstrip_),
1750        initial_tab_positions_,
1751        move_behavior_ == MOVE_VISIBILE_TABS,
1752        true);
1753  } else {
1754    if (dock_info_.type() != DockInfo::NONE) {
1755      switch (dock_info_.type()) {
1756        case DockInfo::LEFT_OF_WINDOW:
1757          content::RecordAction(UserMetricsAction("DockingWindow_Left"));
1758          break;
1759
1760        case DockInfo::RIGHT_OF_WINDOW:
1761          content::RecordAction(UserMetricsAction("DockingWindow_Right"));
1762          break;
1763
1764        case DockInfo::BOTTOM_OF_WINDOW:
1765          content::RecordAction(UserMetricsAction("DockingWindow_Bottom"));
1766          break;
1767
1768        case DockInfo::TOP_OF_WINDOW:
1769          content::RecordAction(UserMetricsAction("DockingWindow_Top"));
1770          break;
1771
1772        case DockInfo::MAXIMIZE:
1773          content::RecordAction(
1774              UserMetricsAction("DockingWindow_Maximize"));
1775          break;
1776
1777        case DockInfo::LEFT_HALF:
1778          content::RecordAction(
1779              UserMetricsAction("DockingWindow_LeftHalf"));
1780          break;
1781
1782        case DockInfo::RIGHT_HALF:
1783          content::RecordAction(
1784              UserMetricsAction("DockingWindow_RightHalf"));
1785          break;
1786
1787        case DockInfo::BOTTOM_HALF:
1788          content::RecordAction(
1789              UserMetricsAction("DockingWindow_BottomHalf"));
1790          break;
1791
1792        default:
1793          NOTREACHED();
1794          break;
1795      }
1796    }
1797    // Compel the model to construct a new window for the detached
1798    // WebContentses.
1799    views::Widget* widget = source_tabstrip_->GetWidget();
1800    gfx::Rect window_bounds(widget->GetRestoredBounds());
1801    window_bounds.set_origin(GetWindowCreatePoint(last_point_in_screen_));
1802
1803    // When modifying the following if statement, please make sure not to
1804    // introduce issue listed in http://crbug.com/6223 comment #11.
1805    bool rtl_ui = base::i18n::IsRTL();
1806    bool has_dock_position = (dock_info_.type() != DockInfo::NONE);
1807    if (rtl_ui && has_dock_position) {
1808      // Mirror X axis so the docked tab is aligned using the mouse click as
1809      // the top-right corner.
1810      window_bounds.set_x(window_bounds.x() - window_bounds.width());
1811    }
1812    base::AutoReset<bool> setter(&is_mutating_, true);
1813
1814    std::vector<TabStripModelDelegate::NewStripContents> contentses;
1815    for (size_t i = 0; i < drag_data_.size(); ++i) {
1816      TabStripModelDelegate::NewStripContents item;
1817      item.web_contents = drag_data_[i].contents;
1818      item.add_types = drag_data_[i].pinned ? TabStripModel::ADD_PINNED
1819                                            : TabStripModel::ADD_NONE;
1820      contentses.push_back(item);
1821    };
1822
1823    Browser* new_browser =
1824        GetModel(source_tabstrip_)->delegate()->CreateNewStripWithContents(
1825            contentses, window_bounds, dock_info_, widget->IsMaximized());
1826    ResetSelection(new_browser->tab_strip_model());
1827    new_browser->window()->Show();
1828
1829    // Return the WebContents to normalcy.
1830    if (!detach_into_browser_)
1831      source_dragged_contents()->DecrementCapturerCount();
1832  }
1833
1834  CleanUpHiddenFrame();
1835}
1836
1837void TabDragController::ResetDelegates() {
1838  DCHECK(!detach_into_browser_);
1839  for (size_t i = 0; i < drag_data_.size(); ++i) {
1840    if (drag_data_[i].contents &&
1841        drag_data_[i].contents->GetDelegate() == this) {
1842      drag_data_[i].contents->SetDelegate(
1843          drag_data_[i].original_delegate);
1844    }
1845  }
1846}
1847
1848void TabDragController::CreateDraggedView(
1849    const std::vector<TabRendererData>& data,
1850    const std::vector<gfx::Rect>& renderer_bounds) {
1851#if !defined(USE_AURA)
1852  DCHECK(!view_.get());
1853  DCHECK_EQ(data.size(), drag_data_.size());
1854
1855  // Set up the photo booth to start capturing the contents of the dragged
1856  // WebContents.
1857  NativeViewPhotobooth* photobooth = NativeViewPhotobooth::Create(
1858      source_dragged_contents()->GetView()->GetNativeView());
1859
1860  gfx::Rect content_bounds;
1861  source_dragged_contents()->GetView()->GetContainerBounds(&content_bounds);
1862
1863  std::vector<views::View*> renderers;
1864  for (size_t i = 0; i < drag_data_.size(); ++i) {
1865    Tab* renderer = source_tabstrip_->CreateTabForDragging();
1866    renderer->SetData(data[i]);
1867    renderers.push_back(renderer);
1868  }
1869  // DraggedTabView takes ownership of the renderers.
1870  view_.reset(new DraggedTabView(renderers, renderer_bounds, mouse_offset_,
1871                                 content_bounds.size(), photobooth));
1872#else
1873  // Aura always hits the |detach_into_browser_| path.
1874  NOTREACHED();
1875#endif
1876}
1877
1878gfx::Rect TabDragController::GetViewScreenBounds(
1879    views::View* view) const {
1880  gfx::Point view_topleft;
1881  views::View::ConvertPointToScreen(view, &view_topleft);
1882  gfx::Rect view_screen_bounds = view->GetLocalBounds();
1883  view_screen_bounds.Offset(view_topleft.x(), view_topleft.y());
1884  return view_screen_bounds;
1885}
1886
1887void TabDragController::HideFrame() {
1888#if defined(OS_WIN) && !defined(USE_AURA)
1889  // We don't actually hide the window, rather we just move it way off-screen.
1890  // If we actually hide it, we stop receiving drag events.
1891  //
1892  // Windows coordinates are 16 bit values. Additionally mouse events are
1893  // relative, this means if we move this window to the max position it is easy
1894  // to trigger overflow. To avoid this we don't move to the max position,
1895  // rather some where reasonably large. This should avoid common overflow
1896  // problems.
1897  // An alternative approach is to query the mouse pointer and ignore the
1898  // location on the mouse (early versions did this). This proves problematic as
1899  // if we happen to get behind in event processing it is all to easy to process
1900  // a release in the wrong location, triggering either an unexpected move or an
1901  // unexpected detach.
1902  HWND frame_hwnd = source_tabstrip_->GetWidget()->GetNativeView();
1903  RECT wr;
1904  GetWindowRect(frame_hwnd, &wr);
1905  MoveWindow(frame_hwnd, 0x3FFF, 0x3FFF, wr.right - wr.left,
1906             wr.bottom - wr.top, TRUE);
1907
1908  // We also save the bounds of the window prior to it being moved, so that if
1909  // the drag session is aborted we can restore them.
1910  restore_bounds_ = gfx::Rect(wr);
1911#else
1912  // Shouldn't hit as aura triggers the |detach_into_browser_| path.
1913  NOTREACHED();
1914#endif
1915}
1916
1917void TabDragController::CleanUpHiddenFrame() {
1918  // If the model we started dragging from is now empty, we must ask the
1919  // delegate to close the frame.
1920  if (!detach_into_browser_ && GetModel(source_tabstrip_)->empty())
1921    GetModel(source_tabstrip_)->delegate()->CloseFrameAfterDragSession();
1922}
1923
1924void TabDragController::DockDisplayerDestroyed(
1925    DockDisplayer* controller) {
1926  DockWindows::iterator dock_i =
1927      dock_windows_.find(controller->popup_view());
1928  if (dock_i != dock_windows_.end())
1929    dock_windows_.erase(dock_i);
1930  else
1931    NOTREACHED();
1932
1933  std::vector<DockDisplayer*>::iterator i =
1934      std::find(dock_controllers_.begin(), dock_controllers_.end(),
1935                controller);
1936  if (i != dock_controllers_.end())
1937    dock_controllers_.erase(i);
1938  else
1939    NOTREACHED();
1940}
1941
1942void TabDragController::BringWindowUnderPointToFront(
1943    const gfx::Point& point_in_screen) {
1944  // If we're going to dock to another window, bring it to the front.
1945  gfx::NativeWindow window = dock_info_.window();
1946  if (!window) {
1947    views::View* dragged_view;
1948    if (view_.get())
1949      dragged_view = view_.get();
1950    else
1951      dragged_view = attached_tabstrip_;
1952    gfx::NativeView dragged_native_view =
1953        dragged_view->GetWidget()->GetNativeView();
1954    dock_windows_.insert(dragged_native_view);
1955    window = DockInfo::GetLocalProcessWindowAtPoint(
1956        host_desktop_type_,
1957        point_in_screen,
1958        dock_windows_);
1959    dock_windows_.erase(dragged_native_view);
1960  }
1961  if (window) {
1962    views::Widget* widget_window = views::Widget::GetWidgetForNativeView(
1963        window);
1964    if (widget_window)
1965      widget_window->StackAtTop();
1966    else
1967      return;
1968
1969    // The previous call made the window appear on top of the dragged window,
1970    // move the dragged window to the front.
1971    if (view_.get())
1972      view_->GetWidget()->StackAtTop();
1973    else if (is_dragging_window_)
1974      attached_tabstrip_->GetWidget()->StackAtTop();
1975  }
1976}
1977
1978TabStripModel* TabDragController::GetModel(
1979    TabStrip* tabstrip) const {
1980  return static_cast<BrowserTabStripController*>(tabstrip->controller())->
1981      model();
1982}
1983
1984views::Widget* TabDragController::GetAttachedBrowserWidget() {
1985  return attached_tabstrip_->GetWidget();
1986}
1987
1988bool TabDragController::AreTabsConsecutive() {
1989  for (size_t i = 1; i < drag_data_.size(); ++i) {
1990    if (drag_data_[i - 1].source_model_index + 1 !=
1991        drag_data_[i].source_model_index) {
1992      return false;
1993    }
1994  }
1995  return true;
1996}
1997
1998Browser* TabDragController::CreateBrowserForDrag(
1999    TabStrip* source,
2000    const gfx::Point& point_in_screen,
2001    gfx::Vector2d* drag_offset,
2002    std::vector<gfx::Rect>* drag_bounds) {
2003  gfx::Point center(0, source->height() / 2);
2004  views::View::ConvertPointToWidget(source, &center);
2005  gfx::Rect new_bounds(source->GetWidget()->GetWindowBoundsInScreen());
2006  new_bounds.set_y(point_in_screen.y() - center.y());
2007  switch (GetDetachPosition(point_in_screen)) {
2008    case DETACH_BEFORE:
2009      new_bounds.set_x(point_in_screen.x() - center.x());
2010      new_bounds.Offset(-mouse_offset_.x(), 0);
2011      break;
2012
2013    case DETACH_AFTER: {
2014      gfx::Point right_edge(source->width(), 0);
2015      views::View::ConvertPointToWidget(source, &right_edge);
2016      new_bounds.set_x(point_in_screen.x() - right_edge.x());
2017      new_bounds.Offset(drag_bounds->back().right() - mouse_offset_.x(), 0);
2018      int delta = (*drag_bounds)[0].x();
2019      for (size_t i = 0; i < drag_bounds->size(); ++i)
2020        (*drag_bounds)[i].Offset(-delta, 0);
2021      break;
2022    }
2023
2024    default:
2025      break; // Nothing to do for DETACH_ABOVE_OR_BELOW.
2026  }
2027
2028  *drag_offset = point_in_screen - new_bounds.origin();
2029
2030  Profile* profile =
2031      Profile::FromBrowserContext(drag_data_[0].contents->GetBrowserContext());
2032  Browser::CreateParams create_params(Browser::TYPE_TABBED,
2033                                      profile,
2034                                      host_desktop_type_);
2035  create_params.initial_bounds = new_bounds;
2036  Browser* browser = new Browser(create_params);
2037  SetTrackedByWorkspace(browser->window()->GetNativeWindow(), false);
2038  SetWindowPositionManaged(browser->window()->GetNativeWindow(), false);
2039  // If the window is created maximized then the bounds we supplied are ignored.
2040  // We need to reset them again so they are honored.
2041  browser->window()->SetBounds(new_bounds);
2042  return browser;
2043}
2044
2045gfx::Point TabDragController::GetCursorScreenPoint() {
2046#if defined(USE_ASH)
2047  if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH &&
2048      event_source_ == EVENT_SOURCE_TOUCH &&
2049      aura::Env::GetInstance()->is_touch_down()) {
2050    views::Widget* widget = GetAttachedBrowserWidget();
2051    DCHECK(widget);
2052    aura::Window* widget_window = widget->GetNativeWindow();
2053    DCHECK(widget_window->GetRootWindow());
2054    gfx::Point touch_point;
2055    bool got_touch_point = widget_window->GetRootWindow()->
2056        gesture_recognizer()->GetLastTouchPointForTarget(widget_window,
2057                                                         &touch_point);
2058    DCHECK(got_touch_point);
2059    return touch_point;
2060  }
2061#endif
2062  return screen_->GetCursorScreenPoint();
2063}
2064
2065gfx::Vector2d TabDragController::GetWindowOffset(
2066    const gfx::Point& point_in_screen) {
2067  TabStrip* owning_tabstrip = (attached_tabstrip_ && detach_into_browser_) ?
2068      attached_tabstrip_ : source_tabstrip_;
2069  views::View* toplevel_view = owning_tabstrip->GetWidget()->GetContentsView();
2070
2071  gfx::Point point = point_in_screen;
2072  views::View::ConvertPointFromScreen(toplevel_view, &point);
2073  return point.OffsetFromOrigin();
2074}
2075