1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/ui/views/tabs/tab_drag_controller.h"
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/chrome_notification_types.h"
15 #include "chrome/browser/extensions/extension_function_dispatcher.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/ui/app_modal_dialogs/javascript_dialog_manager.h"
18 #include "chrome/browser/ui/browser_window.h"
19 #include "chrome/browser/ui/media_utils.h"
20 #include "chrome/browser/ui/tabs/tab_strip_model.h"
21 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
22 #include "chrome/browser/ui/views/frame/browser_view.h"
23 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.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_switches.h"
28 #include "content/public/browser/invalidate_type.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/resource/resource_bundle.h"
38 #include "ui/events/event_constants.h"
39 #include "ui/events/event_utils.h"
40 #include "ui/gfx/animation/animation.h"
41 #include "ui/gfx/animation/animation_delegate.h"
42 #include "ui/gfx/animation/slide_animation.h"
43 #include "ui/gfx/canvas.h"
44 #include "ui/gfx/geometry/point_conversions.h"
45 #include "ui/gfx/image/image_skia.h"
46 #include "ui/gfx/screen.h"
47 #include "ui/views/focus/view_storage.h"
48 #include "ui/views/widget/root_view.h"
49 #include "ui/views/widget/widget.h"
52 #include "ash/accelerators/accelerator_commands.h"
53 #include "ash/wm/coordinate_conversion.h"
54 #include "ash/wm/window_state.h"
55 #include "ui/aura/env.h"
56 #include "ui/aura/root_window.h"
57 #include "ui/aura/window.h"
58 #include "ui/events/gestures/gesture_recognizer.h"
62 #include "ui/aura/window.h"
63 #include "ui/events/gestures/gesture_recognizer.h"
66 using base::UserMetricsAction
;
67 using content::OpenURLParams
;
68 using content::WebContents
;
70 static const int kHorizontalMoveThreshold
= 16; // Pixels.
72 // Distance from the next/previous stacked before before we consider the tab
73 // close enough to trigger moving.
74 static const int kStackedDistance
= 36;
76 // If non-null there is a drag underway.
77 static TabDragController
* instance_
= NULL
;
81 // Delay, in ms, during dragging before we bring a window to front.
82 const int kBringToFrontDelay
= 750;
84 // Initial delay before moving tabs when the dragged tab is close to the edge of
86 const int kMoveAttachedInitialDelay
= 600;
88 // Delay for moving tabs after the initial delay has passed.
89 const int kMoveAttachedSubsequentDelay
= 300;
91 // Radius of the rect drawn by DockView.
92 const int kRoundedRectRadius
= 4;
94 // Spacing between tab icons when DockView is showing a docking location that
95 // contains more than one tab.
96 const int kTabSpacing
= 4;
98 // DockView is the view responsible for giving a visual indicator of where a
99 // dock is going to occur.
101 class DockView
: public views::View
{
103 explicit DockView(DockInfo::Type type
) : type_(type
) {}
105 virtual gfx::Size
GetPreferredSize() OVERRIDE
{
106 return gfx::Size(DockInfo::popup_width(), DockInfo::popup_height());
109 virtual void OnPaintBackground(gfx::Canvas
* canvas
) OVERRIDE
{
110 // Fill the background rect.
112 paint
.setColor(SkColorSetRGB(108, 108, 108));
113 paint
.setStyle(SkPaint::kFill_Style
);
114 canvas
->DrawRoundRect(GetLocalBounds(), kRoundedRectRadius
, paint
);
116 ui::ResourceBundle
& rb
= ui::ResourceBundle::GetSharedInstance();
118 gfx::ImageSkia
* high_icon
= rb
.GetImageSkiaNamed(IDR_DOCK_HIGH
);
119 gfx::ImageSkia
* wide_icon
= rb
.GetImageSkiaNamed(IDR_DOCK_WIDE
);
122 bool rtl_ui
= base::i18n::IsRTL();
124 // Flip canvas to draw the mirrored tab images for RTL UI.
125 canvas
->Translate(gfx::Vector2d(width(), 0));
126 canvas
->Scale(-1, 1);
128 int x_of_active_tab
= width() / 2 + kTabSpacing
/ 2;
129 int x_of_inactive_tab
= width() / 2 - high_icon
->width() - kTabSpacing
/ 2;
131 case DockInfo::LEFT_OF_WINDOW
:
132 case DockInfo::LEFT_HALF
:
134 std::swap(x_of_active_tab
, x_of_inactive_tab
);
135 canvas
->DrawImageInt(*high_icon
, x_of_active_tab
,
136 (height() - high_icon
->height()) / 2);
137 if (type_
== DockInfo::LEFT_OF_WINDOW
) {
138 DrawImageWithAlpha(canvas
, *high_icon
, x_of_inactive_tab
,
139 (height() - high_icon
->height()) / 2);
144 case DockInfo::RIGHT_OF_WINDOW
:
145 case DockInfo::RIGHT_HALF
:
147 std::swap(x_of_active_tab
, x_of_inactive_tab
);
148 canvas
->DrawImageInt(*high_icon
, x_of_active_tab
,
149 (height() - high_icon
->height()) / 2);
150 if (type_
== DockInfo::RIGHT_OF_WINDOW
) {
151 DrawImageWithAlpha(canvas
, *high_icon
, x_of_inactive_tab
,
152 (height() - high_icon
->height()) / 2);
156 case DockInfo::TOP_OF_WINDOW
:
157 canvas
->DrawImageInt(*wide_icon
, (width() - wide_icon
->width()) / 2,
158 height() / 2 - high_icon
->height());
161 case DockInfo::MAXIMIZE
: {
162 gfx::ImageSkia
* max_icon
= rb
.GetImageSkiaNamed(IDR_DOCK_MAX
);
163 canvas
->DrawImageInt(*max_icon
, (width() - max_icon
->width()) / 2,
164 (height() - max_icon
->height()) / 2);
168 case DockInfo::BOTTOM_HALF
:
169 case DockInfo::BOTTOM_OF_WINDOW
:
170 canvas
->DrawImageInt(*wide_icon
, (width() - wide_icon
->width()) / 2,
171 height() / 2 + kTabSpacing
/ 2);
172 if (type_
== DockInfo::BOTTOM_OF_WINDOW
) {
173 DrawImageWithAlpha(canvas
, *wide_icon
,
174 (width() - wide_icon
->width()) / 2,
175 height() / 2 - kTabSpacing
/ 2 - wide_icon
->height());
187 void DrawImageWithAlpha(gfx::Canvas
* canvas
, const gfx::ImageSkia
& image
,
191 canvas
->DrawImageInt(image
, x
, y
, paint
);
194 DockInfo::Type type_
;
196 DISALLOW_COPY_AND_ASSIGN(DockView
);
199 void SetWindowPositionManaged(gfx::NativeWindow window
, bool value
) {
201 ash::wm::GetWindowState(window
)->set_window_position_managed(value
);
205 // Returns true if |tab_strip| browser window is docked.
206 bool IsDockedOrSnapped(const TabStrip
* tab_strip
) {
209 ash::wm::WindowState
* window_state
=
210 ash::wm::GetWindowState(tab_strip
->GetWidget()->GetNativeWindow());
211 return window_state
->IsDocked() ||
212 window_state
->window_show_type() == ash::wm::SHOW_TYPE_LEFT_SNAPPED
||
213 window_state
->window_show_type() == ash::wm::SHOW_TYPE_RIGHT_SNAPPED
;
218 // Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
219 // of |bounds| is adjusted by |vertical_adjustment|.
220 bool DoesRectContainVerticalPointExpanded(
221 const gfx::Rect
& bounds
,
222 int vertical_adjustment
,
224 int upper_threshold
= bounds
.bottom() + vertical_adjustment
;
225 int lower_threshold
= bounds
.y() - vertical_adjustment
;
226 return y
>= lower_threshold
&& y
<= upper_threshold
;
229 // Adds |x_offset| to all the rectangles in |rects|.
230 void OffsetX(int x_offset
, std::vector
<gfx::Rect
>* rects
) {
234 for (size_t i
= 0; i
< rects
->size(); ++i
)
235 (*rects
)[i
].set_x((*rects
)[i
].x() + x_offset
);
238 // WidgetObserver implementation that resets the window position managed
240 // We're forced to do this here since BrowserFrameAsh resets the 'window
241 // position managed' property during a show and we need the property set to
242 // false before WorkspaceLayoutManager sees the visibility change.
243 class WindowPositionManagedUpdater
: public views::WidgetObserver
{
245 virtual void OnWidgetVisibilityChanged(views::Widget
* widget
,
246 bool visible
) OVERRIDE
{
247 SetWindowPositionManaged(widget
->GetNativeView(), false);
253 ///////////////////////////////////////////////////////////////////////////////
256 // DockDisplayer is responsible for giving the user a visual indication of a
257 // possible dock position (as represented by DockInfo). DockDisplayer shows
258 // a window with a DockView in it. Two animations are used that correspond to
259 // the state of DockInfo::in_enable_area.
260 class TabDragController::DockDisplayer
: public gfx::AnimationDelegate
{
262 DockDisplayer(TabDragController
* controller
, const DockInfo
& info
)
263 : controller_(controller
),
268 in_enable_area_(info
.in_enable_area()) {
269 popup_
= new views::Widget
;
270 views::Widget::InitParams
params(views::Widget::InitParams::TYPE_POPUP
);
271 params
.opacity
= views::Widget::InitParams::TRANSLUCENT_WINDOW
;
272 params
.keep_on_top
= true;
273 params
.bounds
= info
.GetPopupRect();
274 popup_
->Init(params
);
275 popup_
->SetContentsView(new DockView(info
.type()));
276 popup_
->SetOpacity(0x00);
277 if (info
.in_enable_area())
282 popup_view_
= popup_
->GetNativeView();
285 virtual ~DockDisplayer() {
287 controller_
->DockDisplayerDestroyed(this);
290 // Updates the state based on |in_enable_area|.
291 void UpdateInEnabledArea(bool in_enable_area
) {
292 if (in_enable_area
!= in_enable_area_
) {
293 in_enable_area_
= in_enable_area
;
294 UpdateLayeredAlpha();
298 // Resets the reference to the hosting TabDragController. This is
299 // invoked when the TabDragController is destroyed.
300 void clear_controller() { controller_
= NULL
; }
302 // NativeView of the window we create.
303 gfx::NativeView
popup_view() { return popup_view_
; }
305 // Starts the hide animation. When the window is closed the
306 // TabDragController is notified by way of the DockDisplayerDestroyed
320 virtual void AnimationProgressed(const gfx::Animation
* animation
) OVERRIDE
{
321 UpdateLayeredAlpha();
324 virtual void AnimationEnded(const gfx::Animation
* animation
) OVERRIDE
{
332 void UpdateLayeredAlpha() {
333 double scale
= in_enable_area_
? 1 : .5;
334 popup_
->SetOpacity(static_cast<unsigned char>(animation_
.GetCurrentValue() *
338 // TabDragController that created us.
339 TabDragController
* controller_
;
341 // Window we're showing.
342 views::Widget
* popup_
;
344 // NativeView of |popup_|. We cache this to avoid the possibility of
345 // invoking a method on popup_ after we close it.
346 gfx::NativeView popup_view_
;
348 // Animation for when first made visible.
349 gfx::SlideAnimation animation_
;
351 // Have we been hidden?
354 // Value of DockInfo::in_enable_area.
355 bool in_enable_area_
;
358 TabDragController::TabDragData::TabDragData()
360 original_delegate(NULL
),
361 source_model_index(-1),
366 TabDragController::TabDragData::~TabDragData() {
369 ///////////////////////////////////////////////////////////////////////////////
370 // TabDragController, public:
373 const int TabDragController::kTouchVerticalDetachMagnetism
= 50;
376 const int TabDragController::kVerticalDetachMagnetism
= 15;
378 TabDragController::TabDragController()
379 : detach_into_browser_(true),
380 event_source_(EVENT_SOURCE_MOUSE
),
381 source_tabstrip_(NULL
),
382 attached_tabstrip_(NULL
),
384 host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE
),
385 offset_to_width_ratio_(0),
386 old_focused_view_id_(
387 views::ViewStorage::GetInstance()->CreateStorageID()),
388 last_move_screen_loc_(0),
389 started_drag_(false),
391 source_tab_index_(std::numeric_limits
<size_t>::max()),
393 detach_behavior_(DETACHABLE
),
394 move_behavior_(REORDER
),
395 mouse_move_direction_(0),
396 is_dragging_window_(false),
397 is_dragging_new_browser_(false),
398 was_source_maximized_(false),
399 was_source_fullscreen_(false),
400 did_restore_window_(false),
401 end_run_loop_behavior_(END_RUN_LOOP_STOP_DRAGGING
),
402 waiting_for_run_loop_to_exit_(false),
403 tab_strip_to_attach_to_after_exit_(NULL
),
404 move_loop_widget_(NULL
),
408 weak_factory_(this) {
412 TabDragController::~TabDragController() {
413 views::ViewStorage::GetInstance()->RemoveView(old_focused_view_id_
);
415 if (instance_
== this)
418 if (move_loop_widget_
) {
419 move_loop_widget_
->RemoveObserver(this);
420 SetWindowPositionManaged(move_loop_widget_
->GetNativeView(), true);
423 if (source_tabstrip_
&& detach_into_browser_
)
424 GetModel(source_tabstrip_
)->RemoveObserver(this);
426 base::MessageLoopForUI::current()->RemoveObserver(this);
428 // Reset the delegate of the dragged WebContents. This ends up doing nothing
429 // if the drag was completed.
430 if (!detach_into_browser_
)
433 if (event_source_
== EVENT_SOURCE_TOUCH
) {
434 TabStrip
* capture_tabstrip
= (attached_tabstrip_
&& detach_into_browser_
) ?
435 attached_tabstrip_
: source_tabstrip_
;
436 capture_tabstrip
->GetWidget()->ReleaseCapture();
440 void TabDragController::Init(
441 TabStrip
* source_tabstrip
,
443 const std::vector
<Tab
*>& tabs
,
444 const gfx::Point
& mouse_offset
,
445 int source_tab_offset
,
446 const ui::ListSelectionModel
& initial_selection_model
,
447 DetachBehavior detach_behavior
,
448 MoveBehavior move_behavior
,
449 EventSource event_source
) {
450 DCHECK(!tabs
.empty());
451 DCHECK(std::find(tabs
.begin(), tabs
.end(), source_tab
) != tabs
.end());
452 source_tabstrip_
= source_tabstrip
;
453 was_source_maximized_
= source_tabstrip
->GetWidget()->IsMaximized();
454 was_source_fullscreen_
= source_tabstrip
->GetWidget()->IsFullscreen();
455 screen_
= gfx::Screen::GetScreenFor(
456 source_tabstrip
->GetWidget()->GetNativeView());
457 host_desktop_type_
= chrome::GetHostDesktopTypeForNativeView(
458 source_tabstrip
->GetWidget()->GetNativeView());
459 start_point_in_screen_
= gfx::Point(source_tab_offset
, mouse_offset
.y());
460 views::View::ConvertPointToScreen(source_tab
, &start_point_in_screen_
);
461 event_source_
= event_source
;
462 mouse_offset_
= mouse_offset
;
463 detach_behavior_
= detach_behavior
;
464 move_behavior_
= move_behavior
;
465 last_point_in_screen_
= start_point_in_screen_
;
466 last_move_screen_loc_
= start_point_in_screen_
.x();
467 initial_tab_positions_
= source_tabstrip
->GetTabXCoordinates();
468 if (detach_behavior
== NOT_DETACHABLE
)
469 detach_into_browser_
= false;
471 if (detach_into_browser_
)
472 GetModel(source_tabstrip_
)->AddObserver(this);
474 drag_data_
.resize(tabs
.size());
475 for (size_t i
= 0; i
< tabs
.size(); ++i
)
476 InitTabDragData(tabs
[i
], &(drag_data_
[i
]));
478 std::find(tabs
.begin(), tabs
.end(), source_tab
) - tabs
.begin();
480 // Listen for Esc key presses.
481 base::MessageLoopForUI::current()->AddObserver(this);
483 if (source_tab
->width() > 0) {
484 offset_to_width_ratio_
= static_cast<float>(
485 source_tab
->GetMirroredXInView(source_tab_offset
)) /
486 static_cast<float>(source_tab
->width());
488 InitWindowCreatePoint();
489 initial_selection_model_
.Copy(initial_selection_model
);
491 // Gestures don't automatically do a capture. We don't allow multiple drags at
492 // the same time, so we explicitly capture.
493 if (event_source
== EVENT_SOURCE_TOUCH
)
494 source_tabstrip_
->GetWidget()->SetCapture(source_tabstrip_
);
498 bool TabDragController::IsAttachedTo(const TabStrip
* tab_strip
) {
499 return (instance_
&& instance_
->active() &&
500 instance_
->attached_tabstrip() == tab_strip
);
504 bool TabDragController::IsActive() {
505 return instance_
&& instance_
->active();
508 void TabDragController::SetMoveBehavior(MoveBehavior behavior
) {
512 move_behavior_
= behavior
;
515 void TabDragController::Drag(const gfx::Point
& point_in_screen
) {
516 TRACE_EVENT1("views", "TabDragController::Drag",
517 "point_in_screen", point_in_screen
.ToString());
519 bring_to_front_timer_
.Stop();
520 move_stacked_timer_
.Stop();
522 if (waiting_for_run_loop_to_exit_
)
525 if (!started_drag_
) {
526 if (!CanStartDrag(point_in_screen
))
527 return; // User hasn't dragged far enough yet.
529 // On windows SaveFocus() may trigger a capture lost, which destroys us.
531 base::WeakPtr
<TabDragController
> ref(weak_factory_
.GetWeakPtr());
536 started_drag_
= true;
537 Attach(source_tabstrip_
, gfx::Point());
538 if (detach_into_browser_
&& static_cast<int>(drag_data_
.size()) ==
539 GetModel(source_tabstrip_
)->count()) {
540 if (was_source_maximized_
|| was_source_fullscreen_
) {
541 did_restore_window_
= true;
542 // When all tabs in a maximized browser are dragged the browser gets
543 // restored during the drag and maximized back when the drag ends.
544 views::Widget
* widget
= GetAttachedBrowserWidget();
545 const int last_tabstrip_width
= attached_tabstrip_
->tab_area_width();
546 std::vector
<gfx::Rect
> drag_bounds
= CalculateBoundsForDraggedTabs();
547 OffsetX(GetAttachedDragPoint(point_in_screen
).x(), &drag_bounds
);
548 gfx::Rect
new_bounds(CalculateDraggedBrowserBounds(source_tabstrip_
,
551 new_bounds
.Offset(-widget
->GetRestoredBounds().x() +
552 point_in_screen
.x() -
553 mouse_offset_
.x(), 0);
554 widget
->SetVisibilityChangedAnimationsEnabled(false);
556 widget
->SetBounds(new_bounds
);
557 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width
,
560 widget
->SetVisibilityChangedAnimationsEnabled(true);
562 RunMoveLoop(GetWindowOffset(point_in_screen
));
567 ContinueDragging(point_in_screen
);
570 void TabDragController::EndDrag(EndDragReason reason
) {
571 TRACE_EVENT0("views", "TabDragController::EndDrag");
573 // If we're dragging a window ignore capture lost since it'll ultimately
574 // trigger the move loop to end and we'll revert the drag when RunMoveLoop()
576 if (reason
== END_DRAG_CAPTURE_LOST
&& is_dragging_window_
)
578 EndDragImpl(reason
!= END_DRAG_COMPLETE
&& source_tabstrip_
?
582 void TabDragController::InitTabDragData(Tab
* tab
,
583 TabDragData
* drag_data
) {
584 TRACE_EVENT0("views", "TabDragController::InitTabDragData");
585 drag_data
->source_model_index
=
586 source_tabstrip_
->GetModelIndexOfTab(tab
);
587 drag_data
->contents
= GetModel(source_tabstrip_
)->GetWebContentsAt(
588 drag_data
->source_model_index
);
589 drag_data
->pinned
= source_tabstrip_
->IsTabPinned(tab
);
592 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
593 content::Source
<WebContents
>(drag_data
->contents
));
595 if (!detach_into_browser_
) {
596 drag_data
->original_delegate
= drag_data
->contents
->GetDelegate();
597 drag_data
->contents
->SetDelegate(this);
601 ///////////////////////////////////////////////////////////////////////////////
602 // TabDragController, PageNavigator implementation:
604 WebContents
* TabDragController::OpenURLFromTab(
606 const OpenURLParams
& params
) {
607 if (source_tab_drag_data()->original_delegate
) {
608 OpenURLParams forward_params
= params
;
609 if (params
.disposition
== CURRENT_TAB
)
610 forward_params
.disposition
= NEW_WINDOW
;
612 return source_tab_drag_data()->original_delegate
->OpenURLFromTab(
613 source
, forward_params
);
618 ///////////////////////////////////////////////////////////////////////////////
619 // TabDragController, content::WebContentsDelegate implementation:
621 void TabDragController::NavigationStateChanged(const WebContents
* source
,
622 unsigned changed_flags
) {
623 if (attached_tabstrip_
||
624 changed_flags
== content::INVALIDATE_TYPE_PAGE_ACTIONS
) {
625 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
626 if (drag_data_
[i
].contents
== source
) {
627 // Pass the NavigationStateChanged call to the original delegate so
628 // that the title is updated. Do this only when we are attached as
629 // otherwise the Tab isn't in the TabStrip (except for page action
631 drag_data_
[i
].original_delegate
->NavigationStateChanged(source
,
639 void TabDragController::AddNewContents(WebContents
* source
,
640 WebContents
* new_contents
,
641 WindowOpenDisposition disposition
,
642 const gfx::Rect
& initial_pos
,
645 DCHECK_NE(CURRENT_TAB
, disposition
);
647 // Theoretically could be called while dragging if the page tries to
648 // spawn a window. Route this message back to the browser in most cases.
649 if (source_tab_drag_data()->original_delegate
) {
650 source_tab_drag_data()->original_delegate
->AddNewContents(
651 source
, new_contents
, disposition
, initial_pos
, user_gesture
,
656 bool TabDragController::ShouldSuppressDialogs() {
657 // When a dialog is about to be shown we revert the drag. Otherwise a modal
658 // dialog might appear and attempt to parent itself to a hidden tabcontents.
659 EndDragImpl(CANCELED
);
663 content::JavaScriptDialogManager
*
664 TabDragController::GetJavaScriptDialogManager() {
665 return GetJavaScriptDialogManagerInstance();
668 void TabDragController::RequestMediaAccessPermission(
669 content::WebContents
* web_contents
,
670 const content::MediaStreamRequest
& request
,
671 const content::MediaResponseCallback
& callback
) {
672 ::RequestMediaAccessPermission(
674 Profile::FromBrowserContext(web_contents
->GetBrowserContext()),
679 ///////////////////////////////////////////////////////////////////////////////
680 // TabDragController, content::NotificationObserver implementation:
682 void TabDragController::Observe(
684 const content::NotificationSource
& source
,
685 const content::NotificationDetails
& details
) {
686 DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED
, type
);
687 WebContents
* destroyed_web_contents
=
688 content::Source
<WebContents
>(source
).ptr();
689 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
690 if (drag_data_
[i
].contents
== destroyed_web_contents
) {
691 // One of the tabs we're dragging has been destroyed. Cancel the drag.
692 if (destroyed_web_contents
->GetDelegate() == this)
693 destroyed_web_contents
->SetDelegate(NULL
);
694 drag_data_
[i
].contents
= NULL
;
695 drag_data_
[i
].original_delegate
= NULL
;
696 EndDragImpl(TAB_DESTROYED
);
700 // If we get here it means we got notification for a tab we don't know about.
704 ///////////////////////////////////////////////////////////////////////////////
705 // TabDragController, MessageLoop::Observer implementation:
707 base::EventStatus
TabDragController::WillProcessEvent(
708 const base::NativeEvent
& event
) {
709 return base::EVENT_CONTINUE
;
712 void TabDragController::DidProcessEvent(const base::NativeEvent
& event
) {
713 // If the user presses ESC during a drag, we need to abort and revert things
714 // to the way they were. This is the most reliable way to do this since no
715 // single view or window reliably receives events throughout all the various
716 // kinds of tab dragging.
717 if (ui::EventTypeFromNative(event
) == ui::ET_KEY_PRESSED
&&
718 ui::KeyboardCodeFromNative(event
) == ui::VKEY_ESCAPE
) {
719 EndDrag(END_DRAG_CANCEL
);
723 void TabDragController::OnWidgetBoundsChanged(views::Widget
* widget
,
724 const gfx::Rect
& new_bounds
) {
725 TRACE_EVENT1("views", "TabDragController::OnWidgetBoundsChanged",
726 "new_bounds", new_bounds
.ToString());
728 Drag(GetCursorScreenPoint());
731 void TabDragController::TabStripEmpty() {
732 DCHECK(detach_into_browser_
);
733 GetModel(source_tabstrip_
)->RemoveObserver(this);
734 // NULL out source_tabstrip_ so that we don't attempt to add back to it (in
735 // the case of a revert).
736 source_tabstrip_
= NULL
;
739 ///////////////////////////////////////////////////////////////////////////////
740 // TabDragController, private:
742 void TabDragController::InitWindowCreatePoint() {
743 // window_create_point_ is only used in CompleteDrag() (through
744 // GetWindowCreatePoint() to get the start point of the docked window) when
745 // the attached_tabstrip_ is NULL and all the window's related bound
746 // information are obtained from source_tabstrip_. So, we need to get the
747 // first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise,
748 // the window_create_point_ is not in the correct coordinate system. Please
749 // refer to http://crbug.com/6223 comment #15 for detailed information.
750 views::View
* first_tab
= source_tabstrip_
->tab_at(0);
751 views::View::ConvertPointToWidget(first_tab
, &first_source_tab_point_
);
752 window_create_point_
= first_source_tab_point_
;
753 window_create_point_
.Offset(mouse_offset_
.x(), mouse_offset_
.y());
756 gfx::Point
TabDragController::GetWindowCreatePoint(
757 const gfx::Point
& origin
) const {
758 if (dock_info_
.type() != DockInfo::NONE
&& dock_info_
.in_enable_area()) {
759 // If we're going to dock, we need to return the exact coordinate,
760 // otherwise we may attempt to maximize on the wrong monitor.
764 // If the cursor is outside the monitor area, move it inside. For example,
765 // dropping a tab onto the task bar on Windows produces this situation.
766 gfx::Rect work_area
= screen_
->GetDisplayNearestPoint(origin
).work_area();
767 gfx::Point
create_point(origin
);
768 if (!work_area
.IsEmpty()) {
769 if (create_point
.x() < work_area
.x())
770 create_point
.set_x(work_area
.x());
771 else if (create_point
.x() > work_area
.right())
772 create_point
.set_x(work_area
.right());
773 if (create_point
.y() < work_area
.y())
774 create_point
.set_y(work_area
.y());
775 else if (create_point
.y() > work_area
.bottom())
776 create_point
.set_y(work_area
.bottom());
778 return gfx::Point(create_point
.x() - window_create_point_
.x(),
779 create_point
.y() - window_create_point_
.y());
782 void TabDragController::UpdateDockInfo(const gfx::Point
& point_in_screen
) {
783 TRACE_EVENT1("views", "TabDragController::UpdateDockInfo",
784 "point_in_screen", point_in_screen
.ToString());
786 // Update the DockInfo for the current mouse coordinates.
787 DockInfo dock_info
= GetDockInfoAtPoint(point_in_screen
);
788 if (!dock_info
.equals(dock_info_
)) {
789 // DockInfo for current position differs.
790 if (dock_info_
.type() != DockInfo::NONE
&&
791 !dock_controllers_
.empty()) {
792 // Hide old visual indicator.
793 dock_controllers_
.back()->Hide();
795 dock_info_
= dock_info
;
796 if (dock_info_
.type() != DockInfo::NONE
) {
797 // Show new docking position.
798 DockDisplayer
* controller
= new DockDisplayer(this, dock_info_
);
799 if (controller
->popup_view()) {
800 dock_controllers_
.push_back(controller
);
801 dock_windows_
.insert(controller
->popup_view());
806 } else if (dock_info_
.type() != DockInfo::NONE
&&
807 !dock_controllers_
.empty()) {
808 // Current dock position is the same as last, update the controller's
809 // in_enable_area state as it may have changed.
810 dock_controllers_
.back()->UpdateInEnabledArea(dock_info_
.in_enable_area());
814 void TabDragController::SaveFocus() {
815 DCHECK(source_tabstrip_
);
816 views::View
* focused_view
=
817 source_tabstrip_
->GetFocusManager()->GetFocusedView();
819 views::ViewStorage::GetInstance()->StoreView(old_focused_view_id_
,
821 source_tabstrip_
->GetFocusManager()->SetFocusedView(source_tabstrip_
);
822 // WARNING: we may have been deleted.
825 void TabDragController::RestoreFocus() {
826 if (attached_tabstrip_
!= source_tabstrip_
) {
827 if (is_dragging_new_browser_
) {
828 content::WebContents
* active_contents
= source_dragged_contents();
829 if (active_contents
&& !active_contents
->FocusLocationBarByDefault())
830 active_contents
->GetView()->Focus();
834 views::View
* old_focused_view
=
835 views::ViewStorage::GetInstance()->RetrieveView(old_focused_view_id_
);
836 if (!old_focused_view
)
838 old_focused_view
->GetFocusManager()->SetFocusedView(old_focused_view
);
841 bool TabDragController::CanStartDrag(const gfx::Point
& point_in_screen
) const {
842 // Determine if the mouse has moved beyond a minimum elasticity distance in
843 // any direction from the starting point.
844 static const int kMinimumDragDistance
= 10;
845 int x_offset
= abs(point_in_screen
.x() - start_point_in_screen_
.x());
846 int y_offset
= abs(point_in_screen
.y() - start_point_in_screen_
.y());
847 return sqrt(pow(static_cast<float>(x_offset
), 2) +
848 pow(static_cast<float>(y_offset
), 2)) > kMinimumDragDistance
;
851 void TabDragController::ContinueDragging(const gfx::Point
& point_in_screen
) {
852 TRACE_EVENT1("views", "TabDragController::ContinueDragging",
853 "point_in_screen", point_in_screen
.ToString());
855 DCHECK(!detach_into_browser_
|| attached_tabstrip_
);
857 TabStrip
* target_tabstrip
= detach_behavior_
== DETACHABLE
?
858 GetTargetTabStripForPoint(point_in_screen
) : source_tabstrip_
;
859 bool tab_strip_changed
= (target_tabstrip
!= attached_tabstrip_
);
861 if (attached_tabstrip_
) {
862 int move_delta
= point_in_screen
.x() - last_point_in_screen_
.x();
864 mouse_move_direction_
|= kMovedMouseRight
;
865 else if (move_delta
< 0)
866 mouse_move_direction_
|= kMovedMouseLeft
;
868 last_point_in_screen_
= point_in_screen
;
870 if (tab_strip_changed
) {
871 is_dragging_new_browser_
= false;
872 did_restore_window_
= false;
873 if (detach_into_browser_
&&
874 DragBrowserToNewTabStrip(target_tabstrip
, point_in_screen
) ==
875 DRAG_BROWSER_RESULT_STOP
) {
877 } else if (!detach_into_browser_
) {
878 if (attached_tabstrip_
)
879 Detach(RELEASE_CAPTURE
);
881 Attach(target_tabstrip
, point_in_screen
);
884 if (is_dragging_window_
) {
885 static_cast<base::Timer
*>(&bring_to_front_timer_
)->Start(FROM_HERE
,
886 base::TimeDelta::FromMilliseconds(kBringToFrontDelay
),
887 base::Bind(&TabDragController::BringWindowUnderPointToFront
,
888 base::Unretained(this), point_in_screen
));
891 UpdateDockInfo(point_in_screen
);
893 if (!is_dragging_window_
&& attached_tabstrip_
) {
895 DragActiveTabStacked(point_in_screen
);
897 MoveAttached(point_in_screen
);
898 if (tab_strip_changed
) {
899 // Move the corresponding window to the front. We do this after the
900 // move as on windows activate triggers a synchronous paint.
901 attached_tabstrip_
->GetWidget()->Activate();
907 TabDragController::DragBrowserResultType
908 TabDragController::DragBrowserToNewTabStrip(
909 TabStrip
* target_tabstrip
,
910 const gfx::Point
& point_in_screen
) {
911 TRACE_EVENT1("views", "TabDragController::DragBrowserToNewTabStrip",
912 "point_in_screen", point_in_screen
.ToString());
914 if (!target_tabstrip
) {
915 DetachIntoNewBrowserAndRunMoveLoop(point_in_screen
);
916 return DRAG_BROWSER_RESULT_STOP
;
918 if (is_dragging_window_
) {
919 // ReleaseCapture() is going to result in calling back to us (because it
920 // results in a move). That'll cause all sorts of problems. Reset the
921 // observer so we don't get notified and process the event.
922 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
923 move_loop_widget_
->RemoveObserver(this);
924 move_loop_widget_
= NULL
;
926 views::Widget
* browser_widget
= GetAttachedBrowserWidget();
927 // Need to release the drag controller before starting the move loop as it's
928 // going to trigger capture lost, which cancels drag.
929 attached_tabstrip_
->ReleaseDragController();
930 target_tabstrip
->OwnDragController(this);
931 // Disable animations so that we don't see a close animation on aero.
932 browser_widget
->SetVisibilityChangedAnimationsEnabled(false);
933 // For aura we can't release capture, otherwise it'll cancel a gesture.
934 // Instead we have to directly change capture.
935 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
)
936 target_tabstrip
->GetWidget()->SetCapture(attached_tabstrip_
);
938 browser_widget
->ReleaseCapture();
940 // The Gesture recognizer does not work well currently when capture changes
941 // while a touch gesture is in progress. So we need to manually transfer
942 // gesture sequence and the GR's touch events queue to the new window. This
943 // should really be done somewhere in capture change code and or inside the
944 // GR. But we currently do not have a consistent way for doing it that would
945 // work in all cases. Hence this hack.
946 ui::GestureRecognizer::Get()->TransferEventsTo(
947 browser_widget
->GetNativeView(),
948 target_tabstrip
->GetWidget()->GetNativeView());
951 // The window is going away. Since the drag is still on going we don't want
952 // that to effect the position of any windows.
953 SetWindowPositionManaged(browser_widget
->GetNativeView(), false);
955 // EndMoveLoop is going to snap the window back to its original location.
956 // Hide it so users don't see this.
957 browser_widget
->Hide();
958 browser_widget
->EndMoveLoop();
960 // Ideally we would always swap the tabs now, but on non-ash it seems that
961 // running the move loop implicitly activates the window when done, leading
962 // to all sorts of flicker. So, on non-ash, instead we process the move
963 // after the loop completes. But on chromeos, we can do tab swapping now to
964 // avoid the tab flashing issue(crbug.com/116329).
965 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
966 is_dragging_window_
= false;
967 Detach(DONT_RELEASE_CAPTURE
);
968 Attach(target_tabstrip
, point_in_screen
);
969 // Move the tabs into position.
970 MoveAttached(point_in_screen
);
971 attached_tabstrip_
->GetWidget()->Activate();
973 tab_strip_to_attach_to_after_exit_
= target_tabstrip
;
976 waiting_for_run_loop_to_exit_
= true;
977 end_run_loop_behavior_
= END_RUN_LOOP_CONTINUE_DRAGGING
;
978 return DRAG_BROWSER_RESULT_STOP
;
980 Detach(DONT_RELEASE_CAPTURE
);
981 Attach(target_tabstrip
, point_in_screen
);
982 return DRAG_BROWSER_RESULT_CONTINUE
;
985 void TabDragController::DragActiveTabStacked(
986 const gfx::Point
& point_in_screen
) {
987 if (attached_tabstrip_
->tab_count() !=
988 static_cast<int>(initial_tab_positions_
.size()))
989 return; // TODO: should cancel drag if this happens.
991 int delta
= point_in_screen
.x() - start_point_in_screen_
.x();
992 attached_tabstrip_
->DragActiveTab(initial_tab_positions_
, delta
);
995 void TabDragController::MoveAttachedToNextStackedIndex(
996 const gfx::Point
& point_in_screen
) {
997 int index
= attached_tabstrip_
->touch_layout_
->active_index();
998 if (index
+ 1 >= attached_tabstrip_
->tab_count())
1001 GetModel(attached_tabstrip_
)->MoveSelectedTabsTo(index
+ 1);
1002 StartMoveStackedTimerIfNecessary(point_in_screen
,
1003 kMoveAttachedSubsequentDelay
);
1006 void TabDragController::MoveAttachedToPreviousStackedIndex(
1007 const gfx::Point
& point_in_screen
) {
1008 int index
= attached_tabstrip_
->touch_layout_
->active_index();
1009 if (index
<= attached_tabstrip_
->GetMiniTabCount())
1012 GetModel(attached_tabstrip_
)->MoveSelectedTabsTo(index
- 1);
1013 StartMoveStackedTimerIfNecessary(point_in_screen
,
1014 kMoveAttachedSubsequentDelay
);
1017 void TabDragController::MoveAttached(const gfx::Point
& point_in_screen
) {
1018 DCHECK(attached_tabstrip_
);
1019 DCHECK(!is_dragging_window_
);
1021 gfx::Point dragged_view_point
= GetAttachedDragPoint(point_in_screen
);
1023 // Determine the horizontal move threshold. This is dependent on the width
1024 // of tabs. The smaller the tabs compared to the standard size, the smaller
1026 int threshold
= kHorizontalMoveThreshold
;
1027 if (!attached_tabstrip_
->touch_layout_
.get()) {
1028 double unselected
, selected
;
1029 attached_tabstrip_
->GetCurrentTabWidths(&unselected
, &selected
);
1030 double ratio
= unselected
/ Tab::GetStandardSize().width();
1031 threshold
= static_cast<int>(ratio
* kHorizontalMoveThreshold
);
1033 // else case: touch tabs never shrink.
1035 std::vector
<Tab
*> tabs(drag_data_
.size());
1036 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1037 tabs
[i
] = drag_data_
[i
].attached_tab
;
1039 bool did_layout
= false;
1040 // Update the model, moving the WebContents from one index to another. Do this
1041 // only if we have moved a minimum distance since the last reorder (to prevent
1042 // jitter) or if this the first move and the tabs are not consecutive.
1043 if ((abs(point_in_screen
.x() - last_move_screen_loc_
) > threshold
||
1044 (initial_move_
&& !AreTabsConsecutive()))) {
1045 TabStripModel
* attached_model
= GetModel(attached_tabstrip_
);
1046 gfx::Rect bounds
= GetDraggedViewTabStripBounds(dragged_view_point
);
1047 int to_index
= GetInsertionIndexForDraggedBounds(bounds
);
1048 bool do_move
= true;
1049 // While dragging within a tabstrip the expectation is the insertion index
1050 // is based on the left edge of the tabs being dragged. OTOH when dragging
1051 // into a new tabstrip (attaching) the expectation is the insertion index is
1052 // based on the cursor. This proves problematic as insertion may change the
1053 // size of the tabs, resulting in the index calculated before the insert
1054 // differing from the index calculated after the insert. To alleviate this
1055 // the index is chosen before insertion, and subsequently a new index is
1056 // only used once the mouse moves enough such that the index changes based
1057 // on the direction the mouse moved relative to |attach_x_| (smaller
1058 // x-coordinate should yield a smaller index or larger x-coordinate yields a
1060 if (attach_index_
!= -1) {
1061 gfx::Point
tab_strip_point(point_in_screen
);
1062 views::View::ConvertPointFromScreen(attached_tabstrip_
, &tab_strip_point
);
1064 attached_tabstrip_
->GetMirroredXInView(tab_strip_point
.x());
1065 if (new_x
< attach_x_
)
1066 to_index
= std::min(to_index
, attach_index_
);
1068 to_index
= std::max(to_index
, attach_index_
);
1069 if (to_index
!= attach_index_
)
1070 attach_index_
= -1; // Once a valid move is detected, don't constrain.
1075 WebContents
* last_contents
= drag_data_
[drag_data_
.size() - 1].contents
;
1076 int index_of_last_item
=
1077 attached_model
->GetIndexOfWebContents(last_contents
);
1078 if (initial_move_
) {
1079 // TabStrip determines if the tabs needs to be animated based on model
1080 // position. This means we need to invoke LayoutDraggedTabsAt before
1081 // changing the model.
1082 attached_tabstrip_
->LayoutDraggedTabsAt(
1083 tabs
, source_tab_drag_data()->attached_tab
, dragged_view_point
,
1087 attached_model
->MoveSelectedTabsTo(to_index
);
1089 // Move may do nothing in certain situations (such as when dragging pinned
1090 // tabs). Make sure the tabstrip actually changed before updating
1091 // last_move_screen_loc_.
1092 if (index_of_last_item
!=
1093 attached_model
->GetIndexOfWebContents(last_contents
)) {
1094 last_move_screen_loc_
= point_in_screen
.x();
1100 attached_tabstrip_
->LayoutDraggedTabsAt(
1101 tabs
, source_tab_drag_data()->attached_tab
, dragged_view_point
,
1105 StartMoveStackedTimerIfNecessary(point_in_screen
, kMoveAttachedInitialDelay
);
1107 initial_move_
= false;
1110 void TabDragController::StartMoveStackedTimerIfNecessary(
1111 const gfx::Point
& point_in_screen
,
1113 DCHECK(attached_tabstrip_
);
1115 StackedTabStripLayout
* touch_layout
= attached_tabstrip_
->touch_layout_
.get();
1119 gfx::Point dragged_view_point
= GetAttachedDragPoint(point_in_screen
);
1120 gfx::Rect bounds
= GetDraggedViewTabStripBounds(dragged_view_point
);
1121 int index
= touch_layout
->active_index();
1122 if (ShouldDragToNextStackedTab(bounds
, index
)) {
1123 static_cast<base::Timer
*>(&move_stacked_timer_
)->Start(
1125 base::TimeDelta::FromMilliseconds(delay_ms
),
1126 base::Bind(&TabDragController::MoveAttachedToNextStackedIndex
,
1127 base::Unretained(this), point_in_screen
));
1128 } else if (ShouldDragToPreviousStackedTab(bounds
, index
)) {
1129 static_cast<base::Timer
*>(&move_stacked_timer_
)->Start(
1131 base::TimeDelta::FromMilliseconds(delay_ms
),
1132 base::Bind(&TabDragController::MoveAttachedToPreviousStackedIndex
,
1133 base::Unretained(this), point_in_screen
));
1137 TabDragController::DetachPosition
TabDragController::GetDetachPosition(
1138 const gfx::Point
& point_in_screen
) {
1139 DCHECK(attached_tabstrip_
);
1140 gfx::Point
attached_point(point_in_screen
);
1141 views::View::ConvertPointFromScreen(attached_tabstrip_
, &attached_point
);
1142 if (attached_point
.x() < 0)
1143 return DETACH_BEFORE
;
1144 if (attached_point
.x() >= attached_tabstrip_
->width())
1145 return DETACH_AFTER
;
1146 return DETACH_ABOVE_OR_BELOW
;
1149 DockInfo
TabDragController::GetDockInfoAtPoint(
1150 const gfx::Point
& point_in_screen
) {
1151 // TODO: add support for dock info when |detach_into_browser_| is true.
1152 if (attached_tabstrip_
|| detach_into_browser_
) {
1153 // If the mouse is over a tab strip, don't offer a dock position.
1157 if (dock_info_
.IsValidForPoint(point_in_screen
)) {
1158 // It's possible any given screen coordinate has multiple docking
1159 // positions. Check the current info first to avoid having the docking
1160 // position bounce around.
1164 gfx::NativeView dragged_view
= GetAttachedBrowserWidget()->GetNativeView();
1165 dock_windows_
.insert(dragged_view
);
1166 DockInfo info
= DockInfo::GetDockInfoAtPoint(
1170 dock_windows_
.erase(dragged_view
);
1174 TabStrip
* TabDragController::GetTargetTabStripForPoint(
1175 const gfx::Point
& point_in_screen
) {
1176 TRACE_EVENT1("views", "TabDragController::GetTargetTabStripForPoint",
1177 "point_in_screen", point_in_screen
.ToString());
1179 if (move_only() && attached_tabstrip_
) {
1180 DCHECK_EQ(DETACHABLE
, detach_behavior_
);
1181 // move_only() is intended for touch, in which case we only want to detach
1182 // if the touch point moves significantly in the vertical distance.
1183 gfx::Rect tabstrip_bounds
= GetViewScreenBounds(attached_tabstrip_
);
1184 if (DoesRectContainVerticalPointExpanded(tabstrip_bounds
,
1185 kTouchVerticalDetachMagnetism
,
1186 point_in_screen
.y()))
1187 return attached_tabstrip_
;
1189 gfx::NativeView dragged_view
= NULL
;
1190 if (is_dragging_window_
)
1191 dragged_view
= attached_tabstrip_
->GetWidget()->GetNativeView();
1193 dock_windows_
.insert(dragged_view
);
1194 gfx::NativeWindow local_window
=
1195 DockInfo::GetLocalProcessWindowAtPoint(
1200 dock_windows_
.erase(dragged_view
);
1201 TabStrip
* tab_strip
= GetTabStripForWindow(local_window
);
1202 if (tab_strip
&& DoesTabStripContain(tab_strip
, point_in_screen
))
1204 return is_dragging_window_
? attached_tabstrip_
: NULL
;
1207 TabStrip
* TabDragController::GetTabStripForWindow(gfx::NativeWindow window
) {
1210 BrowserView
* browser_view
=
1211 BrowserView::GetBrowserViewForNativeWindow(window
);
1212 // We don't allow drops on windows that don't have tabstrips.
1213 if (!browser_view
||
1214 !browser_view
->browser()->SupportsWindowFeature(
1215 Browser::FEATURE_TABSTRIP
))
1218 TabStrip
* other_tabstrip
= browser_view
->tabstrip();
1219 TabStrip
* tab_strip
=
1220 attached_tabstrip_
? attached_tabstrip_
: source_tabstrip_
;
1223 return other_tabstrip
->controller()->IsCompatibleWith(tab_strip
) ?
1224 other_tabstrip
: NULL
;
1227 bool TabDragController::DoesTabStripContain(
1229 const gfx::Point
& point_in_screen
) const {
1230 // Make sure the specified screen point is actually within the bounds of the
1231 // specified tabstrip...
1232 gfx::Rect tabstrip_bounds
= GetViewScreenBounds(tabstrip
);
1233 return point_in_screen
.x() < tabstrip_bounds
.right() &&
1234 point_in_screen
.x() >= tabstrip_bounds
.x() &&
1235 DoesRectContainVerticalPointExpanded(tabstrip_bounds
,
1236 kVerticalDetachMagnetism
,
1237 point_in_screen
.y());
1240 void TabDragController::Attach(TabStrip
* attached_tabstrip
,
1241 const gfx::Point
& point_in_screen
) {
1242 TRACE_EVENT1("views", "TabDragController::Attach",
1243 "point_in_screen", point_in_screen
.ToString());
1245 DCHECK(!attached_tabstrip_
); // We should already have detached by the time
1248 attached_tabstrip_
= attached_tabstrip
;
1250 std::vector
<Tab
*> tabs
=
1251 GetTabsMatchingDraggedContents(attached_tabstrip_
);
1254 // Transitioning from detached to attached to a new tabstrip. Add tabs to
1257 selection_model_before_attach_
.Copy(attached_tabstrip
->GetSelectionModel());
1259 if (!detach_into_browser_
) {
1260 // Remove ourselves as the delegate now that the dragged WebContents is
1261 // being inserted back into a Browser.
1262 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1263 drag_data_
[i
].contents
->SetDelegate(NULL
);
1264 drag_data_
[i
].original_delegate
= NULL
;
1267 // Return the WebContents to normalcy.
1268 source_dragged_contents()->DecrementCapturerCount();
1271 // Inserting counts as a move. We don't want the tabs to jitter when the
1272 // user moves the tab immediately after attaching it.
1273 last_move_screen_loc_
= point_in_screen
.x();
1275 // Figure out where to insert the tab based on the bounds of the dragged
1276 // representation and the ideal bounds of the other Tabs already in the
1277 // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
1278 // changing due to animation).
1279 gfx::Point
tab_strip_point(point_in_screen
);
1280 views::View::ConvertPointFromScreen(attached_tabstrip_
, &tab_strip_point
);
1281 tab_strip_point
.set_x(
1282 attached_tabstrip_
->GetMirroredXInView(tab_strip_point
.x()));
1283 tab_strip_point
.Offset(0, -mouse_offset_
.y());
1284 gfx::Rect bounds
= GetDraggedViewTabStripBounds(tab_strip_point
);
1285 int index
= GetInsertionIndexForDraggedBounds(bounds
);
1286 attach_index_
= index
;
1287 attach_x_
= tab_strip_point
.x();
1288 base::AutoReset
<bool> setter(&is_mutating_
, true);
1289 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1290 int add_types
= TabStripModel::ADD_NONE
;
1291 if (attached_tabstrip_
->touch_layout_
.get()) {
1292 // StackedTabStripLayout positions relative to the active tab, if we
1293 // don't add the tab as active things bounce around.
1294 DCHECK_EQ(1u, drag_data_
.size());
1295 add_types
|= TabStripModel::ADD_ACTIVE
;
1297 if (drag_data_
[i
].pinned
)
1298 add_types
|= TabStripModel::ADD_PINNED
;
1299 GetModel(attached_tabstrip_
)->InsertWebContentsAt(
1300 index
+ i
, drag_data_
[i
].contents
, add_types
);
1303 tabs
= GetTabsMatchingDraggedContents(attached_tabstrip_
);
1305 DCHECK_EQ(tabs
.size(), drag_data_
.size());
1306 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1307 drag_data_
[i
].attached_tab
= tabs
[i
];
1309 attached_tabstrip_
->StartedDraggingTabs(tabs
);
1311 ResetSelection(GetModel(attached_tabstrip_
));
1313 // The size of the dragged tab may have changed. Adjust the x offset so that
1314 // ratio of mouse_offset_ to original width is maintained.
1315 std::vector
<Tab
*> tabs_to_source(tabs
);
1316 tabs_to_source
.erase(tabs_to_source
.begin() + source_tab_index_
+ 1,
1317 tabs_to_source
.end());
1318 int new_x
= attached_tabstrip_
->GetSizeNeededForTabs(tabs_to_source
) -
1319 tabs
[source_tab_index_
]->width() +
1320 static_cast<int>(offset_to_width_ratio_
*
1321 tabs
[source_tab_index_
]->width());
1322 mouse_offset_
.set_x(new_x
);
1324 // Transfer ownership of us to the new tabstrip as well as making sure the
1325 // window has capture. This is important so that if activation changes the
1326 // drag isn't prematurely canceled.
1327 if (detach_into_browser_
) {
1328 attached_tabstrip_
->GetWidget()->SetCapture(attached_tabstrip_
);
1329 attached_tabstrip_
->OwnDragController(this);
1332 // Redirect all mouse events to the TabStrip so that the tab that originated
1333 // the drag can safely be deleted.
1334 if (detach_into_browser_
|| attached_tabstrip_
== source_tabstrip_
) {
1335 static_cast<views::internal::RootView
*>(
1336 attached_tabstrip_
->GetWidget()->GetRootView())->SetMouseHandler(
1337 attached_tabstrip_
);
1341 void TabDragController::Detach(ReleaseCapture release_capture
) {
1342 TRACE_EVENT1("views", "TabDragController::Detach",
1343 "release_capture", release_capture
);
1347 // When the user detaches we assume they want to reorder.
1348 move_behavior_
= REORDER
;
1350 // Release ownership of the drag controller and mouse capture. When we
1351 // reattach ownership is transfered.
1352 if (detach_into_browser_
) {
1353 attached_tabstrip_
->ReleaseDragController();
1354 if (release_capture
== RELEASE_CAPTURE
)
1355 attached_tabstrip_
->GetWidget()->ReleaseCapture();
1358 mouse_move_direction_
= kMovedMouseLeft
| kMovedMouseRight
;
1360 // Prevent the WebContents HWND from being hidden by any of the model
1361 // operations performed during the drag.
1362 if (!detach_into_browser_
)
1363 source_dragged_contents()->IncrementCapturerCount(gfx::Size());
1365 std::vector
<gfx::Rect
> drag_bounds
= CalculateBoundsForDraggedTabs();
1366 TabStripModel
* attached_model
= GetModel(attached_tabstrip_
);
1367 std::vector
<TabRendererData
> tab_data
;
1368 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1369 tab_data
.push_back(drag_data_
[i
].attached_tab
->data());
1370 int index
= attached_model
->GetIndexOfWebContents(drag_data_
[i
].contents
);
1371 DCHECK_NE(-1, index
);
1373 // Hide the tab so that the user doesn't see it animate closed.
1374 drag_data_
[i
].attached_tab
->SetVisible(false);
1376 attached_model
->DetachWebContentsAt(index
);
1378 // Detaching resets the delegate, but we still want to be the delegate.
1379 if (!detach_into_browser_
)
1380 drag_data_
[i
].contents
->SetDelegate(this);
1382 // Detaching may end up deleting the tab, drop references to it.
1383 drag_data_
[i
].attached_tab
= NULL
;
1386 // If we've removed the last Tab from the TabStrip, hide the frame now.
1387 if (!attached_model
->empty()) {
1388 if (!selection_model_before_attach_
.empty() &&
1389 selection_model_before_attach_
.active() >= 0 &&
1390 selection_model_before_attach_
.active() < attached_model
->count()) {
1391 // Restore the selection.
1392 attached_model
->SetSelectionFromModel(selection_model_before_attach_
);
1393 } else if (attached_tabstrip_
== source_tabstrip_
&&
1394 !initial_selection_model_
.empty()) {
1395 RestoreInitialSelection();
1399 attached_tabstrip_
->DraggedTabsDetached();
1400 attached_tabstrip_
= NULL
;
1403 void TabDragController::DetachIntoNewBrowserAndRunMoveLoop(
1404 const gfx::Point
& point_in_screen
) {
1405 if (GetModel(attached_tabstrip_
)->count() ==
1406 static_cast<int>(drag_data_
.size())) {
1407 // All the tabs in a browser are being dragged but all the tabs weren't
1408 // initially being dragged. For this to happen the user would have to
1409 // start dragging a set of tabs, the other tabs close, then detach.
1410 RunMoveLoop(GetWindowOffset(point_in_screen
));
1414 const int last_tabstrip_width
= attached_tabstrip_
->tab_area_width();
1415 std::vector
<gfx::Rect
> drag_bounds
= CalculateBoundsForDraggedTabs();
1416 OffsetX(GetAttachedDragPoint(point_in_screen
).x(), &drag_bounds
);
1418 gfx::Vector2d drag_offset
;
1419 Browser
* browser
= CreateBrowserForDrag(
1420 attached_tabstrip_
, point_in_screen
, &drag_offset
, &drag_bounds
);
1422 gfx::NativeView attached_native_view
=
1423 attached_tabstrip_
->GetWidget()->GetNativeView();
1425 Detach(host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
?
1426 DONT_RELEASE_CAPTURE
: RELEASE_CAPTURE
);
1427 BrowserView
* dragged_browser_view
=
1428 BrowserView::GetBrowserViewForBrowser(browser
);
1429 views::Widget
* dragged_widget
= dragged_browser_view
->GetWidget();
1431 // The Gesture recognizer does not work well currently when capture changes
1432 // while a touch gesture is in progress. So we need to manually transfer
1433 // gesture sequence and the GR's touch events queue to the new window. This
1434 // should really be done somewhere in capture change code and or inside the
1435 // GR. But we currently do not have a consistent way for doing it that would
1436 // work in all cases. Hence this hack.
1437 ui::GestureRecognizer::Get()->TransferEventsTo(
1438 attached_native_view
,
1439 dragged_widget
->GetNativeView());
1441 dragged_widget
->SetVisibilityChangedAnimationsEnabled(false);
1442 Attach(dragged_browser_view
->tabstrip(), gfx::Point());
1443 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width
,
1446 WindowPositionManagedUpdater updater
;
1447 dragged_widget
->AddObserver(&updater
);
1448 browser
->window()->Show();
1449 dragged_widget
->RemoveObserver(&updater
);
1450 dragged_widget
->SetVisibilityChangedAnimationsEnabled(true);
1451 // Activate may trigger a focus loss, destroying us.
1453 base::WeakPtr
<TabDragController
> ref(weak_factory_
.GetWeakPtr());
1454 browser
->window()->Activate();
1458 RunMoveLoop(drag_offset
);
1461 void TabDragController::RunMoveLoop(const gfx::Vector2d
& drag_offset
) {
1462 // If the user drags the whole window we'll assume they are going to attach to
1463 // another window and therefore want to reorder.
1464 move_behavior_
= REORDER
;
1466 move_loop_widget_
= GetAttachedBrowserWidget();
1467 DCHECK(move_loop_widget_
);
1468 move_loop_widget_
->AddObserver(this);
1469 is_dragging_window_
= true;
1470 base::WeakPtr
<TabDragController
> ref(weak_factory_
.GetWeakPtr());
1471 // Running the move loop releases mouse capture on non-ash, which triggers
1472 // destroying the drag loop. Release mouse capture ourself before this while
1473 // the DragController isn't owned by the TabStrip.
1474 if (host_desktop_type_
!= chrome::HOST_DESKTOP_TYPE_ASH
) {
1475 attached_tabstrip_
->ReleaseDragController();
1476 attached_tabstrip_
->GetWidget()->ReleaseCapture();
1477 attached_tabstrip_
->OwnDragController(this);
1479 const views::Widget::MoveLoopSource move_loop_source
=
1480 event_source_
== EVENT_SOURCE_MOUSE
?
1481 views::Widget::MOVE_LOOP_SOURCE_MOUSE
:
1482 views::Widget::MOVE_LOOP_SOURCE_TOUCH
;
1483 const views::Widget::MoveLoopEscapeBehavior escape_behavior
=
1484 is_dragging_new_browser_
?
1485 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE
:
1486 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE
;
1487 views::Widget::MoveLoopResult result
=
1488 move_loop_widget_
->RunMoveLoop(
1489 drag_offset
, move_loop_source
, escape_behavior
);
1490 content::NotificationService::current()->Notify(
1491 chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE
,
1492 content::NotificationService::AllBrowserContextsAndSources(),
1493 content::NotificationService::NoDetails());
1497 // Under chromeos we immediately set the |move_loop_widget_| to NULL.
1498 if (move_loop_widget_
) {
1499 move_loop_widget_
->RemoveObserver(this);
1500 move_loop_widget_
= NULL
;
1502 is_dragging_window_
= false;
1503 waiting_for_run_loop_to_exit_
= false;
1504 if (end_run_loop_behavior_
== END_RUN_LOOP_CONTINUE_DRAGGING
) {
1505 end_run_loop_behavior_
= END_RUN_LOOP_STOP_DRAGGING
;
1506 if (tab_strip_to_attach_to_after_exit_
) {
1507 gfx::Point
point_in_screen(GetCursorScreenPoint());
1508 Detach(DONT_RELEASE_CAPTURE
);
1509 Attach(tab_strip_to_attach_to_after_exit_
, point_in_screen
);
1510 // Move the tabs into position.
1511 MoveAttached(point_in_screen
);
1512 attached_tabstrip_
->GetWidget()->Activate();
1513 // Activate may trigger a focus loss, destroying us.
1516 tab_strip_to_attach_to_after_exit_
= NULL
;
1518 DCHECK(attached_tabstrip_
);
1519 attached_tabstrip_
->GetWidget()->SetCapture(attached_tabstrip_
);
1520 } else if (active_
) {
1521 EndDrag(result
== views::Widget::MOVE_LOOP_CANCELED
?
1522 END_DRAG_CANCEL
: END_DRAG_COMPLETE
);
1526 int TabDragController::GetInsertionIndexFrom(const gfx::Rect
& dragged_bounds
,
1529 for (int i
= start
, tab_count
= attached_tabstrip_
->tab_count();
1530 i
>= 0 && i
< tab_count
; i
+= delta
) {
1531 const gfx::Rect
& ideal_bounds
= attached_tabstrip_
->ideal_bounds(i
);
1532 gfx::Rect left_half
, right_half
;
1533 ideal_bounds
.SplitVertically(&left_half
, &right_half
);
1534 if (dragged_bounds
.x() >= right_half
.x() &&
1535 dragged_bounds
.x() < right_half
.right()) {
1537 } else if (dragged_bounds
.x() >= left_half
.x() &&
1538 dragged_bounds
.x() < left_half
.right()) {
1545 int TabDragController::GetInsertionIndexForDraggedBounds(
1546 const gfx::Rect
& dragged_bounds
) const {
1548 if (attached_tabstrip_
->touch_layout_
.get()) {
1549 index
= GetInsertionIndexForDraggedBoundsStacked(dragged_bounds
);
1551 // Only move the tab to the left/right if the user actually moved the
1552 // mouse that way. This is necessary as tabs with stacked tabs
1553 // before/after them have multiple drag positions.
1554 int active_index
= attached_tabstrip_
->touch_layout_
->active_index();
1555 if ((index
< active_index
&&
1556 (mouse_move_direction_
& kMovedMouseLeft
) == 0) ||
1557 (index
> active_index
&&
1558 (mouse_move_direction_
& kMovedMouseRight
) == 0)) {
1559 index
= active_index
;
1563 index
= GetInsertionIndexFrom(dragged_bounds
, 0, 1);
1566 int tab_count
= attached_tabstrip_
->tab_count();
1567 int right_tab_x
= tab_count
== 0 ? 0 :
1568 attached_tabstrip_
->ideal_bounds(tab_count
- 1).right();
1569 if (dragged_bounds
.right() > right_tab_x
) {
1570 index
= GetModel(attached_tabstrip_
)->count();
1576 if (!drag_data_
[0].attached_tab
) {
1577 // If 'attached_tab' is NULL, it means we're in the process of attaching and
1578 // don't need to constrain the index.
1582 int max_index
= GetModel(attached_tabstrip_
)->count() -
1583 static_cast<int>(drag_data_
.size());
1584 return std::max(0, std::min(max_index
, index
));
1587 bool TabDragController::ShouldDragToNextStackedTab(
1588 const gfx::Rect
& dragged_bounds
,
1590 if (index
+ 1 >= attached_tabstrip_
->tab_count() ||
1591 !attached_tabstrip_
->touch_layout_
->IsStacked(index
+ 1) ||
1592 (mouse_move_direction_
& kMovedMouseRight
) == 0)
1595 int active_x
= attached_tabstrip_
->ideal_bounds(index
).x();
1596 int next_x
= attached_tabstrip_
->ideal_bounds(index
+ 1).x();
1597 int mid_x
= std::min(next_x
- kStackedDistance
,
1598 active_x
+ (next_x
- active_x
) / 4);
1599 return dragged_bounds
.x() >= mid_x
;
1602 bool TabDragController::ShouldDragToPreviousStackedTab(
1603 const gfx::Rect
& dragged_bounds
,
1605 if (index
- 1 < attached_tabstrip_
->GetMiniTabCount() ||
1606 !attached_tabstrip_
->touch_layout_
->IsStacked(index
- 1) ||
1607 (mouse_move_direction_
& kMovedMouseLeft
) == 0)
1610 int active_x
= attached_tabstrip_
->ideal_bounds(index
).x();
1611 int previous_x
= attached_tabstrip_
->ideal_bounds(index
- 1).x();
1612 int mid_x
= std::max(previous_x
+ kStackedDistance
,
1613 active_x
- (active_x
- previous_x
) / 4);
1614 return dragged_bounds
.x() <= mid_x
;
1617 int TabDragController::GetInsertionIndexForDraggedBoundsStacked(
1618 const gfx::Rect
& dragged_bounds
) const {
1619 StackedTabStripLayout
* touch_layout
= attached_tabstrip_
->touch_layout_
.get();
1620 int active_index
= touch_layout
->active_index();
1621 // Search from the active index to the front of the tabstrip. Do this as tabs
1622 // overlap each other from the active index.
1623 int index
= GetInsertionIndexFrom(dragged_bounds
, active_index
, -1);
1624 if (index
!= active_index
)
1627 return GetInsertionIndexFrom(dragged_bounds
, active_index
+ 1, 1);
1629 // The position to drag to corresponds to the active tab. If the next/previous
1630 // tab is stacked, then shorten the distance used to determine insertion
1631 // bounds. We do this as GetInsertionIndexFrom() uses the bounds of the
1632 // tabs. When tabs are stacked the next/previous tab is on top of the tab.
1633 if (active_index
+ 1 < attached_tabstrip_
->tab_count() &&
1634 touch_layout
->IsStacked(active_index
+ 1)) {
1635 index
= GetInsertionIndexFrom(dragged_bounds
, active_index
+ 1, 1);
1636 if (index
== -1 && ShouldDragToNextStackedTab(dragged_bounds
, active_index
))
1637 index
= active_index
+ 1;
1638 else if (index
== -1)
1639 index
= active_index
;
1640 } else if (ShouldDragToPreviousStackedTab(dragged_bounds
, active_index
)) {
1641 index
= active_index
- 1;
1646 gfx::Rect
TabDragController::GetDraggedViewTabStripBounds(
1647 const gfx::Point
& tab_strip_point
) {
1648 // attached_tab is NULL when inserting into a new tabstrip.
1649 if (source_tab_drag_data()->attached_tab
) {
1650 return gfx::Rect(tab_strip_point
.x(), tab_strip_point
.y(),
1651 source_tab_drag_data()->attached_tab
->width(),
1652 source_tab_drag_data()->attached_tab
->height());
1655 double sel_width
, unselected_width
;
1656 attached_tabstrip_
->GetCurrentTabWidths(&sel_width
, &unselected_width
);
1657 return gfx::Rect(tab_strip_point
.x(), tab_strip_point
.y(),
1658 static_cast<int>(sel_width
),
1659 Tab::GetStandardSize().height());
1662 gfx::Point
TabDragController::GetAttachedDragPoint(
1663 const gfx::Point
& point_in_screen
) {
1664 DCHECK(attached_tabstrip_
); // The tab must be attached.
1666 gfx::Point
tab_loc(point_in_screen
);
1667 views::View::ConvertPointFromScreen(attached_tabstrip_
, &tab_loc
);
1669 attached_tabstrip_
->GetMirroredXInView(tab_loc
.x()) - mouse_offset_
.x();
1671 // TODO: consider caching this.
1672 std::vector
<Tab
*> attached_tabs
;
1673 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1674 attached_tabs
.push_back(drag_data_
[i
].attached_tab
);
1675 const int size
= attached_tabstrip_
->GetSizeNeededForTabs(attached_tabs
);
1676 const int max_x
= attached_tabstrip_
->width() - size
;
1677 return gfx::Point(std::min(std::max(x
, 0), max_x
), 0);
1680 std::vector
<Tab
*> TabDragController::GetTabsMatchingDraggedContents(
1681 TabStrip
* tabstrip
) {
1682 TabStripModel
* model
= GetModel(attached_tabstrip_
);
1683 std::vector
<Tab
*> tabs
;
1684 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1685 int model_index
= model
->GetIndexOfWebContents(drag_data_
[i
].contents
);
1686 if (model_index
== TabStripModel::kNoTab
)
1687 return std::vector
<Tab
*>();
1688 tabs
.push_back(tabstrip
->tab_at(model_index
));
1693 std::vector
<gfx::Rect
> TabDragController::CalculateBoundsForDraggedTabs() {
1694 std::vector
<gfx::Rect
> drag_bounds
;
1695 std::vector
<Tab
*> attached_tabs
;
1696 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1697 attached_tabs
.push_back(drag_data_
[i
].attached_tab
);
1698 attached_tabstrip_
->CalculateBoundsForDraggedTabs(attached_tabs
,
1703 void TabDragController::EndDragImpl(EndDragType type
) {
1707 bring_to_front_timer_
.Stop();
1708 move_stacked_timer_
.Stop();
1710 if (is_dragging_window_
) {
1711 waiting_for_run_loop_to_exit_
= true;
1713 if (type
== NORMAL
|| (type
== TAB_DESTROYED
&& drag_data_
.size() > 1)) {
1714 SetWindowPositionManaged(GetAttachedBrowserWidget()->GetNativeView(),
1718 // End the nested drag loop.
1719 GetAttachedBrowserWidget()->EndMoveLoop();
1722 // Hide the current dock controllers.
1723 for (size_t i
= 0; i
< dock_controllers_
.size(); ++i
) {
1724 // Be sure and clear the controller first, that way if Hide ends up
1725 // deleting the controller it won't call us back.
1726 dock_controllers_
[i
]->clear_controller();
1727 dock_controllers_
[i
]->Hide();
1729 dock_controllers_
.clear();
1730 dock_windows_
.clear();
1732 if (type
!= TAB_DESTROYED
) {
1733 // We only finish up the drag if we were actually dragging. If start_drag_
1734 // is false, the user just clicked and released and didn't move the mouse
1735 // enough to trigger a drag.
1736 if (started_drag_
) {
1738 if (type
== CANCELED
)
1743 } else if (drag_data_
.size() > 1) {
1744 initial_selection_model_
.Clear();
1746 } // else case the only tab we were dragging was deleted. Nothing to do.
1748 if (!detach_into_browser_
)
1751 // Clear out drag data so we don't attempt to do anything with it.
1754 TabStrip
* owning_tabstrip
= (attached_tabstrip_
&& detach_into_browser_
) ?
1755 attached_tabstrip_
: source_tabstrip_
;
1756 owning_tabstrip
->DestroyDragController();
1759 void TabDragController::RevertDrag() {
1760 std::vector
<Tab
*> tabs
;
1761 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1762 if (drag_data_
[i
].contents
) {
1763 // Contents is NULL if a tab was destroyed while the drag was under way.
1764 tabs
.push_back(drag_data_
[i
].attached_tab
);
1769 bool restore_frame
= !detach_into_browser_
&&
1770 attached_tabstrip_
!= source_tabstrip_
;
1771 if (attached_tabstrip_
) {
1772 if (did_restore_window_
)
1773 MaximizeAttachedWindow();
1774 if (attached_tabstrip_
== source_tabstrip_
) {
1775 source_tabstrip_
->StoppedDraggingTabs(
1776 tabs
, initial_tab_positions_
, move_behavior_
== MOVE_VISIBILE_TABS
,
1779 attached_tabstrip_
->DraggedTabsDetached();
1783 if (initial_selection_model_
.empty())
1784 ResetSelection(GetModel(source_tabstrip_
));
1786 GetModel(source_tabstrip_
)->SetSelectionFromModel(initial_selection_model_
);
1788 // If we're not attached to any TabStrip, or attached to some other TabStrip,
1789 // we need to restore the bounds of the original TabStrip's frame, in case
1790 // it has been hidden.
1791 if (restore_frame
&& !restore_bounds_
.IsEmpty())
1792 source_tabstrip_
->GetWidget()->SetBounds(restore_bounds_
);
1794 if (detach_into_browser_
&& source_tabstrip_
)
1795 source_tabstrip_
->GetWidget()->Activate();
1797 // Return the WebContents to normalcy. If the tab was attached to a
1798 // TabStrip before the revert, the decrement has already occurred.
1799 // If the tab was destroyed, don't attempt to dereference the
1800 // WebContents pointer.
1801 if (!detach_into_browser_
&& !attached_tabstrip_
&& source_dragged_contents())
1802 source_dragged_contents()->DecrementCapturerCount();
1805 void TabDragController::ResetSelection(TabStripModel
* model
) {
1807 ui::ListSelectionModel selection_model
;
1808 bool has_one_valid_tab
= false;
1809 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1810 // |contents| is NULL if a tab was deleted out from under us.
1811 if (drag_data_
[i
].contents
) {
1812 int index
= model
->GetIndexOfWebContents(drag_data_
[i
].contents
);
1813 DCHECK_NE(-1, index
);
1814 selection_model
.AddIndexToSelection(index
);
1815 if (!has_one_valid_tab
|| i
== source_tab_index_
) {
1816 // Reset the active/lead to the first tab. If the source tab is still
1817 // valid we'll reset these again later on.
1818 selection_model
.set_active(index
);
1819 selection_model
.set_anchor(index
);
1820 has_one_valid_tab
= true;
1824 if (!has_one_valid_tab
)
1827 model
->SetSelectionFromModel(selection_model
);
1830 void TabDragController::RestoreInitialSelection() {
1831 // First time detaching from the source tabstrip. Reset selection model to
1832 // initial_selection_model_. Before resetting though we have to remove all
1833 // the tabs from initial_selection_model_ as it was created with the tabs
1835 ui::ListSelectionModel selection_model
;
1836 selection_model
.Copy(initial_selection_model_
);
1837 for (DragData::const_reverse_iterator
i(drag_data_
.rbegin());
1838 i
!= drag_data_
.rend(); ++i
) {
1839 selection_model
.DecrementFrom(i
->source_model_index
);
1841 // We may have cleared out the selection model. Only reset it if it
1842 // contains something.
1843 if (selection_model
.empty())
1846 // The anchor/active may have been among the tabs that were dragged out. Force
1847 // the anchor/active to be valid.
1848 if (selection_model
.anchor() == ui::ListSelectionModel::kUnselectedIndex
)
1849 selection_model
.set_anchor(selection_model
.selected_indices()[0]);
1850 if (selection_model
.active() == ui::ListSelectionModel::kUnselectedIndex
)
1851 selection_model
.set_active(selection_model
.selected_indices()[0]);
1852 GetModel(source_tabstrip_
)->SetSelectionFromModel(selection_model
);
1855 void TabDragController::RevertDragAt(size_t drag_index
) {
1856 DCHECK(started_drag_
);
1857 DCHECK(source_tabstrip_
);
1859 base::AutoReset
<bool> setter(&is_mutating_
, true);
1860 TabDragData
* data
= &(drag_data_
[drag_index
]);
1861 if (attached_tabstrip_
) {
1863 GetModel(attached_tabstrip_
)->GetIndexOfWebContents(data
->contents
);
1864 if (attached_tabstrip_
!= source_tabstrip_
) {
1865 // The Tab was inserted into another TabStrip. We need to put it back
1866 // into the original one.
1867 GetModel(attached_tabstrip_
)->DetachWebContentsAt(index
);
1868 // TODO(beng): (Cleanup) seems like we should use Attach() for this
1870 GetModel(source_tabstrip_
)->InsertWebContentsAt(
1871 data
->source_model_index
, data
->contents
,
1872 (data
->pinned
? TabStripModel::ADD_PINNED
: 0));
1874 // The Tab was moved within the TabStrip where the drag was initiated.
1875 // Move it back to the starting location.
1876 GetModel(source_tabstrip_
)->MoveWebContentsAt(
1877 index
, data
->source_model_index
, false);
1880 // The Tab was detached from the TabStrip where the drag began, and has not
1881 // been attached to any other TabStrip. We need to put it back into the
1883 GetModel(source_tabstrip_
)->InsertWebContentsAt(
1884 data
->source_model_index
, data
->contents
,
1885 (data
->pinned
? TabStripModel::ADD_PINNED
: 0));
1889 void TabDragController::CompleteDrag() {
1890 DCHECK(started_drag_
);
1892 if (attached_tabstrip_
) {
1893 if (is_dragging_new_browser_
|| did_restore_window_
) {
1894 if (IsDockedOrSnapped(attached_tabstrip_
)) {
1895 was_source_maximized_
= false;
1896 was_source_fullscreen_
= false;
1899 // If source window was maximized - maximize the new window as well.
1900 if (was_source_maximized_
|| was_source_fullscreen_
)
1901 MaximizeAttachedWindow();
1903 attached_tabstrip_
->StoppedDraggingTabs(
1904 GetTabsMatchingDraggedContents(attached_tabstrip_
),
1905 initial_tab_positions_
,
1906 move_behavior_
== MOVE_VISIBILE_TABS
,
1909 if (dock_info_
.type() != DockInfo::NONE
) {
1910 switch (dock_info_
.type()) {
1911 case DockInfo::LEFT_OF_WINDOW
:
1912 content::RecordAction(UserMetricsAction("DockingWindow_Left"));
1915 case DockInfo::RIGHT_OF_WINDOW
:
1916 content::RecordAction(UserMetricsAction("DockingWindow_Right"));
1919 case DockInfo::BOTTOM_OF_WINDOW
:
1920 content::RecordAction(UserMetricsAction("DockingWindow_Bottom"));
1923 case DockInfo::TOP_OF_WINDOW
:
1924 content::RecordAction(UserMetricsAction("DockingWindow_Top"));
1927 case DockInfo::MAXIMIZE
:
1928 content::RecordAction(
1929 UserMetricsAction("DockingWindow_Maximize"));
1932 case DockInfo::LEFT_HALF
:
1933 content::RecordAction(
1934 UserMetricsAction("DockingWindow_LeftHalf"));
1937 case DockInfo::RIGHT_HALF
:
1938 content::RecordAction(
1939 UserMetricsAction("DockingWindow_RightHalf"));
1942 case DockInfo::BOTTOM_HALF
:
1943 content::RecordAction(
1944 UserMetricsAction("DockingWindow_BottomHalf"));
1952 // Compel the model to construct a new window for the detached
1954 views::Widget
* widget
= source_tabstrip_
->GetWidget();
1955 gfx::Rect
window_bounds(widget
->GetRestoredBounds());
1956 window_bounds
.set_origin(GetWindowCreatePoint(last_point_in_screen_
));
1958 // When modifying the following if statement, please make sure not to
1959 // introduce issue listed in http://crbug.com/6223 comment #11.
1960 bool rtl_ui
= base::i18n::IsRTL();
1961 bool has_dock_position
= (dock_info_
.type() != DockInfo::NONE
);
1962 if (rtl_ui
&& has_dock_position
) {
1963 // Mirror X axis so the docked tab is aligned using the mouse click as
1964 // the top-right corner.
1965 window_bounds
.set_x(window_bounds
.x() - window_bounds
.width());
1967 base::AutoReset
<bool> setter(&is_mutating_
, true);
1969 std::vector
<TabStripModelDelegate::NewStripContents
> contentses
;
1970 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1971 TabStripModelDelegate::NewStripContents item
;
1972 item
.web_contents
= drag_data_
[i
].contents
;
1973 item
.add_types
= drag_data_
[i
].pinned
? TabStripModel::ADD_PINNED
1974 : TabStripModel::ADD_NONE
;
1975 contentses
.push_back(item
);
1978 Browser
* new_browser
=
1979 GetModel(source_tabstrip_
)->delegate()->CreateNewStripWithContents(
1980 contentses
, window_bounds
, dock_info_
, widget
->IsMaximized());
1981 ResetSelection(new_browser
->tab_strip_model());
1982 new_browser
->window()->Show();
1984 // Return the WebContents to normalcy.
1985 if (!detach_into_browser_
)
1986 source_dragged_contents()->DecrementCapturerCount();
1989 CleanUpHiddenFrame();
1992 void TabDragController::MaximizeAttachedWindow() {
1993 GetAttachedBrowserWidget()->Maximize();
1994 #if defined(USE_ASH)
1995 if (was_source_fullscreen_
&&
1996 host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
1997 // In fullscreen mode it is only possible to get here if the source
1998 // was in "immersive fullscreen" mode, so toggle it back on.
1999 ash::accelerators::ToggleFullscreen();
2004 void TabDragController::ResetDelegates() {
2005 DCHECK(!detach_into_browser_
);
2006 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
2007 if (drag_data_
[i
].contents
&&
2008 drag_data_
[i
].contents
->GetDelegate() == this) {
2009 drag_data_
[i
].contents
->SetDelegate(
2010 drag_data_
[i
].original_delegate
);
2015 gfx::Rect
TabDragController::GetViewScreenBounds(
2016 views::View
* view
) const {
2017 gfx::Point view_topleft
;
2018 views::View::ConvertPointToScreen(view
, &view_topleft
);
2019 gfx::Rect view_screen_bounds
= view
->GetLocalBounds();
2020 view_screen_bounds
.Offset(view_topleft
.x(), view_topleft
.y());
2021 return view_screen_bounds
;
2024 void TabDragController::CleanUpHiddenFrame() {
2025 // If the model we started dragging from is now empty, we must ask the
2026 // delegate to close the frame.
2027 if (!detach_into_browser_
&& GetModel(source_tabstrip_
)->empty())
2028 GetModel(source_tabstrip_
)->delegate()->CloseFrameAfterDragSession();
2031 void TabDragController::DockDisplayerDestroyed(
2032 DockDisplayer
* controller
) {
2033 DockWindows::iterator dock_i
=
2034 dock_windows_
.find(controller
->popup_view());
2035 if (dock_i
!= dock_windows_
.end())
2036 dock_windows_
.erase(dock_i
);
2040 std::vector
<DockDisplayer
*>::iterator i
=
2041 std::find(dock_controllers_
.begin(), dock_controllers_
.end(),
2043 if (i
!= dock_controllers_
.end())
2044 dock_controllers_
.erase(i
);
2049 void TabDragController::BringWindowUnderPointToFront(
2050 const gfx::Point
& point_in_screen
) {
2051 // If we're going to dock to another window, bring it to the front.
2052 gfx::NativeWindow window
= dock_info_
.window();
2054 gfx::NativeView dragged_native_view
=
2055 attached_tabstrip_
->GetWidget()->GetNativeView();
2056 dock_windows_
.insert(dragged_native_view
);
2057 window
= DockInfo::GetLocalProcessWindowAtPoint(
2061 dock_windows_
.erase(dragged_native_view
);
2062 // Only bring browser windows to front - only windows with a TabStrip can
2063 // be tab drag targets.
2064 if (!GetTabStripForWindow(window
))
2068 views::Widget
* widget_window
= views::Widget::GetWidgetForNativeView(
2073 #if defined(USE_ASH)
2074 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
2075 // TODO(varkha): The code below ensures that the phantom drag widget
2076 // is shown on top of browser windows. The code should be moved to ash/
2077 // and the phantom should be able to assert its top-most state on its own.
2078 // One strategy would be for DragWindowController to
2079 // be able to observe stacking changes to the phantom drag widget's
2080 // siblings in order to keep it on top. One way is to implement a
2081 // notification that is sent to a window parent's observers when a
2082 // stacking order is changed among the children of that same parent.
2083 // Note that OnWindowStackingChanged is sent only to the child that is the
2084 // argument of one of the Window::StackChildX calls and not to all its
2085 // siblings affected by the stacking change.
2086 aura::Window
* browser_window
= widget_window
->GetNativeView();
2087 // Find a topmost non-popup window and stack the recipient browser above
2088 // it in order to avoid stacking the browser window on top of the phantom
2089 // drag widget created by DragWindowController in a second display.
2090 for (aura::Window::Windows::const_reverse_iterator it
=
2091 browser_window
->parent()->children().rbegin();
2092 it
!= browser_window
->parent()->children().rend(); ++it
) {
2093 // If the iteration reached the recipient browser window then it is
2094 // already topmost and it is safe to return with no stacking change.
2095 if (*it
== browser_window
)
2097 if ((*it
)->type() != ui::wm::WINDOW_TYPE_POPUP
) {
2098 widget_window
->StackAbove(*it
);
2103 widget_window
->StackAtTop();
2106 widget_window
->StackAtTop();
2109 // The previous call made the window appear on top of the dragged window,
2110 // move the dragged window to the front.
2111 if (is_dragging_window_
)
2112 attached_tabstrip_
->GetWidget()->StackAtTop();
2116 TabStripModel
* TabDragController::GetModel(
2117 TabStrip
* tabstrip
) const {
2118 return static_cast<BrowserTabStripController
*>(tabstrip
->controller())->
2122 views::Widget
* TabDragController::GetAttachedBrowserWidget() {
2123 return attached_tabstrip_
->GetWidget();
2126 bool TabDragController::AreTabsConsecutive() {
2127 for (size_t i
= 1; i
< drag_data_
.size(); ++i
) {
2128 if (drag_data_
[i
- 1].source_model_index
+ 1 !=
2129 drag_data_
[i
].source_model_index
) {
2136 gfx::Rect
TabDragController::CalculateDraggedBrowserBounds(
2138 const gfx::Point
& point_in_screen
,
2139 std::vector
<gfx::Rect
>* drag_bounds
) {
2140 gfx::Point
center(0, source
->height() / 2);
2141 views::View::ConvertPointToWidget(source
, ¢er
);
2142 gfx::Rect
new_bounds(source
->GetWidget()->GetRestoredBounds());
2143 if (source
->GetWidget()->IsMaximized()) {
2144 // If the restore bounds is really small, we don't want to honor it
2145 // (dragging a really small window looks wrong), instead make sure the new
2146 // window is at least 50% the size of the old.
2147 const gfx::Size
max_size(
2148 source
->GetWidget()->GetWindowBoundsInScreen().size());
2149 new_bounds
.set_width(
2150 std::max(max_size
.width() / 2, new_bounds
.width()));
2151 new_bounds
.set_height(
2152 std::max(max_size
.height() / 2, new_bounds
.height()));
2154 new_bounds
.set_y(point_in_screen
.y() - center
.y());
2155 switch (GetDetachPosition(point_in_screen
)) {
2157 new_bounds
.set_x(point_in_screen
.x() - center
.x());
2158 new_bounds
.Offset(-mouse_offset_
.x(), 0);
2160 case DETACH_AFTER
: {
2161 gfx::Point
right_edge(source
->width(), 0);
2162 views::View::ConvertPointToWidget(source
, &right_edge
);
2163 new_bounds
.set_x(point_in_screen
.x() - right_edge
.x());
2164 new_bounds
.Offset(drag_bounds
->back().right() - mouse_offset_
.x(), 0);
2165 OffsetX(-(*drag_bounds
)[0].x(), drag_bounds
);
2169 break; // Nothing to do for DETACH_ABOVE_OR_BELOW.
2172 // To account for the extra vertical on restored windows that is absent on
2173 // maximized windows, add an additional vertical offset extracted from the tab
2175 if (source
->GetWidget()->IsMaximized())
2176 new_bounds
.Offset(0, -source
->button_v_offset());
2180 void TabDragController::AdjustBrowserAndTabBoundsForDrag(
2181 int last_tabstrip_width
,
2182 const gfx::Point
& point_in_screen
,
2183 std::vector
<gfx::Rect
>* drag_bounds
) {
2184 attached_tabstrip_
->InvalidateLayout();
2185 attached_tabstrip_
->DoLayout();
2186 const int dragged_tabstrip_width
= attached_tabstrip_
->tab_area_width();
2188 // If the new tabstrip is smaller than the old resize the tabs.
2189 if (dragged_tabstrip_width
< last_tabstrip_width
) {
2190 const float leading_ratio
=
2191 drag_bounds
->front().x() / static_cast<float>(last_tabstrip_width
);
2192 *drag_bounds
= CalculateBoundsForDraggedTabs();
2194 if (drag_bounds
->back().right() < dragged_tabstrip_width
) {
2196 std::min(static_cast<int>(leading_ratio
* dragged_tabstrip_width
),
2197 dragged_tabstrip_width
-
2198 (drag_bounds
->back().right() -
2199 drag_bounds
->front().x()));
2200 OffsetX(delta_x
, drag_bounds
);
2203 // Reposition the restored window such that the tab that was dragged remains
2204 // under the mouse cursor.
2206 static_cast<int>((*drag_bounds
)[source_tab_index_
].width() *
2207 offset_to_width_ratio_
) +
2208 (*drag_bounds
)[source_tab_index_
].x(), 0);
2209 views::View::ConvertPointToWidget(attached_tabstrip_
, &offset
);
2210 gfx::Rect bounds
= GetAttachedBrowserWidget()->GetWindowBoundsInScreen();
2211 bounds
.set_x(point_in_screen
.x() - offset
.x());
2212 GetAttachedBrowserWidget()->SetBounds(bounds
);
2214 attached_tabstrip_
->SetTabBoundsForDrag(*drag_bounds
);
2217 Browser
* TabDragController::CreateBrowserForDrag(
2219 const gfx::Point
& point_in_screen
,
2220 gfx::Vector2d
* drag_offset
,
2221 std::vector
<gfx::Rect
>* drag_bounds
) {
2222 gfx::Rect
new_bounds(CalculateDraggedBrowserBounds(source
,
2225 *drag_offset
= point_in_screen
- new_bounds
.origin();
2228 Profile::FromBrowserContext(drag_data_
[0].contents
->GetBrowserContext());
2229 Browser::CreateParams
create_params(Browser::TYPE_TABBED
,
2231 host_desktop_type_
);
2232 create_params
.initial_bounds
= new_bounds
;
2233 Browser
* browser
= new Browser(create_params
);
2234 is_dragging_new_browser_
= true;
2235 SetWindowPositionManaged(browser
->window()->GetNativeWindow(), false);
2236 // If the window is created maximized then the bounds we supplied are ignored.
2237 // We need to reset them again so they are honored.
2238 browser
->window()->SetBounds(new_bounds
);
2243 gfx::Point
TabDragController::GetCursorScreenPoint() {
2244 #if defined(USE_ASH)
2245 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
&&
2246 event_source_
== EVENT_SOURCE_TOUCH
&&
2247 aura::Env::GetInstance()->is_touch_down()) {
2248 views::Widget
* widget
= GetAttachedBrowserWidget();
2250 aura::Window
* widget_window
= widget
->GetNativeWindow();
2251 DCHECK(widget_window
->GetRootWindow());
2252 gfx::PointF touch_point_f
;
2253 bool got_touch_point
= ui::GestureRecognizer::Get()->
2254 GetLastTouchPointForTarget(widget_window
, &touch_point_f
);
2255 // TODO(tdresser): Switch to using gfx::PointF. See crbug.com/337824.
2256 gfx::Point touch_point
= gfx::ToFlooredPoint(touch_point_f
);
2257 DCHECK(got_touch_point
);
2258 ash::wm::ConvertPointToScreen(widget_window
->GetRootWindow(), &touch_point
);
2262 return screen_
->GetCursorScreenPoint();
2265 gfx::Vector2d
TabDragController::GetWindowOffset(
2266 const gfx::Point
& point_in_screen
) {
2267 TabStrip
* owning_tabstrip
= (attached_tabstrip_
&& detach_into_browser_
) ?
2268 attached_tabstrip_
: source_tabstrip_
;
2269 views::View
* toplevel_view
= owning_tabstrip
->GetWidget()->GetContentsView();
2271 gfx::Point point
= point_in_screen
;
2272 views::View::ConvertPointFromScreen(toplevel_view
, &point
);
2273 return point
.OffsetFromOrigin();