Infobar material design refresh: layout
[chromium-blink-merge.git] / chrome / browser / ui / views / tabs / tab_drag_controller.cc
blob0a26de6d63fabe3890929b1c9464dafa25f30a2b
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/events/event_constants.h"
33 #include "ui/events/gestures/gesture_recognizer.h"
34 #include "ui/gfx/geometry/point_conversions.h"
35 #include "ui/gfx/screen.h"
36 #include "ui/views/event_monitor.h"
37 #include "ui/views/focus/view_storage.h"
38 #include "ui/views/widget/root_view.h"
39 #include "ui/views/widget/widget.h"
41 #if defined(USE_ASH)
42 #include "ash/accelerators/accelerator_commands.h"
43 #include "ash/shell.h"
44 #include "ash/wm/maximize_mode/maximize_mode_controller.h"
45 #include "ash/wm/window_state.h"
46 #include "ui/wm/core/coordinate_conversion.h"
47 #endif
49 #if defined(USE_AURA)
50 #include "ui/aura/env.h"
51 #include "ui/aura/window.h"
52 #include "ui/wm/core/window_modality_controller.h"
53 #endif
55 using base::UserMetricsAction;
56 using content::OpenURLParams;
57 using content::WebContents;
59 // If non-null there is a drag underway.
60 static TabDragController* instance_ = NULL;
62 namespace {
64 // Delay, in ms, during dragging before we bring a window to front.
65 const int kBringToFrontDelay = 750;
67 // Initial delay before moving tabs when the dragged tab is close to the edge of
68 // the stacked tabs.
69 const int kMoveAttachedInitialDelay = 600;
71 // Delay for moving tabs after the initial delay has passed.
72 const int kMoveAttachedSubsequentDelay = 300;
74 const int kHorizontalMoveThreshold = 16; // DIPs.
76 // Distance from the next/previous stacked before before we consider the tab
77 // close enough to trigger moving.
78 const int kStackedDistance = 36;
80 // A dragged window is forced to be a bit smaller than maximized bounds during a
81 // drag. This prevents the dragged browser widget from getting maximized at
82 // creation and makes it easier to drag tabs out of a restored window that had
83 // maximized size.
84 const int kMaximizedWindowInset = 10; // DIPs.
86 #if defined(USE_ASH)
87 void SetWindowPositionManaged(gfx::NativeWindow window, bool value) {
88 ash::wm::GetWindowState(window)->set_window_position_managed(value);
91 // Returns true if |tab_strip| browser window is docked.
92 bool IsDockedOrSnapped(const TabStrip* tab_strip) {
93 DCHECK(tab_strip);
94 ash::wm::WindowState* window_state =
95 ash::wm::GetWindowState(tab_strip->GetWidget()->GetNativeWindow());
96 return window_state->IsDocked() || window_state->IsSnapped();
98 #else
99 void SetWindowPositionManaged(gfx::NativeWindow window, bool value) {
102 bool IsDockedOrSnapped(const TabStrip* tab_strip) {
103 return false;
105 #endif
107 #if defined(USE_AURA)
108 gfx::NativeWindow GetModalTransient(gfx::NativeWindow window) {
109 return wm::GetModalTransient(window);
111 #else
112 gfx::NativeWindow GetModalTransient(gfx::NativeWindow window) {
113 NOTIMPLEMENTED();
114 return NULL;
116 #endif
118 // Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
119 // of |bounds| is adjusted by |vertical_adjustment|.
120 bool DoesRectContainVerticalPointExpanded(
121 const gfx::Rect& bounds,
122 int vertical_adjustment,
123 int y) {
124 int upper_threshold = bounds.bottom() + vertical_adjustment;
125 int lower_threshold = bounds.y() - vertical_adjustment;
126 return y >= lower_threshold && y <= upper_threshold;
129 // Adds |x_offset| to all the rectangles in |rects|.
130 void OffsetX(int x_offset, std::vector<gfx::Rect>* rects) {
131 if (x_offset == 0)
132 return;
134 for (size_t i = 0; i < rects->size(); ++i)
135 (*rects)[i].set_x((*rects)[i].x() + x_offset);
138 // WidgetObserver implementation that resets the window position managed
139 // property on Show.
140 // We're forced to do this here since BrowserFrameAsh resets the 'window
141 // position managed' property during a show and we need the property set to
142 // false before WorkspaceLayoutManager sees the visibility change.
143 class WindowPositionManagedUpdater : public views::WidgetObserver {
144 public:
145 void OnWidgetVisibilityChanged(views::Widget* widget, bool visible) override {
146 SetWindowPositionManaged(widget->GetNativeWindow(), false);
150 // EscapeTracker installs an event monitor and runs a callback when it receives
151 // the escape key.
152 class EscapeTracker : public ui::EventHandler {
153 public:
154 explicit EscapeTracker(const base::Closure& callback)
155 : escape_callback_(callback),
156 event_monitor_(views::EventMonitor::CreateApplicationMonitor(this)) {
159 private:
160 // ui::EventHandler:
161 void OnKeyEvent(ui::KeyEvent* key) override {
162 if (key->type() == ui::ET_KEY_PRESSED &&
163 key->key_code() == ui::VKEY_ESCAPE) {
164 escape_callback_.Run();
168 base::Closure escape_callback_;
169 scoped_ptr<views::EventMonitor> event_monitor_;
171 DISALLOW_COPY_AND_ASSIGN(EscapeTracker);
174 } // namespace
176 TabDragController::TabDragData::TabDragData()
177 : contents(NULL),
178 source_model_index(-1),
179 attached_tab(NULL),
180 pinned(false) {
183 TabDragController::TabDragData::~TabDragData() {
186 ///////////////////////////////////////////////////////////////////////////////
187 // TabDragController, public:
189 // static
190 const int TabDragController::kTouchVerticalDetachMagnetism = 50;
192 // static
193 const int TabDragController::kVerticalDetachMagnetism = 15;
195 TabDragController::TabDragController()
196 : event_source_(EVENT_SOURCE_MOUSE),
197 source_tabstrip_(NULL),
198 attached_tabstrip_(NULL),
199 screen_(NULL),
200 host_desktop_type_(chrome::HOST_DESKTOP_TYPE_NATIVE),
201 can_release_capture_(true),
202 offset_to_width_ratio_(0),
203 old_focused_view_id_(
204 views::ViewStorage::GetInstance()->CreateStorageID()),
205 last_move_screen_loc_(0),
206 started_drag_(false),
207 active_(true),
208 source_tab_index_(std::numeric_limits<size_t>::max()),
209 initial_move_(true),
210 detach_behavior_(DETACHABLE),
211 move_behavior_(REORDER),
212 mouse_move_direction_(0),
213 is_dragging_window_(false),
214 is_dragging_new_browser_(false),
215 was_source_maximized_(false),
216 was_source_fullscreen_(false),
217 did_restore_window_(false),
218 end_run_loop_behavior_(END_RUN_LOOP_STOP_DRAGGING),
219 waiting_for_run_loop_to_exit_(false),
220 tab_strip_to_attach_to_after_exit_(NULL),
221 move_loop_widget_(NULL),
222 is_mutating_(false),
223 attach_x_(-1),
224 attach_index_(-1),
225 weak_factory_(this) {
226 instance_ = this;
229 TabDragController::~TabDragController() {
230 views::ViewStorage::GetInstance()->RemoveView(old_focused_view_id_);
232 if (instance_ == this)
233 instance_ = NULL;
235 if (move_loop_widget_) {
236 move_loop_widget_->RemoveObserver(this);
237 SetWindowPositionManaged(move_loop_widget_->GetNativeWindow(), true);
240 if (source_tabstrip_)
241 GetModel(source_tabstrip_)->RemoveObserver(this);
243 if (event_source_ == EVENT_SOURCE_TOUCH) {
244 TabStrip* capture_tabstrip = attached_tabstrip_ ?
245 attached_tabstrip_ : source_tabstrip_;
246 capture_tabstrip->GetWidget()->ReleaseCapture();
250 void TabDragController::Init(
251 TabStrip* source_tabstrip,
252 Tab* source_tab,
253 const std::vector<Tab*>& tabs,
254 const gfx::Point& mouse_offset,
255 int source_tab_offset,
256 const ui::ListSelectionModel& initial_selection_model,
257 MoveBehavior move_behavior,
258 EventSource event_source) {
259 DCHECK(!tabs.empty());
260 DCHECK(std::find(tabs.begin(), tabs.end(), source_tab) != tabs.end());
261 source_tabstrip_ = source_tabstrip;
262 was_source_maximized_ = source_tabstrip->GetWidget()->IsMaximized();
263 was_source_fullscreen_ = source_tabstrip->GetWidget()->IsFullscreen();
264 screen_ = gfx::Screen::GetScreenFor(
265 source_tabstrip->GetWidget()->GetNativeView());
266 host_desktop_type_ = chrome::GetHostDesktopTypeForNativeView(
267 source_tabstrip->GetWidget()->GetNativeView());
268 // Do not release capture when transferring capture between widgets on:
269 // - Desktop Linux
270 // Mouse capture is not synchronous on desktop Linux. Chrome makes
271 // transferring capture between widgets without releasing capture appear
272 // synchronous on desktop Linux, so use that.
273 // - Ash
274 // Releasing capture on Ash cancels gestures so avoid it.
275 #if defined(OS_LINUX)
276 can_release_capture_ = false;
277 #else
278 can_release_capture_ =
279 (host_desktop_type_ != chrome::HOST_DESKTOP_TYPE_ASH);
280 #endif
281 start_point_in_screen_ = gfx::Point(source_tab_offset, mouse_offset.y());
282 views::View::ConvertPointToScreen(source_tab, &start_point_in_screen_);
283 event_source_ = event_source;
284 mouse_offset_ = mouse_offset;
285 move_behavior_ = move_behavior;
286 last_point_in_screen_ = start_point_in_screen_;
287 last_move_screen_loc_ = start_point_in_screen_.x();
288 initial_tab_positions_ = source_tabstrip->GetTabXCoordinates();
290 GetModel(source_tabstrip_)->AddObserver(this);
292 drag_data_.resize(tabs.size());
293 for (size_t i = 0; i < tabs.size(); ++i)
294 InitTabDragData(tabs[i], &(drag_data_[i]));
295 source_tab_index_ =
296 std::find(tabs.begin(), tabs.end(), source_tab) - tabs.begin();
298 // Listen for Esc key presses.
299 escape_tracker_.reset(
300 new EscapeTracker(base::Bind(&TabDragController::EndDrag,
301 weak_factory_.GetWeakPtr(),
302 END_DRAG_CANCEL)));
304 if (source_tab->width() > 0) {
305 offset_to_width_ratio_ = static_cast<float>(
306 source_tab->GetMirroredXInView(source_tab_offset)) /
307 static_cast<float>(source_tab->width());
309 InitWindowCreatePoint();
310 initial_selection_model_.Copy(initial_selection_model);
312 // Gestures don't automatically do a capture. We don't allow multiple drags at
313 // the same time, so we explicitly capture.
314 if (event_source == EVENT_SOURCE_TOUCH)
315 source_tabstrip_->GetWidget()->SetCapture(source_tabstrip_);
317 #if defined(USE_ASH)
318 if (ash::Shell::HasInstance() &&
319 ash::Shell::GetInstance()->maximize_mode_controller()->
320 IsMaximizeModeWindowManagerEnabled()) {
321 detach_behavior_ = NOT_DETACHABLE;
323 #endif
326 // static
327 bool TabDragController::IsAttachedTo(const TabStrip* tab_strip) {
328 return (instance_ && instance_->active() &&
329 instance_->attached_tabstrip() == tab_strip);
332 // static
333 bool TabDragController::IsActive() {
334 return instance_ && instance_->active();
337 void TabDragController::SetMoveBehavior(MoveBehavior behavior) {
338 if (started_drag())
339 return;
341 move_behavior_ = behavior;
344 void TabDragController::Drag(const gfx::Point& point_in_screen) {
345 TRACE_EVENT1("views", "TabDragController::Drag",
346 "point_in_screen", point_in_screen.ToString());
348 bring_to_front_timer_.Stop();
349 move_stacked_timer_.Stop();
351 if (waiting_for_run_loop_to_exit_)
352 return;
354 if (!started_drag_) {
355 if (!CanStartDrag(point_in_screen))
356 return; // User hasn't dragged far enough yet.
358 // On windows SaveFocus() may trigger a capture lost, which destroys us.
360 base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
361 SaveFocus();
362 if (!ref)
363 return;
365 started_drag_ = true;
366 Attach(source_tabstrip_, gfx::Point());
367 if (static_cast<int>(drag_data_.size()) ==
368 GetModel(source_tabstrip_)->count()) {
369 if (was_source_maximized_ || was_source_fullscreen_) {
370 did_restore_window_ = true;
371 // When all tabs in a maximized browser are dragged the browser gets
372 // restored during the drag and maximized back when the drag ends.
373 views::Widget* widget = GetAttachedBrowserWidget();
374 const int last_tabstrip_width = attached_tabstrip_->tab_area_width();
375 std::vector<gfx::Rect> drag_bounds = CalculateBoundsForDraggedTabs();
376 OffsetX(GetAttachedDragPoint(point_in_screen).x(), &drag_bounds);
377 gfx::Rect new_bounds(CalculateDraggedBrowserBounds(source_tabstrip_,
378 point_in_screen,
379 &drag_bounds));
380 new_bounds.Offset(-widget->GetRestoredBounds().x() +
381 point_in_screen.x() -
382 mouse_offset_.x(), 0);
383 widget->SetVisibilityChangedAnimationsEnabled(false);
384 widget->Restore();
385 widget->SetBounds(new_bounds);
386 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width,
387 point_in_screen,
388 &drag_bounds);
389 widget->SetVisibilityChangedAnimationsEnabled(true);
391 RunMoveLoop(GetWindowOffset(point_in_screen));
392 return;
396 ContinueDragging(point_in_screen);
399 void TabDragController::EndDrag(EndDragReason reason) {
400 TRACE_EVENT0("views", "TabDragController::EndDrag");
402 // If we're dragging a window ignore capture lost since it'll ultimately
403 // trigger the move loop to end and we'll revert the drag when RunMoveLoop()
404 // finishes.
405 if (reason == END_DRAG_CAPTURE_LOST && is_dragging_window_)
406 return;
407 EndDragImpl(reason != END_DRAG_COMPLETE && source_tabstrip_ ?
408 CANCELED : NORMAL);
411 void TabDragController::InitTabDragData(Tab* tab,
412 TabDragData* drag_data) {
413 TRACE_EVENT0("views", "TabDragController::InitTabDragData");
414 drag_data->source_model_index =
415 source_tabstrip_->GetModelIndexOfTab(tab);
416 drag_data->contents = GetModel(source_tabstrip_)->GetWebContentsAt(
417 drag_data->source_model_index);
418 drag_data->pinned = source_tabstrip_->IsTabPinned(tab);
419 registrar_.Add(
420 this,
421 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
422 content::Source<WebContents>(drag_data->contents));
425 ///////////////////////////////////////////////////////////////////////////////
426 // TabDragController, content::NotificationObserver implementation:
428 void TabDragController::Observe(
429 int type,
430 const content::NotificationSource& source,
431 const content::NotificationDetails& details) {
432 DCHECK_EQ(content::NOTIFICATION_WEB_CONTENTS_DESTROYED, type);
433 WebContents* destroyed_web_contents =
434 content::Source<WebContents>(source).ptr();
435 for (size_t i = 0; i < drag_data_.size(); ++i) {
436 if (drag_data_[i].contents == destroyed_web_contents) {
437 // One of the tabs we're dragging has been destroyed. Cancel the drag.
438 drag_data_[i].contents = NULL;
439 EndDragImpl(TAB_DESTROYED);
440 return;
443 // If we get here it means we got notification for a tab we don't know about.
444 NOTREACHED();
447 void TabDragController::OnWidgetBoundsChanged(views::Widget* widget,
448 const gfx::Rect& new_bounds) {
449 TRACE_EVENT1("views", "TabDragController::OnWidgetBoundsChanged",
450 "new_bounds", new_bounds.ToString());
452 Drag(GetCursorScreenPoint());
455 void TabDragController::TabStripEmpty() {
456 GetModel(source_tabstrip_)->RemoveObserver(this);
457 // NULL out source_tabstrip_ so that we don't attempt to add back to it (in
458 // the case of a revert).
459 source_tabstrip_ = NULL;
462 ///////////////////////////////////////////////////////////////////////////////
463 // TabDragController, private:
465 void TabDragController::InitWindowCreatePoint() {
466 // window_create_point_ is only used in CompleteDrag() (through
467 // GetWindowCreatePoint() to get the start point of the docked window) when
468 // the attached_tabstrip_ is NULL and all the window's related bound
469 // information are obtained from source_tabstrip_. So, we need to get the
470 // first_tab based on source_tabstrip_, not attached_tabstrip_. Otherwise,
471 // the window_create_point_ is not in the correct coordinate system. Please
472 // refer to http://crbug.com/6223 comment #15 for detailed information.
473 views::View* first_tab = source_tabstrip_->tab_at(0);
474 views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_);
475 window_create_point_ = first_source_tab_point_;
476 window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y());
479 gfx::Point TabDragController::GetWindowCreatePoint(
480 const gfx::Point& origin) const {
481 // If the cursor is outside the monitor area, move it inside. For example,
482 // dropping a tab onto the task bar on Windows produces this situation.
483 gfx::Rect work_area = screen_->GetDisplayNearestPoint(origin).work_area();
484 gfx::Point create_point(origin);
485 if (!work_area.IsEmpty()) {
486 if (create_point.x() < work_area.x())
487 create_point.set_x(work_area.x());
488 else if (create_point.x() > work_area.right())
489 create_point.set_x(work_area.right());
490 if (create_point.y() < work_area.y())
491 create_point.set_y(work_area.y());
492 else if (create_point.y() > work_area.bottom())
493 create_point.set_y(work_area.bottom());
495 return gfx::Point(create_point.x() - window_create_point_.x(),
496 create_point.y() - window_create_point_.y());
499 void TabDragController::SaveFocus() {
500 DCHECK(source_tabstrip_);
501 views::View* focused_view =
502 source_tabstrip_->GetFocusManager()->GetFocusedView();
503 if (focused_view)
504 views::ViewStorage::GetInstance()->StoreView(old_focused_view_id_,
505 focused_view);
506 source_tabstrip_->GetFocusManager()->SetFocusedView(source_tabstrip_);
507 // WARNING: we may have been deleted.
510 void TabDragController::RestoreFocus() {
511 if (attached_tabstrip_ != source_tabstrip_) {
512 if (is_dragging_new_browser_) {
513 content::WebContents* active_contents = source_dragged_contents();
514 if (active_contents && !active_contents->FocusLocationBarByDefault())
515 active_contents->Focus();
517 return;
519 views::View* old_focused_view =
520 views::ViewStorage::GetInstance()->RetrieveView(old_focused_view_id_);
521 if (!old_focused_view)
522 return;
523 old_focused_view->GetFocusManager()->SetFocusedView(old_focused_view);
526 bool TabDragController::CanStartDrag(const gfx::Point& point_in_screen) const {
527 // Determine if the mouse has moved beyond a minimum elasticity distance in
528 // any direction from the starting point.
529 static const int kMinimumDragDistance = 10;
530 int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x());
531 int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y());
532 return sqrt(pow(static_cast<float>(x_offset), 2) +
533 pow(static_cast<float>(y_offset), 2)) > kMinimumDragDistance;
536 void TabDragController::ContinueDragging(const gfx::Point& point_in_screen) {
537 TRACE_EVENT1("views", "TabDragController::ContinueDragging",
538 "point_in_screen", point_in_screen.ToString());
540 DCHECK(attached_tabstrip_);
542 TabStrip* target_tabstrip = detach_behavior_ == DETACHABLE ?
543 GetTargetTabStripForPoint(point_in_screen) : source_tabstrip_;
544 bool tab_strip_changed = (target_tabstrip != attached_tabstrip_);
546 if (attached_tabstrip_) {
547 int move_delta = point_in_screen.x() - last_point_in_screen_.x();
548 if (move_delta > 0)
549 mouse_move_direction_ |= kMovedMouseRight;
550 else if (move_delta < 0)
551 mouse_move_direction_ |= kMovedMouseLeft;
553 last_point_in_screen_ = point_in_screen;
555 if (tab_strip_changed) {
556 is_dragging_new_browser_ = false;
557 did_restore_window_ = false;
558 if (DragBrowserToNewTabStrip(target_tabstrip, point_in_screen) ==
559 DRAG_BROWSER_RESULT_STOP) {
560 return;
563 if (is_dragging_window_) {
564 static_cast<base::Timer*>(&bring_to_front_timer_)->Start(FROM_HERE,
565 base::TimeDelta::FromMilliseconds(kBringToFrontDelay),
566 base::Bind(&TabDragController::BringWindowUnderPointToFront,
567 base::Unretained(this), point_in_screen));
570 if (!is_dragging_window_ && attached_tabstrip_) {
571 if (move_only()) {
572 DragActiveTabStacked(point_in_screen);
573 } else {
574 MoveAttached(point_in_screen);
575 if (tab_strip_changed) {
576 // Move the corresponding window to the front. We do this after the
577 // move as on windows activate triggers a synchronous paint.
578 attached_tabstrip_->GetWidget()->Activate();
584 TabDragController::DragBrowserResultType
585 TabDragController::DragBrowserToNewTabStrip(
586 TabStrip* target_tabstrip,
587 const gfx::Point& point_in_screen) {
588 TRACE_EVENT1("views", "TabDragController::DragBrowserToNewTabStrip",
589 "point_in_screen", point_in_screen.ToString());
591 if (!target_tabstrip) {
592 DetachIntoNewBrowserAndRunMoveLoop(point_in_screen);
593 return DRAG_BROWSER_RESULT_STOP;
596 #if defined(USE_AURA)
597 // Only Aura windows are gesture consumers.
598 ui::GestureRecognizer::Get()->TransferEventsTo(
599 GetAttachedBrowserWidget()->GetNativeView(),
600 target_tabstrip->GetWidget()->GetNativeView());
601 #endif
603 if (is_dragging_window_) {
604 // ReleaseCapture() is going to result in calling back to us (because it
605 // results in a move). That'll cause all sorts of problems. Reset the
606 // observer so we don't get notified and process the event.
607 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
608 move_loop_widget_->RemoveObserver(this);
609 move_loop_widget_ = NULL;
611 views::Widget* browser_widget = GetAttachedBrowserWidget();
612 // Need to release the drag controller before starting the move loop as it's
613 // going to trigger capture lost, which cancels drag.
614 attached_tabstrip_->ReleaseDragController();
615 target_tabstrip->OwnDragController(this);
616 // Disable animations so that we don't see a close animation on aero.
617 browser_widget->SetVisibilityChangedAnimationsEnabled(false);
618 if (can_release_capture_)
619 browser_widget->ReleaseCapture();
620 else
621 target_tabstrip->GetWidget()->SetCapture(attached_tabstrip_);
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_->GetPinnedTabCount())
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);
1035 BrowserView* dragged_browser_view =
1036 BrowserView::GetBrowserViewForBrowser(browser);
1037 views::Widget* dragged_widget = dragged_browser_view->GetWidget();
1039 #if defined(USE_AURA)
1040 // Only Aura windows are gesture consumers.
1041 gfx::NativeView attached_native_view =
1042 attached_tabstrip_->GetWidget()->GetNativeView();
1043 ui::GestureRecognizer::Get()->TransferEventsTo(
1044 attached_native_view, dragged_widget->GetNativeView());
1045 #endif
1047 Detach(can_release_capture_ ? RELEASE_CAPTURE : DONT_RELEASE_CAPTURE);
1049 dragged_widget->SetVisibilityChangedAnimationsEnabled(false);
1050 Attach(dragged_browser_view->tabstrip(), gfx::Point());
1051 AdjustBrowserAndTabBoundsForDrag(last_tabstrip_width,
1052 point_in_screen,
1053 &drag_bounds);
1054 WindowPositionManagedUpdater updater;
1055 dragged_widget->AddObserver(&updater);
1056 browser->window()->Show();
1057 dragged_widget->RemoveObserver(&updater);
1058 dragged_widget->SetVisibilityChangedAnimationsEnabled(true);
1059 // Activate may trigger a focus loss, destroying us.
1061 base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
1062 browser->window()->Activate();
1063 if (!ref)
1064 return;
1066 RunMoveLoop(drag_offset);
1069 void TabDragController::RunMoveLoop(const gfx::Vector2d& drag_offset) {
1070 // If the user drags the whole window we'll assume they are going to attach to
1071 // another window and therefore want to reorder.
1072 move_behavior_ = REORDER;
1074 move_loop_widget_ = GetAttachedBrowserWidget();
1075 DCHECK(move_loop_widget_);
1076 move_loop_widget_->AddObserver(this);
1077 is_dragging_window_ = true;
1078 base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
1079 if (can_release_capture_) {
1080 // Running the move loop releases mouse capture, which triggers destroying
1081 // the drag loop. Release mouse capture now while the DragController is not
1082 // owned by the TabStrip.
1083 attached_tabstrip_->ReleaseDragController();
1084 attached_tabstrip_->GetWidget()->ReleaseCapture();
1085 attached_tabstrip_->OwnDragController(this);
1087 const views::Widget::MoveLoopSource move_loop_source =
1088 event_source_ == EVENT_SOURCE_MOUSE ?
1089 views::Widget::MOVE_LOOP_SOURCE_MOUSE :
1090 views::Widget::MOVE_LOOP_SOURCE_TOUCH;
1091 const views::Widget::MoveLoopEscapeBehavior escape_behavior =
1092 is_dragging_new_browser_ ?
1093 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE :
1094 views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE;
1095 views::Widget::MoveLoopResult result =
1096 move_loop_widget_->RunMoveLoop(
1097 drag_offset, move_loop_source, escape_behavior);
1098 content::NotificationService::current()->Notify(
1099 chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE,
1100 content::NotificationService::AllBrowserContextsAndSources(),
1101 content::NotificationService::NoDetails());
1103 if (!ref)
1104 return;
1105 if (move_loop_widget_) {
1106 move_loop_widget_->RemoveObserver(this);
1107 move_loop_widget_ = NULL;
1109 is_dragging_window_ = false;
1110 waiting_for_run_loop_to_exit_ = false;
1111 if (end_run_loop_behavior_ == END_RUN_LOOP_CONTINUE_DRAGGING) {
1112 end_run_loop_behavior_ = END_RUN_LOOP_STOP_DRAGGING;
1113 if (tab_strip_to_attach_to_after_exit_) {
1114 gfx::Point point_in_screen(GetCursorScreenPoint());
1115 Detach(DONT_RELEASE_CAPTURE);
1116 Attach(tab_strip_to_attach_to_after_exit_, point_in_screen);
1117 // Move the tabs into position.
1118 MoveAttached(point_in_screen);
1119 attached_tabstrip_->GetWidget()->Activate();
1120 // Activate may trigger a focus loss, destroying us.
1121 if (!ref)
1122 return;
1123 tab_strip_to_attach_to_after_exit_ = NULL;
1125 DCHECK(attached_tabstrip_);
1126 attached_tabstrip_->GetWidget()->SetCapture(attached_tabstrip_);
1127 } else if (active_) {
1128 EndDrag(result == views::Widget::MOVE_LOOP_CANCELED ?
1129 END_DRAG_CANCEL : END_DRAG_COMPLETE);
1133 int TabDragController::GetInsertionIndexFrom(const gfx::Rect& dragged_bounds,
1134 int start) const {
1135 const int last_tab = attached_tabstrip_->tab_count() - 1;
1136 // Make the actual "drag insertion point" be just after the leading edge of
1137 // the first dragged tab. This is closer to where the user thinks of the tab
1138 // as "starting" than just dragged_bounds.x(), especially with narrow tabs.
1139 const int dragged_x = dragged_bounds.x() + Tab::leading_width_for_drag();
1140 if (start < 0 || start > last_tab ||
1141 dragged_x < attached_tabstrip_->ideal_bounds(start).x())
1142 return -1;
1144 for (int i = start; i <= last_tab; ++i) {
1145 const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i);
1146 if (dragged_x < (ideal_bounds.x() + (ideal_bounds.width() / 2)))
1147 return i;
1150 return (dragged_x < attached_tabstrip_->ideal_bounds(last_tab).right()) ?
1151 (last_tab + 1) : -1;
1154 int TabDragController::GetInsertionIndexFromReversed(
1155 const gfx::Rect& dragged_bounds,
1156 int start) const {
1157 // Make the actual "drag insertion point" be just after the leading edge of
1158 // the first dragged tab. This is closer to where the user thinks of the tab
1159 // as "starting" than just dragged_bounds.x(), especially with narrow tabs.
1160 const int dragged_x = dragged_bounds.x() + Tab::leading_width_for_drag();
1161 if (start < 0 || start >= attached_tabstrip_->tab_count() ||
1162 dragged_x >= attached_tabstrip_->ideal_bounds(start).right())
1163 return -1;
1165 for (int i = start; i >= 0; --i) {
1166 const gfx::Rect& ideal_bounds = attached_tabstrip_->ideal_bounds(i);
1167 if (dragged_x >= (ideal_bounds.x() + (ideal_bounds.width() / 2)))
1168 return i + 1;
1171 return (dragged_x >= attached_tabstrip_->ideal_bounds(0).x()) ? 0 : -1;
1174 int TabDragController::GetInsertionIndexForDraggedBounds(
1175 const gfx::Rect& dragged_bounds) const {
1176 // If the strip has no tabs, the only position to insert at is 0.
1177 const int tab_count = attached_tabstrip_->tab_count();
1178 if (!tab_count)
1179 return 0;
1181 int index = -1;
1182 if (attached_tabstrip_->touch_layout_.get()) {
1183 index = GetInsertionIndexForDraggedBoundsStacked(dragged_bounds);
1184 if (index != -1) {
1185 // Only move the tab to the left/right if the user actually moved the
1186 // mouse that way. This is necessary as tabs with stacked tabs
1187 // before/after them have multiple drag positions.
1188 int active_index = attached_tabstrip_->touch_layout_->active_index();
1189 if ((index < active_index &&
1190 (mouse_move_direction_ & kMovedMouseLeft) == 0) ||
1191 (index > active_index &&
1192 (mouse_move_direction_ & kMovedMouseRight) == 0)) {
1193 index = active_index;
1196 } else {
1197 index = GetInsertionIndexFrom(dragged_bounds, 0);
1199 if (index == -1) {
1200 const int last_tab_right =
1201 attached_tabstrip_->ideal_bounds(tab_count - 1).right();
1202 index = (dragged_bounds.right() > last_tab_right) ? tab_count : 0;
1205 const Tab* last_visible_tab = attached_tabstrip_->GetLastVisibleTab();
1206 int last_insertion_point = last_visible_tab ?
1207 (attached_tabstrip_->GetModelIndexOfTab(last_visible_tab) + 1) : 0;
1208 if (drag_data_[0].attached_tab) {
1209 // We're not in the process of attaching, so clamp the insertion point to
1210 // keep it within the visible region.
1211 last_insertion_point = std::max(
1212 0, last_insertion_point - static_cast<int>(drag_data_.size()));
1215 // Ensure the first dragged tab always stays in the visible index range.
1216 return std::min(index, last_insertion_point);
1219 bool TabDragController::ShouldDragToNextStackedTab(
1220 const gfx::Rect& dragged_bounds,
1221 int index) const {
1222 if (index + 1 >= attached_tabstrip_->tab_count() ||
1223 !attached_tabstrip_->touch_layout_->IsStacked(index + 1) ||
1224 (mouse_move_direction_ & kMovedMouseRight) == 0)
1225 return false;
1227 int active_x = attached_tabstrip_->ideal_bounds(index).x();
1228 int next_x = attached_tabstrip_->ideal_bounds(index + 1).x();
1229 int mid_x = std::min(next_x - kStackedDistance,
1230 active_x + (next_x - active_x) / 4);
1231 // TODO(pkasting): Should this add Tab::leading_width_for_drag() as
1232 // GetInsertionIndexFrom() does?
1233 return dragged_bounds.x() >= mid_x;
1236 bool TabDragController::ShouldDragToPreviousStackedTab(
1237 const gfx::Rect& dragged_bounds,
1238 int index) const {
1239 if (index - 1 < attached_tabstrip_->GetPinnedTabCount() ||
1240 !attached_tabstrip_->touch_layout_->IsStacked(index - 1) ||
1241 (mouse_move_direction_ & kMovedMouseLeft) == 0)
1242 return false;
1244 int active_x = attached_tabstrip_->ideal_bounds(index).x();
1245 int previous_x = attached_tabstrip_->ideal_bounds(index - 1).x();
1246 int mid_x = std::max(previous_x + kStackedDistance,
1247 active_x - (active_x - previous_x) / 4);
1248 // TODO(pkasting): Should this add Tab::leading_width_for_drag() as
1249 // GetInsertionIndexFrom() does?
1250 return dragged_bounds.x() <= mid_x;
1253 int TabDragController::GetInsertionIndexForDraggedBoundsStacked(
1254 const gfx::Rect& dragged_bounds) const {
1255 StackedTabStripLayout* touch_layout = attached_tabstrip_->touch_layout_.get();
1256 int active_index = touch_layout->active_index();
1257 // Search from the active index to the front of the tabstrip. Do this as tabs
1258 // overlap each other from the active index.
1259 int index = GetInsertionIndexFromReversed(dragged_bounds, active_index);
1260 if (index != active_index)
1261 return index;
1262 if (index == -1)
1263 return GetInsertionIndexFrom(dragged_bounds, active_index + 1);
1265 // The position to drag to corresponds to the active tab. If the next/previous
1266 // tab is stacked, then shorten the distance used to determine insertion
1267 // bounds. We do this as GetInsertionIndexFrom() uses the bounds of the
1268 // tabs. When tabs are stacked the next/previous tab is on top of the tab.
1269 if (active_index + 1 < attached_tabstrip_->tab_count() &&
1270 touch_layout->IsStacked(active_index + 1)) {
1271 index = GetInsertionIndexFrom(dragged_bounds, active_index + 1);
1272 if (index == -1 && ShouldDragToNextStackedTab(dragged_bounds, active_index))
1273 index = active_index + 1;
1274 else if (index == -1)
1275 index = active_index;
1276 } else if (ShouldDragToPreviousStackedTab(dragged_bounds, active_index)) {
1277 index = active_index - 1;
1279 return index;
1282 gfx::Rect TabDragController::GetDraggedViewTabStripBounds(
1283 const gfx::Point& tab_strip_point) {
1284 // attached_tab is NULL when inserting into a new tabstrip.
1285 if (source_tab_drag_data()->attached_tab) {
1286 return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1287 source_tab_drag_data()->attached_tab->width(),
1288 source_tab_drag_data()->attached_tab->height());
1291 double sel_width, unselected_width;
1292 attached_tabstrip_->GetCurrentTabWidths(&sel_width, &unselected_width);
1293 return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1294 static_cast<int>(sel_width),
1295 Tab::GetStandardSize().height());
1298 gfx::Point TabDragController::GetAttachedDragPoint(
1299 const gfx::Point& point_in_screen) {
1300 DCHECK(attached_tabstrip_); // The tab must be attached.
1302 gfx::Point tab_loc(point_in_screen);
1303 views::View::ConvertPointFromScreen(attached_tabstrip_, &tab_loc);
1304 const int x =
1305 attached_tabstrip_->GetMirroredXInView(tab_loc.x()) - mouse_offset_.x();
1307 // TODO: consider caching this.
1308 std::vector<Tab*> attached_tabs;
1309 for (size_t i = 0; i < drag_data_.size(); ++i)
1310 attached_tabs.push_back(drag_data_[i].attached_tab);
1311 const int size = attached_tabstrip_->GetSizeNeededForTabs(attached_tabs);
1312 const int max_x = attached_tabstrip_->width() - size;
1313 return gfx::Point(std::min(std::max(x, 0), max_x), 0);
1316 std::vector<Tab*> TabDragController::GetTabsMatchingDraggedContents(
1317 TabStrip* tabstrip) {
1318 TabStripModel* model = GetModel(attached_tabstrip_);
1319 std::vector<Tab*> tabs;
1320 for (size_t i = 0; i < drag_data_.size(); ++i) {
1321 int model_index = model->GetIndexOfWebContents(drag_data_[i].contents);
1322 if (model_index == TabStripModel::kNoTab)
1323 return std::vector<Tab*>();
1324 tabs.push_back(tabstrip->tab_at(model_index));
1326 return tabs;
1329 std::vector<gfx::Rect> TabDragController::CalculateBoundsForDraggedTabs() {
1330 std::vector<gfx::Rect> drag_bounds;
1331 std::vector<Tab*> attached_tabs;
1332 for (size_t i = 0; i < drag_data_.size(); ++i)
1333 attached_tabs.push_back(drag_data_[i].attached_tab);
1334 attached_tabstrip_->CalculateBoundsForDraggedTabs(attached_tabs,
1335 &drag_bounds);
1336 return drag_bounds;
1339 void TabDragController::EndDragImpl(EndDragType type) {
1340 DCHECK(active_);
1341 active_ = false;
1343 bring_to_front_timer_.Stop();
1344 move_stacked_timer_.Stop();
1346 if (is_dragging_window_) {
1347 waiting_for_run_loop_to_exit_ = true;
1349 if (type == NORMAL || (type == TAB_DESTROYED && drag_data_.size() > 1)) {
1350 SetWindowPositionManaged(GetAttachedBrowserWidget()->GetNativeWindow(),
1351 true);
1354 // End the nested drag loop.
1355 GetAttachedBrowserWidget()->EndMoveLoop();
1358 if (type != TAB_DESTROYED) {
1359 // We only finish up the drag if we were actually dragging. If start_drag_
1360 // is false, the user just clicked and released and didn't move the mouse
1361 // enough to trigger a drag.
1362 if (started_drag_) {
1363 RestoreFocus();
1364 if (type == CANCELED)
1365 RevertDrag();
1366 else
1367 CompleteDrag();
1369 } else if (drag_data_.size() > 1) {
1370 initial_selection_model_.Clear();
1371 if (started_drag_)
1372 RevertDrag();
1373 } // else case the only tab we were dragging was deleted. Nothing to do.
1375 // Clear out drag data so we don't attempt to do anything with it.
1376 drag_data_.clear();
1378 TabStrip* owning_tabstrip = attached_tabstrip_ ?
1379 attached_tabstrip_ : source_tabstrip_;
1380 owning_tabstrip->DestroyDragController();
1383 void TabDragController::RevertDrag() {
1384 std::vector<Tab*> tabs;
1385 for (size_t i = 0; i < drag_data_.size(); ++i) {
1386 if (drag_data_[i].contents) {
1387 // Contents is NULL if a tab was destroyed while the drag was under way.
1388 tabs.push_back(drag_data_[i].attached_tab);
1389 RevertDragAt(i);
1393 if (attached_tabstrip_) {
1394 if (did_restore_window_)
1395 MaximizeAttachedWindow();
1396 if (attached_tabstrip_ == source_tabstrip_) {
1397 source_tabstrip_->StoppedDraggingTabs(
1398 tabs, initial_tab_positions_, move_behavior_ == MOVE_VISIBILE_TABS,
1399 false);
1400 } else {
1401 attached_tabstrip_->DraggedTabsDetached();
1405 if (initial_selection_model_.empty())
1406 ResetSelection(GetModel(source_tabstrip_));
1407 else
1408 GetModel(source_tabstrip_)->SetSelectionFromModel(initial_selection_model_);
1410 if (source_tabstrip_)
1411 source_tabstrip_->GetWidget()->Activate();
1414 void TabDragController::ResetSelection(TabStripModel* model) {
1415 DCHECK(model);
1416 ui::ListSelectionModel selection_model;
1417 bool has_one_valid_tab = false;
1418 for (size_t i = 0; i < drag_data_.size(); ++i) {
1419 // |contents| is NULL if a tab was deleted out from under us.
1420 if (drag_data_[i].contents) {
1421 int index = model->GetIndexOfWebContents(drag_data_[i].contents);
1422 DCHECK_NE(-1, index);
1423 selection_model.AddIndexToSelection(index);
1424 if (!has_one_valid_tab || i == source_tab_index_) {
1425 // Reset the active/lead to the first tab. If the source tab is still
1426 // valid we'll reset these again later on.
1427 selection_model.set_active(index);
1428 selection_model.set_anchor(index);
1429 has_one_valid_tab = true;
1433 if (!has_one_valid_tab)
1434 return;
1436 model->SetSelectionFromModel(selection_model);
1439 void TabDragController::RestoreInitialSelection() {
1440 // First time detaching from the source tabstrip. Reset selection model to
1441 // initial_selection_model_. Before resetting though we have to remove all
1442 // the tabs from initial_selection_model_ as it was created with the tabs
1443 // still there.
1444 ui::ListSelectionModel selection_model;
1445 selection_model.Copy(initial_selection_model_);
1446 for (DragData::const_reverse_iterator i(drag_data_.rbegin());
1447 i != drag_data_.rend(); ++i) {
1448 selection_model.DecrementFrom(i->source_model_index);
1450 // We may have cleared out the selection model. Only reset it if it
1451 // contains something.
1452 if (selection_model.empty())
1453 return;
1455 // The anchor/active may have been among the tabs that were dragged out. Force
1456 // the anchor/active to be valid.
1457 if (selection_model.anchor() == ui::ListSelectionModel::kUnselectedIndex)
1458 selection_model.set_anchor(selection_model.selected_indices()[0]);
1459 if (selection_model.active() == ui::ListSelectionModel::kUnselectedIndex)
1460 selection_model.set_active(selection_model.selected_indices()[0]);
1461 GetModel(source_tabstrip_)->SetSelectionFromModel(selection_model);
1464 void TabDragController::RevertDragAt(size_t drag_index) {
1465 DCHECK(started_drag_);
1466 DCHECK(source_tabstrip_);
1468 base::AutoReset<bool> setter(&is_mutating_, true);
1469 TabDragData* data = &(drag_data_[drag_index]);
1470 if (attached_tabstrip_) {
1471 int index =
1472 GetModel(attached_tabstrip_)->GetIndexOfWebContents(data->contents);
1473 if (attached_tabstrip_ != source_tabstrip_) {
1474 // The Tab was inserted into another TabStrip. We need to put it back
1475 // into the original one.
1476 GetModel(attached_tabstrip_)->DetachWebContentsAt(index);
1477 // TODO(beng): (Cleanup) seems like we should use Attach() for this
1478 // somehow.
1479 GetModel(source_tabstrip_)->InsertWebContentsAt(
1480 data->source_model_index, data->contents,
1481 (data->pinned ? TabStripModel::ADD_PINNED : 0));
1482 } else {
1483 // The Tab was moved within the TabStrip where the drag was initiated.
1484 // Move it back to the starting location.
1485 GetModel(source_tabstrip_)->MoveWebContentsAt(
1486 index, data->source_model_index, false);
1488 } else {
1489 // The Tab was detached from the TabStrip where the drag began, and has not
1490 // been attached to any other TabStrip. We need to put it back into the
1491 // source TabStrip.
1492 GetModel(source_tabstrip_)->InsertWebContentsAt(
1493 data->source_model_index, data->contents,
1494 (data->pinned ? TabStripModel::ADD_PINNED : 0));
1498 void TabDragController::CompleteDrag() {
1499 DCHECK(started_drag_);
1501 if (attached_tabstrip_) {
1502 if (is_dragging_new_browser_ || did_restore_window_) {
1503 if (IsDockedOrSnapped(attached_tabstrip_)) {
1504 was_source_maximized_ = false;
1505 was_source_fullscreen_ = false;
1508 // If source window was maximized - maximize the new window as well.
1509 if (was_source_maximized_ || was_source_fullscreen_)
1510 MaximizeAttachedWindow();
1512 attached_tabstrip_->StoppedDraggingTabs(
1513 GetTabsMatchingDraggedContents(attached_tabstrip_),
1514 initial_tab_positions_,
1515 move_behavior_ == MOVE_VISIBILE_TABS,
1516 true);
1517 } else {
1518 // Compel the model to construct a new window for the detached
1519 // WebContentses.
1520 views::Widget* widget = source_tabstrip_->GetWidget();
1521 gfx::Rect window_bounds(widget->GetRestoredBounds());
1522 window_bounds.set_origin(GetWindowCreatePoint(last_point_in_screen_));
1524 base::AutoReset<bool> setter(&is_mutating_, true);
1526 std::vector<TabStripModelDelegate::NewStripContents> contentses;
1527 for (size_t i = 0; i < drag_data_.size(); ++i) {
1528 TabStripModelDelegate::NewStripContents item;
1529 item.web_contents = drag_data_[i].contents;
1530 item.add_types = drag_data_[i].pinned ? TabStripModel::ADD_PINNED
1531 : TabStripModel::ADD_NONE;
1532 contentses.push_back(item);
1535 Browser* new_browser =
1536 GetModel(source_tabstrip_)->delegate()->CreateNewStripWithContents(
1537 contentses, window_bounds, widget->IsMaximized());
1538 ResetSelection(new_browser->tab_strip_model());
1539 new_browser->window()->Show();
1543 void TabDragController::MaximizeAttachedWindow() {
1544 GetAttachedBrowserWidget()->Maximize();
1545 #if defined(USE_ASH)
1546 if (was_source_fullscreen_ &&
1547 host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
1548 // In fullscreen mode it is only possible to get here if the source
1549 // was in "immersive fullscreen" mode, so toggle it back on.
1550 ash::accelerators::ToggleFullscreen();
1552 #endif
1555 gfx::Rect TabDragController::GetViewScreenBounds(
1556 views::View* view) const {
1557 gfx::Point view_topleft;
1558 views::View::ConvertPointToScreen(view, &view_topleft);
1559 gfx::Rect view_screen_bounds = view->GetLocalBounds();
1560 view_screen_bounds.Offset(view_topleft.x(), view_topleft.y());
1561 return view_screen_bounds;
1564 void TabDragController::BringWindowUnderPointToFront(
1565 const gfx::Point& point_in_screen) {
1566 gfx::NativeWindow window = GetLocalProcessWindow(point_in_screen, true);
1568 // Only bring browser windows to front - only windows with a TabStrip can
1569 // be tab drag targets.
1570 if (!GetTabStripForWindow(window))
1571 return;
1573 if (window) {
1574 views::Widget* widget_window = views::Widget::GetWidgetForNativeWindow(
1575 window);
1576 if (!widget_window)
1577 return;
1579 #if defined(USE_ASH)
1580 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH) {
1581 // TODO(varkha): The code below ensures that the phantom drag widget
1582 // is shown on top of browser windows. The code should be moved to ash/
1583 // and the phantom should be able to assert its top-most state on its own.
1584 // One strategy would be for DragWindowController to
1585 // be able to observe stacking changes to the phantom drag widget's
1586 // siblings in order to keep it on top. One way is to implement a
1587 // notification that is sent to a window parent's observers when a
1588 // stacking order is changed among the children of that same parent.
1589 // Note that OnWindowStackingChanged is sent only to the child that is the
1590 // argument of one of the Window::StackChildX calls and not to all its
1591 // siblings affected by the stacking change.
1592 aura::Window* browser_window = widget_window->GetNativeView();
1593 // Find a topmost non-popup window and stack the recipient browser above
1594 // it in order to avoid stacking the browser window on top of the phantom
1595 // drag widget created by DragWindowController in a second display.
1596 for (aura::Window::Windows::const_reverse_iterator it =
1597 browser_window->parent()->children().rbegin();
1598 it != browser_window->parent()->children().rend(); ++it) {
1599 // If the iteration reached the recipient browser window then it is
1600 // already topmost and it is safe to return with no stacking change.
1601 if (*it == browser_window)
1602 return;
1603 if ((*it)->type() != ui::wm::WINDOW_TYPE_POPUP) {
1604 widget_window->StackAbove(*it);
1605 break;
1608 } else {
1609 widget_window->StackAtTop();
1611 #else
1612 widget_window->StackAtTop();
1613 #endif
1615 // The previous call made the window appear on top of the dragged window,
1616 // move the dragged window to the front.
1617 if (is_dragging_window_)
1618 attached_tabstrip_->GetWidget()->StackAtTop();
1622 TabStripModel* TabDragController::GetModel(
1623 TabStrip* tabstrip) const {
1624 return static_cast<BrowserTabStripController*>(tabstrip->controller())->
1625 model();
1628 views::Widget* TabDragController::GetAttachedBrowserWidget() {
1629 return attached_tabstrip_->GetWidget();
1632 bool TabDragController::AreTabsConsecutive() {
1633 for (size_t i = 1; i < drag_data_.size(); ++i) {
1634 if (drag_data_[i - 1].source_model_index + 1 !=
1635 drag_data_[i].source_model_index) {
1636 return false;
1639 return true;
1642 gfx::Rect TabDragController::CalculateDraggedBrowserBounds(
1643 TabStrip* source,
1644 const gfx::Point& point_in_screen,
1645 std::vector<gfx::Rect>* drag_bounds) {
1646 gfx::Point center(0, source->height() / 2);
1647 views::View::ConvertPointToWidget(source, &center);
1648 gfx::Rect new_bounds(source->GetWidget()->GetRestoredBounds());
1650 gfx::Rect work_area =
1651 screen_->GetDisplayNearestPoint(last_point_in_screen_).work_area();
1652 if (new_bounds.size().width() >= work_area.size().width() &&
1653 new_bounds.size().height() >= work_area.size().height()) {
1654 new_bounds = work_area;
1655 new_bounds.Inset(kMaximizedWindowInset, kMaximizedWindowInset,
1656 kMaximizedWindowInset, kMaximizedWindowInset);
1657 // Behave as if the |source| was maximized at the start of a drag since this
1658 // is consistent with a browser window creation logic in case of windows
1659 // that are as large as the |work_area|.
1660 was_source_maximized_ = true;
1663 if (source->GetWidget()->IsMaximized()) {
1664 // If the restore bounds is really small, we don't want to honor it
1665 // (dragging a really small window looks wrong), instead make sure the new
1666 // window is at least 50% the size of the old.
1667 const gfx::Size max_size(
1668 source->GetWidget()->GetWindowBoundsInScreen().size());
1669 new_bounds.set_width(
1670 std::max(max_size.width() / 2, new_bounds.width()));
1671 new_bounds.set_height(
1672 std::max(max_size.height() / 2, new_bounds.height()));
1674 new_bounds.set_y(point_in_screen.y() - center.y());
1675 switch (GetDetachPosition(point_in_screen)) {
1676 case DETACH_BEFORE:
1677 new_bounds.set_x(point_in_screen.x() - center.x());
1678 new_bounds.Offset(-mouse_offset_.x(), 0);
1679 break;
1680 case DETACH_AFTER: {
1681 gfx::Point right_edge(source->width(), 0);
1682 views::View::ConvertPointToWidget(source, &right_edge);
1683 new_bounds.set_x(point_in_screen.x() - right_edge.x());
1684 new_bounds.Offset(drag_bounds->back().right() - mouse_offset_.x(), 0);
1685 OffsetX(-(*drag_bounds)[0].x(), drag_bounds);
1686 break;
1688 default:
1689 break; // Nothing to do for DETACH_ABOVE_OR_BELOW.
1692 // To account for the extra vertical on restored windows that is absent on
1693 // maximized windows, add an additional vertical offset extracted from the tab
1694 // strip.
1695 if (source->GetWidget()->IsMaximized())
1696 new_bounds.Offset(0, -source->kNewTabButtonVerticalOffset);
1697 return new_bounds;
1700 void TabDragController::AdjustBrowserAndTabBoundsForDrag(
1701 int last_tabstrip_width,
1702 const gfx::Point& point_in_screen,
1703 std::vector<gfx::Rect>* drag_bounds) {
1704 attached_tabstrip_->InvalidateLayout();
1705 attached_tabstrip_->DoLayout();
1706 const int dragged_tabstrip_width = attached_tabstrip_->tab_area_width();
1708 // If the new tabstrip is smaller than the old resize the tabs.
1709 if (dragged_tabstrip_width < last_tabstrip_width) {
1710 const float leading_ratio =
1711 drag_bounds->front().x() / static_cast<float>(last_tabstrip_width);
1712 *drag_bounds = CalculateBoundsForDraggedTabs();
1714 if (drag_bounds->back().right() < dragged_tabstrip_width) {
1715 const int delta_x =
1716 std::min(static_cast<int>(leading_ratio * dragged_tabstrip_width),
1717 dragged_tabstrip_width -
1718 (drag_bounds->back().right() -
1719 drag_bounds->front().x()));
1720 OffsetX(delta_x, drag_bounds);
1723 // Reposition the restored window such that the tab that was dragged remains
1724 // under the mouse cursor.
1725 gfx::Point offset(
1726 static_cast<int>((*drag_bounds)[source_tab_index_].width() *
1727 offset_to_width_ratio_) +
1728 (*drag_bounds)[source_tab_index_].x(), 0);
1729 views::View::ConvertPointToWidget(attached_tabstrip_, &offset);
1730 gfx::Rect bounds = GetAttachedBrowserWidget()->GetWindowBoundsInScreen();
1731 bounds.set_x(point_in_screen.x() - offset.x());
1732 GetAttachedBrowserWidget()->SetBounds(bounds);
1734 attached_tabstrip_->SetTabBoundsForDrag(*drag_bounds);
1737 Browser* TabDragController::CreateBrowserForDrag(
1738 TabStrip* source,
1739 const gfx::Point& point_in_screen,
1740 gfx::Vector2d* drag_offset,
1741 std::vector<gfx::Rect>* drag_bounds) {
1742 gfx::Rect new_bounds(CalculateDraggedBrowserBounds(source,
1743 point_in_screen,
1744 drag_bounds));
1745 *drag_offset = point_in_screen - new_bounds.origin();
1747 Profile* profile =
1748 Profile::FromBrowserContext(drag_data_[0].contents->GetBrowserContext());
1749 Browser::CreateParams create_params(Browser::TYPE_TABBED,
1750 profile,
1751 host_desktop_type_);
1752 create_params.initial_bounds = new_bounds;
1753 Browser* browser = new Browser(create_params);
1754 is_dragging_new_browser_ = true;
1755 SetWindowPositionManaged(browser->window()->GetNativeWindow(), false);
1756 // If the window is created maximized then the bounds we supplied are ignored.
1757 // We need to reset them again so they are honored.
1758 browser->window()->SetBounds(new_bounds);
1760 return browser;
1763 gfx::Point TabDragController::GetCursorScreenPoint() {
1764 #if defined(USE_ASH)
1765 if (host_desktop_type_ == chrome::HOST_DESKTOP_TYPE_ASH &&
1766 event_source_ == EVENT_SOURCE_TOUCH &&
1767 aura::Env::GetInstance()->is_touch_down()) {
1768 views::Widget* widget = GetAttachedBrowserWidget();
1769 DCHECK(widget);
1770 aura::Window* widget_window = widget->GetNativeWindow();
1771 DCHECK(widget_window->GetRootWindow());
1772 gfx::PointF touch_point_f;
1773 bool got_touch_point = ui::GestureRecognizer::Get()->
1774 GetLastTouchPointForTarget(widget_window, &touch_point_f);
1775 CHECK(got_touch_point);
1776 // TODO(tdresser): Switch to using gfx::PointF. See crbug.com/337824.
1777 gfx::Point touch_point = gfx::ToFlooredPoint(touch_point_f);
1778 wm::ConvertPointToScreen(widget_window->GetRootWindow(), &touch_point);
1779 return touch_point;
1781 #endif
1783 return screen_->GetCursorScreenPoint();
1786 gfx::Vector2d TabDragController::GetWindowOffset(
1787 const gfx::Point& point_in_screen) {
1788 TabStrip* owning_tabstrip = attached_tabstrip_ ?
1789 attached_tabstrip_ : source_tabstrip_;
1790 views::View* toplevel_view = owning_tabstrip->GetWidget()->GetContentsView();
1792 gfx::Point point = point_in_screen;
1793 views::View::ConvertPointFromScreen(toplevel_view, &point);
1794 return point.OffsetFromOrigin();
1797 gfx::NativeWindow TabDragController::GetLocalProcessWindow(
1798 const gfx::Point& screen_point,
1799 bool exclude_dragged_view) {
1800 std::set<gfx::NativeWindow> exclude;
1801 if (exclude_dragged_view) {
1802 gfx::NativeWindow dragged_window =
1803 attached_tabstrip_->GetWidget()->GetNativeWindow();
1804 if (dragged_window)
1805 exclude.insert(dragged_window);
1807 #if defined(OS_LINUX) && !defined(OS_CHROMEOS)
1808 // Exclude windows which are pending deletion via Browser::TabStripEmpty().
1809 // These windows can be returned in the Linux Aura port because the browser
1810 // window which was used for dragging is not hidden once all of its tabs are
1811 // attached to another browser window in DragBrowserToNewTabStrip().
1812 // TODO(pkotwicz): Fix this properly (crbug.com/358482)
1813 BrowserList* browser_list = BrowserList::GetInstance(
1814 chrome::HOST_DESKTOP_TYPE_NATIVE);
1815 for (BrowserList::const_iterator it = browser_list->begin();
1816 it != browser_list->end(); ++it) {
1817 if ((*it)->tab_strip_model()->empty())
1818 exclude.insert((*it)->window()->GetNativeWindow());
1820 #endif
1821 return GetLocalProcessWindowAtPoint(host_desktop_type_,
1822 screen_point,
1823 exclude);