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/dragged_tab_view.h"
25 #include "chrome/browser/ui/views/tabs/native_view_photobooth.h"
26 #include "chrome/browser/ui/views/tabs/stacked_tab_strip_layout.h"
27 #include "chrome/browser/ui/views/tabs/tab.h"
28 #include "chrome/browser/ui/views/tabs/tab_strip.h"
29 #include "chrome/common/chrome_switches.h"
30 #include "content/public/browser/invalidate_type.h"
31 #include "content/public/browser/notification_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/browser/web_contents.h"
37 #include "content/public/browser/web_contents_view.h"
38 #include "grit/theme_resources.h"
39 #include "ui/base/resource/resource_bundle.h"
40 #include "ui/events/event_constants.h"
41 #include "ui/events/event_utils.h"
42 #include "ui/gfx/animation/animation.h"
43 #include "ui/gfx/animation/animation_delegate.h"
44 #include "ui/gfx/animation/slide_animation.h"
45 #include "ui/gfx/canvas.h"
46 #include "ui/gfx/image/image_skia.h"
47 #include "ui/gfx/screen.h"
48 #include "ui/views/focus/view_storage.h"
49 #include "ui/views/widget/root_view.h"
50 #include "ui/views/widget/widget.h"
53 #include "ash/accelerators/accelerator_commands.h"
54 #include "ash/wm/coordinate_conversion.h"
55 #include "ash/wm/window_state.h"
56 #include "ui/aura/env.h"
57 #include "ui/aura/root_window.h"
58 #include "ui/aura/window.h"
59 #include "ui/events/gestures/gesture_recognizer.h"
62 #if defined(OS_WIN) && defined(USE_AURA)
63 #include "ui/aura/window.h"
64 #include "ui/events/gestures/gesture_recognizer.h"
67 using base::UserMetricsAction
;
68 using content::OpenURLParams
;
69 using content::WebContents
;
71 static const int kHorizontalMoveThreshold
= 16; // Pixels.
73 // Distance from the next/previous stacked before before we consider the tab
74 // close enough to trigger moving.
75 static const int kStackedDistance
= 36;
77 // If non-null there is a drag underway.
78 static TabDragController
* instance_
= NULL
;
82 // Delay, in ms, during dragging before we bring a window to front.
83 const int kBringToFrontDelay
= 750;
85 // Initial delay before moving tabs when the dragged tab is close to the edge of
87 const int kMoveAttachedInitialDelay
= 600;
89 // Delay for moving tabs after the initial delay has passed.
90 const int kMoveAttachedSubsequentDelay
= 300;
92 // Radius of the rect drawn by DockView.
93 const int kRoundedRectRadius
= 4;
95 // Spacing between tab icons when DockView is showing a docking location that
96 // contains more than one tab.
97 const int kTabSpacing
= 4;
99 // DockView is the view responsible for giving a visual indicator of where a
100 // dock is going to occur.
102 class DockView
: public views::View
{
104 explicit DockView(DockInfo::Type type
) : type_(type
) {}
106 virtual gfx::Size
GetPreferredSize() OVERRIDE
{
107 return gfx::Size(DockInfo::popup_width(), DockInfo::popup_height());
110 virtual void OnPaintBackground(gfx::Canvas
* canvas
) OVERRIDE
{
111 // Fill the background rect.
113 paint
.setColor(SkColorSetRGB(108, 108, 108));
114 paint
.setStyle(SkPaint::kFill_Style
);
115 canvas
->DrawRoundRect(GetLocalBounds(), kRoundedRectRadius
, paint
);
117 ui::ResourceBundle
& rb
= ui::ResourceBundle::GetSharedInstance();
119 gfx::ImageSkia
* high_icon
= rb
.GetImageSkiaNamed(IDR_DOCK_HIGH
);
120 gfx::ImageSkia
* wide_icon
= rb
.GetImageSkiaNamed(IDR_DOCK_WIDE
);
123 bool rtl_ui
= base::i18n::IsRTL();
125 // Flip canvas to draw the mirrored tab images for RTL UI.
126 canvas
->Translate(gfx::Vector2d(width(), 0));
127 canvas
->Scale(-1, 1);
129 int x_of_active_tab
= width() / 2 + kTabSpacing
/ 2;
130 int x_of_inactive_tab
= width() / 2 - high_icon
->width() - kTabSpacing
/ 2;
132 case DockInfo::LEFT_OF_WINDOW
:
133 case DockInfo::LEFT_HALF
:
135 std::swap(x_of_active_tab
, x_of_inactive_tab
);
136 canvas
->DrawImageInt(*high_icon
, x_of_active_tab
,
137 (height() - high_icon
->height()) / 2);
138 if (type_
== DockInfo::LEFT_OF_WINDOW
) {
139 DrawImageWithAlpha(canvas
, *high_icon
, x_of_inactive_tab
,
140 (height() - high_icon
->height()) / 2);
145 case DockInfo::RIGHT_OF_WINDOW
:
146 case DockInfo::RIGHT_HALF
:
148 std::swap(x_of_active_tab
, x_of_inactive_tab
);
149 canvas
->DrawImageInt(*high_icon
, x_of_active_tab
,
150 (height() - high_icon
->height()) / 2);
151 if (type_
== DockInfo::RIGHT_OF_WINDOW
) {
152 DrawImageWithAlpha(canvas
, *high_icon
, x_of_inactive_tab
,
153 (height() - high_icon
->height()) / 2);
157 case DockInfo::TOP_OF_WINDOW
:
158 canvas
->DrawImageInt(*wide_icon
, (width() - wide_icon
->width()) / 2,
159 height() / 2 - high_icon
->height());
162 case DockInfo::MAXIMIZE
: {
163 gfx::ImageSkia
* max_icon
= rb
.GetImageSkiaNamed(IDR_DOCK_MAX
);
164 canvas
->DrawImageInt(*max_icon
, (width() - max_icon
->width()) / 2,
165 (height() - max_icon
->height()) / 2);
169 case DockInfo::BOTTOM_HALF
:
170 case DockInfo::BOTTOM_OF_WINDOW
:
171 canvas
->DrawImageInt(*wide_icon
, (width() - wide_icon
->width()) / 2,
172 height() / 2 + kTabSpacing
/ 2);
173 if (type_
== DockInfo::BOTTOM_OF_WINDOW
) {
174 DrawImageWithAlpha(canvas
, *wide_icon
,
175 (width() - wide_icon
->width()) / 2,
176 height() / 2 - kTabSpacing
/ 2 - wide_icon
->height());
188 void DrawImageWithAlpha(gfx::Canvas
* canvas
, const gfx::ImageSkia
& image
,
192 canvas
->DrawImageInt(image
, x
, y
, paint
);
195 DockInfo::Type type_
;
197 DISALLOW_COPY_AND_ASSIGN(DockView
);
200 void SetWindowPositionManaged(gfx::NativeWindow window
, bool value
) {
202 ash::wm::GetWindowState(window
)->set_window_position_managed(value
);
206 // Returns true if |tab_strip| browser window is docked.
207 bool IsDockedOrSnapped(const TabStrip
* tab_strip
) {
210 ash::wm::WindowState
* window_state
=
211 ash::wm::GetWindowState(tab_strip
->GetWidget()->GetNativeWindow());
212 return window_state
->IsDocked() ||
213 window_state
->window_show_type() == ash::wm::SHOW_TYPE_LEFT_SNAPPED
||
214 window_state
->window_show_type() == ash::wm::SHOW_TYPE_RIGHT_SNAPPED
;
219 // Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
220 // of |bounds| is adjusted by |vertical_adjustment|.
221 bool DoesRectContainVerticalPointExpanded(
222 const gfx::Rect
& bounds
,
223 int vertical_adjustment
,
225 int upper_threshold
= bounds
.bottom() + vertical_adjustment
;
226 int lower_threshold
= bounds
.y() - vertical_adjustment
;
227 return y
>= lower_threshold
&& y
<= upper_threshold
;
230 // Adds |x_offset| to all the rectangles in |rects|.
231 void OffsetX(int x_offset
, std::vector
<gfx::Rect
>* rects
) {
235 for (size_t i
= 0; i
< rects
->size(); ++i
)
236 (*rects
)[i
].set_x((*rects
)[i
].x() + x_offset
);
239 // WidgetObserver implementation that resets the window position managed
241 // We're forced to do this here since BrowserFrameAsh resets the 'window
242 // position managed' property during a show and we need the property set to
243 // false before WorkspaceLayoutManager sees the visibility change.
244 class WindowPositionManagedUpdater
: public views::WidgetObserver
{
246 virtual void OnWidgetVisibilityChanged(views::Widget
* widget
,
247 bool visible
) OVERRIDE
{
248 SetWindowPositionManaged(widget
->GetNativeView(), false);
254 ///////////////////////////////////////////////////////////////////////////////
257 // DockDisplayer is responsible for giving the user a visual indication of a
258 // possible dock position (as represented by DockInfo). DockDisplayer shows
259 // a window with a DockView in it. Two animations are used that correspond to
260 // the state of DockInfo::in_enable_area.
261 class TabDragController::DockDisplayer
: public gfx::AnimationDelegate
{
263 DockDisplayer(TabDragController
* controller
, const DockInfo
& info
)
264 : controller_(controller
),
269 in_enable_area_(info
.in_enable_area()) {
270 popup_
= new views::Widget
;
271 views::Widget::InitParams
params(views::Widget::InitParams::TYPE_POPUP
);
272 params
.opacity
= views::Widget::InitParams::TRANSLUCENT_WINDOW
;
273 params
.keep_on_top
= true;
274 params
.bounds
= info
.GetPopupRect();
275 popup_
->Init(params
);
276 popup_
->SetContentsView(new DockView(info
.type()));
277 popup_
->SetOpacity(0x00);
278 if (info
.in_enable_area())
283 popup_view_
= popup_
->GetNativeView();
286 virtual ~DockDisplayer() {
288 controller_
->DockDisplayerDestroyed(this);
291 // Updates the state based on |in_enable_area|.
292 void UpdateInEnabledArea(bool in_enable_area
) {
293 if (in_enable_area
!= in_enable_area_
) {
294 in_enable_area_
= in_enable_area
;
295 UpdateLayeredAlpha();
299 // Resets the reference to the hosting TabDragController. This is
300 // invoked when the TabDragController is destroyed.
301 void clear_controller() { controller_
= NULL
; }
303 // NativeView of the window we create.
304 gfx::NativeView
popup_view() { return popup_view_
; }
306 // Starts the hide animation. When the window is closed the
307 // TabDragController is notified by way of the DockDisplayerDestroyed
321 virtual void AnimationProgressed(const gfx::Animation
* animation
) OVERRIDE
{
322 UpdateLayeredAlpha();
325 virtual void AnimationEnded(const gfx::Animation
* animation
) OVERRIDE
{
333 void UpdateLayeredAlpha() {
334 double scale
= in_enable_area_
? 1 : .5;
335 popup_
->SetOpacity(static_cast<unsigned char>(animation_
.GetCurrentValue() *
339 // TabDragController that created us.
340 TabDragController
* controller_
;
342 // Window we're showing.
343 views::Widget
* popup_
;
345 // NativeView of |popup_|. We cache this to avoid the possibility of
346 // invoking a method on popup_ after we close it.
347 gfx::NativeView popup_view_
;
349 // Animation for when first made visible.
350 gfx::SlideAnimation animation_
;
352 // Have we been hidden?
355 // Value of DockInfo::in_enable_area.
356 bool in_enable_area_
;
359 TabDragController::TabDragData::TabDragData()
361 original_delegate(NULL
),
362 source_model_index(-1),
367 TabDragController::TabDragData::~TabDragData() {
370 ///////////////////////////////////////////////////////////////////////////////
371 // TabDragController, public:
374 const int TabDragController::kTouchVerticalDetachMagnetism
= 50;
377 const int TabDragController::kVerticalDetachMagnetism
= 15;
379 TabDragController::TabDragController()
380 : detach_into_browser_(true),
381 event_source_(EVENT_SOURCE_MOUSE
),
382 source_tabstrip_(NULL
),
383 attached_tabstrip_(NULL
),
385 host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE
),
386 offset_to_width_ratio_(0),
387 old_focused_view_id_(
388 views::ViewStorage::GetInstance()->CreateStorageID()),
389 last_move_screen_loc_(0),
390 started_drag_(false),
392 source_tab_index_(std::numeric_limits
<size_t>::max()),
394 detach_behavior_(DETACHABLE
),
395 move_behavior_(REORDER
),
396 mouse_move_direction_(0),
397 is_dragging_window_(false),
398 is_dragging_new_browser_(false),
399 was_source_maximized_(false),
400 was_source_fullscreen_(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 // Need to delete the view here manually _before_ we reset the dragged
429 // contents to NULL, otherwise if the view is animating to its destination
430 // bounds, it won't be able to clean up properly since its cleanup routine
431 // uses GetIndexForDraggedContents, which will be invalid.
434 // Reset the delegate of the dragged WebContents. This ends up doing nothing
435 // if the drag was completed.
436 if (!detach_into_browser_
)
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
);
493 bool TabDragController::IsAttachedTo(const TabStrip
* tab_strip
) {
494 return (instance_
&& instance_
->active() &&
495 instance_
->attached_tabstrip() == tab_strip
);
499 bool TabDragController::IsActive() {
500 return instance_
&& instance_
->active();
503 void TabDragController::SetMoveBehavior(MoveBehavior behavior
) {
507 move_behavior_
= behavior
;
510 void TabDragController::Drag(const gfx::Point
& point_in_screen
) {
511 TRACE_EVENT1("views", "TabDragController::Drag",
512 "point_in_screen", point_in_screen
.ToString());
514 bring_to_front_timer_
.Stop();
515 move_stacked_timer_
.Stop();
517 if (waiting_for_run_loop_to_exit_
)
520 if (!started_drag_
) {
521 if (!CanStartDrag(point_in_screen
))
522 return; // User hasn't dragged far enough yet.
524 // On windows SaveFocus() may trigger a capture lost, which destroys us.
526 base::WeakPtr
<TabDragController
> ref(weak_factory_
.GetWeakPtr());
531 started_drag_
= true;
532 Attach(source_tabstrip_
, gfx::Point());
533 if (detach_into_browser_
&& static_cast<int>(drag_data_
.size()) ==
534 GetModel(source_tabstrip_
)->count()) {
536 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
&&
537 (was_source_maximized_
|| was_source_fullscreen_
)) {
538 // When all tabs in a maximized browser are dragged the browser gets
539 // restored during the drag and maximized back when the drag ends.
540 views::Widget
* widget
= GetAttachedBrowserWidget();
541 const int last_tabstrip_width
= attached_tabstrip_
->tab_area_width();
542 std::vector
<gfx::Rect
> drag_bounds
= CalculateBoundsForDraggedTabs();
543 OffsetX(GetAttachedDragPoint(point_in_screen
).x(), &drag_bounds
);
544 gfx::Rect
new_bounds(CalculateDraggedBrowserBounds(source_tabstrip_
,
547 new_bounds
.Offset(-widget
->GetRestoredBounds().x() +
548 point_in_screen
.x() -
549 mouse_offset_
.x(), 0);
550 widget
->SetVisibilityChangedAnimationsEnabled(false);
552 widget
->SetBounds(new_bounds
);
553 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width
,
556 widget
->SetVisibilityChangedAnimationsEnabled(true);
557 is_dragging_new_browser_
= true;
560 RunMoveLoop(GetWindowOffset(point_in_screen
));
565 ContinueDragging(point_in_screen
);
568 void TabDragController::EndDrag(EndDragReason reason
) {
569 TRACE_EVENT0("views", "TabDragController::EndDrag");
571 // If we're dragging a window ignore capture lost since it'll ultimately
572 // trigger the move loop to end and we'll revert the drag when RunMoveLoop()
574 if (reason
== END_DRAG_CAPTURE_LOST
&& is_dragging_window_
)
576 EndDragImpl(reason
!= END_DRAG_COMPLETE
&& source_tabstrip_
?
580 void TabDragController::InitTabDragData(Tab
* tab
,
581 TabDragData
* drag_data
) {
582 TRACE_EVENT0("views", "TabDragController::InitTabDragData");
583 drag_data
->source_model_index
=
584 source_tabstrip_
->GetModelIndexOfTab(tab
);
585 drag_data
->contents
= GetModel(source_tabstrip_
)->GetWebContentsAt(
586 drag_data
->source_model_index
);
587 drag_data
->pinned
= source_tabstrip_
->IsTabPinned(tab
);
590 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
591 content::Source
<WebContents
>(drag_data
->contents
));
593 if (!detach_into_browser_
) {
594 drag_data
->original_delegate
= drag_data
->contents
->GetDelegate();
595 drag_data
->contents
->SetDelegate(this);
599 ///////////////////////////////////////////////////////////////////////////////
600 // TabDragController, PageNavigator implementation:
602 WebContents
* TabDragController::OpenURLFromTab(
604 const OpenURLParams
& params
) {
605 if (source_tab_drag_data()->original_delegate
) {
606 OpenURLParams forward_params
= params
;
607 if (params
.disposition
== CURRENT_TAB
)
608 forward_params
.disposition
= NEW_WINDOW
;
610 return source_tab_drag_data()->original_delegate
->OpenURLFromTab(
611 source
, forward_params
);
616 ///////////////////////////////////////////////////////////////////////////////
617 // TabDragController, content::WebContentsDelegate implementation:
619 void TabDragController::NavigationStateChanged(const WebContents
* source
,
620 unsigned changed_flags
) {
621 if (attached_tabstrip_
||
622 changed_flags
== content::INVALIDATE_TYPE_PAGE_ACTIONS
) {
623 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
624 if (drag_data_
[i
].contents
== source
) {
625 // Pass the NavigationStateChanged call to the original delegate so
626 // that the title is updated. Do this only when we are attached as
627 // otherwise the Tab isn't in the TabStrip (except for page action
629 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 void TabDragController::LoadingStateChanged(WebContents
* source
) {
657 // It would be nice to respond to this message by changing the
658 // screen shot in the dragged tab.
663 bool TabDragController::ShouldSuppressDialogs() {
664 // When a dialog is about to be shown we revert the drag. Otherwise a modal
665 // dialog might appear and attempt to parent itself to a hidden tabcontents.
666 EndDragImpl(CANCELED
);
670 content::JavaScriptDialogManager
*
671 TabDragController::GetJavaScriptDialogManager() {
672 return GetJavaScriptDialogManagerInstance();
675 void TabDragController::RequestMediaAccessPermission(
676 content::WebContents
* web_contents
,
677 const content::MediaStreamRequest
& request
,
678 const content::MediaResponseCallback
& callback
) {
679 ::RequestMediaAccessPermission(
681 Profile::FromBrowserContext(web_contents
->GetBrowserContext()),
686 ///////////////////////////////////////////////////////////////////////////////
687 // TabDragController, content::NotificationObserver implementation:
689 void TabDragController::Observe(
691 const content::NotificationSource
& source
,
692 const content::NotificationDetails
& details
) {
693 DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED
, type
);
694 WebContents
* destroyed_web_contents
=
695 content::Source
<WebContents
>(source
).ptr();
696 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
697 if (drag_data_
[i
].contents
== destroyed_web_contents
) {
698 // One of the tabs we're dragging has been destroyed. Cancel the drag.
699 if (destroyed_web_contents
->GetDelegate() == this)
700 destroyed_web_contents
->SetDelegate(NULL
);
701 drag_data_
[i
].contents
= NULL
;
702 drag_data_
[i
].original_delegate
= NULL
;
703 EndDragImpl(TAB_DESTROYED
);
707 // If we get here it means we got notification for a tab we don't know about.
711 ///////////////////////////////////////////////////////////////////////////////
712 // TabDragController, MessageLoop::Observer implementation:
714 base::EventStatus
TabDragController::WillProcessEvent(
715 const base::NativeEvent
& event
) {
716 return base::EVENT_CONTINUE
;
719 void TabDragController::DidProcessEvent(const base::NativeEvent
& event
) {
720 // If the user presses ESC during a drag, we need to abort and revert things
721 // to the way they were. This is the most reliable way to do this since no
722 // single view or window reliably receives events throughout all the various
723 // kinds of tab dragging.
724 if (ui::EventTypeFromNative(event
) == ui::ET_KEY_PRESSED
&&
725 ui::KeyboardCodeFromNative(event
) == ui::VKEY_ESCAPE
) {
726 EndDrag(END_DRAG_CANCEL
);
730 void TabDragController::OnWidgetBoundsChanged(views::Widget
* widget
,
731 const gfx::Rect
& new_bounds
) {
732 TRACE_EVENT1("views", "TabDragController::OnWidgetBoundsChanged",
733 "new_bounds", new_bounds
.ToString());
735 Drag(GetCursorScreenPoint());
738 void TabDragController::TabStripEmpty() {
739 DCHECK(detach_into_browser_
);
740 GetModel(source_tabstrip_
)->RemoveObserver(this);
741 // NULL out source_tabstrip_ so that we don't attempt to add back to it (in
742 // the case of a revert).
743 source_tabstrip_
= NULL
;
746 ///////////////////////////////////////////////////////////////////////////////
747 // TabDragController, private:
749 void TabDragController::InitWindowCreatePoint() {
750 // window_create_point_ is only used in CompleteDrag() (through
751 // GetWindowCreatePoint() to get the start point of the docked window) when
752 // the attached_tabstrip_ is NULL and all the window's related bound
753 // information are obtained from source_tabstrip_. So, we need to get the
754 // first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise,
755 // the window_create_point_ is not in the correct coordinate system. Please
756 // refer to http://crbug.com/6223 comment #15 for detailed information.
757 views::View
* first_tab
= source_tabstrip_
->tab_at(0);
758 views::View::ConvertPointToWidget(first_tab
, &first_source_tab_point_
);
759 window_create_point_
= first_source_tab_point_
;
760 window_create_point_
.Offset(mouse_offset_
.x(), mouse_offset_
.y());
763 gfx::Point
TabDragController::GetWindowCreatePoint(
764 const gfx::Point
& origin
) const {
765 if (dock_info_
.type() != DockInfo::NONE
&& dock_info_
.in_enable_area()) {
766 // If we're going to dock, we need to return the exact coordinate,
767 // otherwise we may attempt to maximize on the wrong monitor.
771 // If the cursor is outside the monitor area, move it inside. For example,
772 // dropping a tab onto the task bar on Windows produces this situation.
773 gfx::Rect work_area
= screen_
->GetDisplayNearestPoint(origin
).work_area();
774 gfx::Point
create_point(origin
);
775 if (!work_area
.IsEmpty()) {
776 if (create_point
.x() < work_area
.x())
777 create_point
.set_x(work_area
.x());
778 else if (create_point
.x() > work_area
.right())
779 create_point
.set_x(work_area
.right());
780 if (create_point
.y() < work_area
.y())
781 create_point
.set_y(work_area
.y());
782 else if (create_point
.y() > work_area
.bottom())
783 create_point
.set_y(work_area
.bottom());
785 return gfx::Point(create_point
.x() - window_create_point_
.x(),
786 create_point
.y() - window_create_point_
.y());
789 void TabDragController::UpdateDockInfo(const gfx::Point
& point_in_screen
) {
790 TRACE_EVENT1("views", "TabDragController::UpdateDockInfo",
791 "point_in_screen", point_in_screen
.ToString());
793 // Update the DockInfo for the current mouse coordinates.
794 DockInfo dock_info
= GetDockInfoAtPoint(point_in_screen
);
795 if (!dock_info
.equals(dock_info_
)) {
796 // DockInfo for current position differs.
797 if (dock_info_
.type() != DockInfo::NONE
&&
798 !dock_controllers_
.empty()) {
799 // Hide old visual indicator.
800 dock_controllers_
.back()->Hide();
802 dock_info_
= dock_info
;
803 if (dock_info_
.type() != DockInfo::NONE
) {
804 // Show new docking position.
805 DockDisplayer
* controller
= new DockDisplayer(this, dock_info_
);
806 if (controller
->popup_view()) {
807 dock_controllers_
.push_back(controller
);
808 dock_windows_
.insert(controller
->popup_view());
813 } else if (dock_info_
.type() != DockInfo::NONE
&&
814 !dock_controllers_
.empty()) {
815 // Current dock position is the same as last, update the controller's
816 // in_enable_area state as it may have changed.
817 dock_controllers_
.back()->UpdateInEnabledArea(dock_info_
.in_enable_area());
821 void TabDragController::SaveFocus() {
822 DCHECK(source_tabstrip_
);
823 views::View
* focused_view
=
824 source_tabstrip_
->GetFocusManager()->GetFocusedView();
826 views::ViewStorage::GetInstance()->StoreView(old_focused_view_id_
,
828 source_tabstrip_
->GetFocusManager()->SetFocusedView(source_tabstrip_
);
829 // WARNING: we may have been deleted.
832 void TabDragController::RestoreFocus() {
833 if (attached_tabstrip_
!= source_tabstrip_
) {
834 if (is_dragging_new_browser_
) {
835 content::WebContents
* active_contents
= source_dragged_contents();
836 if (active_contents
&& !active_contents
->FocusLocationBarByDefault())
837 active_contents
->GetView()->Focus();
841 views::View
* old_focused_view
=
842 views::ViewStorage::GetInstance()->RetrieveView(
843 old_focused_view_id_
);
844 if (!old_focused_view
)
846 old_focused_view
->GetFocusManager()->SetFocusedView(old_focused_view
);
849 bool TabDragController::CanStartDrag(const gfx::Point
& point_in_screen
) const {
850 // Determine if the mouse has moved beyond a minimum elasticity distance in
851 // any direction from the starting point.
852 static const int kMinimumDragDistance
= 10;
853 int x_offset
= abs(point_in_screen
.x() - start_point_in_screen_
.x());
854 int y_offset
= abs(point_in_screen
.y() - start_point_in_screen_
.y());
855 return sqrt(pow(static_cast<float>(x_offset
), 2) +
856 pow(static_cast<float>(y_offset
), 2)) > kMinimumDragDistance
;
859 void TabDragController::ContinueDragging(const gfx::Point
& point_in_screen
) {
860 TRACE_EVENT1("views", "TabDragController::ContinueDragging",
861 "point_in_screen", point_in_screen
.ToString());
863 DCHECK(!detach_into_browser_
|| attached_tabstrip_
);
865 TabStrip
* target_tabstrip
= detach_behavior_
== DETACHABLE
?
866 GetTargetTabStripForPoint(point_in_screen
) : source_tabstrip_
;
867 bool tab_strip_changed
= (target_tabstrip
!= attached_tabstrip_
);
869 if (attached_tabstrip_
) {
870 int move_delta
= point_in_screen
.x() - last_point_in_screen_
.x();
872 mouse_move_direction_
|= kMovedMouseRight
;
873 else if (move_delta
< 0)
874 mouse_move_direction_
|= kMovedMouseLeft
;
876 last_point_in_screen_
= point_in_screen
;
878 if (tab_strip_changed
) {
879 is_dragging_new_browser_
= false;
880 if (detach_into_browser_
&&
881 DragBrowserToNewTabStrip(target_tabstrip
, point_in_screen
) ==
882 DRAG_BROWSER_RESULT_STOP
) {
884 } else if (!detach_into_browser_
) {
885 if (attached_tabstrip_
)
886 Detach(RELEASE_CAPTURE
);
888 Attach(target_tabstrip
, point_in_screen
);
891 if (view_
.get() || is_dragging_window_
) {
892 static_cast<base::Timer
*>(&bring_to_front_timer_
)->Start(FROM_HERE
,
893 base::TimeDelta::FromMilliseconds(kBringToFrontDelay
),
894 base::Bind(&TabDragController::BringWindowUnderPointToFront
,
895 base::Unretained(this), point_in_screen
));
898 UpdateDockInfo(point_in_screen
);
900 if (!is_dragging_window_
) {
901 if (attached_tabstrip_
) {
903 DragActiveTabStacked(point_in_screen
);
905 MoveAttached(point_in_screen
);
906 if (tab_strip_changed
) {
907 // Move the corresponding window to the front. We do this after the
908 // move as on windows activate triggers a synchronous paint.
909 attached_tabstrip_
->GetWidget()->Activate();
913 MoveDetached(point_in_screen
);
918 TabDragController::DragBrowserResultType
919 TabDragController::DragBrowserToNewTabStrip(
920 TabStrip
* target_tabstrip
,
921 const gfx::Point
& point_in_screen
) {
922 TRACE_EVENT1("views", "TabDragController::DragBrowserToNewTabStrip",
923 "point_in_screen", point_in_screen
.ToString());
925 if (!target_tabstrip
) {
926 DetachIntoNewBrowserAndRunMoveLoop(point_in_screen
);
927 return DRAG_BROWSER_RESULT_STOP
;
929 if (is_dragging_window_
) {
930 // ReleaseCapture() is going to result in calling back to us (because it
931 // results in a move). That'll cause all sorts of problems. Reset the
932 // observer so we don't get notified and process the event.
933 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
934 move_loop_widget_
->RemoveObserver(this);
935 move_loop_widget_
= NULL
;
937 views::Widget
* browser_widget
= GetAttachedBrowserWidget();
938 // Need to release the drag controller before starting the move loop as it's
939 // going to trigger capture lost, which cancels drag.
940 attached_tabstrip_
->ReleaseDragController();
941 target_tabstrip
->OwnDragController(this);
942 // Disable animations so that we don't see a close animation on aero.
943 browser_widget
->SetVisibilityChangedAnimationsEnabled(false);
944 // For aura we can't release capture, otherwise it'll cancel a gesture.
945 // Instead we have to directly change capture.
946 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
)
947 target_tabstrip
->GetWidget()->SetCapture(attached_tabstrip_
);
949 browser_widget
->ReleaseCapture();
950 #if defined(OS_WIN) && defined(USE_AURA)
951 // The Gesture recognizer does not work well currently when capture changes
952 // while a touch gesture is in progress. So we need to manually transfer
953 // gesture sequence and the GR's touch events queue to the new window. This
954 // should really be done somewhere in capture change code and or inside the
955 // GR. But we currently do not have a consistent way for doing it that would
956 // work in all cases. Hence this hack.
957 ui::GestureRecognizer::Get()->TransferEventsTo(
958 browser_widget
->GetNativeView(),
959 target_tabstrip
->GetWidget()->GetNativeView());
962 // The window is going away. Since the drag is still on going we don't want
963 // that to effect the position of any windows.
964 SetWindowPositionManaged(browser_widget
->GetNativeView(), false);
966 // EndMoveLoop is going to snap the window back to its original location.
967 // Hide it so users don't see this.
968 browser_widget
->Hide();
969 browser_widget
->EndMoveLoop();
971 // Ideally we would always swap the tabs now, but on non-ash it seems that
972 // running the move loop implicitly activates the window when done, leading
973 // to all sorts of flicker. So, on non-ash, instead we process the move
974 // after the loop completes. But on chromeos, we can do tab swapping now to
975 // avoid the tab flashing issue(crbug.com/116329).
976 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
977 is_dragging_window_
= false;
978 Detach(DONT_RELEASE_CAPTURE
);
979 Attach(target_tabstrip
, point_in_screen
);
980 // Move the tabs into position.
981 MoveAttached(point_in_screen
);
982 attached_tabstrip_
->GetWidget()->Activate();
984 tab_strip_to_attach_to_after_exit_
= target_tabstrip
;
987 waiting_for_run_loop_to_exit_
= true;
988 end_run_loop_behavior_
= END_RUN_LOOP_CONTINUE_DRAGGING
;
989 return DRAG_BROWSER_RESULT_STOP
;
991 Detach(DONT_RELEASE_CAPTURE
);
992 Attach(target_tabstrip
, point_in_screen
);
993 return DRAG_BROWSER_RESULT_CONTINUE
;
996 void TabDragController::DragActiveTabStacked(
997 const gfx::Point
& point_in_screen
) {
998 if (attached_tabstrip_
->tab_count() !=
999 static_cast<int>(initial_tab_positions_
.size()))
1000 return; // TODO: should cancel drag if this happens.
1002 int delta
= point_in_screen
.x() - start_point_in_screen_
.x();
1003 attached_tabstrip_
->DragActiveTab(initial_tab_positions_
, delta
);
1006 void TabDragController::MoveAttachedToNextStackedIndex(
1007 const gfx::Point
& point_in_screen
) {
1008 int index
= attached_tabstrip_
->touch_layout_
->active_index();
1009 if (index
+ 1 >= attached_tabstrip_
->tab_count())
1012 GetModel(attached_tabstrip_
)->MoveSelectedTabsTo(index
+ 1);
1013 StartMoveStackedTimerIfNecessary(point_in_screen
,
1014 kMoveAttachedSubsequentDelay
);
1017 void TabDragController::MoveAttachedToPreviousStackedIndex(
1018 const gfx::Point
& point_in_screen
) {
1019 int index
= attached_tabstrip_
->touch_layout_
->active_index();
1020 if (index
<= attached_tabstrip_
->GetMiniTabCount())
1023 GetModel(attached_tabstrip_
)->MoveSelectedTabsTo(index
- 1);
1024 StartMoveStackedTimerIfNecessary(point_in_screen
,
1025 kMoveAttachedSubsequentDelay
);
1028 void TabDragController::MoveAttached(const gfx::Point
& point_in_screen
) {
1029 DCHECK(attached_tabstrip_
);
1030 DCHECK(!view_
.get());
1031 DCHECK(!is_dragging_window_
);
1033 gfx::Point dragged_view_point
= GetAttachedDragPoint(point_in_screen
);
1035 // Determine the horizontal move threshold. This is dependent on the width
1036 // of tabs. The smaller the tabs compared to the standard size, the smaller
1038 int threshold
= kHorizontalMoveThreshold
;
1039 if (!attached_tabstrip_
->touch_layout_
.get()) {
1040 double unselected
, selected
;
1041 attached_tabstrip_
->GetCurrentTabWidths(&unselected
, &selected
);
1042 double ratio
= unselected
/ Tab::GetStandardSize().width();
1043 threshold
= static_cast<int>(ratio
* kHorizontalMoveThreshold
);
1045 // else case: touch tabs never shrink.
1047 std::vector
<Tab
*> tabs(drag_data_
.size());
1048 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1049 tabs
[i
] = drag_data_
[i
].attached_tab
;
1051 bool did_layout
= false;
1052 // Update the model, moving the WebContents from one index to another. Do this
1053 // only if we have moved a minimum distance since the last reorder (to prevent
1054 // jitter) or if this the first move and the tabs are not consecutive.
1055 if ((abs(point_in_screen
.x() - last_move_screen_loc_
) > threshold
||
1056 (initial_move_
&& !AreTabsConsecutive()))) {
1057 TabStripModel
* attached_model
= GetModel(attached_tabstrip_
);
1058 gfx::Rect bounds
= GetDraggedViewTabStripBounds(dragged_view_point
);
1059 int to_index
= GetInsertionIndexForDraggedBounds(bounds
);
1060 bool do_move
= true;
1061 // While dragging within a tabstrip the expectation is the insertion index
1062 // is based on the left edge of the tabs being dragged. OTOH when dragging
1063 // into a new tabstrip (attaching) the expectation is the insertion index is
1064 // based on the cursor. This proves problematic as insertion may change the
1065 // size of the tabs, resulting in the index calculated before the insert
1066 // differing from the index calculated after the insert. To alleviate this
1067 // the index is chosen before insertion, and subsequently a new index is
1068 // only used once the mouse moves enough such that the index changes based
1069 // on the direction the mouse moved relative to |attach_x_| (smaller
1070 // x-coordinate should yield a smaller index or larger x-coordinate yields a
1072 if (attach_index_
!= -1) {
1073 gfx::Point
tab_strip_point(point_in_screen
);
1074 views::View::ConvertPointFromScreen(attached_tabstrip_
, &tab_strip_point
);
1076 attached_tabstrip_
->GetMirroredXInView(tab_strip_point
.x());
1077 if (new_x
< attach_x_
)
1078 to_index
= std::min(to_index
, attach_index_
);
1080 to_index
= std::max(to_index
, attach_index_
);
1081 if (to_index
!= attach_index_
)
1082 attach_index_
= -1; // Once a valid move is detected, don't constrain.
1087 WebContents
* last_contents
= drag_data_
[drag_data_
.size() - 1].contents
;
1088 int index_of_last_item
=
1089 attached_model
->GetIndexOfWebContents(last_contents
);
1090 if (initial_move_
) {
1091 // TabStrip determines if the tabs needs to be animated based on model
1092 // position. This means we need to invoke LayoutDraggedTabsAt before
1093 // changing the model.
1094 attached_tabstrip_
->LayoutDraggedTabsAt(
1095 tabs
, source_tab_drag_data()->attached_tab
, dragged_view_point
,
1099 attached_model
->MoveSelectedTabsTo(to_index
);
1101 // Move may do nothing in certain situations (such as when dragging pinned
1102 // tabs). Make sure the tabstrip actually changed before updating
1103 // last_move_screen_loc_.
1104 if (index_of_last_item
!=
1105 attached_model
->GetIndexOfWebContents(last_contents
)) {
1106 last_move_screen_loc_
= point_in_screen
.x();
1112 attached_tabstrip_
->LayoutDraggedTabsAt(
1113 tabs
, source_tab_drag_data()->attached_tab
, dragged_view_point
,
1117 StartMoveStackedTimerIfNecessary(point_in_screen
, kMoveAttachedInitialDelay
);
1119 initial_move_
= false;
1122 void TabDragController::MoveDetached(const gfx::Point
& point_in_screen
) {
1123 DCHECK(!attached_tabstrip_
);
1124 DCHECK(view_
.get());
1125 DCHECK(!is_dragging_window_
);
1127 // Move the View. There are no changes to the model if we're detached.
1128 view_
->MoveTo(point_in_screen
);
1131 void TabDragController::StartMoveStackedTimerIfNecessary(
1132 const gfx::Point
& point_in_screen
,
1134 DCHECK(attached_tabstrip_
);
1136 StackedTabStripLayout
* touch_layout
= attached_tabstrip_
->touch_layout_
.get();
1140 gfx::Point dragged_view_point
= GetAttachedDragPoint(point_in_screen
);
1141 gfx::Rect bounds
= GetDraggedViewTabStripBounds(dragged_view_point
);
1142 int index
= touch_layout
->active_index();
1143 if (ShouldDragToNextStackedTab(bounds
, index
)) {
1144 static_cast<base::Timer
*>(&move_stacked_timer_
)->Start(
1146 base::TimeDelta::FromMilliseconds(delay_ms
),
1147 base::Bind(&TabDragController::MoveAttachedToNextStackedIndex
,
1148 base::Unretained(this), point_in_screen
));
1149 } else if (ShouldDragToPreviousStackedTab(bounds
, index
)) {
1150 static_cast<base::Timer
*>(&move_stacked_timer_
)->Start(
1152 base::TimeDelta::FromMilliseconds(delay_ms
),
1153 base::Bind(&TabDragController::MoveAttachedToPreviousStackedIndex
,
1154 base::Unretained(this), point_in_screen
));
1158 TabDragController::DetachPosition
TabDragController::GetDetachPosition(
1159 const gfx::Point
& point_in_screen
) {
1160 DCHECK(attached_tabstrip_
);
1161 gfx::Point
attached_point(point_in_screen
);
1162 views::View::ConvertPointFromScreen(attached_tabstrip_
, &attached_point
);
1163 if (attached_point
.x() < 0)
1164 return DETACH_BEFORE
;
1165 if (attached_point
.x() >= attached_tabstrip_
->width())
1166 return DETACH_AFTER
;
1167 return DETACH_ABOVE_OR_BELOW
;
1170 DockInfo
TabDragController::GetDockInfoAtPoint(
1171 const gfx::Point
& point_in_screen
) {
1172 // TODO: add support for dock info when |detach_into_browser_| is true.
1173 if (attached_tabstrip_
|| detach_into_browser_
) {
1174 // If the mouse is over a tab strip, don't offer a dock position.
1178 if (dock_info_
.IsValidForPoint(point_in_screen
)) {
1179 // It's possible any given screen coordinate has multiple docking
1180 // positions. Check the current info first to avoid having the docking
1181 // position bounce around.
1185 gfx::NativeView dragged_view
= view_
->GetWidget()->GetNativeView();
1186 dock_windows_
.insert(dragged_view
);
1187 DockInfo info
= DockInfo::GetDockInfoAtPoint(
1191 dock_windows_
.erase(dragged_view
);
1195 TabStrip
* TabDragController::GetTargetTabStripForPoint(
1196 const gfx::Point
& point_in_screen
) {
1197 TRACE_EVENT1("views", "TabDragController::GetTargetTabStripForPoint",
1198 "point_in_screen", point_in_screen
.ToString());
1200 if (move_only() && attached_tabstrip_
) {
1201 DCHECK_EQ(DETACHABLE
, detach_behavior_
);
1202 // move_only() is intended for touch, in which case we only want to detach
1203 // if the touch point moves significantly in the vertical distance.
1204 gfx::Rect tabstrip_bounds
= GetViewScreenBounds(attached_tabstrip_
);
1205 if (DoesRectContainVerticalPointExpanded(tabstrip_bounds
,
1206 kTouchVerticalDetachMagnetism
,
1207 point_in_screen
.y()))
1208 return attached_tabstrip_
;
1210 gfx::NativeView dragged_view
= NULL
;
1212 dragged_view
= view_
->GetWidget()->GetNativeView();
1213 else if (is_dragging_window_
)
1214 dragged_view
= attached_tabstrip_
->GetWidget()->GetNativeView();
1216 dock_windows_
.insert(dragged_view
);
1217 gfx::NativeWindow local_window
=
1218 DockInfo::GetLocalProcessWindowAtPoint(
1223 dock_windows_
.erase(dragged_view
);
1224 TabStrip
* tab_strip
= GetTabStripForWindow(local_window
);
1225 if (tab_strip
&& DoesTabStripContain(tab_strip
, point_in_screen
))
1227 return is_dragging_window_
? attached_tabstrip_
: NULL
;
1230 TabStrip
* TabDragController::GetTabStripForWindow(gfx::NativeWindow window
) {
1233 BrowserView
* browser_view
=
1234 BrowserView::GetBrowserViewForNativeWindow(window
);
1235 // We don't allow drops on windows that don't have tabstrips.
1236 if (!browser_view
||
1237 !browser_view
->browser()->SupportsWindowFeature(
1238 Browser::FEATURE_TABSTRIP
))
1241 TabStrip
* other_tabstrip
= browser_view
->tabstrip();
1242 TabStrip
* tab_strip
=
1243 attached_tabstrip_
? attached_tabstrip_
: source_tabstrip_
;
1246 return other_tabstrip
->controller()->IsCompatibleWith(tab_strip
) ?
1247 other_tabstrip
: NULL
;
1250 bool TabDragController::DoesTabStripContain(
1252 const gfx::Point
& point_in_screen
) const {
1253 // Make sure the specified screen point is actually within the bounds of the
1254 // specified tabstrip...
1255 gfx::Rect tabstrip_bounds
= GetViewScreenBounds(tabstrip
);
1256 return point_in_screen
.x() < tabstrip_bounds
.right() &&
1257 point_in_screen
.x() >= tabstrip_bounds
.x() &&
1258 DoesRectContainVerticalPointExpanded(tabstrip_bounds
,
1259 kVerticalDetachMagnetism
,
1260 point_in_screen
.y());
1263 void TabDragController::Attach(TabStrip
* attached_tabstrip
,
1264 const gfx::Point
& point_in_screen
) {
1265 TRACE_EVENT1("views", "TabDragController::Attach",
1266 "point_in_screen", point_in_screen
.ToString());
1268 DCHECK(!attached_tabstrip_
); // We should already have detached by the time
1271 attached_tabstrip_
= attached_tabstrip
;
1273 // And we don't need the dragged view.
1276 std::vector
<Tab
*> tabs
=
1277 GetTabsMatchingDraggedContents(attached_tabstrip_
);
1280 // Transitioning from detached to attached to a new tabstrip. Add tabs to
1283 selection_model_before_attach_
.Copy(attached_tabstrip
->GetSelectionModel());
1285 if (!detach_into_browser_
) {
1286 // Remove ourselves as the delegate now that the dragged WebContents is
1287 // being inserted back into a Browser.
1288 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1289 drag_data_
[i
].contents
->SetDelegate(NULL
);
1290 drag_data_
[i
].original_delegate
= NULL
;
1293 // Return the WebContents to normalcy.
1294 source_dragged_contents()->DecrementCapturerCount();
1297 // Inserting counts as a move. We don't want the tabs to jitter when the
1298 // user moves the tab immediately after attaching it.
1299 last_move_screen_loc_
= point_in_screen
.x();
1301 // Figure out where to insert the tab based on the bounds of the dragged
1302 // representation and the ideal bounds of the other Tabs already in the
1303 // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
1304 // changing due to animation).
1305 gfx::Point
tab_strip_point(point_in_screen
);
1306 views::View::ConvertPointFromScreen(attached_tabstrip_
, &tab_strip_point
);
1307 tab_strip_point
.set_x(
1308 attached_tabstrip_
->GetMirroredXInView(tab_strip_point
.x()));
1309 tab_strip_point
.Offset(0, -mouse_offset_
.y());
1310 gfx::Rect bounds
= GetDraggedViewTabStripBounds(tab_strip_point
);
1311 int index
= GetInsertionIndexForDraggedBounds(bounds
);
1312 attach_index_
= index
;
1313 attach_x_
= tab_strip_point
.x();
1314 base::AutoReset
<bool> setter(&is_mutating_
, true);
1315 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1316 int add_types
= TabStripModel::ADD_NONE
;
1317 if (attached_tabstrip_
->touch_layout_
.get()) {
1318 // StackedTabStripLayout positions relative to the active tab, if we
1319 // don't add the tab as active things bounce around.
1320 DCHECK_EQ(1u, drag_data_
.size());
1321 add_types
|= TabStripModel::ADD_ACTIVE
;
1323 if (drag_data_
[i
].pinned
)
1324 add_types
|= TabStripModel::ADD_PINNED
;
1325 GetModel(attached_tabstrip_
)->InsertWebContentsAt(
1326 index
+ i
, drag_data_
[i
].contents
, add_types
);
1329 tabs
= GetTabsMatchingDraggedContents(attached_tabstrip_
);
1331 DCHECK_EQ(tabs
.size(), drag_data_
.size());
1332 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1333 drag_data_
[i
].attached_tab
= tabs
[i
];
1335 attached_tabstrip_
->StartedDraggingTabs(tabs
);
1337 ResetSelection(GetModel(attached_tabstrip_
));
1339 // The size of the dragged tab may have changed. Adjust the x offset so that
1340 // ratio of mouse_offset_ to original width is maintained.
1341 std::vector
<Tab
*> tabs_to_source(tabs
);
1342 tabs_to_source
.erase(tabs_to_source
.begin() + source_tab_index_
+ 1,
1343 tabs_to_source
.end());
1344 int new_x
= attached_tabstrip_
->GetSizeNeededForTabs(tabs_to_source
) -
1345 tabs
[source_tab_index_
]->width() +
1346 static_cast<int>(offset_to_width_ratio_
*
1347 tabs
[source_tab_index_
]->width());
1348 mouse_offset_
.set_x(new_x
);
1350 // Transfer ownership of us to the new tabstrip as well as making sure the
1351 // window has capture. This is important so that if activation changes the
1352 // drag isn't prematurely canceled.
1353 if (detach_into_browser_
) {
1354 attached_tabstrip_
->GetWidget()->SetCapture(attached_tabstrip_
);
1355 attached_tabstrip_
->OwnDragController(this);
1358 // Redirect all mouse events to the TabStrip so that the tab that originated
1359 // the drag can safely be deleted.
1360 if (detach_into_browser_
|| attached_tabstrip_
== source_tabstrip_
) {
1361 static_cast<views::internal::RootView
*>(
1362 attached_tabstrip_
->GetWidget()->GetRootView())->SetMouseHandler(
1363 attached_tabstrip_
);
1367 void TabDragController::Detach(ReleaseCapture release_capture
) {
1368 TRACE_EVENT1("views", "TabDragController::Detach",
1369 "release_capture", release_capture
);
1373 // When the user detaches we assume they want to reorder.
1374 move_behavior_
= REORDER
;
1376 // Release ownership of the drag controller and mouse capture. When we
1377 // reattach ownership is transfered.
1378 if (detach_into_browser_
) {
1379 attached_tabstrip_
->ReleaseDragController();
1380 if (release_capture
== RELEASE_CAPTURE
)
1381 attached_tabstrip_
->GetWidget()->ReleaseCapture();
1384 mouse_move_direction_
= kMovedMouseLeft
| kMovedMouseRight
;
1386 // Prevent the WebContents HWND from being hidden by any of the model
1387 // operations performed during the drag.
1388 if (!detach_into_browser_
)
1389 source_dragged_contents()->IncrementCapturerCount();
1391 std::vector
<gfx::Rect
> drag_bounds
= CalculateBoundsForDraggedTabs();
1392 TabStripModel
* attached_model
= GetModel(attached_tabstrip_
);
1393 std::vector
<TabRendererData
> tab_data
;
1394 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1395 tab_data
.push_back(drag_data_
[i
].attached_tab
->data());
1396 int index
= attached_model
->GetIndexOfWebContents(drag_data_
[i
].contents
);
1397 DCHECK_NE(-1, index
);
1399 // Hide the tab so that the user doesn't see it animate closed.
1400 drag_data_
[i
].attached_tab
->SetVisible(false);
1402 attached_model
->DetachWebContentsAt(index
);
1404 // Detaching resets the delegate, but we still want to be the delegate.
1405 if (!detach_into_browser_
)
1406 drag_data_
[i
].contents
->SetDelegate(this);
1408 // Detaching may end up deleting the tab, drop references to it.
1409 drag_data_
[i
].attached_tab
= NULL
;
1412 // If we've removed the last Tab from the TabStrip, hide the frame now.
1413 if (!attached_model
->empty()) {
1414 if (!selection_model_before_attach_
.empty() &&
1415 selection_model_before_attach_
.active() >= 0 &&
1416 selection_model_before_attach_
.active() < attached_model
->count()) {
1417 // Restore the selection.
1418 attached_model
->SetSelectionFromModel(selection_model_before_attach_
);
1419 } else if (attached_tabstrip_
== source_tabstrip_
&&
1420 !initial_selection_model_
.empty()) {
1421 // First time detaching from the source tabstrip. Reset selection model to
1422 // initial_selection_model_. Before resetting though we have to remove all
1423 // the tabs from initial_selection_model_ as it was created with the tabs
1425 ui::ListSelectionModel selection_model
;
1426 selection_model
.Copy(initial_selection_model_
);
1427 for (DragData::const_reverse_iterator
i(drag_data_
.rbegin());
1428 i
!= drag_data_
.rend(); ++i
) {
1429 selection_model
.DecrementFrom(i
->source_model_index
);
1431 // We may have cleared out the selection model. Only reset it if it
1432 // contains something.
1433 if (!selection_model
.empty())
1434 attached_model
->SetSelectionFromModel(selection_model
);
1438 // Create the dragged view.
1439 if (!detach_into_browser_
)
1440 CreateDraggedView(tab_data
, drag_bounds
);
1442 attached_tabstrip_
->DraggedTabsDetached();
1443 attached_tabstrip_
= NULL
;
1446 void TabDragController::DetachIntoNewBrowserAndRunMoveLoop(
1447 const gfx::Point
& point_in_screen
) {
1448 if (GetModel(attached_tabstrip_
)->count() ==
1449 static_cast<int>(drag_data_
.size())) {
1450 // All the tabs in a browser are being dragged but all the tabs weren't
1451 // initially being dragged. For this to happen the user would have to
1452 // start dragging a set of tabs, the other tabs close, then detach.
1453 RunMoveLoop(GetWindowOffset(point_in_screen
));
1457 const int last_tabstrip_width
= attached_tabstrip_
->tab_area_width();
1458 std::vector
<gfx::Rect
> drag_bounds
= CalculateBoundsForDraggedTabs();
1459 OffsetX(GetAttachedDragPoint(point_in_screen
).x(), &drag_bounds
);
1461 gfx::Vector2d drag_offset
;
1462 Browser
* browser
= CreateBrowserForDrag(
1463 attached_tabstrip_
, point_in_screen
, &drag_offset
, &drag_bounds
);
1464 #if defined(OS_WIN) && defined(USE_AURA)
1465 gfx::NativeView attached_native_view
=
1466 attached_tabstrip_
->GetWidget()->GetNativeView();
1468 Detach(host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
?
1469 DONT_RELEASE_CAPTURE
: RELEASE_CAPTURE
);
1470 BrowserView
* dragged_browser_view
=
1471 BrowserView::GetBrowserViewForBrowser(browser
);
1472 views::Widget
* dragged_widget
= dragged_browser_view
->GetWidget();
1473 #if defined(OS_WIN) && defined(USE_AURA)
1474 // The Gesture recognizer does not work well currently when capture changes
1475 // while a touch gesture is in progress. So we need to manually transfer
1476 // gesture sequence and the GR's touch events queue to the new window. This
1477 // should really be done somewhere in capture change code and or inside the
1478 // GR. But we currently do not have a consistent way for doing it that would
1479 // work in all cases. Hence this hack.
1480 ui::GestureRecognizer::Get()->TransferEventsTo(
1481 attached_native_view
,
1482 dragged_widget
->GetNativeView());
1484 dragged_widget
->SetVisibilityChangedAnimationsEnabled(false);
1485 Attach(dragged_browser_view
->tabstrip(), gfx::Point());
1486 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width
,
1489 WindowPositionManagedUpdater updater
;
1490 dragged_widget
->AddObserver(&updater
);
1491 browser
->window()->Show();
1492 dragged_widget
->RemoveObserver(&updater
);
1493 dragged_widget
->SetVisibilityChangedAnimationsEnabled(true);
1494 // Activate may trigger a focus loss, destroying us.
1496 base::WeakPtr
<TabDragController
> ref(weak_factory_
.GetWeakPtr());
1497 browser
->window()->Activate();
1501 RunMoveLoop(drag_offset
);
1504 void TabDragController::RunMoveLoop(const gfx::Vector2d
& drag_offset
) {
1505 // If the user drags the whole window we'll assume they are going to attach to
1506 // another window and therefore want to reorder.
1507 move_behavior_
= REORDER
;
1509 move_loop_widget_
= GetAttachedBrowserWidget();
1510 DCHECK(move_loop_widget_
);
1511 move_loop_widget_
->AddObserver(this);
1512 is_dragging_window_
= true;
1513 base::WeakPtr
<TabDragController
> ref(weak_factory_
.GetWeakPtr());
1514 // Running the move loop releases mouse capture on non-ash, which triggers
1515 // destroying the drag loop. Release mouse capture ourself before this while
1516 // the DragController isn't owned by the TabStrip.
1517 if (host_desktop_type_
!= chrome::HOST_DESKTOP_TYPE_ASH
) {
1518 attached_tabstrip_
->ReleaseDragController();
1519 attached_tabstrip_
->GetWidget()->ReleaseCapture();
1520 attached_tabstrip_
->OwnDragController(this);
1522 const views::Widget::MoveLoopSource move_loop_source
=
1523 event_source_
== EVENT_SOURCE_MOUSE
?
1524 views::Widget::MOVE_LOOP_SOURCE_MOUSE
:
1525 views::Widget::MOVE_LOOP_SOURCE_TOUCH
;
1526 const views::Widget::MoveLoopEscapeBehavior escape_behavior
=
1527 is_dragging_new_browser_
?
1528 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE
:
1529 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE
;
1530 views::Widget::MoveLoopResult result
=
1531 move_loop_widget_
->RunMoveLoop(
1532 drag_offset
, move_loop_source
, escape_behavior
);
1533 content::NotificationService::current()->Notify(
1534 chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE
,
1535 content::NotificationService::AllBrowserContextsAndSources(),
1536 content::NotificationService::NoDetails());
1540 // Under chromeos we immediately set the |move_loop_widget_| to NULL.
1541 if (move_loop_widget_
) {
1542 move_loop_widget_
->RemoveObserver(this);
1543 move_loop_widget_
= NULL
;
1545 is_dragging_window_
= false;
1546 waiting_for_run_loop_to_exit_
= false;
1547 if (end_run_loop_behavior_
== END_RUN_LOOP_CONTINUE_DRAGGING
) {
1548 end_run_loop_behavior_
= END_RUN_LOOP_STOP_DRAGGING
;
1549 if (tab_strip_to_attach_to_after_exit_
) {
1550 gfx::Point
point_in_screen(GetCursorScreenPoint());
1551 Detach(DONT_RELEASE_CAPTURE
);
1552 Attach(tab_strip_to_attach_to_after_exit_
, point_in_screen
);
1553 // Move the tabs into position.
1554 MoveAttached(point_in_screen
);
1555 attached_tabstrip_
->GetWidget()->Activate();
1556 // Activate may trigger a focus loss, destroying us.
1559 tab_strip_to_attach_to_after_exit_
= NULL
;
1561 DCHECK(attached_tabstrip_
);
1562 attached_tabstrip_
->GetWidget()->SetCapture(attached_tabstrip_
);
1563 } else if (active_
) {
1564 EndDrag(result
== views::Widget::MOVE_LOOP_CANCELED
?
1565 END_DRAG_CANCEL
: END_DRAG_COMPLETE
);
1569 int TabDragController::GetInsertionIndexFrom(const gfx::Rect
& dragged_bounds
,
1572 for (int i
= start
, tab_count
= attached_tabstrip_
->tab_count();
1573 i
>= 0 && i
< tab_count
; i
+= delta
) {
1574 const gfx::Rect
& ideal_bounds
= attached_tabstrip_
->ideal_bounds(i
);
1575 gfx::Rect left_half
, right_half
;
1576 ideal_bounds
.SplitVertically(&left_half
, &right_half
);
1577 if (dragged_bounds
.x() >= right_half
.x() &&
1578 dragged_bounds
.x() < right_half
.right()) {
1580 } else if (dragged_bounds
.x() >= left_half
.x() &&
1581 dragged_bounds
.x() < left_half
.right()) {
1588 int TabDragController::GetInsertionIndexForDraggedBounds(
1589 const gfx::Rect
& dragged_bounds
) const {
1591 if (attached_tabstrip_
->touch_layout_
.get()) {
1592 index
= GetInsertionIndexForDraggedBoundsStacked(dragged_bounds
);
1594 // Only move the tab to the left/right if the user actually moved the
1595 // mouse that way. This is necessary as tabs with stacked tabs
1596 // before/after them have multiple drag positions.
1597 int active_index
= attached_tabstrip_
->touch_layout_
->active_index();
1598 if ((index
< active_index
&&
1599 (mouse_move_direction_
& kMovedMouseLeft
) == 0) ||
1600 (index
> active_index
&&
1601 (mouse_move_direction_
& kMovedMouseRight
) == 0)) {
1602 index
= active_index
;
1606 index
= GetInsertionIndexFrom(dragged_bounds
, 0, 1);
1609 int tab_count
= attached_tabstrip_
->tab_count();
1610 int right_tab_x
= tab_count
== 0 ? 0 :
1611 attached_tabstrip_
->ideal_bounds(tab_count
- 1).right();
1612 if (dragged_bounds
.right() > right_tab_x
) {
1613 index
= GetModel(attached_tabstrip_
)->count();
1619 if (!drag_data_
[0].attached_tab
) {
1620 // If 'attached_tab' is NULL, it means we're in the process of attaching and
1621 // don't need to constrain the index.
1625 int max_index
= GetModel(attached_tabstrip_
)->count() -
1626 static_cast<int>(drag_data_
.size());
1627 return std::max(0, std::min(max_index
, index
));
1630 bool TabDragController::ShouldDragToNextStackedTab(
1631 const gfx::Rect
& dragged_bounds
,
1633 if (index
+ 1 >= attached_tabstrip_
->tab_count() ||
1634 !attached_tabstrip_
->touch_layout_
->IsStacked(index
+ 1) ||
1635 (mouse_move_direction_
& kMovedMouseRight
) == 0)
1638 int active_x
= attached_tabstrip_
->ideal_bounds(index
).x();
1639 int next_x
= attached_tabstrip_
->ideal_bounds(index
+ 1).x();
1640 int mid_x
= std::min(next_x
- kStackedDistance
,
1641 active_x
+ (next_x
- active_x
) / 4);
1642 return dragged_bounds
.x() >= mid_x
;
1645 bool TabDragController::ShouldDragToPreviousStackedTab(
1646 const gfx::Rect
& dragged_bounds
,
1648 if (index
- 1 < attached_tabstrip_
->GetMiniTabCount() ||
1649 !attached_tabstrip_
->touch_layout_
->IsStacked(index
- 1) ||
1650 (mouse_move_direction_
& kMovedMouseLeft
) == 0)
1653 int active_x
= attached_tabstrip_
->ideal_bounds(index
).x();
1654 int previous_x
= attached_tabstrip_
->ideal_bounds(index
- 1).x();
1655 int mid_x
= std::max(previous_x
+ kStackedDistance
,
1656 active_x
- (active_x
- previous_x
) / 4);
1657 return dragged_bounds
.x() <= mid_x
;
1660 int TabDragController::GetInsertionIndexForDraggedBoundsStacked(
1661 const gfx::Rect
& dragged_bounds
) const {
1662 StackedTabStripLayout
* touch_layout
= attached_tabstrip_
->touch_layout_
.get();
1663 int active_index
= touch_layout
->active_index();
1664 // Search from the active index to the front of the tabstrip. Do this as tabs
1665 // overlap each other from the active index.
1666 int index
= GetInsertionIndexFrom(dragged_bounds
, active_index
, -1);
1667 if (index
!= active_index
)
1670 return GetInsertionIndexFrom(dragged_bounds
, active_index
+ 1, 1);
1672 // The position to drag to corresponds to the active tab. If the next/previous
1673 // tab is stacked, then shorten the distance used to determine insertion
1674 // bounds. We do this as GetInsertionIndexFrom() uses the bounds of the
1675 // tabs. When tabs are stacked the next/previous tab is on top of the tab.
1676 if (active_index
+ 1 < attached_tabstrip_
->tab_count() &&
1677 touch_layout
->IsStacked(active_index
+ 1)) {
1678 index
= GetInsertionIndexFrom(dragged_bounds
, active_index
+ 1, 1);
1679 if (index
== -1 && ShouldDragToNextStackedTab(dragged_bounds
, active_index
))
1680 index
= active_index
+ 1;
1681 else if (index
== -1)
1682 index
= active_index
;
1683 } else if (ShouldDragToPreviousStackedTab(dragged_bounds
, active_index
)) {
1684 index
= active_index
- 1;
1689 gfx::Rect
TabDragController::GetDraggedViewTabStripBounds(
1690 const gfx::Point
& tab_strip_point
) {
1691 // attached_tab is NULL when inserting into a new tabstrip.
1692 if (source_tab_drag_data()->attached_tab
) {
1693 return gfx::Rect(tab_strip_point
.x(), tab_strip_point
.y(),
1694 source_tab_drag_data()->attached_tab
->width(),
1695 source_tab_drag_data()->attached_tab
->height());
1698 double sel_width
, unselected_width
;
1699 attached_tabstrip_
->GetCurrentTabWidths(&sel_width
, &unselected_width
);
1700 return gfx::Rect(tab_strip_point
.x(), tab_strip_point
.y(),
1701 static_cast<int>(sel_width
),
1702 Tab::GetStandardSize().height());
1705 gfx::Point
TabDragController::GetAttachedDragPoint(
1706 const gfx::Point
& point_in_screen
) {
1707 DCHECK(attached_tabstrip_
); // The tab must be attached.
1709 gfx::Point
tab_loc(point_in_screen
);
1710 views::View::ConvertPointFromScreen(attached_tabstrip_
, &tab_loc
);
1712 attached_tabstrip_
->GetMirroredXInView(tab_loc
.x()) - mouse_offset_
.x();
1714 // TODO: consider caching this.
1715 std::vector
<Tab
*> attached_tabs
;
1716 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1717 attached_tabs
.push_back(drag_data_
[i
].attached_tab
);
1718 const int size
= attached_tabstrip_
->GetSizeNeededForTabs(attached_tabs
);
1719 const int max_x
= attached_tabstrip_
->width() - size
;
1720 return gfx::Point(std::min(std::max(x
, 0), max_x
), 0);
1723 std::vector
<Tab
*> TabDragController::GetTabsMatchingDraggedContents(
1724 TabStrip
* tabstrip
) {
1725 TabStripModel
* model
= GetModel(attached_tabstrip_
);
1726 std::vector
<Tab
*> tabs
;
1727 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1728 int model_index
= model
->GetIndexOfWebContents(drag_data_
[i
].contents
);
1729 if (model_index
== TabStripModel::kNoTab
)
1730 return std::vector
<Tab
*>();
1731 tabs
.push_back(tabstrip
->tab_at(model_index
));
1736 std::vector
<gfx::Rect
> TabDragController::CalculateBoundsForDraggedTabs() {
1737 std::vector
<gfx::Rect
> drag_bounds
;
1738 std::vector
<Tab
*> attached_tabs
;
1739 for (size_t i
= 0; i
< drag_data_
.size(); ++i
)
1740 attached_tabs
.push_back(drag_data_
[i
].attached_tab
);
1741 attached_tabstrip_
->CalculateBoundsForDraggedTabs(attached_tabs
,
1746 void TabDragController::EndDragImpl(EndDragType type
) {
1750 bring_to_front_timer_
.Stop();
1751 move_stacked_timer_
.Stop();
1753 if (is_dragging_window_
) {
1754 waiting_for_run_loop_to_exit_
= true;
1756 if (type
== NORMAL
|| (type
== TAB_DESTROYED
&& drag_data_
.size() > 1)) {
1757 SetWindowPositionManaged(GetAttachedBrowserWidget()->GetNativeView(),
1761 // End the nested drag loop.
1762 GetAttachedBrowserWidget()->EndMoveLoop();
1765 // Hide the current dock controllers.
1766 for (size_t i
= 0; i
< dock_controllers_
.size(); ++i
) {
1767 // Be sure and clear the controller first, that way if Hide ends up
1768 // deleting the controller it won't call us back.
1769 dock_controllers_
[i
]->clear_controller();
1770 dock_controllers_
[i
]->Hide();
1772 dock_controllers_
.clear();
1773 dock_windows_
.clear();
1775 if (type
!= TAB_DESTROYED
) {
1776 // We only finish up the drag if we were actually dragging. If start_drag_
1777 // is false, the user just clicked and released and didn't move the mouse
1778 // enough to trigger a drag.
1779 if (started_drag_
) {
1781 if (type
== CANCELED
)
1786 } else if (drag_data_
.size() > 1) {
1787 initial_selection_model_
.Clear();
1789 } // else case the only tab we were dragging was deleted. Nothing to do.
1791 if (!detach_into_browser_
)
1794 // Clear out drag data so we don't attempt to do anything with it.
1797 TabStrip
* owning_tabstrip
= (attached_tabstrip_
&& detach_into_browser_
) ?
1798 attached_tabstrip_
: source_tabstrip_
;
1799 owning_tabstrip
->DestroyDragController();
1802 void TabDragController::RevertDrag() {
1803 std::vector
<Tab
*> tabs
;
1804 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1805 if (drag_data_
[i
].contents
) {
1806 // Contents is NULL if a tab was destroyed while the drag was under way.
1807 tabs
.push_back(drag_data_
[i
].attached_tab
);
1812 bool restore_frame
= !detach_into_browser_
&&
1813 attached_tabstrip_
!= source_tabstrip_
;
1814 if (attached_tabstrip_
) {
1815 if (attached_tabstrip_
== source_tabstrip_
) {
1816 source_tabstrip_
->StoppedDraggingTabs(
1817 tabs
, initial_tab_positions_
, move_behavior_
== MOVE_VISIBILE_TABS
,
1820 attached_tabstrip_
->DraggedTabsDetached();
1824 if (initial_selection_model_
.empty())
1825 ResetSelection(GetModel(source_tabstrip_
));
1827 GetModel(source_tabstrip_
)->SetSelectionFromModel(initial_selection_model_
);
1829 // If we're not attached to any TabStrip, or attached to some other TabStrip,
1830 // we need to restore the bounds of the original TabStrip's frame, in case
1831 // it has been hidden.
1832 if (restore_frame
&& !restore_bounds_
.IsEmpty())
1833 source_tabstrip_
->GetWidget()->SetBounds(restore_bounds_
);
1835 if (detach_into_browser_
&& source_tabstrip_
)
1836 source_tabstrip_
->GetWidget()->Activate();
1838 // Return the WebContents to normalcy. If the tab was attached to a
1839 // TabStrip before the revert, the decrement has already occurred.
1840 // If the tab was destroyed, don't attempt to dereference the
1841 // WebContents pointer.
1842 if (!detach_into_browser_
&& !attached_tabstrip_
&& source_dragged_contents())
1843 source_dragged_contents()->DecrementCapturerCount();
1846 void TabDragController::ResetSelection(TabStripModel
* model
) {
1848 ui::ListSelectionModel selection_model
;
1849 bool has_one_valid_tab
= false;
1850 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1851 // |contents| is NULL if a tab was deleted out from under us.
1852 if (drag_data_
[i
].contents
) {
1853 int index
= model
->GetIndexOfWebContents(drag_data_
[i
].contents
);
1854 DCHECK_NE(-1, index
);
1855 selection_model
.AddIndexToSelection(index
);
1856 if (!has_one_valid_tab
|| i
== source_tab_index_
) {
1857 // Reset the active/lead to the first tab. If the source tab is still
1858 // valid we'll reset these again later on.
1859 selection_model
.set_active(index
);
1860 selection_model
.set_anchor(index
);
1861 has_one_valid_tab
= true;
1865 if (!has_one_valid_tab
)
1868 model
->SetSelectionFromModel(selection_model
);
1871 void TabDragController::RevertDragAt(size_t drag_index
) {
1872 DCHECK(started_drag_
);
1873 DCHECK(source_tabstrip_
);
1875 base::AutoReset
<bool> setter(&is_mutating_
, true);
1876 TabDragData
* data
= &(drag_data_
[drag_index
]);
1877 if (attached_tabstrip_
) {
1879 GetModel(attached_tabstrip_
)->GetIndexOfWebContents(data
->contents
);
1880 if (attached_tabstrip_
!= source_tabstrip_
) {
1881 // The Tab was inserted into another TabStrip. We need to put it back
1882 // into the original one.
1883 GetModel(attached_tabstrip_
)->DetachWebContentsAt(index
);
1884 // TODO(beng): (Cleanup) seems like we should use Attach() for this
1886 GetModel(source_tabstrip_
)->InsertWebContentsAt(
1887 data
->source_model_index
, data
->contents
,
1888 (data
->pinned
? TabStripModel::ADD_PINNED
: 0));
1890 // The Tab was moved within the TabStrip where the drag was initiated.
1891 // Move it back to the starting location.
1892 GetModel(source_tabstrip_
)->MoveWebContentsAt(
1893 index
, data
->source_model_index
, false);
1896 // The Tab was detached from the TabStrip where the drag began, and has not
1897 // been attached to any other TabStrip. We need to put it back into the
1899 GetModel(source_tabstrip_
)->InsertWebContentsAt(
1900 data
->source_model_index
, data
->contents
,
1901 (data
->pinned
? TabStripModel::ADD_PINNED
: 0));
1905 void TabDragController::CompleteDrag() {
1906 DCHECK(started_drag_
);
1908 if (attached_tabstrip_
) {
1909 if (is_dragging_new_browser_
) {
1910 if (IsDockedOrSnapped(attached_tabstrip_
)) {
1911 DCHECK_EQ(host_desktop_type_
, chrome::HOST_DESKTOP_TYPE_ASH
);
1912 was_source_maximized_
= false;
1913 was_source_fullscreen_
= false;
1915 // If source window was maximized - maximize the new window as well.
1916 if (was_source_maximized_
|| was_source_fullscreen_
)
1917 GetAttachedBrowserWidget()->Maximize();
1918 #if defined(USE_ASH)
1919 if (was_source_fullscreen_
&&
1920 host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
1921 // In fullscreen mode it is only possible to get here if the source
1922 // was in "immersive fullscreen" mode, so toggle it back on.
1923 ash::accelerators::ToggleFullscreen();
1927 attached_tabstrip_
->StoppedDraggingTabs(
1928 GetTabsMatchingDraggedContents(attached_tabstrip_
),
1929 initial_tab_positions_
,
1930 move_behavior_
== MOVE_VISIBILE_TABS
,
1933 if (dock_info_
.type() != DockInfo::NONE
) {
1934 switch (dock_info_
.type()) {
1935 case DockInfo::LEFT_OF_WINDOW
:
1936 content::RecordAction(UserMetricsAction("DockingWindow_Left"));
1939 case DockInfo::RIGHT_OF_WINDOW
:
1940 content::RecordAction(UserMetricsAction("DockingWindow_Right"));
1943 case DockInfo::BOTTOM_OF_WINDOW
:
1944 content::RecordAction(UserMetricsAction("DockingWindow_Bottom"));
1947 case DockInfo::TOP_OF_WINDOW
:
1948 content::RecordAction(UserMetricsAction("DockingWindow_Top"));
1951 case DockInfo::MAXIMIZE
:
1952 content::RecordAction(
1953 UserMetricsAction("DockingWindow_Maximize"));
1956 case DockInfo::LEFT_HALF
:
1957 content::RecordAction(
1958 UserMetricsAction("DockingWindow_LeftHalf"));
1961 case DockInfo::RIGHT_HALF
:
1962 content::RecordAction(
1963 UserMetricsAction("DockingWindow_RightHalf"));
1966 case DockInfo::BOTTOM_HALF
:
1967 content::RecordAction(
1968 UserMetricsAction("DockingWindow_BottomHalf"));
1976 // Compel the model to construct a new window for the detached
1978 views::Widget
* widget
= source_tabstrip_
->GetWidget();
1979 gfx::Rect
window_bounds(widget
->GetRestoredBounds());
1980 window_bounds
.set_origin(GetWindowCreatePoint(last_point_in_screen_
));
1982 // When modifying the following if statement, please make sure not to
1983 // introduce issue listed in http://crbug.com/6223 comment #11.
1984 bool rtl_ui
= base::i18n::IsRTL();
1985 bool has_dock_position
= (dock_info_
.type() != DockInfo::NONE
);
1986 if (rtl_ui
&& has_dock_position
) {
1987 // Mirror X axis so the docked tab is aligned using the mouse click as
1988 // the top-right corner.
1989 window_bounds
.set_x(window_bounds
.x() - window_bounds
.width());
1991 base::AutoReset
<bool> setter(&is_mutating_
, true);
1993 std::vector
<TabStripModelDelegate::NewStripContents
> contentses
;
1994 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
1995 TabStripModelDelegate::NewStripContents item
;
1996 item
.web_contents
= drag_data_
[i
].contents
;
1997 item
.add_types
= drag_data_
[i
].pinned
? TabStripModel::ADD_PINNED
1998 : TabStripModel::ADD_NONE
;
1999 contentses
.push_back(item
);
2002 Browser
* new_browser
=
2003 GetModel(source_tabstrip_
)->delegate()->CreateNewStripWithContents(
2004 contentses
, window_bounds
, dock_info_
, widget
->IsMaximized());
2005 ResetSelection(new_browser
->tab_strip_model());
2006 new_browser
->window()->Show();
2008 // Return the WebContents to normalcy.
2009 if (!detach_into_browser_
)
2010 source_dragged_contents()->DecrementCapturerCount();
2013 CleanUpHiddenFrame();
2016 void TabDragController::ResetDelegates() {
2017 DCHECK(!detach_into_browser_
);
2018 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
2019 if (drag_data_
[i
].contents
&&
2020 drag_data_
[i
].contents
->GetDelegate() == this) {
2021 drag_data_
[i
].contents
->SetDelegate(
2022 drag_data_
[i
].original_delegate
);
2027 void TabDragController::CreateDraggedView(
2028 const std::vector
<TabRendererData
>& data
,
2029 const std::vector
<gfx::Rect
>& renderer_bounds
) {
2030 #if !defined(USE_AURA)
2031 DCHECK(!view_
.get());
2032 DCHECK_EQ(data
.size(), drag_data_
.size());
2034 // Set up the photo booth to start capturing the contents of the dragged
2036 NativeViewPhotobooth
* photobooth
= NativeViewPhotobooth::Create(
2037 source_dragged_contents()->GetView()->GetNativeView());
2039 gfx::Rect content_bounds
;
2040 source_dragged_contents()->GetView()->GetContainerBounds(&content_bounds
);
2042 std::vector
<views::View
*> renderers
;
2043 for (size_t i
= 0; i
< drag_data_
.size(); ++i
) {
2044 Tab
* renderer
= source_tabstrip_
->CreateTabForDragging();
2045 renderer
->SetData(data
[i
]);
2046 renderers
.push_back(renderer
);
2048 // DraggedTabView takes ownership of the renderers.
2049 view_
.reset(new DraggedTabView(renderers
, renderer_bounds
, mouse_offset_
,
2050 content_bounds
.size(), photobooth
));
2052 // Aura always hits the |detach_into_browser_| path.
2057 gfx::Rect
TabDragController::GetViewScreenBounds(
2058 views::View
* view
) const {
2059 gfx::Point view_topleft
;
2060 views::View::ConvertPointToScreen(view
, &view_topleft
);
2061 gfx::Rect view_screen_bounds
= view
->GetLocalBounds();
2062 view_screen_bounds
.Offset(view_topleft
.x(), view_topleft
.y());
2063 return view_screen_bounds
;
2066 void TabDragController::CleanUpHiddenFrame() {
2067 // If the model we started dragging from is now empty, we must ask the
2068 // delegate to close the frame.
2069 if (!detach_into_browser_
&& GetModel(source_tabstrip_
)->empty())
2070 GetModel(source_tabstrip_
)->delegate()->CloseFrameAfterDragSession();
2073 void TabDragController::DockDisplayerDestroyed(
2074 DockDisplayer
* controller
) {
2075 DockWindows::iterator dock_i
=
2076 dock_windows_
.find(controller
->popup_view());
2077 if (dock_i
!= dock_windows_
.end())
2078 dock_windows_
.erase(dock_i
);
2082 std::vector
<DockDisplayer
*>::iterator i
=
2083 std::find(dock_controllers_
.begin(), dock_controllers_
.end(),
2085 if (i
!= dock_controllers_
.end())
2086 dock_controllers_
.erase(i
);
2091 void TabDragController::BringWindowUnderPointToFront(
2092 const gfx::Point
& point_in_screen
) {
2093 // If we're going to dock to another window, bring it to the front.
2094 gfx::NativeWindow window
= dock_info_
.window();
2096 views::View
* dragged_view
;
2098 dragged_view
= view_
.get();
2100 dragged_view
= attached_tabstrip_
;
2101 gfx::NativeView dragged_native_view
=
2102 dragged_view
->GetWidget()->GetNativeView();
2103 dock_windows_
.insert(dragged_native_view
);
2104 window
= DockInfo::GetLocalProcessWindowAtPoint(
2108 dock_windows_
.erase(dragged_native_view
);
2109 // Only bring browser windows to front - only windows with a TabStrip can
2110 // be tab drag targets.
2111 if (!GetTabStripForWindow(window
))
2115 views::Widget
* widget_window
= views::Widget::GetWidgetForNativeView(
2120 #if defined(USE_ASH)
2121 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
) {
2122 // TODO(varkha): The code below ensures that the phantom drag widget
2123 // is shown on top of browser windows. The code should be moved to ash/
2124 // and the phantom should be able to assert its top-most state on its own.
2125 // One strategy would be for DragWindowController to
2126 // be able to observe stacking changes to the phantom drag widget's
2127 // siblings in order to keep it on top. One way is to implement a
2128 // notification that is sent to a window parent's observers when a
2129 // stacking order is changed among the children of that same parent.
2130 // Note that OnWindowStackingChanged is sent only to the child that is the
2131 // argument of one of the Window::StackChildX calls and not to all its
2132 // siblings affected by the stacking change.
2133 aura::Window
* browser_window
= widget_window
->GetNativeView();
2134 // Find a topmost non-popup window and stack the recipient browser above
2135 // it in order to avoid stacking the browser window on top of the phantom
2136 // drag widget created by DragWindowController in a second display.
2137 for (aura::Window::Windows::const_reverse_iterator it
=
2138 browser_window
->parent()->children().rbegin();
2139 it
!= browser_window
->parent()->children().rend(); ++it
) {
2140 // If the iteration reached the recipient browser window then it is
2141 // already topmost and it is safe to return with no stacking change.
2142 if (*it
== browser_window
)
2144 if ((*it
)->type() != ui::wm::WINDOW_TYPE_POPUP
) {
2145 widget_window
->StackAbove(*it
);
2150 widget_window
->StackAtTop();
2153 widget_window
->StackAtTop();
2156 // The previous call made the window appear on top of the dragged window,
2157 // move the dragged window to the front.
2159 view_
->GetWidget()->StackAtTop();
2160 else if (is_dragging_window_
)
2161 attached_tabstrip_
->GetWidget()->StackAtTop();
2165 TabStripModel
* TabDragController::GetModel(
2166 TabStrip
* tabstrip
) const {
2167 return static_cast<BrowserTabStripController
*>(tabstrip
->controller())->
2171 views::Widget
* TabDragController::GetAttachedBrowserWidget() {
2172 return attached_tabstrip_
->GetWidget();
2175 bool TabDragController::AreTabsConsecutive() {
2176 for (size_t i
= 1; i
< drag_data_
.size(); ++i
) {
2177 if (drag_data_
[i
- 1].source_model_index
+ 1 !=
2178 drag_data_
[i
].source_model_index
) {
2185 gfx::Rect
TabDragController::CalculateDraggedBrowserBounds(
2187 const gfx::Point
& point_in_screen
,
2188 std::vector
<gfx::Rect
>* drag_bounds
) {
2189 gfx::Point
center(0, source
->height() / 2);
2190 views::View::ConvertPointToWidget(source
, ¢er
);
2191 gfx::Rect
new_bounds(source
->GetWidget()->GetRestoredBounds());
2192 if (source
->GetWidget()->IsMaximized()) {
2193 // If the restore bounds is really small, we don't want to honor it
2194 // (dragging a really small window looks wrong), instead make sure the new
2195 // window is at least 50% the size of the old.
2196 const gfx::Size
max_size(
2197 source
->GetWidget()->GetWindowBoundsInScreen().size());
2198 new_bounds
.set_width(
2199 std::max(max_size
.width() / 2, new_bounds
.width()));
2200 new_bounds
.set_height(
2201 std::max(max_size
.height() / 2, new_bounds
.height()));
2203 new_bounds
.set_y(point_in_screen
.y() - center
.y());
2204 switch (GetDetachPosition(point_in_screen
)) {
2206 new_bounds
.set_x(point_in_screen
.x() - center
.x());
2207 new_bounds
.Offset(-mouse_offset_
.x(), 0);
2209 case DETACH_AFTER
: {
2210 gfx::Point
right_edge(source
->width(), 0);
2211 views::View::ConvertPointToWidget(source
, &right_edge
);
2212 new_bounds
.set_x(point_in_screen
.x() - right_edge
.x());
2213 new_bounds
.Offset(drag_bounds
->back().right() - mouse_offset_
.x(), 0);
2214 OffsetX(-(*drag_bounds
)[0].x(), drag_bounds
);
2218 break; // Nothing to do for DETACH_ABOVE_OR_BELOW.
2221 // To account for the extra vertical on restored windows that is absent on
2222 // maximized windows, add an additional vertical offset extracted from the tab
2224 if (source
->GetWidget()->IsMaximized())
2225 new_bounds
.Offset(0, -source
->button_v_offset());
2229 void TabDragController::AdjustBrowserAndTabBoundsForDrag(
2230 int last_tabstrip_width
,
2231 const gfx::Point
& point_in_screen
,
2232 std::vector
<gfx::Rect
>* drag_bounds
) {
2233 attached_tabstrip_
->InvalidateLayout();
2234 attached_tabstrip_
->DoLayout();
2235 const int dragged_tabstrip_width
= attached_tabstrip_
->tab_area_width();
2237 // If the new tabstrip is smaller than the old resize the tabs.
2238 if (dragged_tabstrip_width
< last_tabstrip_width
) {
2239 const float leading_ratio
=
2240 drag_bounds
->front().x() / static_cast<float>(last_tabstrip_width
);
2241 *drag_bounds
= CalculateBoundsForDraggedTabs();
2243 if (drag_bounds
->back().right() < dragged_tabstrip_width
) {
2245 std::min(static_cast<int>(leading_ratio
* dragged_tabstrip_width
),
2246 dragged_tabstrip_width
-
2247 (drag_bounds
->back().right() -
2248 drag_bounds
->front().x()));
2249 OffsetX(delta_x
, drag_bounds
);
2252 // Reposition the restored window such that the tab that was dragged remains
2253 // under the mouse cursor.
2255 static_cast<int>((*drag_bounds
)[source_tab_index_
].width() *
2256 offset_to_width_ratio_
) +
2257 (*drag_bounds
)[source_tab_index_
].x(), 0);
2258 views::View::ConvertPointToWidget(attached_tabstrip_
, &offset
);
2259 gfx::Rect bounds
= GetAttachedBrowserWidget()->GetWindowBoundsInScreen();
2260 bounds
.set_x(point_in_screen
.x() - offset
.x());
2261 GetAttachedBrowserWidget()->SetBounds(bounds
);
2263 attached_tabstrip_
->SetTabBoundsForDrag(*drag_bounds
);
2266 Browser
* TabDragController::CreateBrowserForDrag(
2268 const gfx::Point
& point_in_screen
,
2269 gfx::Vector2d
* drag_offset
,
2270 std::vector
<gfx::Rect
>* drag_bounds
) {
2271 gfx::Rect
new_bounds(CalculateDraggedBrowserBounds(source
,
2274 *drag_offset
= point_in_screen
- new_bounds
.origin();
2277 Profile::FromBrowserContext(drag_data_
[0].contents
->GetBrowserContext());
2278 Browser::CreateParams
create_params(Browser::TYPE_TABBED
,
2280 host_desktop_type_
);
2281 create_params
.initial_bounds
= new_bounds
;
2282 Browser
* browser
= new Browser(create_params
);
2283 is_dragging_new_browser_
= true;
2284 SetWindowPositionManaged(browser
->window()->GetNativeWindow(), false);
2285 // If the window is created maximized then the bounds we supplied are ignored.
2286 // We need to reset them again so they are honored.
2287 browser
->window()->SetBounds(new_bounds
);
2292 gfx::Point
TabDragController::GetCursorScreenPoint() {
2293 #if defined(USE_ASH)
2294 if (host_desktop_type_
== chrome::HOST_DESKTOP_TYPE_ASH
&&
2295 event_source_
== EVENT_SOURCE_TOUCH
&&
2296 aura::Env::GetInstance()->is_touch_down()) {
2297 views::Widget
* widget
= GetAttachedBrowserWidget();
2299 aura::Window
* widget_window
= widget
->GetNativeWindow();
2300 DCHECK(widget_window
->GetRootWindow());
2301 gfx::Point touch_point
;
2302 bool got_touch_point
= ui::GestureRecognizer::Get()->
2303 GetLastTouchPointForTarget(widget_window
, &touch_point
);
2304 DCHECK(got_touch_point
);
2305 ash::wm::ConvertPointToScreen(widget_window
->GetRootWindow(), &touch_point
);
2309 return screen_
->GetCursorScreenPoint();
2312 gfx::Vector2d
TabDragController::GetWindowOffset(
2313 const gfx::Point
& point_in_screen
) {
2314 TabStrip
* owning_tabstrip
= (attached_tabstrip_
&& detach_into_browser_
) ?
2315 attached_tabstrip_
: source_tabstrip_
;
2316 views::View
* toplevel_view
= owning_tabstrip
->GetWidget()->GetContentsView();
2318 gfx::Point point
= point_in_screen
;
2319 views::View::ConvertPointFromScreen(toplevel_view
, &point
);
2320 return point
.OffsetFromOrigin();