MacViews: Get c/b/ui/views/tabs to build on Mac
[chromium-blink-merge.git] / chrome / browser / ui / views / tabs / tab_drag_controller.cc
blob7c737fd3426c3c3d424b5b89a570ab90cc80fd34
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"
7 #include <math.h>
8 #include <set>
10 #include "base/auto_reset.h"
11 #include "base/callback.h"
12 #include "base/i18n/rtl.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/ui/browser_list.h"
16 #include "chrome/browser/ui/browser_window.h"
17 #include "chrome/browser/ui/tabs/tab_strip_model.h"
18 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
19 #include "chrome/browser/ui/views/frame/browser_view.h"
20 #include "chrome/browser/ui/views/tabs/browser_tab_strip_controller.h"
21 #include "chrome/browser/ui/views/tabs/stacked_tab_strip_layout.h"
22 #include "chrome/browser/ui/views/tabs/tab.h"
23 #include "chrome/browser/ui/views/tabs/tab_strip.h"
24 #include "chrome/browser/ui/views/tabs/window_finder.h"
25 #include "content/public/browser/notification_details.h"
26 #include "content/public/browser/notification_service.h"
27 #include "content/public/browser/notification_source.h"
28 #include "content/public/browser/notification_types.h"
29 #include "content/public/browser/user_metrics.h"
30 #include "content/public/browser/web_contents.h"
31 #include "extensions/browser/extension_function_dispatcher.h"
32 #include "ui/aura/env.h"
33 #include "ui/aura/window.h"
34 #include "ui/events/event_constants.h"
35 #include "ui/events/gestures/gesture_recognizer.h"
36 #include "ui/gfx/geometry/point_conversions.h"
37 #include "ui/gfx/screen.h"
38 #include "ui/views/focus/view_storage.h"
39 #include "ui/views/widget/root_view.h"
40 #include "ui/views/widget/widget.h"
42 #if defined(USE_ASH)
43 #include "ash/accelerators/accelerator_commands.h"
44 #include "ash/shell.h"
45 #include "ash/wm/maximize_mode/maximize_mode_controller.h"
46 #include "ash/wm/window_state.h"
47 #include "ui/wm/core/coordinate_conversion.h"
48 #endif
50 #if defined(USE_AURA)
51 #include "ui/wm/core/window_modality_controller.h"
52 #endif
54 using base::UserMetricsAction;
55 using content::OpenURLParams;
56 using content::WebContents;
58 // If non-null there is a drag underway.
59 static TabDragController* instance_ = NULL;
61 namespace {
63 // Delay, in ms, during dragging before we bring a window to front.
64 const int kBringToFrontDelay = 750;
66 // Initial delay before moving tabs when the dragged tab is close to the edge of
67 // the stacked tabs.
68 const int kMoveAttachedInitialDelay = 600;
70 // Delay for moving tabs after the initial delay has passed.
71 const int kMoveAttachedSubsequentDelay = 300;
73 const int kHorizontalMoveThreshold = 16; // Pixels.
75 // Distance from the next/previous stacked before before we consider the tab
76 // close enough to trigger moving.
77 const int kStackedDistance = 36;
79 #if defined(USE_ASH)
80 void SetWindowPositionManaged(gfx::NativeWindow window, bool value) {
81 ash::wm::GetWindowState(window)->set_window_position_managed(value);
84 // Returns true if |tab_strip| browser window is docked.
85 bool IsDockedOrSnapped(const TabStrip* tab_strip) {
86 DCHECK(tab_strip);
87 ash::wm::WindowState* window_state =
88 ash::wm::GetWindowState(tab_strip->GetWidget()->GetNativeWindow());
89 return window_state->IsDocked() || window_state->IsSnapped();
91 #else
92 void SetWindowPositionManaged(gfx::NativeWindow window, bool value) {
95 bool IsDockedOrSnapped(const TabStrip* tab_strip) {
96 return false;
98 #endif
100 #if defined(USE_AURA)
101 gfx::NativeWindow GetModalTransient(gfx::NativeWindow window) {
102 return wm::GetModalTransient(window);
104 #else
105 gfx::NativeWindow GetModalTransient(gfx::NativeWindow window) {
106 NOTIMPLEMENTED();
107 return NULL;
109 #endif
111 // Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
112 // of |bounds| is adjusted by |vertical_adjustment|.
113 bool DoesRectContainVerticalPointExpanded(
114 const gfx::Rect& bounds,
115 int vertical_adjustment,
116 int y) {
117 int upper_threshold = bounds.bottom() + vertical_adjustment;
118 int lower_threshold = bounds.y() - vertical_adjustment;
119 return y >= lower_threshold && y <= upper_threshold;
122 // Adds |x_offset| to all the rectangles in |rects|.
123 void OffsetX(int x_offset, std::vector<gfx::Rect>* rects) {
124 if (x_offset == 0)
125 return;
127 for (size_t i = 0; i < rects->size(); ++i)
128 (*rects)[i].set_x((*rects)[i].x() + x_offset);
131 // WidgetObserver implementation that resets the window position managed
132 // property on Show.
133 // We're forced to do this here since BrowserFrameAsh resets the 'window
134 // position managed' property during a show and we need the property set to
135 // false before WorkspaceLayoutManager sees the visibility change.
136 class WindowPositionManagedUpdater : public views::WidgetObserver {
137 public:
138 virtual void OnWidgetVisibilityChanged(views::Widget* widget,
139 bool visible) override {
140 SetWindowPositionManaged(widget->GetNativeWindow(), false);
144 // EscapeTracker installs itself as a pre-target handler on aura::Env and runs a
145 // callback when it receives the escape key.
146 class EscapeTracker : public ui::EventHandler {
147 public:
148 explicit EscapeTracker(const base::Closure& callback)
149 : escape_callback_(callback) {
150 aura::Env::GetInstance()->AddPreTargetHandler(this);
153 virtual ~EscapeTracker() {
154 aura::Env::GetInstance()->RemovePreTargetHandler(this);
157 private:
158 // ui::EventHandler:
159 virtual void OnKeyEvent(ui::KeyEvent* key) override {
160 if (key->type() == ui::ET_KEY_PRESSED &&
161 key->key_code() == ui::VKEY_ESCAPE) {
162 escape_callback_.Run();
166 base::Closure escape_callback_;
168 DISALLOW_COPY_AND_ASSIGN(EscapeTracker);
171 } // namespace
173 TabDragController::TabDragData::TabDragData()
174 : contents(NULL),
175 source_model_index(-1),
176 attached_tab(NULL),
177 pinned(false) {
180 TabDragController::TabDragData::~TabDragData() {
183 ///////////////////////////////////////////////////////////////////////////////
184 // TabDragController, public:
186 // static
187 const int TabDragController::kTouchVerticalDetachMagnetism = 50;
189 // static
190 const int TabDragController::kVerticalDetachMagnetism = 15;
192 TabDragController::TabDragController()
193 : event_source_(EVENT_SOURCE_MOUSE),
194 source_tabstrip_(NULL),
195 attached_tabstrip_(NULL),
196 screen_(NULL),
197 host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE),
198 can_release_capture_(true),
199 offset_to_width_ratio_(0),
200 old_focused_view_id_(
201 views::ViewStorage::GetInstance()->CreateStorageID()),
202 last_move_screen_loc_(0),
203 started_drag_(false),
204 active_(true),
205 source_tab_index_(std::numeric_limits<size_t>::max()),
206 initial_move_(true),
207 detach_behavior_(DETACHABLE),
208 move_behavior_(REORDER),
209 mouse_move_direction_(0),
210 is_dragging_window_(false),
211 is_dragging_new_browser_(false),
212 was_source_maximized_(false),
213 was_source_fullscreen_(false),
214 did_restore_window_(false),
215 end_run_loop_behavior_(END_RUN_LOOP_STOP_DRAGGING),
216 waiting_for_run_loop_to_exit_(false),
217 tab_strip_to_attach_to_after_exit_(NULL),
218 move_loop_widget_(NULL),
219 is_mutating_(false),
220 attach_x_(-1),
221 attach_index_(-1),
222 weak_factory_(this) {
223 instance_ = this;
226 TabDragController::~TabDragController() {
227 views::ViewStorage::GetInstance()->RemoveView(old_focused_view_id_);
229 if (instance_ == this)
230 instance_ = NULL;
232 if (move_loop_widget_) {
233 move_loop_widget_->RemoveObserver(this);
234 SetWindowPositionManaged(move_loop_widget_->GetNativeWindow(), true);
237 if (source_tabstrip_)
238 GetModel(source_tabstrip_)->RemoveObserver(this);
240 if (event_source_ == EVENT_SOURCE_TOUCH) {
241 TabStrip* capture_tabstrip = attached_tabstrip_ ?
242 attached_tabstrip_ : source_tabstrip_;
243 capture_tabstrip->GetWidget()->ReleaseCapture();
247 void TabDragController::Init(
248 TabStrip* source_tabstrip,
249 Tab* source_tab,
250 const std::vector<Tab*>& tabs,
251 const gfx::Point& mouse_offset,
252 int source_tab_offset,
253 const ui::ListSelectionModel& initial_selection_model,
254 MoveBehavior move_behavior,
255 EventSource event_source) {
256 DCHECK(!tabs.empty());
257 DCHECK(std::find(tabs.begin(), tabs.end(), source_tab) != tabs.end());
258 source_tabstrip_ = source_tabstrip;
259 was_source_maximized_ = source_tabstrip->GetWidget()->IsMaximized();
260 was_source_fullscreen_ = source_tabstrip->GetWidget()->IsFullscreen();
261 screen_ = gfx::Screen::GetScreenFor(
262 source_tabstrip->GetWidget()->GetNativeView());
263 host_desktop_type_ = chrome::GetHostDesktopTypeForNativeView(
264 source_tabstrip->GetWidget()->GetNativeView());
265 // Do not release capture when transferring capture between widgets on:
266 // - Desktop Linux
267 // Mouse capture is not synchronous on desktop Linux. Chrome makes
268 // transferring capture between widgets without releasing capture appear
269 // synchronous on desktop Linux, so use that.
270 // - Ash
271 // Releasing capture on Ash cancels gestures so avoid it.
272 #if defined(OS_LINUX)
273 can_release_capture_ = false;
274 #else
275 can_release_capture_ =
276 (host_desktop_type_ != chrome::HOST_DESKTOP_TYPE_ASH);
277 #endif
278 start_point_in_screen_ = gfx::Point(source_tab_offset, mouse_offset.y());
279 views::View::ConvertPointToScreen(source_tab, &start_point_in_screen_);
280 event_source_ = event_source;
281 mouse_offset_ = mouse_offset;
282 move_behavior_ = move_behavior;
283 last_point_in_screen_ = start_point_in_screen_;
284 last_move_screen_loc_ = start_point_in_screen_.x();
285 initial_tab_positions_ = source_tabstrip->GetTabXCoordinates();
287 GetModel(source_tabstrip_)->AddObserver(this);
289 drag_data_.resize(tabs.size());
290 for (size_t i = 0; i < tabs.size(); ++i)
291 InitTabDragData(tabs[i], &(drag_data_[i]));
292 source_tab_index_ =
293 std::find(tabs.begin(), tabs.end(), source_tab) - tabs.begin();
295 // Listen for Esc key presses.
296 escape_tracker_.reset(
297 new EscapeTracker(base::Bind(&TabDragController::EndDrag,
298 weak_factory_.GetWeakPtr(),
299 END_DRAG_CANCEL)));
301 if (source_tab->width() > 0) {
302 offset_to_width_ratio_ = static_cast<float>(
303 source_tab->GetMirroredXInView(source_tab_offset)) /
304 static_cast<float>(source_tab->width());
306 InitWindowCreatePoint();
307 initial_selection_model_.Copy(initial_selection_model);
309 // Gestures don't automatically do a capture. We don't allow multiple drags at
310 // the same time, so we explicitly capture.
311 if (event_source == EVENT_SOURCE_TOUCH)
312 source_tabstrip_->GetWidget()->SetCapture(source_tabstrip_);
314 #if defined(USE_ASH)
315 if (ash::Shell::HasInstance() &&
316 ash::Shell::GetInstance()->maximize_mode_controller()->
317 IsMaximizeModeWindowManagerEnabled()) {
318 detach_behavior_ = NOT_DETACHABLE;
320 #endif
323 // static
324 bool TabDragController::IsAttachedTo(const TabStrip* tab_strip) {
325 return (instance_ && instance_->active() &&
326 instance_->attached_tabstrip() == tab_strip);
329 // static
330 bool TabDragController::IsActive() {
331 return instance_ && instance_->active();
334 void TabDragController::SetMoveBehavior(MoveBehavior behavior) {
335 if (started_drag())
336 return;
338 move_behavior_ = behavior;
341 void TabDragController::Drag(const gfx::Point& point_in_screen) {
342 TRACE_EVENT1("views", "TabDragController::Drag",
343 "point_in_screen", point_in_screen.ToString());
345 bring_to_front_timer_.Stop();
346 move_stacked_timer_.Stop();
348 if (waiting_for_run_loop_to_exit_)
349 return;
351 if (!started_drag_) {
352 if (!CanStartDrag(point_in_screen))
353 return; // User hasn't dragged far enough yet.
355 // On windows SaveFocus() may trigger a capture lost, which destroys us.
357 base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
358 SaveFocus();
359 if (!ref)
360 return;
362 started_drag_ = true;
363 Attach(source_tabstrip_, gfx::Point());
364 if (static_cast<int>(drag_data_.size()) ==
365 GetModel(source_tabstrip_)->count()) {
366 if (was_source_maximized_ || was_source_fullscreen_) {
367 did_restore_window_ = true;
368 // When all tabs in a maximized browser are dragged the browser gets
369 // restored during the drag and maximized back when the drag ends.
370 views::Widget* widget = GetAttachedBrowserWidget();
371 const int last_tabstrip_width = attached_tabstrip_->tab_area_width();
372 std::vector<gfx::Rect> drag_bounds = CalculateBoundsForDraggedTabs();
373 OffsetX(GetAttachedDragPoint(point_in_screen).x(), &drag_bounds);
374 gfx::Rect new_bounds(CalculateDraggedBrowserBounds(source_tabstrip_,
375 point_in_screen,
376 &drag_bounds));
377 new_bounds.Offset(-widget->GetRestoredBounds().x() +
378 point_in_screen.x() -
379 mouse_offset_.x(), 0);
380 widget->SetVisibilityChangedAnimationsEnabled(false);
381 widget->Restore();
382 widget->SetBounds(new_bounds);
383 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width,
384 point_in_screen,
385 &drag_bounds);
386 widget->SetVisibilityChangedAnimationsEnabled(true);
388 RunMoveLoop(GetWindowOffset(point_in_screen));
389 return;
393 ContinueDragging(point_in_screen);
396 void TabDragController::EndDrag(EndDragReason reason) {
397 TRACE_EVENT0("views", "TabDragController::EndDrag");
399 // If we're dragging a window ignore capture lost since it'll ultimately
400 // trigger the move loop to end and we'll revert the drag when RunMoveLoop()
401 // finishes.
402 if (reason == END_DRAG_CAPTURE_LOST && is_dragging_window_)
403 return;
404 EndDragImpl(reason != END_DRAG_COMPLETE && source_tabstrip_ ?
405 CANCELED : NORMAL);
408 void TabDragController::InitTabDragData(Tab* tab,
409 TabDragData* drag_data) {
410 TRACE_EVENT0("views", "TabDragController::InitTabDragData");
411 drag_data->source_model_index =
412 source_tabstrip_->GetModelIndexOfTab(tab);
413 drag_data->contents = GetModel(source_tabstrip_)->GetWebContentsAt(
414 drag_data->source_model_index);
415 drag_data->pinned = source_tabstrip_->IsTabPinned(tab);
416 registrar_.Add(
417 this,
418 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
419 content::Source<WebContents>(drag_data->contents));
422 ///////////////////////////////////////////////////////////////////////////////
423 // TabDragController, content::NotificationObserver implementation:
425 void TabDragController::Observe(
426 int type,
427 const content::NotificationSource& source,
428 const content::NotificationDetails& details) {
429 DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED, type);
430 WebContents* destroyed_web_contents =
431 content::Source<WebContents>(source).ptr();
432 for (size_t i = 0; i < drag_data_.size(); ++i) {
433 if (drag_data_[i].contents == destroyed_web_contents) {
434 // One of the tabs we're dragging has been destroyed. Cancel the drag.
435 drag_data_[i].contents = NULL;
436 EndDragImpl(TAB_DESTROYED);
437 return;
440 // If we get here it means we got notification for a tab we don't know about.
441 NOTREACHED();
444 void TabDragController::OnWidgetBoundsChanged(views::Widget* widget,
445 const gfx::Rect& new_bounds) {
446 TRACE_EVENT1("views", "TabDragController::OnWidgetBoundsChanged",
447 "new_bounds", new_bounds.ToString());
449 Drag(GetCursorScreenPoint());
452 void TabDragController::TabStripEmpty() {
453 GetModel(source_tabstrip_)->RemoveObserver(this);
454 // NULL out source_tabstrip_ so that we don't attempt to add back to it (in
455 // the case of a revert).
456 source_tabstrip_ = NULL;
459 ///////////////////////////////////////////////////////////////////////////////
460 // TabDragController, private:
462 void TabDragController::InitWindowCreatePoint() {
463 // window_create_point_ is only used in CompleteDrag() (through
464 // GetWindowCreatePoint() to get the start point of the docked window) when
465 // the attached_tabstrip_ is NULL and all the window's related bound
466 // information are obtained from source_tabstrip_. So, we need to get the
467 // first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise,
468 // the window_create_point_ is not in the correct coordinate system. Please
469 // refer to http://crbug.com/6223 comment #15 for detailed information.
470 views::View* first_tab = source_tabstrip_->tab_at(0);
471 views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_);
472 window_create_point_ = first_source_tab_point_;
473 window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y());
476 gfx::Point TabDragController::GetWindowCreatePoint(
477 const gfx::Point& origin) const {
478 // If the cursor is outside the monitor area, move it inside. For example,
479 // dropping a tab onto the task bar on Windows produces this situation.
480 gfx::Rect work_area = screen_->GetDisplayNearestPoint(origin).work_area();
481 gfx::Point create_point(origin);
482 if (!work_area.IsEmpty()) {
483 if (create_point.x() < work_area.x())
484 create_point.set_x(work_area.x());
485 else if (create_point.x() > work_area.right())
486 create_point.set_x(work_area.right());
487 if (create_point.y() < work_area.y())
488 create_point.set_y(work_area.y());
489 else if (create_point.y() > work_area.bottom())
490 create_point.set_y(work_area.bottom());
492 return gfx::Point(create_point.x() - window_create_point_.x(),
493 create_point.y() - window_create_point_.y());
496 void TabDragController::SaveFocus() {
497 DCHECK(source_tabstrip_);
498 views::View* focused_view =
499 source_tabstrip_->GetFocusManager()->GetFocusedView();
500 if (focused_view)
501 views::ViewStorage::GetInstance()->StoreView(old_focused_view_id_,
502 focused_view);
503 source_tabstrip_->GetFocusManager()->SetFocusedView(source_tabstrip_);
504 // WARNING: we may have been deleted.
507 void TabDragController::RestoreFocus() {
508 if (attached_tabstrip_ != source_tabstrip_) {
509 if (is_dragging_new_browser_) {
510 content::WebContents* active_contents = source_dragged_contents();
511 if (active_contents && !active_contents->FocusLocationBarByDefault())
512 active_contents->Focus();
514 return;
516 views::View* old_focused_view =
517 views::ViewStorage::GetInstance()->RetrieveView(old_focused_view_id_);
518 if (!old_focused_view)
519 return;
520 old_focused_view->GetFocusManager()->SetFocusedView(old_focused_view);
523 bool TabDragController::CanStartDrag(const gfx::Point& point_in_screen) const {
524 // Determine if the mouse has moved beyond a minimum elasticity distance in
525 // any direction from the starting point.
526 static const int kMinimumDragDistance = 10;
527 int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x());
528 int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y());
529 return sqrt(pow(static_cast<float>(x_offset), 2) +
530 pow(static_cast<float>(y_offset), 2)) > kMinimumDragDistance;
533 void TabDragController::ContinueDragging(const gfx::Point& point_in_screen) {
534 TRACE_EVENT1("views", "TabDragController::ContinueDragging",
535 "point_in_screen", point_in_screen.ToString());
537 DCHECK(attached_tabstrip_);
539 TabStrip* target_tabstrip = detach_behavior_ == DETACHABLE ?
540 GetTargetTabStripForPoint(point_in_screen) : source_tabstrip_;
541 bool tab_strip_changed = (target_tabstrip != attached_tabstrip_);
543 if (attached_tabstrip_) {
544 int move_delta = point_in_screen.x() - last_point_in_screen_.x();
545 if (move_delta > 0)
546 mouse_move_direction_ |= kMovedMouseRight;
547 else if (move_delta < 0)
548 mouse_move_direction_ |= kMovedMouseLeft;
550 last_point_in_screen_ = point_in_screen;
552 if (tab_strip_changed) {
553 is_dragging_new_browser_ = false;
554 did_restore_window_ = false;
555 if (DragBrowserToNewTabStrip(target_tabstrip, point_in_screen) ==
556 DRAG_BROWSER_RESULT_STOP) {
557 return;
560 if (is_dragging_window_) {
561 static_cast<base::Timer*>(&bring_to_front_timer_)->Start(FROM_HERE,
562 base::TimeDelta::FromMilliseconds(kBringToFrontDelay),
563 base::Bind(&TabDragController::BringWindowUnderPointToFront,
564 base::Unretained(this), point_in_screen));
567 if (!is_dragging_window_ && attached_tabstrip_) {
568 if (move_only()) {
569 DragActiveTabStacked(point_in_screen);
570 } else {
571 MoveAttached(point_in_screen);
572 if (tab_strip_changed) {
573 // Move the corresponding window to the front. We do this after the
574 // move as on windows activate triggers a synchronous paint.
575 attached_tabstrip_->GetWidget()->Activate();
581 TabDragController::DragBrowserResultType
582 TabDragController::DragBrowserToNewTabStrip(
583 TabStrip* target_tabstrip,
584 const gfx::Point& point_in_screen) {
585 TRACE_EVENT1("views", "TabDragController::DragBrowserToNewTabStrip",
586 "point_in_screen", point_in_screen.ToString());
588 if (!target_tabstrip) {
589 DetachIntoNewBrowserAndRunMoveLoop(point_in_screen);
590 return DRAG_BROWSER_RESULT_STOP;
592 if (is_dragging_window_) {
593 // ReleaseCapture() is going to result in calling back to us (because it
594 // results in a move). That'll cause all sorts of problems. Reset the
595 // observer so we don't get notified and process the event.
596 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
597 move_loop_widget_->RemoveObserver(this);
598 move_loop_widget_ = NULL;
600 views::Widget* browser_widget = GetAttachedBrowserWidget();
601 // Need to release the drag controller before starting the move loop as it's
602 // going to trigger capture lost, which cancels drag.
603 attached_tabstrip_->ReleaseDragController();
604 target_tabstrip->OwnDragController(this);
605 // Disable animations so that we don't see a close animation on aero.
606 browser_widget->SetVisibilityChangedAnimationsEnabled(false);
607 if (can_release_capture_)
608 browser_widget->ReleaseCapture();
609 else
610 target_tabstrip->GetWidget()->SetCapture(attached_tabstrip_);
611 #if defined(OS_WIN)
612 // The Gesture recognizer does not work well currently when capture changes
613 // while a touch gesture is in progress. So we need to manually transfer
614 // gesture sequence and the GR's touch events queue to the new window. This
615 // should really be done somewhere in capture change code and or inside the
616 // GR. But we currently do not have a consistent way for doing it that would
617 // work in all cases. Hence this hack.
618 ui::GestureRecognizer::Get()->TransferEventsTo(
619 browser_widget->GetNativeView(),
620 target_tabstrip->GetWidget()->GetNativeView());
621 #endif
623 // The window is going away. Since the drag is still on going we don't want
624 // that to effect the position of any windows.
625 SetWindowPositionManaged(browser_widget->GetNativeWindow(), false);
627 #if !defined(OS_LINUX) || defined(OS_CHROMEOS)
628 // EndMoveLoop is going to snap the window back to its original location.
629 // Hide it so users don't see this. Hiding a window in Linux aura causes
630 // it to lose capture so skip it.
631 browser_widget->Hide();
632 #endif
633 browser_widget->EndMoveLoop();
635 // Ideally we would always swap the tabs now, but on non-ash Windows, it
636 // seems that running the move loop implicitly activates the window when
637 // done, leading to all sorts of flicker. So, on non-ash Windows, instead
638 // we process the move after the loop completes. But on chromeos, we can
639 // do tab swapping now to avoid the tab flashing issue
640 // (crbug.com/116329).
641 if (can_release_capture_) {
642 tab_strip_to_attach_to_after_exit_ = target_tabstrip;
643 } else {
644 is_dragging_window_ = false;
645 Detach(DONT_RELEASE_CAPTURE);
646 Attach(target_tabstrip, point_in_screen);
647 // Move the tabs into position.
648 MoveAttached(point_in_screen);
649 attached_tabstrip_->GetWidget()->Activate();
652 waiting_for_run_loop_to_exit_ = true;
653 end_run_loop_behavior_ = END_RUN_LOOP_CONTINUE_DRAGGING;
654 return DRAG_BROWSER_RESULT_STOP;
656 Detach(DONT_RELEASE_CAPTURE);
657 Attach(target_tabstrip, point_in_screen);
658 return DRAG_BROWSER_RESULT_CONTINUE;
661 void TabDragController::DragActiveTabStacked(
662 const gfx::Point& point_in_screen) {
663 if (attached_tabstrip_->tab_count() !=
664 static_cast<int>(initial_tab_positions_.size()))
665 return; // TODO: should cancel drag if this happens.
667 int delta = point_in_screen.x() - start_point_in_screen_.x();
668 attached_tabstrip_->DragActiveTab(initial_tab_positions_, delta);
671 void TabDragController::MoveAttachedToNextStackedIndex(
672 const gfx::Point& point_in_screen) {
673 int index = attached_tabstrip_->touch_layout_->active_index();
674 if (index + 1 >= attached_tabstrip_->tab_count())
675 return;
677 GetModel(attached_tabstrip_)->MoveSelectedTabsTo(index + 1);
678 StartMoveStackedTimerIfNecessary(point_in_screen,
679 kMoveAttachedSubsequentDelay);
682 void TabDragController::MoveAttachedToPreviousStackedIndex(
683 const gfx::Point& point_in_screen) {
684 int index = attached_tabstrip_->touch_layout_->active_index();
685 if (index <= attached_tabstrip_->GetMiniTabCount())
686 return;
688 GetModel(attached_tabstrip_)->MoveSelectedTabsTo(index - 1);
689 StartMoveStackedTimerIfNecessary(point_in_screen,
690 kMoveAttachedSubsequentDelay);
693 void TabDragController::MoveAttached(const gfx::Point& point_in_screen) {
694 DCHECK(attached_tabstrip_);
695 DCHECK(!is_dragging_window_);
697 gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
699 // Determine the horizontal move threshold. This is dependent on the width
700 // of tabs. The smaller the tabs compared to the standard size, the smaller
701 // the threshold.
702 int threshold = kHorizontalMoveThreshold;
703 if (!attached_tabstrip_->touch_layout_.get()) {
704 double unselected, selected;
705 attached_tabstrip_->GetCurrentTabWidths(&unselected, &selected);
706 double ratio = unselected / Tab::GetStandardSize().width();
707 threshold = static_cast<int>(ratio * kHorizontalMoveThreshold);
709 // else case: touch tabs never shrink.
711 std::vector<Tab*> tabs(drag_data_.size());
712 for (size_t i = 0; i < drag_data_.size(); ++i)
713 tabs[i] = drag_data_[i].attached_tab;
715 bool did_layout = false;
716 // Update the model, moving the WebContents from one index to another. Do this
717 // only if we have moved a minimum distance since the last reorder (to prevent
718 // jitter) or if this the first move and the tabs are not consecutive.
719 if ((abs(point_in_screen.x() - last_move_screen_loc_) > threshold ||
720 (initial_move_ && !AreTabsConsecutive()))) {
721 TabStripModel* attached_model = GetModel(attached_tabstrip_);
722 int to_index = GetInsertionIndexForDraggedBounds(
723 GetDraggedViewTabStripBounds(dragged_view_point));
724 bool do_move = true;
725 // While dragging within a tabstrip the expectation is the insertion index
726 // is based on the left edge of the tabs being dragged. OTOH when dragging
727 // into a new tabstrip (attaching) the expectation is the insertion index is
728 // based on the cursor. This proves problematic as insertion may change the
729 // size of the tabs, resulting in the index calculated before the insert
730 // differing from the index calculated after the insert. To alleviate this
731 // the index is chosen before insertion, and subsequently a new index is
732 // only used once the mouse moves enough such that the index changes based
733 // on the direction the mouse moved relative to |attach_x_| (smaller
734 // x-coordinate should yield a smaller index or larger x-coordinate yields a
735 // larger index).
736 if (attach_index_ != -1) {
737 gfx::Point tab_strip_point(point_in_screen);
738 views::View::ConvertPointFromScreen(attached_tabstrip_, &tab_strip_point);
739 const int new_x =
740 attached_tabstrip_->GetMirroredXInView(tab_strip_point.x());
741 if (new_x < attach_x_)
742 to_index = std::min(to_index, attach_index_);
743 else
744 to_index = std::max(to_index, attach_index_);
745 if (to_index != attach_index_)
746 attach_index_ = -1; // Once a valid move is detected, don't constrain.
747 else
748 do_move = false;
750 if (do_move) {
751 WebContents* last_contents = drag_data_[drag_data_.size() - 1].contents;
752 int index_of_last_item =
753 attached_model->GetIndexOfWebContents(last_contents);
754 if (initial_move_) {
755 // TabStrip determines if the tabs needs to be animated based on model
756 // position. This means we need to invoke LayoutDraggedTabsAt before
757 // changing the model.
758 attached_tabstrip_->LayoutDraggedTabsAt(
759 tabs, source_tab_drag_data()->attached_tab, dragged_view_point,
760 initial_move_);
761 did_layout = true;
763 attached_model->MoveSelectedTabsTo(to_index);
765 // Move may do nothing in certain situations (such as when dragging pinned
766 // tabs). Make sure the tabstrip actually changed before updating
767 // last_move_screen_loc_.
768 if (index_of_last_item !=
769 attached_model->GetIndexOfWebContents(last_contents)) {
770 last_move_screen_loc_ = point_in_screen.x();
775 if (!did_layout) {
776 attached_tabstrip_->LayoutDraggedTabsAt(
777 tabs, source_tab_drag_data()->attached_tab, dragged_view_point,
778 initial_move_);
781 StartMoveStackedTimerIfNecessary(point_in_screen, kMoveAttachedInitialDelay);
783 initial_move_ = false;
786 void TabDragController::StartMoveStackedTimerIfNecessary(
787 const gfx::Point& point_in_screen,
788 int delay_ms) {
789 DCHECK(attached_tabstrip_);
791 StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get();
792 if (!touch_layout)
793 return;
795 gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
796 gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point);
797 int index = touch_layout->active_index();
798 if (ShouldDragToNextStackedTab(bounds, index)) {
799 static_cast<base::Timer*>(&move_stacked_timer_)->Start(
800 FROM_HERE,
801 base::TimeDelta::FromMilliseconds(delay_ms),
802 base::Bind(&TabDragController::MoveAttachedToNextStackedIndex,
803 base::Unretained(this), point_in_screen));
804 } else if (ShouldDragToPreviousStackedTab(bounds, index)) {
805 static_cast<base::Timer*>(&move_stacked_timer_)->Start(
806 FROM_HERE,
807 base::TimeDelta::FromMilliseconds(delay_ms),
808 base::Bind(&TabDragController::MoveAttachedToPreviousStackedIndex,
809 base::Unretained(this), point_in_screen));
813 TabDragController::DetachPosition TabDragController::GetDetachPosition(
814 const gfx::Point& point_in_screen) {
815 DCHECK(attached_tabstrip_);
816 gfx::Point attached_point(point_in_screen);
817 views::View::ConvertPointFromScreen(attached_tabstrip_, &attached_point);
818 if (attached_point.x() < 0)
819 return DETACH_BEFORE;
820 if (attached_point.x() >= attached_tabstrip_->width())
821 return DETACH_AFTER;
822 return DETACH_ABOVE_OR_BELOW;
825 TabStrip* TabDragController::GetTargetTabStripForPoint(
826 const gfx::Point& point_in_screen) {
827 TRACE_EVENT1("views", "TabDragController::GetTargetTabStripForPoint",
828 "point_in_screen", point_in_screen.ToString());
830 if (move_only() && attached_tabstrip_) {
831 // move_only() is intended for touch, in which case we only want to detach
832 // if the touch point moves significantly in the vertical distance.
833 gfx::Rect tabstrip_bounds = GetViewScreenBounds(attached_tabstrip_);
834 if (DoesRectContainVerticalPointExpanded(tabstrip_bounds,
835 kTouchVerticalDetachMagnetism,
836 point_in_screen.y()))
837 return attached_tabstrip_;
839 gfx::NativeWindow local_window =
840 GetLocalProcessWindow(point_in_screen, is_dragging_window_);
841 // Do not allow dragging into a window with a modal dialog, it causes a weird
842 // behavior. See crbug.com/336691
843 if (!GetModalTransient(local_window)) {
844 TabStrip* tab_strip = GetTabStripForWindow(local_window);
845 if (tab_strip && DoesTabStripContain(tab_strip, point_in_screen))
846 return tab_strip;
849 return is_dragging_window_ ? attached_tabstrip_ : NULL;
852 TabStrip* TabDragController::GetTabStripForWindow(gfx::NativeWindow window) {
853 if (!window)
854 return NULL;
855 BrowserView* browser_view =
856 BrowserView::GetBrowserViewForNativeWindow(window);
857 // We don't allow drops on windows that don't have tabstrips.
858 if (!browser_view ||
859 !browser_view->browser()->SupportsWindowFeature(
860 Browser::FEATURE_TABSTRIP))
861 return NULL;
863 TabStrip* other_tabstrip = browser_view->tabstrip();
864 TabStrip* tab_strip =
865 attached_tabstrip_ ? attached_tabstrip_ : source_tabstrip_;
866 DCHECK(tab_strip);
868 return other_tabstrip->controller()->IsCompatibleWith(tab_strip) ?
869 other_tabstrip : NULL;
872 bool TabDragController::DoesTabStripContain(
873 TabStrip* tabstrip,
874 const gfx::Point& point_in_screen) const {
875 // Make sure the specified screen point is actually within the bounds of the
876 // specified tabstrip...
877 gfx::Rect tabstrip_bounds = GetViewScreenBounds(tabstrip);
878 return point_in_screen.x() < tabstrip_bounds.right() &&
879 point_in_screen.x() >= tabstrip_bounds.x() &&
880 DoesRectContainVerticalPointExpanded(tabstrip_bounds,
881 kVerticalDetachMagnetism,
882 point_in_screen.y());
885 void TabDragController::Attach(TabStrip* attached_tabstrip,
886 const gfx::Point& point_in_screen) {
887 TRACE_EVENT1("views", "TabDragController::Attach",
888 "point_in_screen", point_in_screen.ToString());
890 DCHECK(!attached_tabstrip_); // We should already have detached by the time
891 // we get here.
893 attached_tabstrip_ = attached_tabstrip;
895 std::vector<Tab*> tabs =
896 GetTabsMatchingDraggedContents(attached_tabstrip_);
898 if (tabs.empty()) {
899 // Transitioning from detached to attached to a new tabstrip. Add tabs to
900 // the new model.
902 selection_model_before_attach_.Copy(attached_tabstrip->GetSelectionModel());
904 // Inserting counts as a move. We don't want the tabs to jitter when the
905 // user moves the tab immediately after attaching it.
906 last_move_screen_loc_ = point_in_screen.x();
908 // Figure out where to insert the tab based on the bounds of the dragged
909 // representation and the ideal bounds of the other Tabs already in the
910 // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
911 // changing due to animation).
912 gfx::Point tab_strip_point(point_in_screen);
913 views::View::ConvertPointFromScreen(attached_tabstrip_, &tab_strip_point);
914 tab_strip_point.set_x(
915 attached_tabstrip_->GetMirroredXInView(tab_strip_point.x()));
916 tab_strip_point.Offset(0, -mouse_offset_.y());
917 int index = GetInsertionIndexForDraggedBounds(
918 GetDraggedViewTabStripBounds(tab_strip_point));
919 attach_index_ = index;
920 attach_x_ = tab_strip_point.x();
921 base::AutoReset<bool> setter(&is_mutating_, true);
922 for (size_t i = 0; i < drag_data_.size(); ++i) {
923 int add_types = TabStripModel::ADD_NONE;
924 if (attached_tabstrip_->touch_layout_.get()) {
925 // StackedTabStripLayout positions relative to the active tab, if we
926 // don't add the tab as active things bounce around.
927 DCHECK_EQ(1u, drag_data_.size());
928 add_types |= TabStripModel::ADD_ACTIVE;
930 if (drag_data_[i].pinned)
931 add_types |= TabStripModel::ADD_PINNED;
932 GetModel(attached_tabstrip_)->InsertWebContentsAt(
933 index + i, drag_data_[i].contents, add_types);
936 tabs = GetTabsMatchingDraggedContents(attached_tabstrip_);
938 DCHECK_EQ(tabs.size(), drag_data_.size());
939 for (size_t i = 0; i < drag_data_.size(); ++i)
940 drag_data_[i].attached_tab = tabs[i];
942 attached_tabstrip_->StartedDraggingTabs(tabs);
944 ResetSelection(GetModel(attached_tabstrip_));
946 // The size of the dragged tab may have changed. Adjust the x offset so that
947 // ratio of mouse_offset_ to original width is maintained.
948 std::vector<Tab*> tabs_to_source(tabs);
949 tabs_to_source.erase(tabs_to_source.begin() + source_tab_index_ + 1,
950 tabs_to_source.end());
951 int new_x = attached_tabstrip_->GetSizeNeededForTabs(tabs_to_source) -
952 tabs[source_tab_index_]->width() +
953 static_cast<int>(offset_to_width_ratio_ *
954 tabs[source_tab_index_]->width());
955 mouse_offset_.set_x(new_x);
957 // Transfer ownership of us to the new tabstrip as well as making sure the
958 // window has capture. This is important so that if activation changes the
959 // drag isn't prematurely canceled.
960 attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_);
961 attached_tabstrip_->OwnDragController(this);
964 void TabDragController::Detach(ReleaseCapture release_capture) {
965 TRACE_EVENT1("views", "TabDragController::Detach",
966 "release_capture", release_capture);
968 attach_index_ = -1;
970 // When the user detaches we assume they want to reorder.
971 move_behavior_ = REORDER;
973 // Release ownership of the drag controller and mouse capture. When we
974 // reattach ownership is transfered.
975 attached_tabstrip_->ReleaseDragController();
976 if (release_capture == RELEASE_CAPTURE)
977 attached_tabstrip_->GetWidget()->ReleaseCapture();
979 mouse_move_direction_ = kMovedMouseLeft | kMovedMouseRight;
981 std::vector<gfx::Rect> drag_bounds = CalculateBoundsForDraggedTabs();
982 TabStripModel* attached_model = GetModel(attached_tabstrip_);
983 std::vector<TabRendererData> tab_data;
984 for (size_t i = 0; i < drag_data_.size(); ++i) {
985 tab_data.push_back(drag_data_[i].attached_tab->data());
986 int index = attached_model->GetIndexOfWebContents(drag_data_[i].contents);
987 DCHECK_NE(-1, index);
989 // Hide the tab so that the user doesn't see it animate closed.
990 drag_data_[i].attached_tab->SetVisible(false);
991 drag_data_[i].attached_tab->set_detached();
993 attached_model->DetachWebContentsAt(index);
995 // Detaching may end up deleting the tab, drop references to it.
996 drag_data_[i].attached_tab = NULL;
999 // If we've removed the last Tab from the TabStrip, hide the frame now.
1000 if (!attached_model->empty()) {
1001 if (!selection_model_before_attach_.empty() &&
1002 selection_model_before_attach_.active() >= 0 &&
1003 selection_model_before_attach_.active() < attached_model->count()) {
1004 // Restore the selection.
1005 attached_model->SetSelectionFromModel(selection_model_before_attach_);
1006 } else if (attached_tabstrip_ == source_tabstrip_ &&
1007 !initial_selection_model_.empty()) {
1008 RestoreInitialSelection();
1012 attached_tabstrip_->DraggedTabsDetached();
1013 attached_tabstrip_ = NULL;
1016 void TabDragController::DetachIntoNewBrowserAndRunMoveLoop(
1017 const gfx::Point& point_in_screen) {
1018 if (GetModel(attached_tabstrip_)->count() ==
1019 static_cast<int>(drag_data_.size())) {
1020 // All the tabs in a browser are being dragged but all the tabs weren't
1021 // initially being dragged. For this to happen the user would have to
1022 // start dragging a set of tabs, the other tabs close, then detach.
1023 RunMoveLoop(GetWindowOffset(point_in_screen));
1024 return;
1027 const int last_tabstrip_width = attached_tabstrip_->tab_area_width();
1028 std::vector<gfx::Rect> drag_bounds = CalculateBoundsForDraggedTabs();
1029 OffsetX(GetAttachedDragPoint(point_in_screen).x(), &drag_bounds);
1031 gfx::Vector2d drag_offset;
1032 Browser* browser = CreateBrowserForDrag(
1033 attached_tabstrip_, point_in_screen, &drag_offset, &drag_bounds);
1034 #if defined(OS_WIN)
1035 gfx::NativeView attached_native_view =
1036 attached_tabstrip_->GetWidget()->GetNativeView();
1037 #endif
1038 Detach(can_release_capture_ ? RELEASE_CAPTURE : DONT_RELEASE_CAPTURE);
1039 BrowserView* dragged_browser_view =
1040 BrowserView::GetBrowserViewForBrowser(browser);
1041 views::Widget* dragged_widget = dragged_browser_view->GetWidget();
1042 #if defined(OS_WIN)
1043 // The Gesture recognizer does not work well currently when capture changes
1044 // while a touch gesture is in progress. So we need to manually transfer
1045 // gesture sequence and the GR's touch events queue to the new window. This
1046 // should really be done somewhere in capture change code and or inside the
1047 // GR. But we currently do not have a consistent way for doing it that would
1048 // work in all cases. Hence this hack.
1049 ui::GestureRecognizer::Get()->TransferEventsTo(
1050 attached_native_view,
1051 dragged_widget->GetNativeView());
1052 #endif
1053 dragged_widget->SetVisibilityChangedAnimationsEnabled(false);
1054 Attach(dragged_browser_view->tabstrip(), gfx::Point());
1055 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width,
1056 point_in_screen,
1057 &drag_bounds);
1058 WindowPositionManagedUpdater updater;
1059 dragged_widget->AddObserver(&updater);
1060 browser->window()->Show();
1061 dragged_widget->RemoveObserver(&updater);
1062 dragged_widget->SetVisibilityChangedAnimationsEnabled(true);
1063 // Activate may trigger a focus loss, destroying us.
1065 base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
1066 browser->window()->Activate();
1067 if (!ref)
1068 return;
1070 RunMoveLoop(drag_offset);
1073 void TabDragController::RunMoveLoop(const gfx::Vector2d& drag_offset) {
1074 // If the user drags the whole window we'll assume they are going to attach to
1075 // another window and therefore want to reorder.
1076 move_behavior_ = REORDER;
1078 move_loop_widget_ = GetAttachedBrowserWidget();
1079 DCHECK(move_loop_widget_);
1080 move_loop_widget_->AddObserver(this);
1081 is_dragging_window_ = true;
1082 base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
1083 if (can_release_capture_) {
1084 // Running the move loop releases mouse capture, which triggers destroying
1085 // the drag loop. Release mouse capture now while the DragController is not
1086 // owned by the TabStrip.
1087 attached_tabstrip_->ReleaseDragController();
1088 attached_tabstrip_->GetWidget()->ReleaseCapture();
1089 attached_tabstrip_->OwnDragController(this);
1091 const views::Widget::MoveLoopSource move_loop_source =
1092 event_source_ == EVENT_SOURCE_MOUSE ?
1093 views::Widget::MOVE_LOOP_SOURCE_MOUSE :
1094 views::Widget::MOVE_LOOP_SOURCE_TOUCH;
1095 const views::Widget::MoveLoopEscapeBehavior escape_behavior =
1096 is_dragging_new_browser_ ?
1097 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE :
1098 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE;
1099 views::Widget::MoveLoopResult result =
1100 move_loop_widget_->RunMoveLoop(
1101 drag_offset, move_loop_source, escape_behavior);
1102 content::NotificationService::current()->Notify(
1103 chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE,
1104 content::NotificationService::AllBrowserContextsAndSources(),
1105 content::NotificationService::NoDetails());
1107 if (!ref)
1108 return;
1109 if (move_loop_widget_) {
1110 move_loop_widget_->RemoveObserver(this);
1111 move_loop_widget_ = NULL;
1113 is_dragging_window_ = false;
1114 waiting_for_run_loop_to_exit_ = false;
1115 if (end_run_loop_behavior_ == END_RUN_LOOP_CONTINUE_DRAGGING) {
1116 end_run_loop_behavior_ = END_RUN_LOOP_STOP_DRAGGING;
1117 if (tab_strip_to_attach_to_after_exit_) {
1118 gfx::Point point_in_screen(GetCursorScreenPoint());
1119 Detach(DONT_RELEASE_CAPTURE);
1120 Attach(tab_strip_to_attach_to_after_exit_, point_in_screen);
1121 // Move the tabs into position.
1122 MoveAttached(point_in_screen);
1123 attached_tabstrip_->GetWidget()->Activate();
1124 // Activate may trigger a focus loss, destroying us.
1125 if (!ref)
1126 return;
1127 tab_strip_to_attach_to_after_exit_ = NULL;
1129 DCHECK(attached_tabstrip_);
1130 attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_);
1131 } else if (active_) {
1132 EndDrag(result == views::Widget::MOVE_LOOP_CANCELED ?
1133 END_DRAG_CANCEL : END_DRAG_COMPLETE);
1137 int TabDragController::GetInsertionIndexFrom(const gfx::Rect& dragged_bounds,
1138 int start) const {
1139 const int last_tab = attached_tabstrip_->tab_count() - 1;
1140 // Make the actual "drag insertion point" be just after the leading edge of
1141 // the first dragged tab. This is closer to where the user thinks of the tab
1142 // as "starting" than just dragged_bounds.x(), especially with narrow tabs.
1143 const int dragged_x = dragged_bounds.x() + Tab::leading_width_for_drag();
1144 if (start < 0 || start > last_tab ||
1145 dragged_x < attached_tabstrip_->ideal_bounds(start).x())
1146 return -1;
1148 for (int i = start; i <= last_tab; ++i) {
1149 const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i);
1150 if (dragged_x < (ideal_bounds.x() + (ideal_bounds.width() / 2)))
1151 return i;
1154 return (dragged_x < attached_tabstrip_->ideal_bounds(last_tab).right()) ?
1155 (last_tab + 1) : -1;
1158 int TabDragController::GetInsertionIndexFromReversed(
1159 const gfx::Rect& dragged_bounds,
1160 int start) const {
1161 // Make the actual "drag insertion point" be just after the leading edge of
1162 // the first dragged tab. This is closer to where the user thinks of the tab
1163 // as "starting" than just dragged_bounds.x(), especially with narrow tabs.
1164 const int dragged_x = dragged_bounds.x() + Tab::leading_width_for_drag();
1165 if (start < 0 || start >= attached_tabstrip_->tab_count() ||
1166 dragged_x >= attached_tabstrip_->ideal_bounds(start).right())
1167 return -1;
1169 for (int i = start; i >= 0; --i) {
1170 const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i);
1171 if (dragged_x >= (ideal_bounds.x() + (ideal_bounds.width() / 2)))
1172 return i + 1;
1175 return (dragged_x >= attached_tabstrip_->ideal_bounds(0).x()) ? 0 : -1;
1178 int TabDragController::GetInsertionIndexForDraggedBounds(
1179 const gfx::Rect& dragged_bounds) const {
1180 // If the strip has no tabs, the only position to insert at is 0.
1181 const int tab_count = attached_tabstrip_->tab_count();
1182 if (!tab_count)
1183 return 0;
1185 int index = -1;
1186 if (attached_tabstrip_->touch_layout_.get()) {
1187 index = GetInsertionIndexForDraggedBoundsStacked(dragged_bounds);
1188 if (index != -1) {
1189 // Only move the tab to the left/right if the user actually moved the
1190 // mouse that way. This is necessary as tabs with stacked tabs
1191 // before/after them have multiple drag positions.
1192 int active_index = attached_tabstrip_->touch_layout_->active_index();
1193 if ((index < active_index &&
1194 (mouse_move_direction_ & kMovedMouseLeft) == 0) ||
1195 (index > active_index &&
1196 (mouse_move_direction_ & kMovedMouseRight) == 0)) {
1197 index = active_index;
1200 } else {
1201 index = GetInsertionIndexFrom(dragged_bounds, 0);
1203 if (index == -1) {
1204 const int last_tab_right =
1205 attached_tabstrip_->ideal_bounds(tab_count - 1).right();
1206 index = (dragged_bounds.right() > last_tab_right) ? tab_count : 0;
1209 const Tab* last_visible_tab = attached_tabstrip_->GetLastVisibleTab();
1210 int last_insertion_point = last_visible_tab ?
1211 (attached_tabstrip_->GetModelIndexOfTab(last_visible_tab) + 1) : 0;
1212 if (drag_data_[0].attached_tab) {
1213 // We're not in the process of attaching, so clamp the insertion point to
1214 // keep it within the visible region.
1215 last_insertion_point = std::max(
1216 0, last_insertion_point - static_cast<int>(drag_data_.size()));
1219 // Ensure the first dragged tab always stays in the visible index range.
1220 return std::min(index, last_insertion_point);
1223 bool TabDragController::ShouldDragToNextStackedTab(
1224 const gfx::Rect& dragged_bounds,
1225 int index) const {
1226 if (index + 1 >= attached_tabstrip_->tab_count() ||
1227 !attached_tabstrip_->touch_layout_->IsStacked(index + 1) ||
1228 (mouse_move_direction_ & kMovedMouseRight) == 0)
1229 return false;
1231 int active_x = attached_tabstrip_->ideal_bounds(index).x();
1232 int next_x = attached_tabstrip_->ideal_bounds(index + 1).x();
1233 int mid_x = std::min(next_x - kStackedDistance,
1234 active_x + (next_x - active_x) / 4);
1235 // TODO(pkasting): Should this add Tab::leading_width_for_drag() as
1236 // GetInsertionIndexFrom() does?
1237 return dragged_bounds.x() >= mid_x;
1240 bool TabDragController::ShouldDragToPreviousStackedTab(
1241 const gfx::Rect& dragged_bounds,
1242 int index) const {
1243 if (index - 1 < attached_tabstrip_->GetMiniTabCount() ||
1244 !attached_tabstrip_->touch_layout_->IsStacked(index - 1) ||
1245 (mouse_move_direction_ & kMovedMouseLeft) == 0)
1246 return false;
1248 int active_x = attached_tabstrip_->ideal_bounds(index).x();
1249 int previous_x = attached_tabstrip_->ideal_bounds(index - 1).x();
1250 int mid_x = std::max(previous_x + kStackedDistance,
1251 active_x - (active_x - previous_x) / 4);
1252 // TODO(pkasting): Should this add Tab::leading_width_for_drag() as
1253 // GetInsertionIndexFrom() does?
1254 return dragged_bounds.x() <= mid_x;
1257 int TabDragController::GetInsertionIndexForDraggedBoundsStacked(
1258 const gfx::Rect& dragged_bounds) const {
1259 StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get();
1260 int active_index = touch_layout->active_index();
1261 // Search from the active index to the front of the tabstrip. Do this as tabs
1262 // overlap each other from the active index.
1263 int index = GetInsertionIndexFromReversed(dragged_bounds, active_index);
1264 if (index != active_index)
1265 return index;
1266 if (index == -1)
1267 return GetInsertionIndexFrom(dragged_bounds, active_index + 1);
1269 // The position to drag to corresponds to the active tab. If the next/previous
1270 // tab is stacked, then shorten the distance used to determine insertion
1271 // bounds. We do this as GetInsertionIndexFrom() uses the bounds of the
1272 // tabs. When tabs are stacked the next/previous tab is on top of the tab.
1273 if (active_index + 1 < attached_tabstrip_->tab_count() &&
1274 touch_layout->IsStacked(active_index + 1)) {
1275 index = GetInsertionIndexFrom(dragged_bounds, active_index + 1);
1276 if (index == -1 && ShouldDragToNextStackedTab(dragged_bounds, active_index))
1277 index = active_index + 1;
1278 else if (index == -1)
1279 index = active_index;
1280 } else if (ShouldDragToPreviousStackedTab(dragged_bounds, active_index)) {
1281 index = active_index - 1;
1283 return index;
1286 gfx::Rect TabDragController::GetDraggedViewTabStripBounds(
1287 const gfx::Point& tab_strip_point) {
1288 // attached_tab is NULL when inserting into a new tabstrip.
1289 if (source_tab_drag_data()->attached_tab) {
1290 return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1291 source_tab_drag_data()->attached_tab->width(),
1292 source_tab_drag_data()->attached_tab->height());
1295 double sel_width, unselected_width;
1296 attached_tabstrip_->GetCurrentTabWidths(&sel_width, &unselected_width);
1297 return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1298 static_cast<int>(sel_width),
1299 Tab::GetStandardSize().height());
1302 gfx::Point TabDragController::GetAttachedDragPoint(
1303 const gfx::Point& point_in_screen) {
1304 DCHECK(attached_tabstrip_); // The tab must be attached.
1306 gfx::Point tab_loc(point_in_screen);
1307 views::View::ConvertPointFromScreen(attached_tabstrip_, &tab_loc);
1308 const int x =
1309 attached_tabstrip_->GetMirroredXInView(tab_loc.x()) - mouse_offset_.x();
1311 // TODO: consider caching this.
1312 std::vector<Tab*> attached_tabs;
1313 for (size_t i = 0; i < drag_data_.size(); ++i)
1314 attached_tabs.push_back(drag_data_[i].attached_tab);
1315 const int size = attached_tabstrip_->GetSizeNeededForTabs(attached_tabs);
1316 const int max_x = attached_tabstrip_->width() - size;
1317 return gfx::Point(std::min(std::max(x, 0), max_x), 0);
1320 std::vector<Tab*> TabDragController::GetTabsMatchingDraggedContents(
1321 TabStrip* tabstrip) {
1322 TabStripModel* model = GetModel(attached_tabstrip_);
1323 std::vector<Tab*> tabs;
1324 for (size_t i = 0; i < drag_data_.size(); ++i) {
1325 int model_index = model->GetIndexOfWebContents(drag_data_[i].contents);
1326 if (model_index == TabStripModel::kNoTab)
1327 return std::vector<Tab*>();
1328 tabs.push_back(tabstrip->tab_at(model_index));
1330 return tabs;
1333 std::vector<gfx::Rect> TabDragController::CalculateBoundsForDraggedTabs() {
1334 std::vector<gfx::Rect> drag_bounds;
1335 std::vector<Tab*> attached_tabs;
1336 for (size_t i = 0; i < drag_data_.size(); ++i)
1337 attached_tabs.push_back(drag_data_[i].attached_tab);
1338 attached_tabstrip_->CalculateBoundsForDraggedTabs(attached_tabs,
1339 &drag_bounds);
1340 return drag_bounds;
1343 void TabDragController::EndDragImpl(EndDragType type) {
1344 DCHECK(active_);
1345 active_ = false;
1347 bring_to_front_timer_.Stop();
1348 move_stacked_timer_.Stop();
1350 if (is_dragging_window_) {
1351 waiting_for_run_loop_to_exit_ = true;
1353 if (type == NORMAL || (type == TAB_DESTROYED && drag_data_.size() > 1)) {
1354 SetWindowPositionManaged(GetAttachedBrowserWidget()->GetNativeWindow(),
1355 true);
1358 // End the nested drag loop.
1359 GetAttachedBrowserWidget()->EndMoveLoop();
1362 if (type != TAB_DESTROYED) {
1363 // We only finish up the drag if we were actually dragging. If start_drag_
1364 // is false, the user just clicked and released and didn't move the mouse
1365 // enough to trigger a drag.
1366 if (started_drag_) {
1367 RestoreFocus();
1368 if (type == CANCELED)
1369 RevertDrag();
1370 else
1371 CompleteDrag();
1373 } else if (drag_data_.size() > 1) {
1374 initial_selection_model_.Clear();
1375 if (started_drag_)
1376 RevertDrag();
1377 } // else case the only tab we were dragging was deleted. Nothing to do.
1379 // Clear out drag data so we don't attempt to do anything with it.
1380 drag_data_.clear();
1382 TabStrip* owning_tabstrip = attached_tabstrip_ ?
1383 attached_tabstrip_ : source_tabstrip_;
1384 owning_tabstrip->DestroyDragController();
1387 void TabDragController::RevertDrag() {
1388 std::vector<Tab*> tabs;
1389 for (size_t i = 0; i < drag_data_.size(); ++i) {
1390 if (drag_data_[i].contents) {
1391 // Contents is NULL if a tab was destroyed while the drag was under way.
1392 tabs.push_back(drag_data_[i].attached_tab);
1393 RevertDragAt(i);
1397 if (attached_tabstrip_) {
1398 if (did_restore_window_)
1399 MaximizeAttachedWindow();
1400 if (attached_tabstrip_ == source_tabstrip_) {
1401 source_tabstrip_->StoppedDraggingTabs(
1402 tabs, initial_tab_positions_, move_behavior_ == MOVE_VISIBILE_TABS,
1403 false);
1404 } else {
1405 attached_tabstrip_->DraggedTabsDetached();
1409 if (initial_selection_model_.empty())
1410 ResetSelection(GetModel(source_tabstrip_));
1411 else
1412 GetModel(source_tabstrip_)->SetSelectionFromModel(initial_selection_model_);
1414 if (source_tabstrip_)
1415 source_tabstrip_->GetWidget()->Activate();
1418 void TabDragController::ResetSelection(TabStripModel* model) {
1419 DCHECK(model);
1420 ui::ListSelectionModel selection_model;
1421 bool has_one_valid_tab = false;
1422 for (size_t i = 0; i < drag_data_.size(); ++i) {
1423 // |contents| is NULL if a tab was deleted out from under us.
1424 if (drag_data_[i].contents) {
1425 int index = model->GetIndexOfWebContents(drag_data_[i].contents);
1426 DCHECK_NE(-1, index);
1427 selection_model.AddIndexToSelection(index);
1428 if (!has_one_valid_tab || i == source_tab_index_) {
1429 // Reset the active/lead to the first tab. If the source tab is still
1430 // valid we'll reset these again later on.
1431 selection_model.set_active(index);
1432 selection_model.set_anchor(index);
1433 has_one_valid_tab = true;
1437 if (!has_one_valid_tab)
1438 return;
1440 model->SetSelectionFromModel(selection_model);
1443 void TabDragController::RestoreInitialSelection() {
1444 // First time detaching from the source tabstrip. Reset selection model to
1445 // initial_selection_model_. Before resetting though we have to remove all
1446 // the tabs from initial_selection_model_ as it was created with the tabs
1447 // still there.
1448 ui::ListSelectionModel selection_model;
1449 selection_model.Copy(initial_selection_model_);
1450 for (DragData::const_reverse_iterator i(drag_data_.rbegin());
1451 i != drag_data_.rend(); ++i) {
1452 selection_model.DecrementFrom(i->source_model_index);
1454 // We may have cleared out the selection model. Only reset it if it
1455 // contains something.
1456 if (selection_model.empty())
1457 return;
1459 // The anchor/active may have been among the tabs that were dragged out. Force
1460 // the anchor/active to be valid.
1461 if (selection_model.anchor() == ui::ListSelectionModel::kUnselectedIndex)
1462 selection_model.set_anchor(selection_model.selected_indices()[0]);
1463 if (selection_model.active() == ui::ListSelectionModel::kUnselectedIndex)
1464 selection_model.set_active(selection_model.selected_indices()[0]);
1465 GetModel(source_tabstrip_)->SetSelectionFromModel(selection_model);
1468 void TabDragController::RevertDragAt(size_t drag_index) {
1469 DCHECK(started_drag_);
1470 DCHECK(source_tabstrip_);
1472 base::AutoReset<bool> setter(&is_mutating_, true);
1473 TabDragData* data = &(drag_data_[drag_index]);
1474 if (attached_tabstrip_) {
1475 int index =
1476 GetModel(attached_tabstrip_)->GetIndexOfWebContents(data->contents);
1477 if (attached_tabstrip_ != source_tabstrip_) {
1478 // The Tab was inserted into another TabStrip. We need to put it back
1479 // into the original one.
1480 GetModel(attached_tabstrip_)->DetachWebContentsAt(index);
1481 // TODO(beng): (Cleanup) seems like we should use Attach() for this
1482 // somehow.
1483 GetModel(source_tabstrip_)->InsertWebContentsAt(
1484 data->source_model_index, data->contents,
1485 (data->pinned ? TabStripModel::ADD_PINNED : 0));
1486 } else {
1487 // The Tab was moved within the TabStrip where the drag was initiated.
1488 // Move it back to the starting location.
1489 GetModel(source_tabstrip_)->MoveWebContentsAt(
1490 index, data->source_model_index, false);
1492 } else {
1493 // The Tab was detached from the TabStrip where the drag began, and has not
1494 // been attached to any other TabStrip. We need to put it back into the
1495 // source TabStrip.
1496 GetModel(source_tabstrip_)->InsertWebContentsAt(
1497 data->source_model_index, data->contents,
1498 (data->pinned ? TabStripModel::ADD_PINNED : 0));
1502 void TabDragController::CompleteDrag() {
1503 DCHECK(started_drag_);
1505 if (attached_tabstrip_) {
1506 if (is_dragging_new_browser_ || did_restore_window_) {
1507 if (IsDockedOrSnapped(attached_tabstrip_)) {
1508 was_source_maximized_ = false;
1509 was_source_fullscreen_ = false;
1512 // If source window was maximized - maximize the new window as well.
1513 if (was_source_maximized_ || was_source_fullscreen_)
1514 MaximizeAttachedWindow();
1516 attached_tabstrip_->StoppedDraggingTabs(
1517 GetTabsMatchingDraggedContents(attached_tabstrip_),
1518 initial_tab_positions_,
1519 move_behavior_ == MOVE_VISIBILE_TABS,
1520 true);
1521 } else {
1522 // Compel the model to construct a new window for the detached
1523 // WebContentses.
1524 views::Widget* widget = source_tabstrip_->GetWidget();
1525 gfx::Rect window_bounds(widget->GetRestoredBounds());
1526 window_bounds.set_origin(GetWindowCreatePoint(last_point_in_screen_));
1528 base::AutoReset<bool> setter(&is_mutating_, true);
1530 std::vector<TabStripModelDelegate::NewStripContents> contentses;
1531 for (size_t i = 0; i < drag_data_.size(); ++i) {
1532 TabStripModelDelegate::NewStripContents item;
1533 item.web_contents = drag_data_[i].contents;
1534 item.add_types = drag_data_[i].pinned ? TabStripModel::ADD_PINNED
1535 : TabStripModel::ADD_NONE;
1536 contentses.push_back(item);
1539 Browser* new_browser =
1540 GetModel(source_tabstrip_)->delegate()->CreateNewStripWithContents(
1541 contentses, window_bounds, widget->IsMaximized());
1542 ResetSelection(new_browser->tab_strip_model());
1543 new_browser->window()->Show();
1547 void TabDragController::MaximizeAttachedWindow() {
1548 GetAttachedBrowserWidget()->Maximize();
1549 #if defined(USE_ASH)
1550 if (was_source_fullscreen_ &&
1551 host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
1552 // In fullscreen mode it is only possible to get here if the source
1553 // was in "immersive fullscreen" mode, so toggle it back on.
1554 ash::accelerators::ToggleFullscreen();
1556 #endif
1559 gfx::Rect TabDragController::GetViewScreenBounds(
1560 views::View* view) const {
1561 gfx::Point view_topleft;
1562 views::View::ConvertPointToScreen(view, &view_topleft);
1563 gfx::Rect view_screen_bounds = view->GetLocalBounds();
1564 view_screen_bounds.Offset(view_topleft.x(), view_topleft.y());
1565 return view_screen_bounds;
1568 void TabDragController::BringWindowUnderPointToFront(
1569 const gfx::Point& point_in_screen) {
1570 gfx::NativeWindow window = GetLocalProcessWindow(point_in_screen, true);
1572 // Only bring browser windows to front - only windows with a TabStrip can
1573 // be tab drag targets.
1574 if (!GetTabStripForWindow(window))
1575 return;
1577 if (window) {
1578 views::Widget* widget_window = views::Widget::GetWidgetForNativeWindow(
1579 window);
1580 if (!widget_window)
1581 return;
1583 #if defined(USE_ASH)
1584 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
1585 // TODO(varkha): The code below ensures that the phantom drag widget
1586 // is shown on top of browser windows. The code should be moved to ash/
1587 // and the phantom should be able to assert its top-most state on its own.
1588 // One strategy would be for DragWindowController to
1589 // be able to observe stacking changes to the phantom drag widget's
1590 // siblings in order to keep it on top. One way is to implement a
1591 // notification that is sent to a window parent's observers when a
1592 // stacking order is changed among the children of that same parent.
1593 // Note that OnWindowStackingChanged is sent only to the child that is the
1594 // argument of one of the Window::StackChildX calls and not to all its
1595 // siblings affected by the stacking change.
1596 aura::Window* browser_window = widget_window->GetNativeView();
1597 // Find a topmost non-popup window and stack the recipient browser above
1598 // it in order to avoid stacking the browser window on top of the phantom
1599 // drag widget created by DragWindowController in a second display.
1600 for (aura::Window::Windows::const_reverse_iterator it =
1601 browser_window->parent()->children().rbegin();
1602 it != browser_window->parent()->children().rend(); ++it) {
1603 // If the iteration reached the recipient browser window then it is
1604 // already topmost and it is safe to return with no stacking change.
1605 if (*it == browser_window)
1606 return;
1607 if ((*it)->type() != ui::wm::WINDOW_TYPE_POPUP) {
1608 widget_window->StackAbove(*it);
1609 break;
1612 } else {
1613 widget_window->StackAtTop();
1615 #else
1616 widget_window->StackAtTop();
1617 #endif
1619 // The previous call made the window appear on top of the dragged window,
1620 // move the dragged window to the front.
1621 if (is_dragging_window_)
1622 attached_tabstrip_->GetWidget()->StackAtTop();
1626 TabStripModel* TabDragController::GetModel(
1627 TabStrip* tabstrip) const {
1628 return static_cast<BrowserTabStripController*>(tabstrip->controller())->
1629 model();
1632 views::Widget* TabDragController::GetAttachedBrowserWidget() {
1633 return attached_tabstrip_->GetWidget();
1636 bool TabDragController::AreTabsConsecutive() {
1637 for (size_t i = 1; i < drag_data_.size(); ++i) {
1638 if (drag_data_[i - 1].source_model_index + 1 !=
1639 drag_data_[i].source_model_index) {
1640 return false;
1643 return true;
1646 gfx::Rect TabDragController::CalculateDraggedBrowserBounds(
1647 TabStrip* source,
1648 const gfx::Point& point_in_screen,
1649 std::vector<gfx::Rect>* drag_bounds) {
1650 gfx::Point center(0, source->height() / 2);
1651 views::View::ConvertPointToWidget(source, &center);
1652 gfx::Rect new_bounds(source->GetWidget()->GetRestoredBounds());
1653 if (source->GetWidget()->IsMaximized()) {
1654 // If the restore bounds is really small, we don't want to honor it
1655 // (dragging a really small window looks wrong), instead make sure the new
1656 // window is at least 50% the size of the old.
1657 const gfx::Size max_size(
1658 source->GetWidget()->GetWindowBoundsInScreen().size());
1659 new_bounds.set_width(
1660 std::max(max_size.width() / 2, new_bounds.width()));
1661 new_bounds.set_height(
1662 std::max(max_size.height() / 2, new_bounds.height()));
1664 new_bounds.set_y(point_in_screen.y() - center.y());
1665 switch (GetDetachPosition(point_in_screen)) {
1666 case DETACH_BEFORE:
1667 new_bounds.set_x(point_in_screen.x() - center.x());
1668 new_bounds.Offset(-mouse_offset_.x(), 0);
1669 break;
1670 case DETACH_AFTER: {
1671 gfx::Point right_edge(source->width(), 0);
1672 views::View::ConvertPointToWidget(source, &right_edge);
1673 new_bounds.set_x(point_in_screen.x() - right_edge.x());
1674 new_bounds.Offset(drag_bounds->back().right() - mouse_offset_.x(), 0);
1675 OffsetX(-(*drag_bounds)[0].x(), drag_bounds);
1676 break;
1678 default:
1679 break; // Nothing to do for DETACH_ABOVE_OR_BELOW.
1682 // To account for the extra vertical on restored windows that is absent on
1683 // maximized windows, add an additional vertical offset extracted from the tab
1684 // strip.
1685 if (source->GetWidget()->IsMaximized())
1686 new_bounds.Offset(0, -source->kNewTabButtonVerticalOffset);
1687 return new_bounds;
1690 void TabDragController::AdjustBrowserAndTabBoundsForDrag(
1691 int last_tabstrip_width,
1692 const gfx::Point& point_in_screen,
1693 std::vector<gfx::Rect>* drag_bounds) {
1694 attached_tabstrip_->InvalidateLayout();
1695 attached_tabstrip_->DoLayout();
1696 const int dragged_tabstrip_width = attached_tabstrip_->tab_area_width();
1698 // If the new tabstrip is smaller than the old resize the tabs.
1699 if (dragged_tabstrip_width < last_tabstrip_width) {
1700 const float leading_ratio =
1701 drag_bounds->front().x() / static_cast<float>(last_tabstrip_width);
1702 *drag_bounds = CalculateBoundsForDraggedTabs();
1704 if (drag_bounds->back().right() < dragged_tabstrip_width) {
1705 const int delta_x =
1706 std::min(static_cast<int>(leading_ratio * dragged_tabstrip_width),
1707 dragged_tabstrip_width -
1708 (drag_bounds->back().right() -
1709 drag_bounds->front().x()));
1710 OffsetX(delta_x, drag_bounds);
1713 // Reposition the restored window such that the tab that was dragged remains
1714 // under the mouse cursor.
1715 gfx::Point offset(
1716 static_cast<int>((*drag_bounds)[source_tab_index_].width() *
1717 offset_to_width_ratio_) +
1718 (*drag_bounds)[source_tab_index_].x(), 0);
1719 views::View::ConvertPointToWidget(attached_tabstrip_, &offset);
1720 gfx::Rect bounds = GetAttachedBrowserWidget()->GetWindowBoundsInScreen();
1721 bounds.set_x(point_in_screen.x() - offset.x());
1722 GetAttachedBrowserWidget()->SetBounds(bounds);
1724 attached_tabstrip_->SetTabBoundsForDrag(*drag_bounds);
1727 Browser* TabDragController::CreateBrowserForDrag(
1728 TabStrip* source,
1729 const gfx::Point& point_in_screen,
1730 gfx::Vector2d* drag_offset,
1731 std::vector<gfx::Rect>* drag_bounds) {
1732 gfx::Rect new_bounds(CalculateDraggedBrowserBounds(source,
1733 point_in_screen,
1734 drag_bounds));
1735 *drag_offset = point_in_screen - new_bounds.origin();
1737 Profile* profile =
1738 Profile::FromBrowserContext(drag_data_[0].contents->GetBrowserContext());
1739 Browser::CreateParams create_params(Browser::TYPE_TABBED,
1740 profile,
1741 host_desktop_type_);
1742 create_params.initial_bounds = new_bounds;
1743 Browser* browser = new Browser(create_params);
1744 is_dragging_new_browser_ = true;
1745 SetWindowPositionManaged(browser->window()->GetNativeWindow(), false);
1746 // If the window is created maximized then the bounds we supplied are ignored.
1747 // We need to reset them again so they are honored.
1748 browser->window()->SetBounds(new_bounds);
1750 return browser;
1753 gfx::Point TabDragController::GetCursorScreenPoint() {
1754 #if defined(USE_ASH)
1755 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH &&
1756 event_source_ == EVENT_SOURCE_TOUCH &&
1757 aura::Env::GetInstance()->is_touch_down()) {
1758 views::Widget* widget = GetAttachedBrowserWidget();
1759 DCHECK(widget);
1760 aura::Window* widget_window = widget->GetNativeWindow();
1761 DCHECK(widget_window->GetRootWindow());
1762 gfx::PointF touch_point_f;
1763 bool got_touch_point = ui::GestureRecognizer::Get()->
1764 GetLastTouchPointForTarget(widget_window, &touch_point_f);
1765 // TODO(tdresser): Switch to using gfx::PointF. See crbug.com/337824.
1766 gfx::Point touch_point = gfx::ToFlooredPoint(touch_point_f);
1767 DCHECK(got_touch_point);
1768 wm::ConvertPointToScreen(widget_window->GetRootWindow(), &touch_point);
1769 return touch_point;
1771 #endif
1773 return screen_->GetCursorScreenPoint();
1776 gfx::Vector2d TabDragController::GetWindowOffset(
1777 const gfx::Point& point_in_screen) {
1778 TabStrip* owning_tabstrip = attached_tabstrip_ ?
1779 attached_tabstrip_ : source_tabstrip_;
1780 views::View* toplevel_view = owning_tabstrip->GetWidget()->GetContentsView();
1782 gfx::Point point = point_in_screen;
1783 views::View::ConvertPointFromScreen(toplevel_view, &point);
1784 return point.OffsetFromOrigin();
1787 gfx::NativeWindow TabDragController::GetLocalProcessWindow(
1788 const gfx::Point& screen_point,
1789 bool exclude_dragged_view) {
1790 std::set<gfx::NativeWindow> exclude;
1791 if (exclude_dragged_view) {
1792 gfx::NativeWindow dragged_window =
1793 attached_tabstrip_->GetWidget()->GetNativeWindow();
1794 if (dragged_window)
1795 exclude.insert(dragged_window);
1797 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1798 // Exclude windows which are pending deletion via Browser::TabStripEmpty().
1799 // These windows can be returned in the Linux Aura port because the browser
1800 // window which was used for dragging is not hidden once all of its tabs are
1801 // attached to another browser window in DragBrowserToNewTabStrip().
1802 // TODO(pkotwicz): Fix this properly (crbug.com/358482)
1803 BrowserList* browser_list = BrowserList::GetInstance(
1804 chrome::HOST_DESKTOP_TYPE_NATIVE);
1805 for (BrowserList::const_iterator it = browser_list->begin();
1806 it != browser_list->end(); ++it) {
1807 if ((*it)->tab_strip_model()->empty())
1808 exclude.insert((*it)->window()->GetNativeWindow());
1810 #endif
1811 return GetLocalProcessWindowAtPoint(host_desktop_type_,
1812 screen_point,
1813 exclude);