1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "chrome/browser/ui/views/tabs/tab_drag_controller.h"
6 
7 #include <algorithm>
8 #include <limits>
9 #include <set>
10 #include <utility>
11 
12 #include "base/auto_reset.h"
13 #include "base/bind.h"
14 #include "base/callback.h"
15 #include "base/i18n/rtl.h"
16 #include "base/numerics/ranges.h"
17 #include "base/numerics/safe_conversions.h"
18 #include "base/stl_util.h"
19 #include "build/build_config.h"
20 #include "chrome/browser/chrome_notification_types.h"
21 #include "chrome/browser/profiles/profile.h"
22 #include "chrome/browser/ui/browser_commands.h"
23 #include "chrome/browser/ui/browser_list.h"
24 #include "chrome/browser/ui/browser_window.h"
25 #include "chrome/browser/ui/layout_constants.h"
26 #include "chrome/browser/ui/sad_tab_helper.h"
27 #include "chrome/browser/ui/tabs/tab_group.h"
28 #include "chrome/browser/ui/tabs/tab_group_model.h"
29 #include "chrome/browser/ui/tabs/tab_strip_model.h"
30 #include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
31 #include "chrome/browser/ui/ui_features.h"
32 #include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"
33 #include "chrome/browser/ui/views/frame/browser_view.h"
34 #include "chrome/browser/ui/views/tabs/tab.h"
35 #include "chrome/browser/ui/views/tabs/tab_slot_view.h"
36 #include "chrome/browser/ui/views/tabs/tab_strip.h"
37 #include "chrome/browser/ui/views/tabs/tab_strip_layout_helper.h"
38 #include "chrome/browser/ui/views/tabs/tab_style_views.h"
39 #include "chrome/browser/ui/views/tabs/window_finder.h"
40 #include "components/tab_groups/tab_group_id.h"
41 #include "content/public/browser/notification_service.h"
42 #include "content/public/browser/notification_source.h"
43 #include "content/public/browser/web_contents.h"
44 #include "ui/display/display.h"
45 #include "ui/display/screen.h"
46 #include "ui/events/gestures/gesture_recognizer.h"
47 #include "ui/events/types/event_type.h"
48 #include "ui/gfx/geometry/point_conversions.h"
49 #include "ui/views/event_monitor.h"
50 #include "ui/views/view_tracker.h"
51 #include "ui/views/widget/root_view.h"
52 
53 #if defined(OS_CHROMEOS)
54 #include "ash/public/cpp/ash_features.h"
55 #include "ash/public/cpp/tablet_mode.h"
56 #include "ash/public/cpp/window_properties.h"  // nogncheck
57 #include "chromeos/ui/base/window_properties.h"
58 #include "chromeos/ui/base/window_state_type.h"  // nogncheck
59 #include "ui/aura/window_delegate.h"
60 #include "ui/wm/core/coordinate_conversion.h"
61 #endif
62 
63 #if defined(USE_AURA)
64 #include "ui/aura/env.h"                            // nogncheck
65 #include "ui/aura/window.h"                         // nogncheck
66 #include "ui/wm/core/window_modality_controller.h"  // nogncheck
67 #endif
68 
69 using content::OpenURLParams;
70 using content::WebContents;
71 
72 // If non-null there is a drag underway.
73 static TabDragController* g_tab_drag_controller = nullptr;
74 
75 namespace {
76 
77 // Initial delay before moving tabs when the dragged tab is close to the edge of
78 // the stacked tabs.
79 constexpr auto kMoveAttachedInitialDelay =
80     base::TimeDelta::FromMilliseconds(600);
81 
82 // Delay for moving tabs after the initial delay has passed.
83 constexpr auto kMoveAttachedSubsequentDelay =
84     base::TimeDelta::FromMilliseconds(300);
85 
86 // A dragged window is forced to be a bit smaller than maximized bounds during a
87 // drag. This prevents the dragged browser widget from getting maximized at
88 // creation and makes it easier to drag tabs out of a restored window that had
89 // maximized size.
90 constexpr int kMaximizedWindowInset = 10;  // DIPs.
91 
92 #if defined(OS_CHROMEOS)
93 
94 // Returns the aura::Window which stores the window properties for tab-dragging.
GetWindowForTabDraggingProperties(const TabDragContext * context)95 aura::Window* GetWindowForTabDraggingProperties(const TabDragContext* context) {
96   return context ? context->AsView()->GetWidget()->GetNativeWindow() : nullptr;
97 }
98 
99 // Returns true if |context| browser window is snapped.
IsSnapped(const TabDragContext * context)100 bool IsSnapped(const TabDragContext* context) {
101   DCHECK(context);
102   chromeos::WindowStateType type =
103       GetWindowForTabDraggingProperties(context)->GetProperty(
104           chromeos::kWindowStateTypeKey);
105   return type == chromeos::WindowStateType::kLeftSnapped ||
106          type == chromeos::WindowStateType::kRightSnapped;
107 }
108 
109 // In Chrome OS tablet mode, when dragging a tab/tabs around, the desired
110 // browser size during dragging is one-fourth of the workspace size or the
111 // window's minimum size.
GetDraggedBrowserBoundsInTabletMode(aura::Window * window)112 gfx::Rect GetDraggedBrowserBoundsInTabletMode(aura::Window* window) {
113   const gfx::Rect work_area =
114       display::Screen::GetScreen()->GetDisplayNearestWindow(window).work_area();
115   gfx::Size mininum_size;
116   if (window->delegate())
117     mininum_size = window->delegate()->GetMinimumSize();
118 
119   gfx::Rect bounds(window->GetBoundsInScreen());
120   bounds.set_width(std::max(work_area.width() / 2, mininum_size.width()));
121   bounds.set_height(std::max(work_area.height() / 2, mininum_size.height()));
122   return bounds;
123 }
124 
125 // Store the current window bounds if we're in Chrome OS tablet mode and tab
126 // dragging is allowed on browser windows.
StoreCurrentDraggedBrowserBoundsInTabletMode(aura::Window * window,const gfx::Rect & bounds_in_screen)127 void StoreCurrentDraggedBrowserBoundsInTabletMode(
128     aura::Window* window,
129     const gfx::Rect& bounds_in_screen) {
130   if (ash::TabletMode::Get()->InTabletMode()) {
131     // The bounds that is stored in ash::kRestoreBoundsOverrideKey will be used
132     // by DragDetails to calculate the window bounds during dragging in tablet
133     // mode.
134     window->SetProperty(ash::kRestoreBoundsOverrideKey,
135                         new gfx::Rect(bounds_in_screen));
136   }
137 }
138 
139 // Returns true if |context| is currently showing in overview mode in Chrome
140 // OS.
IsShowingInOverview(TabDragContext * context)141 bool IsShowingInOverview(TabDragContext* context) {
142   return context && GetWindowForTabDraggingProperties(context)->GetProperty(
143                         chromeos::kIsShowingInOverviewKey);
144 }
145 
146 // Returns true if we should attach the dragged tabs into |target_context|
147 // after the drag ends. Currently it only happens on Chrome OS, when the dragged
148 // tabs are dragged over an overview window, we should not try to attach it
149 // to the overview window during dragging, but should wait to do so until the
150 // drag ends.
ShouldAttachOnEnd(TabDragContext * target_context)151 bool ShouldAttachOnEnd(TabDragContext* target_context) {
152   return IsShowingInOverview(target_context);
153 }
154 
155 // Returns true if |context| can detach from the current context and attach
156 // into another eligible browser window's context.
CanDetachFromTabStrip(TabDragContext * context)157 bool CanDetachFromTabStrip(TabDragContext* context) {
158   return context && GetWindowForTabDraggingProperties(context)->GetProperty(
159                         ash::kCanAttachToAnotherWindowKey);
160 }
161 
162 #else
IsSnapped(const TabDragContext * context)163 bool IsSnapped(const TabDragContext* context) {
164   return false;
165 }
166 
IsShowingInOverview(TabDragContext * context)167 bool IsShowingInOverview(TabDragContext* context) {
168   return false;
169 }
170 
ShouldAttachOnEnd(TabDragContext * target_context)171 bool ShouldAttachOnEnd(TabDragContext* target_context) {
172   return false;
173 }
174 
CanDetachFromTabStrip(TabDragContext * context)175 bool CanDetachFromTabStrip(TabDragContext* context) {
176   return true;
177 }
178 
179 #endif  // #if defined(OS_CHROMEOS)
180 
SetCapture(TabDragContext * context)181 void SetCapture(TabDragContext* context) {
182   context->AsView()->GetWidget()->SetCapture(context->AsView());
183 }
184 
GetTabstripScreenBounds(const TabDragContext * context)185 gfx::Rect GetTabstripScreenBounds(const TabDragContext* context) {
186   const views::View* view = context->AsView();
187   gfx::Point view_topleft;
188   views::View::ConvertPointToScreen(view, &view_topleft);
189   gfx::Rect view_screen_bounds = view->GetLocalBounds();
190   view_screen_bounds.Offset(view_topleft.x(), view_topleft.y());
191   return view_screen_bounds;
192 }
193 
194 // Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
195 // of |bounds| is adjusted by |vertical_adjustment|.
DoesRectContainVerticalPointExpanded(const gfx::Rect & bounds,int vertical_adjustment,int y)196 bool DoesRectContainVerticalPointExpanded(const gfx::Rect& bounds,
197                                           int vertical_adjustment,
198                                           int y) {
199   int upper_threshold = bounds.bottom() + vertical_adjustment;
200   int lower_threshold = bounds.y() - vertical_adjustment;
201   return y >= lower_threshold && y <= upper_threshold;
202 }
203 
204 // Adds |x_offset| to all the rectangles in |rects|.
OffsetX(int x_offset,std::vector<gfx::Rect> * rects)205 void OffsetX(int x_offset, std::vector<gfx::Rect>* rects) {
206   if (x_offset == 0)
207     return;
208 
209   for (size_t i = 0; i < rects->size(); ++i)
210     (*rects)[i].set_x((*rects)[i].x() + x_offset);
211 }
212 
213 }  // namespace
214 
215 // KeyEventTracker installs an event monitor and runs a callback to end the drag
216 // when it receives any key event.
217 class KeyEventTracker : public ui::EventObserver {
218  public:
KeyEventTracker(base::OnceClosure end_drag_callback,base::OnceClosure revert_drag_callback,gfx::NativeWindow context)219   KeyEventTracker(base::OnceClosure end_drag_callback,
220                   base::OnceClosure revert_drag_callback,
221                   gfx::NativeWindow context)
222       : end_drag_callback_(std::move(end_drag_callback)),
223         revert_drag_callback_(std::move(revert_drag_callback)) {
224     event_monitor_ = views::EventMonitor::CreateApplicationMonitor(
225         this, context, {ui::ET_KEY_PRESSED});
226   }
227   KeyEventTracker(const KeyEventTracker&) = delete;
228   KeyEventTracker& operator=(const KeyEventTracker&) = delete;
229   ~KeyEventTracker() override = default;
230 
231  private:
232   // ui::EventObserver:
OnEvent(const ui::Event & event)233   void OnEvent(const ui::Event& event) override {
234     if (event.AsKeyEvent()->key_code() == ui::VKEY_ESCAPE &&
235         revert_drag_callback_) {
236       std::move(revert_drag_callback_).Run();
237     } else if (event.AsKeyEvent()->key_code() != ui::VKEY_ESCAPE &&
238                end_drag_callback_) {
239       std::move(end_drag_callback_).Run();
240     }
241   }
242 
243   base::OnceClosure end_drag_callback_;
244   base::OnceClosure revert_drag_callback_;
245   std::unique_ptr<views::EventMonitor> event_monitor_;
246 };
247 
248 class TabDragController::SourceTabStripEmptinessTracker
249     : public TabStripModelObserver {
250  public:
SourceTabStripEmptinessTracker(TabStripModel * tabstrip,TabDragController * parent)251   explicit SourceTabStripEmptinessTracker(TabStripModel* tabstrip,
252                                           TabDragController* parent)
253       : tab_strip_(tabstrip), parent_(parent) {
254     tab_strip_->AddObserver(this);
255   }
256 
257  private:
TabStripEmpty()258   void TabStripEmpty() override {
259     tab_strip_->RemoveObserver(this);
260     parent_->OnSourceTabStripEmpty();
261   }
262 
263   TabStripModel* const tab_strip_;
264   TabDragController* const parent_;
265 };
266 
267 class TabDragController::DraggedTabsClosedTracker
268     : public TabStripModelObserver {
269  public:
DraggedTabsClosedTracker(TabStripModel * tabstrip,TabDragController * parent)270   DraggedTabsClosedTracker(TabStripModel* tabstrip, TabDragController* parent)
271       : parent_(parent) {
272     tabstrip->AddObserver(this);
273   }
274 
OnTabStripModelChanged(TabStripModel * model,const TabStripModelChange & change,const TabStripSelectionChange & selection)275   void OnTabStripModelChanged(
276       TabStripModel* model,
277       const TabStripModelChange& change,
278       const TabStripSelectionChange& selection) override {
279     if (change.type() != TabStripModelChange::Type::kRemoved)
280       return;
281     for (const auto& contents : change.GetRemove()->contents)
282       parent_->OnActiveStripWebContentsRemoved(contents.contents);
283   }
284 
285  private:
286   TabDragController* const parent_;
287 };
288 
TabDragData()289 TabDragController::TabDragData::TabDragData()
290     : contents(nullptr),
291       source_model_index(TabStripModel::kNoTab),
292       attached_view(nullptr),
293       pinned(false) {}
294 
~TabDragData()295 TabDragController::TabDragData::~TabDragData() {}
296 
297 TabDragController::TabDragData::TabDragData(TabDragData&&) = default;
298 
299 #if defined(OS_CHROMEOS)
300 
301 // The class to track the current deferred target tabstrip and also to observe
302 // its native window's property ash::kIsDeferredTabDraggingTargetWindowKey.
303 // The reason we need to observe the window property is the property might be
304 // cleared outside of TabDragController (i.e. by ash), and we should update the
305 // tracked deferred target tabstrip in this case.
306 class TabDragController::DeferredTargetTabstripObserver
307     : public aura::WindowObserver {
308  public:
309   DeferredTargetTabstripObserver() = default;
310   DeferredTargetTabstripObserver(const DeferredTargetTabstripObserver&) =
311       delete;
312   DeferredTargetTabstripObserver& operator=(
313       const DeferredTargetTabstripObserver&) = delete;
~DeferredTargetTabstripObserver()314   ~DeferredTargetTabstripObserver() override {
315     if (deferred_target_context_) {
316       GetWindowForTabDraggingProperties(deferred_target_context_)
317           ->RemoveObserver(this);
318       deferred_target_context_ = nullptr;
319     }
320   }
321 
SetDeferredTargetTabstrip(TabDragContext * deferred_target_context)322   void SetDeferredTargetTabstrip(TabDragContext* deferred_target_context) {
323     if (deferred_target_context_ == deferred_target_context)
324       return;
325 
326     // Clear the window property on the previous |deferred_target_context_|.
327     if (deferred_target_context_) {
328       aura::Window* old_window =
329           GetWindowForTabDraggingProperties(deferred_target_context_);
330       old_window->RemoveObserver(this);
331       old_window->ClearProperty(ash::kIsDeferredTabDraggingTargetWindowKey);
332     }
333 
334     deferred_target_context_ = deferred_target_context;
335 
336     // Set the window property on the new |deferred_target_context_|.
337     if (deferred_target_context_) {
338       aura::Window* new_window =
339           GetWindowForTabDraggingProperties(deferred_target_context_);
340       new_window->SetProperty(ash::kIsDeferredTabDraggingTargetWindowKey, true);
341       new_window->AddObserver(this);
342     }
343   }
344 
345   // aura::WindowObserver:
OnWindowPropertyChanged(aura::Window * window,const void * key,intptr_t old)346   void OnWindowPropertyChanged(aura::Window* window,
347                                const void* key,
348                                intptr_t old) override {
349     DCHECK_EQ(window,
350               GetWindowForTabDraggingProperties(deferred_target_context_));
351 
352     if (key == ash::kIsDeferredTabDraggingTargetWindowKey &&
353         !window->GetProperty(ash::kIsDeferredTabDraggingTargetWindowKey)) {
354       SetDeferredTargetTabstrip(nullptr);
355     }
356 
357     // else do nothing. currently it's only possible that ash clears the window
358     // property, but doesn't set the window property.
359   }
360 
OnWindowDestroying(aura::Window * window)361   void OnWindowDestroying(aura::Window* window) override {
362     DCHECK_EQ(window,
363               GetWindowForTabDraggingProperties(deferred_target_context_));
364     SetDeferredTargetTabstrip(nullptr);
365   }
366 
deferred_target_context()367   TabDragContext* deferred_target_context() { return deferred_target_context_; }
368 
369  private:
370   TabDragContext* deferred_target_context_ = nullptr;
371 };
372 
373 #endif
374 
375 ///////////////////////////////////////////////////////////////////////////////
376 // TabDragController, public:
377 
378 // static
379 const int TabDragController::kTouchVerticalDetachMagnetism = 50;
380 
381 // static
382 const int TabDragController::kVerticalDetachMagnetism = 15;
383 
TabDragController()384 TabDragController::TabDragController()
385     : current_state_(DragState::kNotStarted),
386       event_source_(EVENT_SOURCE_MOUSE),
387       source_context_(nullptr),
388       attached_context_(nullptr),
389       can_release_capture_(true),
390       offset_to_width_ratio_(0),
391       old_focused_view_tracker_(std::make_unique<views::ViewTracker>()),
392       last_move_screen_loc_(0),
393       source_view_index_(std::numeric_limits<size_t>::max()),
394       initial_move_(true),
395       detach_behavior_(DETACHABLE),
396       move_behavior_(REORDER),
397       mouse_has_ever_moved_left_(false),
398       mouse_has_ever_moved_right_(false),
399       is_dragging_new_browser_(false),
400       was_source_maximized_(false),
401       was_source_fullscreen_(false),
402       did_restore_window_(false),
403       tab_strip_to_attach_to_after_exit_(nullptr),
404       move_loop_widget_(nullptr),
405       is_mutating_(false),
406       attach_x_(-1),
407       attach_index_(-1) {
408   g_tab_drag_controller = this;
409 }
410 
~TabDragController()411 TabDragController::~TabDragController() {
412   if (g_tab_drag_controller == this)
413     g_tab_drag_controller = nullptr;
414 
415   widget_observer_.RemoveAll();
416 
417   if (is_dragging_window())
418     GetAttachedBrowserWidget()->EndMoveLoop();
419 
420   if (event_source_ == EVENT_SOURCE_TOUCH) {
421     TabDragContext* capture_context =
422         attached_context_ ? attached_context_ : source_context_;
423     capture_context->AsView()->GetWidget()->ReleaseCapture();
424   }
425   CHECK(!IsInObserverList());
426 }
427 
Init(TabDragContext * source_context,TabSlotView * source_view,const std::vector<TabSlotView * > & dragging_views,const gfx::Point & mouse_offset,int source_view_offset,ui::ListSelectionModel initial_selection_model,MoveBehavior move_behavior,EventSource event_source)428 void TabDragController::Init(TabDragContext* source_context,
429                              TabSlotView* source_view,
430                              const std::vector<TabSlotView*>& dragging_views,
431                              const gfx::Point& mouse_offset,
432                              int source_view_offset,
433                              ui::ListSelectionModel initial_selection_model,
434                              MoveBehavior move_behavior,
435                              EventSource event_source) {
436   DCHECK(!dragging_views.empty());
437   DCHECK(base::Contains(dragging_views, source_view));
438   source_context_ = source_context;
439   was_source_maximized_ = source_context->AsView()->GetWidget()->IsMaximized();
440   was_source_fullscreen_ =
441       source_context->AsView()->GetWidget()->IsFullscreen();
442   // Do not release capture when transferring capture between widgets on:
443   // - Desktop Linux
444   //     Mouse capture is not synchronous on desktop Linux. Chrome makes
445   //     transferring capture between widgets without releasing capture appear
446   //     synchronous on desktop Linux, so use that.
447   // - Chrome OS
448   //     Releasing capture on Ash cancels gestures so avoid it.
449 #if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_BSD)
450   can_release_capture_ = false;
451 #endif
452   start_point_in_screen_ = gfx::Point(source_view_offset, mouse_offset.y());
453   views::View::ConvertPointToScreen(source_view, &start_point_in_screen_);
454   event_source_ = event_source;
455   mouse_offset_ = mouse_offset;
456   move_behavior_ = move_behavior;
457   last_point_in_screen_ = start_point_in_screen_;
458   last_move_screen_loc_ = start_point_in_screen_.x();
459   initial_tab_positions_ = source_context->GetTabXCoordinates();
460 
461   source_context_emptiness_tracker_ =
462       std::make_unique<SourceTabStripEmptinessTracker>(
463           source_context_->GetTabStripModel(), this);
464 
465   header_drag_ = source_view->GetTabSlotViewType() ==
466                  TabSlotView::ViewType::kTabGroupHeader;
467   if (header_drag_)
468     group_ = source_view->group();
469 
470   drag_data_.resize(dragging_views.size());
471   for (size_t i = 0; i < dragging_views.size(); ++i)
472     InitDragData(dragging_views[i], &(drag_data_[i]));
473   source_view_index_ =
474       std::find(dragging_views.begin(), dragging_views.end(), source_view) -
475       dragging_views.begin();
476 
477   // Listen for Esc key presses.
478   key_event_tracker_ = std::make_unique<KeyEventTracker>(
479       base::BindOnce(&TabDragController::EndDrag, base::Unretained(this),
480                      END_DRAG_COMPLETE),
481       base::BindOnce(&TabDragController::EndDrag, base::Unretained(this),
482                      END_DRAG_CANCEL),
483       source_context_->AsView()->GetWidget()->GetNativeWindow());
484 
485   if (source_view->width() > 0) {
486     offset_to_width_ratio_ =
487         float{source_view->GetMirroredXInView(source_view_offset)} /
488         float{source_view->width()};
489   }
490   InitWindowCreatePoint();
491   initial_selection_model_ = std::move(initial_selection_model);
492 
493   // Gestures don't automatically do a capture. We don't allow multiple drags at
494   // the same time, so we explicitly capture.
495   if (event_source == EVENT_SOURCE_TOUCH) {
496     // Taking capture may cause capture to be lost, ending the drag and
497     // destroying |this|.
498     base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
499     SetCapture(source_context_);
500     if (!ref)
501       return;
502   }
503 
504   window_finder_ = std::make_unique<WindowFinder>();
505 }
506 
507 // static
IsAttachedTo(const TabDragContext * context)508 bool TabDragController::IsAttachedTo(const TabDragContext* context) {
509   return (g_tab_drag_controller && g_tab_drag_controller->active() &&
510           g_tab_drag_controller->attached_context() == context);
511 }
512 
513 // static
IsActive()514 bool TabDragController::IsActive() {
515   return g_tab_drag_controller && g_tab_drag_controller->active();
516 }
517 
518 // static
GetSourceContext()519 TabDragContext* TabDragController::GetSourceContext() {
520   return g_tab_drag_controller ? g_tab_drag_controller->source_context_
521                                : nullptr;
522 }
523 
SetMoveBehavior(MoveBehavior behavior)524 void TabDragController::SetMoveBehavior(MoveBehavior behavior) {
525   if (current_state_ == DragState::kNotStarted)
526     move_behavior_ = behavior;
527 }
528 
IsDraggingTab(content::WebContents * contents)529 bool TabDragController::IsDraggingTab(content::WebContents* contents) {
530   for (auto& drag_data : drag_data_) {
531     if (drag_data.contents == contents)
532       return true;
533   }
534   return false;
535 }
536 
Drag(const gfx::Point & point_in_screen)537 void TabDragController::Drag(const gfx::Point& point_in_screen) {
538   TRACE_EVENT1("views", "TabDragController::Drag", "point_in_screen",
539                point_in_screen.ToString());
540 
541   bring_to_front_timer_.Stop();
542   move_stacked_timer_.Stop();
543 
544   if (current_state_ == DragState::kWaitingToDragTabs ||
545       current_state_ == DragState::kWaitingToStop ||
546       current_state_ == DragState::kStopped)
547     return;
548 
549   if (current_state_ == DragState::kNotStarted) {
550     if (!CanStartDrag(point_in_screen))
551       return;  // User hasn't dragged far enough yet.
552 
553     // On windows SaveFocus() may trigger a capture lost, which destroys us.
554     {
555       base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
556       SaveFocus();
557       if (!ref)
558         return;
559     }
560     current_state_ = DragState::kDraggingTabs;
561     Attach(source_context_, gfx::Point());
562     if (num_dragging_tabs() == source_context_->GetTabStripModel()->count()) {
563       views::Widget* widget = GetAttachedBrowserWidget();
564       gfx::Rect new_bounds;
565       gfx::Vector2d drag_offset;
566       if (was_source_maximized_ || was_source_fullscreen_) {
567         did_restore_window_ = true;
568         // When all tabs in a maximized browser are dragged the browser gets
569         // restored during the drag and maximized back when the drag ends.
570         const int tab_area_width = attached_context_->GetTabDragAreaWidth();
571         std::vector<gfx::Rect> drag_bounds =
572             attached_context_->CalculateBoundsForDraggedViews(attached_views_);
573         OffsetX(GetAttachedDragPoint(point_in_screen).x(), &drag_bounds);
574         new_bounds = CalculateDraggedBrowserBounds(
575             source_context_, point_in_screen, &drag_bounds);
576         new_bounds.Offset(-widget->GetRestoredBounds().x() +
577                               point_in_screen.x() - mouse_offset_.x(),
578                           0);
579         widget->SetVisibilityChangedAnimationsEnabled(false);
580         widget->Restore();
581         widget->SetBounds(new_bounds);
582         drag_offset = GetWindowOffset(point_in_screen);
583         AdjustBrowserAndTabBoundsForDrag(tab_area_width, point_in_screen,
584                                          &drag_offset, &drag_bounds);
585         widget->SetVisibilityChangedAnimationsEnabled(true);
586       } else {
587         new_bounds =
588             CalculateNonMaximizedDraggedBrowserBounds(widget, point_in_screen);
589         widget->SetBounds(new_bounds);
590         drag_offset = GetWindowOffset(point_in_screen);
591       }
592 
593 #if defined(OS_CHROMEOS)
594       StoreCurrentDraggedBrowserBoundsInTabletMode(widget->GetNativeWindow(),
595                                                    new_bounds);
596 #endif
597 
598       RunMoveLoop(drag_offset);
599       return;
600     }
601   }
602 
603   if (ContinueDragging(point_in_screen) == Liveness::DELETED)
604     return;
605 }
606 
EndDrag(EndDragReason reason)607 void TabDragController::EndDrag(EndDragReason reason) {
608   TRACE_EVENT0("views", "TabDragController::EndDrag");
609 
610   // If we're dragging a window ignore capture lost since it'll ultimately
611   // trigger the move loop to end and we'll revert the drag when RunMoveLoop()
612   // finishes.
613   if (reason == END_DRAG_CAPTURE_LOST &&
614       current_state_ == DragState::kDraggingWindow) {
615     return;
616   }
617 
618   // If we're dragging a window, end the move loop, returning control to
619   // RunMoveLoop() which will end the drag.
620   if (current_state_ == DragState::kDraggingWindow) {
621     current_state_ = DragState::kWaitingToStop;
622     GetAttachedBrowserWidget()->EndMoveLoop();
623     return;
624   }
625 
626 #if defined(OS_CHROMEOS)
627   // It's possible that in Chrome OS we defer the windows that are showing in
628   // overview to attach into during dragging. If so we need to attach the
629   // dragged tabs to it first.
630   if (reason == END_DRAG_COMPLETE && deferred_target_context_observer_)
631     PerformDeferredAttach();
632 
633   // It's also possible that we need to merge the dragged tabs back into the
634   // source window even if the dragged tabs is dragged away from the source
635   // window.
636   if (source_context_ &&
637       GetWindowForTabDraggingProperties(source_context_)
638           ->GetProperty(ash::kIsDeferredTabDraggingTargetWindowKey)) {
639     GetWindowForTabDraggingProperties(source_context_)
640         ->ClearProperty(ash::kIsDeferredTabDraggingTargetWindowKey);
641     reason = END_DRAG_CANCEL;
642   }
643 #endif
644 
645   EndDragImpl(reason != END_DRAG_COMPLETE && source_context_ ? CANCELED
646                                                              : NORMAL);
647 }
648 
InitDragData(TabSlotView * view,TabDragData * drag_data)649 void TabDragController::InitDragData(TabSlotView* view,
650                                      TabDragData* drag_data) {
651   TRACE_EVENT0("views", "TabDragController::InitDragData");
652   const int source_model_index = source_context_->GetIndexOf(view);
653   drag_data->source_model_index = source_model_index;
654   if (source_model_index != TabStripModel::kNoTab) {
655     drag_data->contents = source_context_->GetTabStripModel()->GetWebContentsAt(
656         drag_data->source_model_index);
657     drag_data->pinned = source_context_->IsTabPinned(static_cast<Tab*>(view));
658   }
659   base::Optional<tab_groups::TabGroupId> tab_group_id = view->group();
660   if (tab_group_id.has_value()) {
661     drag_data->tab_group_data = TabDragData::TabGroupData{
662         tab_group_id.value(), *source_context_->GetTabStripModel()
663                                    ->group_model()
664                                    ->GetTabGroup(tab_group_id.value())
665                                    ->visual_data()};
666   }
667 }
668 
OnWidgetBoundsChanged(views::Widget * widget,const gfx::Rect & new_bounds)669 void TabDragController::OnWidgetBoundsChanged(views::Widget* widget,
670                                               const gfx::Rect& new_bounds) {
671   TRACE_EVENT1("views", "TabDragController::OnWidgetBoundsChanged",
672                "new_bounds", new_bounds.ToString());
673   // Detaching and attaching can be suppresed temporarily to suppress attaching
674   // to incorrect window on changing bounds. We should prevent Drag() itself,
675   // otherwise it can clear deferred attaching tab.
676   if (!CanDetachFromTabStrip(attached_context_))
677     return;
678 #if defined(USE_AURA)
679   aura::Env* env = aura::Env::GetInstance();
680   // WidgetBoundsChanged happens as a step of ending a drag, but Drag() doesn't
681   // have to be called -- GetCursorScreenPoint() may return an incorrect
682   // location in such case and causes a weird effect. See
683   // https://crbug.com/914527 for the details.
684   if (!env->IsMouseButtonDown() && !env->is_touch_down())
685     return;
686 #endif
687   Drag(GetCursorScreenPoint());
688 }
689 
OnWidgetDestroyed(views::Widget * widget)690 void TabDragController::OnWidgetDestroyed(views::Widget* widget) {
691   widget_observer_.Remove(widget);
692 }
693 
OnSourceTabStripEmpty()694 void TabDragController::OnSourceTabStripEmpty() {
695   // NULL out source_context_ so that we don't attempt to add back to it (in
696   // the case of a revert).
697   source_context_ = nullptr;
698 #if defined(OS_CHROMEOS)
699   // Also update the source window info for the current dragged window.
700   if (attached_context_) {
701     GetWindowForTabDraggingProperties(attached_context_)
702         ->ClearProperty(ash::kTabDraggingSourceWindowKey);
703   }
704 #endif
705 }
706 
OnActiveStripWebContentsRemoved(content::WebContents * contents)707 void TabDragController::OnActiveStripWebContentsRemoved(
708     content::WebContents* contents) {
709   // Mark closed tabs as destroyed so we don't try to manipulate them later.
710   for (auto it = drag_data_.begin(); it != drag_data_.end(); it++) {
711     if (it->contents == contents) {
712       it->contents = nullptr;
713       break;
714     }
715   }
716 }
717 
718 ///////////////////////////////////////////////////////////////////////////////
719 // TabDragController, private:
720 
InitWindowCreatePoint()721 void TabDragController::InitWindowCreatePoint() {
722   // window_create_point_ is only used in CompleteDrag() (through
723   // GetWindowCreatePoint() to get the start point of the docked window) when
724   // the attached_context_ is NULL and all the window's related bound
725   // information are obtained from source_context_. So, we need to get the
726   // first_tab based on source_context_, not attached_context_. Otherwise,
727   // the window_create_point_ is not in the correct coordinate system. Please
728   // refer to http://crbug.com/6223 comment #15 for detailed information.
729   views::View* first_tab = source_context_->GetTabAt(0);
730   views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_);
731   window_create_point_ = first_source_tab_point_;
732   window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y());
733 }
734 
GetWindowCreatePoint(const gfx::Point & origin) const735 gfx::Point TabDragController::GetWindowCreatePoint(
736     const gfx::Point& origin) const {
737   // If the cursor is outside the monitor area, move it inside. For example,
738   // dropping a tab onto the task bar on Windows produces this situation.
739   gfx::Rect work_area =
740       display::Screen::GetScreen()->GetDisplayNearestPoint(origin).work_area();
741   gfx::Point create_point(origin);
742   if (!work_area.IsEmpty()) {
743     if (create_point.x() < work_area.x())
744       create_point.set_x(work_area.x());
745     else if (create_point.x() > work_area.right())
746       create_point.set_x(work_area.right());
747     if (create_point.y() < work_area.y())
748       create_point.set_y(work_area.y());
749     else if (create_point.y() > work_area.bottom())
750       create_point.set_y(work_area.bottom());
751   }
752   return gfx::Point(create_point.x() - window_create_point_.x(),
753                     create_point.y() - window_create_point_.y());
754 }
755 
SaveFocus()756 void TabDragController::SaveFocus() {
757   DCHECK(source_context_);
758   old_focused_view_tracker_->SetView(
759       source_context_->AsView()->GetFocusManager()->GetFocusedView());
760   source_context_->AsView()->GetFocusManager()->ClearFocus();
761   // WARNING: we may have been deleted.
762 }
763 
RestoreFocus()764 void TabDragController::RestoreFocus() {
765   if (attached_context_ != source_context_) {
766     if (is_dragging_new_browser_) {
767       content::WebContents* active_contents = source_dragged_contents();
768       if (active_contents && !active_contents->FocusLocationBarByDefault())
769         active_contents->Focus();
770     }
771     return;
772   }
773   views::View* old_focused_view = old_focused_view_tracker_->view();
774   if (!old_focused_view)
775     return;
776   old_focused_view->GetFocusManager()->SetFocusedView(old_focused_view);
777 }
778 
CanStartDrag(const gfx::Point & point_in_screen) const779 bool TabDragController::CanStartDrag(const gfx::Point& point_in_screen) const {
780   // Determine if the mouse has moved beyond a minimum elasticity distance in
781   // any direction from the starting point.
782   static const int kMinimumDragDistance = 10;
783   int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x());
784   int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y());
785   return sqrt(pow(float{x_offset}, 2) + pow(float{y_offset}, 2)) >
786          kMinimumDragDistance;
787 }
788 
ContinueDragging(const gfx::Point & point_in_screen)789 TabDragController::Liveness TabDragController::ContinueDragging(
790     const gfx::Point& point_in_screen) {
791   TRACE_EVENT1("views", "TabDragController::ContinueDragging",
792                "point_in_screen", point_in_screen.ToString());
793 
794   DCHECK(attached_context_);
795 
796   TabDragContext* target_context = source_context_;
797   if (detach_behavior_ == DETACHABLE &&
798       GetTargetTabStripForPoint(point_in_screen, &target_context) ==
799           Liveness::DELETED) {
800     return Liveness::DELETED;
801   }
802 
803   // The dragged tabs may not be able to attach into |target_context| during
804   // dragging if the window accociated with |target_context| is currently
805   // showing in overview mode in Chrome OS, in this case we defer attaching into
806   // it till the drag ends and reset |target_context| here.
807   if (ShouldAttachOnEnd(target_context)) {
808     SetDeferredTargetTabstrip(target_context);
809     target_context = current_state_ == DragState::kDraggingWindow
810                          ? attached_context_
811                          : nullptr;
812   } else {
813     SetDeferredTargetTabstrip(nullptr);
814   }
815 
816   bool tab_strip_changed = (target_context != attached_context_);
817 
818   if (attached_context_) {
819     int move_delta = point_in_screen.x() - last_point_in_screen_.x();
820     if (move_delta > 0)
821       mouse_has_ever_moved_right_ = true;
822     else if (move_delta < 0)
823       mouse_has_ever_moved_left_ = true;
824   }
825   last_point_in_screen_ = point_in_screen;
826 
827   if (tab_strip_changed) {
828     is_dragging_new_browser_ = false;
829     did_restore_window_ = false;
830     if (DragBrowserToNewTabStrip(target_context, point_in_screen) ==
831         DRAG_BROWSER_RESULT_STOP) {
832       return Liveness::ALIVE;
833     }
834   }
835   if (current_state_ == DragState::kDraggingWindow) {
836     bring_to_front_timer_.Start(
837         FROM_HERE, base::TimeDelta::FromMilliseconds(750),
838         base::BindOnce(&TabDragController::BringWindowUnderPointToFront,
839                        base::Unretained(this), point_in_screen));
840   }
841 
842   if (current_state_ == DragState::kDraggingTabs) {
843     if (move_only()) {
844       DragActiveTabStacked(point_in_screen);
845     } else {
846       MoveAttached(point_in_screen);
847       if (tab_strip_changed) {
848         // Move the corresponding window to the front. We do this after the
849         // move as on windows activate triggers a synchronous paint.
850         attached_context_->AsView()->GetWidget()->Activate();
851       }
852     }
853   }
854   return Liveness::ALIVE;
855 }
856 
857 TabDragController::DragBrowserResultType
DragBrowserToNewTabStrip(TabDragContext * target_context,const gfx::Point & point_in_screen)858 TabDragController::DragBrowserToNewTabStrip(TabDragContext* target_context,
859                                             const gfx::Point& point_in_screen) {
860   TRACE_EVENT1("views", "TabDragController::DragBrowserToNewTabStrip",
861                "point_in_screen", point_in_screen.ToString());
862 
863   if (!target_context) {
864     DetachIntoNewBrowserAndRunMoveLoop(point_in_screen);
865     return DRAG_BROWSER_RESULT_STOP;
866   }
867 
868 #if defined(USE_AURA)
869   // Only Aura windows are gesture consumers.
870   gfx::NativeView attached_native_view =
871       GetAttachedBrowserWidget()->GetNativeView();
872   GetAttachedBrowserWidget()->GetGestureRecognizer()->TransferEventsTo(
873       attached_native_view,
874       target_context->AsView()->GetWidget()->GetNativeView(),
875       ui::TransferTouchesBehavior::kDontCancel);
876 #endif
877 
878   if (current_state_ == DragState::kDraggingWindow) {
879     // ReleaseCapture() is going to result in calling back to us (because it
880     // results in a move). That'll cause all sorts of problems.  Reset the
881     // observer so we don't get notified and process the event.
882 #if defined(OS_CHROMEOS)
883     if (widget_observer_.IsObserving(move_loop_widget_))
884       widget_observer_.Remove(move_loop_widget_);
885     move_loop_widget_ = nullptr;
886 #endif  // OS_CHROMEOS
887     views::Widget* browser_widget = GetAttachedBrowserWidget();
888     // Need to release the drag controller before starting the move loop as it's
889     // going to trigger capture lost, which cancels drag.
890     attached_context_->ReleaseDragController();
891     target_context->OwnDragController(this);
892     // Disable animations so that we don't see a close animation on aero.
893     browser_widget->SetVisibilityChangedAnimationsEnabled(false);
894     if (can_release_capture_)
895       browser_widget->ReleaseCapture();
896     else
897       SetCapture(target_context);
898 
899 #if (!defined(OS_LINUX) || defined(OS_CHROMEOS)) && !defined(OS_BSD)
900     // EndMoveLoop is going to snap the window back to its original location.
901     // Hide it so users don't see this. Hiding a window in Linux aura causes
902     // it to lose capture so skip it.
903     browser_widget->Hide();
904 #endif
905     browser_widget->EndMoveLoop();
906 
907     // Ideally we would always swap the tabs now, but on non-ash Windows, it
908     // seems that running the move loop implicitly activates the window when
909     // done, leading to all sorts of flicker. So, on non-ash Windows, instead
910     // we process the move after the loop completes. But on chromeos, we can
911     // do tab swapping now to avoid the tab flashing issue
912     // (crbug.com/116329).
913     if (can_release_capture_) {
914       tab_strip_to_attach_to_after_exit_ = target_context;
915       current_state_ = DragState::kWaitingToDragTabs;
916     } else {
917       Detach(DONT_RELEASE_CAPTURE);
918       Attach(target_context, point_in_screen);
919       current_state_ = DragState::kDraggingTabs;
920       // Move the tabs into position.
921       MoveAttached(point_in_screen);
922       attached_context_->AsView()->GetWidget()->Activate();
923     }
924 
925     return DRAG_BROWSER_RESULT_STOP;
926   }
927   Detach(DONT_RELEASE_CAPTURE);
928   Attach(target_context, point_in_screen);
929   return DRAG_BROWSER_RESULT_CONTINUE;
930 }
931 
DragActiveTabStacked(const gfx::Point & point_in_screen)932 void TabDragController::DragActiveTabStacked(
933     const gfx::Point& point_in_screen) {
934   if (attached_context_->GetTabCount() != int{initial_tab_positions_.size()})
935     return;  // TODO: should cancel drag if this happens.
936 
937   int delta = point_in_screen.x() - start_point_in_screen_.x();
938   attached_context_->DragActiveTabStacked(initial_tab_positions_, delta);
939 }
940 
MoveAttachedToNextStackedIndex(const gfx::Point & point_in_screen)941 void TabDragController::MoveAttachedToNextStackedIndex(
942     const gfx::Point& point_in_screen) {
943   int index = *attached_context_->GetActiveTouchIndex();
944   if (index + 1 >= attached_context_->GetTabCount())
945     return;
946 
947   attached_context_->GetTabStripModel()->MoveSelectedTabsTo(index + 1);
948   StartMoveStackedTimerIfNecessary(point_in_screen,
949                                    kMoveAttachedSubsequentDelay);
950 }
951 
MoveAttachedToPreviousStackedIndex(const gfx::Point & point_in_screen)952 void TabDragController::MoveAttachedToPreviousStackedIndex(
953     const gfx::Point& point_in_screen) {
954   int index = *attached_context_->GetActiveTouchIndex();
955   if (index <= attached_context_->GetPinnedTabCount())
956     return;
957 
958   attached_context_->GetTabStripModel()->MoveSelectedTabsTo(index - 1);
959   StartMoveStackedTimerIfNecessary(point_in_screen,
960                                    kMoveAttachedSubsequentDelay);
961 }
962 
MoveAttached(const gfx::Point & point_in_screen)963 void TabDragController::MoveAttached(const gfx::Point& point_in_screen) {
964   DCHECK(attached_context_);
965   DCHECK_EQ(current_state_, DragState::kDraggingTabs);
966 
967   gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
968 
969   const int threshold = attached_context_->GetHorizontalDragThreshold();
970 
971   std::vector<TabSlotView*> views(drag_data_.size());
972   for (size_t i = 0; i < drag_data_.size(); ++i)
973     views[i] = drag_data_[i].attached_view;
974 
975   bool did_layout = false;
976   // Update the model, moving the WebContents from one index to another. Do this
977   // only if we have moved a minimum distance since the last reorder (to prevent
978   // jitter) or if this the first move and the tabs are not consecutive.
979   if ((abs(point_in_screen.x() - last_move_screen_loc_) > threshold ||
980        (initial_move_ && !AreTabsConsecutive()))) {
981     TabStripModel* attached_model = attached_context_->GetTabStripModel();
982     int to_index = attached_context_->GetInsertionIndexForDraggedBounds(
983         GetDraggedViewTabStripBounds(dragged_view_point), false,
984         num_dragging_tabs(), mouse_has_ever_moved_left_,
985         mouse_has_ever_moved_right_, group_);
986     bool do_move = true;
987     // While dragging within a tabstrip the expectation is the insertion index
988     // is based on the left edge of the tabs being dragged. OTOH when dragging
989     // into a new tabstrip (attaching) the expectation is the insertion index is
990     // based on the cursor. This proves problematic as insertion may change the
991     // size of the tabs, resulting in the index calculated before the insert
992     // differing from the index calculated after the insert. To alleviate this
993     // the index is chosen before insertion, and subsequently a new index is
994     // only used once the mouse moves enough such that the index changes based
995     // on the direction the mouse moved relative to |attach_x_| (smaller
996     // x-coordinate should yield a smaller index or larger x-coordinate yields a
997     // larger index).
998     if (attach_index_ != -1) {
999       gfx::Point tab_strip_point(point_in_screen);
1000       views::View::ConvertPointFromScreen(attached_context_->AsView(),
1001                                           &tab_strip_point);
1002       const int new_x =
1003           attached_context_->AsView()->GetMirroredXInView(tab_strip_point.x());
1004       if (new_x < attach_x_)
1005         to_index = std::min(to_index, attach_index_);
1006       else
1007         to_index = std::max(to_index, attach_index_);
1008       if (to_index != attach_index_)
1009         attach_index_ = -1;  // Once a valid move is detected, don't constrain.
1010       else
1011         do_move = false;
1012     }
1013     if (do_move) {
1014       WebContents* last_contents = drag_data_.back().contents;
1015       int index_of_last_item =
1016           attached_model->GetIndexOfWebContents(last_contents);
1017       if (initial_move_) {
1018         // TabDragContext determines if the tabs needs to be animated
1019         // based on model position. This means we need to invoke
1020         // LayoutDraggedTabsAt before changing the model.
1021         attached_context_->LayoutDraggedViewsAt(
1022             views, source_view_drag_data()->attached_view, dragged_view_point,
1023             initial_move_);
1024         did_layout = true;
1025       }
1026 
1027       attached_model->MoveSelectedTabsTo(to_index);
1028 
1029       if (header_drag_) {
1030         attached_model->MoveTabGroup(group_.value());
1031       } else {
1032         UpdateGroupForDraggedTabs();
1033       }
1034 
1035       // Move may do nothing in certain situations (such as when dragging pinned
1036       // tabs). Make sure the tabstrip actually changed before updating
1037       // last_move_screen_loc_.
1038       if (index_of_last_item !=
1039           attached_model->GetIndexOfWebContents(last_contents)) {
1040         last_move_screen_loc_ = point_in_screen.x();
1041       }
1042     }
1043   }
1044 
1045   if (!did_layout) {
1046     attached_context_->LayoutDraggedViewsAt(
1047         views, source_view_drag_data()->attached_view, dragged_view_point,
1048         initial_move_);
1049   }
1050 
1051   StartMoveStackedTimerIfNecessary(point_in_screen, kMoveAttachedInitialDelay);
1052 
1053   initial_move_ = false;
1054 }
1055 
StartMoveStackedTimerIfNecessary(const gfx::Point & point_in_screen,base::TimeDelta delay)1056 void TabDragController::StartMoveStackedTimerIfNecessary(
1057     const gfx::Point& point_in_screen,
1058     base::TimeDelta delay) {
1059   DCHECK(attached_context_);
1060 
1061   base::Optional<int> touch_index = attached_context_->GetActiveTouchIndex();
1062   if (!touch_index)
1063     return;
1064 
1065   gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
1066   gfx::Rect bounds = GetDraggedViewTabStripBounds(dragged_view_point);
1067   if (attached_context_->ShouldDragToNextStackedTab(
1068           bounds, *touch_index, mouse_has_ever_moved_right_)) {
1069     move_stacked_timer_.Start(
1070         FROM_HERE, delay,
1071         base::BindOnce(&TabDragController::MoveAttachedToNextStackedIndex,
1072                        base::Unretained(this), point_in_screen));
1073   } else if (attached_context_->ShouldDragToPreviousStackedTab(
1074                  bounds, *touch_index, mouse_has_ever_moved_left_)) {
1075     move_stacked_timer_.Start(
1076         FROM_HERE, delay,
1077         base::BindOnce(&TabDragController::MoveAttachedToPreviousStackedIndex,
1078                        base::Unretained(this), point_in_screen));
1079   }
1080 }
1081 
GetDetachPosition(const gfx::Point & point_in_screen)1082 TabDragController::DetachPosition TabDragController::GetDetachPosition(
1083     const gfx::Point& point_in_screen) {
1084   DCHECK(attached_context_);
1085   gfx::Point attached_point(point_in_screen);
1086   views::View::ConvertPointFromScreen(attached_context_->AsView(),
1087                                       &attached_point);
1088   if (attached_point.x() < attached_context_->TabDragAreaBeginX())
1089     return DETACH_BEFORE;
1090   if (attached_point.x() >= attached_context_->TabDragAreaEndX())
1091     return DETACH_AFTER;
1092   return DETACH_ABOVE_OR_BELOW;
1093 }
1094 
GetTargetTabStripForPoint(const gfx::Point & point_in_screen,TabDragContext ** context)1095 TabDragController::Liveness TabDragController::GetTargetTabStripForPoint(
1096     const gfx::Point& point_in_screen,
1097     TabDragContext** context) {
1098   *context = nullptr;
1099   TRACE_EVENT1("views", "TabDragController::GetTargetTabStripForPoint",
1100                "point_in_screen", point_in_screen.ToString());
1101 
1102   if (move_only() && attached_context_) {
1103     // move_only() is intended for touch, in which case we only want to detach
1104     // if the touch point moves significantly in the vertical distance.
1105     gfx::Rect tabstrip_bounds = GetTabstripScreenBounds(attached_context_);
1106     if (DoesRectContainVerticalPointExpanded(tabstrip_bounds,
1107                                              kTouchVerticalDetachMagnetism,
1108                                              point_in_screen.y())) {
1109       *context = attached_context_;
1110       return Liveness::ALIVE;
1111     }
1112   }
1113   gfx::NativeWindow local_window;
1114   const Liveness state = GetLocalProcessWindow(
1115       point_in_screen, current_state_ == DragState::kDraggingWindow,
1116       &local_window);
1117   if (state == Liveness::DELETED)
1118     return Liveness::DELETED;
1119 
1120   if (local_window && CanAttachTo(local_window)) {
1121     TabDragContext* destination_tab_strip =
1122         BrowserView::GetBrowserViewForNativeWindow(local_window)
1123             ->tabstrip()
1124             ->GetDragContext();
1125     if (ShouldAttachOnEnd(destination_tab_strip)) {
1126       // No need to check if the specified screen point is within the bounds of
1127       // the tabstrip as arriving here we know that the window is currently
1128       // showing in overview mode in Chrome OS and its bounds contain the
1129       // specified screen point, and these two conditions are enough for a
1130       // window to be a valid target window to attach the dragged tabs.
1131       *context = destination_tab_strip;
1132       return Liveness::ALIVE;
1133     } else if (destination_tab_strip &&
1134                DoesTabStripContain(destination_tab_strip, point_in_screen)) {
1135       *context = destination_tab_strip;
1136       return Liveness::ALIVE;
1137     }
1138   }
1139 
1140   *context = current_state_ == DragState::kDraggingWindow ? attached_context_
1141                                                           : nullptr;
1142   return Liveness::ALIVE;
1143 }
1144 
DoesTabStripContain(TabDragContext * context,const gfx::Point & point_in_screen) const1145 bool TabDragController::DoesTabStripContain(
1146     TabDragContext* context,
1147     const gfx::Point& point_in_screen) const {
1148   // Make sure the specified screen point is actually within the bounds of the
1149   // specified context...
1150   gfx::Rect tabstrip_bounds = GetTabstripScreenBounds(context);
1151   const int x_in_strip = point_in_screen.x() - tabstrip_bounds.x();
1152   return (x_in_strip >= context->TabDragAreaBeginX()) &&
1153          (x_in_strip < context->TabDragAreaEndX()) &&
1154          DoesRectContainVerticalPointExpanded(
1155              tabstrip_bounds, kVerticalDetachMagnetism, point_in_screen.y());
1156 }
1157 
Attach(TabDragContext * attached_context,const gfx::Point & point_in_screen,bool set_capture)1158 void TabDragController::Attach(TabDragContext* attached_context,
1159                                const gfx::Point& point_in_screen,
1160                                bool set_capture) {
1161   TRACE_EVENT1("views", "TabDragController::Attach", "point_in_screen",
1162                point_in_screen.ToString());
1163 
1164   DCHECK(!attached_context_);  // We should already have detached by the time
1165                                // we get here.
1166 
1167   attached_context_ = attached_context;
1168 
1169   std::vector<TabSlotView*> views =
1170       GetViewsMatchingDraggedContents(attached_context_);
1171 
1172   if (views.empty()) {
1173     // Transitioning from detached to attached to a new context. Add tabs to
1174     // the new model.
1175 
1176     selection_model_before_attach_ =
1177         attached_context->GetTabStripModel()->selection_model();
1178 
1179     // Inserting counts as a move. We don't want the tabs to jitter when the
1180     // user moves the tab immediately after attaching it.
1181     last_move_screen_loc_ = point_in_screen.x();
1182 
1183     // Register a new group if necessary, so that the insertion index in the
1184     // tab strip can be calculated based on the group membership of tabs.
1185     if (header_drag_) {
1186       attached_context_->GetTabStripModel()->group_model()->AddTabGroup(
1187           group_.value(),
1188           source_view_drag_data()->tab_group_data.value().group_visual_data);
1189     }
1190 
1191     // Figure out where to insert the tab based on the bounds of the dragged
1192     // representation and the ideal bounds of the other Tabs already in the
1193     // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
1194     // changing due to animation).
1195     gfx::Point tab_strip_point(point_in_screen);
1196     views::View::ConvertPointFromScreen(attached_context_->AsView(),
1197                                         &tab_strip_point);
1198     tab_strip_point.set_x(
1199         attached_context_->AsView()->GetMirroredXInView(tab_strip_point.x()));
1200     tab_strip_point.Offset(0, -mouse_offset_.y());
1201     int index = attached_context_->GetInsertionIndexForDraggedBounds(
1202         GetDraggedViewTabStripBounds(tab_strip_point), true,
1203         num_dragging_tabs(), mouse_has_ever_moved_left_,
1204         mouse_has_ever_moved_right_, group_);
1205     attach_index_ = index;
1206     attach_x_ = tab_strip_point.x();
1207 
1208     base::AutoReset<bool> setter(&is_mutating_, true);
1209     for (size_t i = first_tab_index(); i < drag_data_.size(); ++i) {
1210       int add_types = TabStripModel::ADD_NONE;
1211       if (attached_context_->GetActiveTouchIndex()) {
1212         // StackedTabStripLayout positions relative to the active tab, if we
1213         // don't add the tab as active things bounce around.
1214         DCHECK_EQ(1u, drag_data_.size());
1215         add_types |= TabStripModel::ADD_ACTIVE;
1216       }
1217       if (drag_data_[i].pinned)
1218         add_types |= TabStripModel::ADD_PINNED;
1219 
1220       // We should have owned_contents here, this CHECK is used to gather data
1221       // for https://crbug.com/677806.
1222       CHECK(drag_data_[i].owned_contents);
1223       attached_context_->GetTabStripModel()->InsertWebContentsAt(
1224           index + i - first_tab_index(),
1225           std::move(drag_data_[i].owned_contents), add_types, group_);
1226 
1227       // If a sad tab is showing, the SadTabView needs to be updated.
1228       SadTabHelper* sad_tab_helper =
1229           SadTabHelper::FromWebContents(drag_data_[i].contents);
1230       if (sad_tab_helper)
1231         sad_tab_helper->ReinstallInWebView();
1232     }
1233 
1234     views = GetViewsMatchingDraggedContents(attached_context_);
1235   }
1236   DCHECK_EQ(views.size(), drag_data_.size());
1237   for (size_t i = 0; i < drag_data_.size(); ++i) {
1238     drag_data_[i].attached_view = views[i];
1239     attached_views_.push_back(views[i]);
1240   }
1241 
1242   ResetSelection(attached_context_->GetTabStripModel());
1243 
1244   // This should be called after ResetSelection() in order to generate
1245   // bounds correctly. http://crbug.com/836004
1246   attached_context_->StartedDragging(views);
1247 
1248   // The size of the dragged tab may have changed. Adjust the x offset so that
1249   // ratio of mouse_offset_ to original width is maintained.
1250   std::vector<TabSlotView*> tabs_to_source(views);
1251   tabs_to_source.erase(tabs_to_source.begin() + source_view_index_ + 1,
1252                        tabs_to_source.end());
1253   int new_x = TabStrip::GetSizeNeededForViews(tabs_to_source) -
1254               views[source_view_index_]->width() +
1255               base::ClampRound(offset_to_width_ratio_ *
1256                                views[source_view_index_]->width());
1257   mouse_offset_.set_x(new_x);
1258 
1259   // Transfer ownership of us to the new tabstrip as well as making sure the
1260   // window has capture. This is important so that if activation changes the
1261   // drag isn't prematurely canceled.
1262   if (set_capture)
1263     SetCapture(attached_context_);
1264   attached_context_->OwnDragController(this);
1265   SetTabDraggingInfo();
1266   attached_context_tabs_closed_tracker_ =
1267       std::make_unique<DraggedTabsClosedTracker>(
1268           attached_context_->GetTabStripModel(), this);
1269 
1270   if (attach_index_ != -1 && !header_drag_)
1271     UpdateGroupForDraggedTabs();
1272 }
1273 
Detach(ReleaseCapture release_capture)1274 void TabDragController::Detach(ReleaseCapture release_capture) {
1275   TRACE_EVENT1("views", "TabDragController::Detach", "release_capture",
1276                release_capture);
1277 
1278   attached_context_tabs_closed_tracker_.reset();
1279 
1280   attach_index_ = -1;
1281 
1282   // When the user detaches we assume they want to reorder.
1283   move_behavior_ = REORDER;
1284 
1285   // Release ownership of the drag controller and mouse capture. When we
1286   // reattach ownership is transfered.
1287   attached_context_->ReleaseDragController();
1288   if (release_capture == RELEASE_CAPTURE)
1289     attached_context_->AsView()->GetWidget()->ReleaseCapture();
1290 
1291   mouse_has_ever_moved_left_ = true;
1292   mouse_has_ever_moved_right_ = true;
1293 
1294   TabStripModel* attached_model = attached_context_->GetTabStripModel();
1295 
1296   std::vector<TabRendererData> tab_data;
1297   for (size_t i = first_tab_index(); i < drag_data_.size(); ++i) {
1298     tab_data.push_back(static_cast<Tab*>(drag_data_[i].attached_view)->data());
1299     int index = attached_model->GetIndexOfWebContents(drag_data_[i].contents);
1300     DCHECK_NE(-1, index);
1301 
1302     // Hide the tab so that the user doesn't see it animate closed.
1303     drag_data_[i].attached_view->SetVisible(false);
1304     drag_data_[i].attached_view->set_detached();
1305     drag_data_[i].owned_contents = attached_model->DetachWebContentsAt(index);
1306 
1307     // Detaching may end up deleting the tab, drop references to it.
1308     drag_data_[i].attached_view = nullptr;
1309   }
1310   if (header_drag_)
1311     source_view_drag_data()->attached_view = nullptr;
1312 
1313   // If we've removed the last Tab from the TabDragContext, hide the
1314   // frame now.
1315   if (!attached_model->empty()) {
1316     if (!selection_model_before_attach_.empty() &&
1317         selection_model_before_attach_.active() >= 0 &&
1318         selection_model_before_attach_.active() < attached_model->count()) {
1319       // Restore the selection.
1320       attached_model->SetSelectionFromModel(selection_model_before_attach_);
1321     } else if (attached_context_ == source_context_ &&
1322                !initial_selection_model_.empty()) {
1323       RestoreInitialSelection();
1324     }
1325   }
1326 
1327   ClearTabDraggingInfo();
1328   attached_context_->DraggedTabsDetached();
1329   attached_context_ = nullptr;
1330   attached_views_.clear();
1331 }
1332 
DetachIntoNewBrowserAndRunMoveLoop(const gfx::Point & point_in_screen)1333 void TabDragController::DetachIntoNewBrowserAndRunMoveLoop(
1334     const gfx::Point& point_in_screen) {
1335   if (attached_context_->GetTabStripModel()->count() == num_dragging_tabs()) {
1336     // All the tabs in a browser are being dragged but all the tabs weren't
1337     // initially being dragged. For this to happen the user would have to
1338     // start dragging a set of tabs, the other tabs close, then detach.
1339     RunMoveLoop(GetWindowOffset(point_in_screen));
1340     return;
1341   }
1342 
1343   const int tab_area_width = attached_context_->GetTabDragAreaWidth();
1344   std::vector<gfx::Rect> drag_bounds =
1345       attached_context_->CalculateBoundsForDraggedViews(attached_views_);
1346   OffsetX(GetAttachedDragPoint(point_in_screen).x(), &drag_bounds);
1347 
1348   gfx::Vector2d drag_offset;
1349   Browser* browser = CreateBrowserForDrag(attached_context_, point_in_screen,
1350                                           &drag_offset, &drag_bounds);
1351 
1352   BrowserView* dragged_browser_view =
1353       BrowserView::GetBrowserViewForBrowser(browser);
1354   views::Widget* dragged_widget = dragged_browser_view->GetWidget();
1355 
1356 #if defined(USE_AURA)
1357   // Only Aura windows are gesture consumers.
1358   views::Widget* attached_widget = attached_context_->AsView()->GetWidget();
1359   // Unlike DragBrowserToNewTabStrip, this does not have to special-handle
1360   // IsUsingWindowServices(), since DesktopWIndowTreeHostMus takes care of it.
1361   attached_widget->GetGestureRecognizer()->TransferEventsTo(
1362       attached_widget->GetNativeView(), dragged_widget->GetNativeView(),
1363       ui::TransferTouchesBehavior::kDontCancel);
1364 #endif
1365 
1366 #if defined(OS_CHROMEOS)
1367   // On ChromeOS, Detach should release capture; |can_release_capture_| is
1368   // false on ChromeOS because it can cancel touches, but for this cases
1369   // the touches are already transferred, so releasing is fine. Without
1370   // releasing, the capture remains and further touch events can be sent to a
1371   // wrong target.
1372   Detach(RELEASE_CAPTURE);
1373 #else
1374   Detach(can_release_capture_ ? RELEASE_CAPTURE : DONT_RELEASE_CAPTURE);
1375 #endif
1376 
1377   dragged_widget->SetCanAppearInExistingFullscreenSpaces(true);
1378   dragged_widget->SetVisibilityChangedAnimationsEnabled(false);
1379   Attach(dragged_browser_view->tabstrip()->GetDragContext(), gfx::Point());
1380   AdjustBrowserAndTabBoundsForDrag(tab_area_width, point_in_screen,
1381                                    &drag_offset, &drag_bounds);
1382   browser->window()->Show();
1383   dragged_widget->SetVisibilityChangedAnimationsEnabled(true);
1384   // Activate may trigger a focus loss, destroying us.
1385   {
1386     base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
1387     browser->window()->Activate();
1388     if (!ref)
1389       return;
1390   }
1391   RunMoveLoop(drag_offset);
1392 }
1393 
RunMoveLoop(const gfx::Vector2d & drag_offset)1394 void TabDragController::RunMoveLoop(const gfx::Vector2d& drag_offset) {
1395   // If the user drags the whole window we'll assume they are going to attach to
1396   // another window and therefore want to reorder.
1397   move_behavior_ = REORDER;
1398 
1399   move_loop_widget_ = GetAttachedBrowserWidget();
1400   DCHECK(move_loop_widget_);
1401   widget_observer_.Add(move_loop_widget_);
1402   current_state_ = DragState::kDraggingWindow;
1403   base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
1404   if (can_release_capture_) {
1405     // Running the move loop releases mouse capture, which triggers destroying
1406     // the drag loop. Release mouse capture now while the DragController is not
1407     // owned by the TabDragContext.
1408     attached_context_->ReleaseDragController();
1409     attached_context_->AsView()->GetWidget()->ReleaseCapture();
1410     attached_context_->OwnDragController(this);
1411   }
1412   const views::Widget::MoveLoopSource move_loop_source =
1413       event_source_ == EVENT_SOURCE_MOUSE
1414           ? views::Widget::MoveLoopSource::kMouse
1415           : views::Widget::MoveLoopSource::kTouch;
1416   const views::Widget::MoveLoopEscapeBehavior escape_behavior =
1417       is_dragging_new_browser_
1418           ? views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE
1419           : views::Widget::MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE;
1420   views::Widget::MoveLoopResult result = move_loop_widget_->RunMoveLoop(
1421       drag_offset, move_loop_source, escape_behavior);
1422   content::NotificationService::current()->Notify(
1423       chrome::NOTIFICATION_TAB_DRAG_LOOP_DONE,
1424       content::NotificationService::AllBrowserContextsAndSources(),
1425       content::NotificationService::NoDetails());
1426 
1427   if (!ref)
1428     return;
1429 
1430   if (widget_observer_.IsObserving(move_loop_widget_))
1431     widget_observer_.Remove(move_loop_widget_);
1432   move_loop_widget_ = nullptr;
1433 
1434   if (current_state_ == DragState::kDraggingWindow) {
1435     current_state_ = DragState::kWaitingToStop;
1436   }
1437 
1438   if (current_state_ == DragState::kWaitingToDragTabs) {
1439     DCHECK(tab_strip_to_attach_to_after_exit_);
1440     gfx::Point point_in_screen(GetCursorScreenPoint());
1441     Detach(DONT_RELEASE_CAPTURE);
1442     Attach(tab_strip_to_attach_to_after_exit_, point_in_screen);
1443     current_state_ = DragState::kDraggingTabs;
1444     // Move the tabs into position.
1445     MoveAttached(point_in_screen);
1446     attached_context_->AsView()->GetWidget()->Activate();
1447     // Activate may trigger a focus loss, destroying us.
1448     if (!ref)
1449       return;
1450     tab_strip_to_attach_to_after_exit_ = nullptr;
1451   } else if (current_state_ == DragState::kWaitingToStop) {
1452     EndDrag(result == views::Widget::MOVE_LOOP_CANCELED ? END_DRAG_CANCEL
1453                                                         : END_DRAG_COMPLETE);
1454   }
1455 }
1456 
GetDraggedViewTabStripBounds(const gfx::Point & tab_strip_point)1457 gfx::Rect TabDragController::GetDraggedViewTabStripBounds(
1458     const gfx::Point& tab_strip_point) {
1459   // attached_view is null when inserting into a new context.
1460   // TODO(pkasting): This assumes there is just one tab being dragged, which is
1461   // wrong when dragging multiple tabs; need to check all of |drag_data_|.
1462   if (source_view_drag_data()->attached_view) {
1463     return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1464                      source_view_drag_data()->attached_view->width(),
1465                      source_view_drag_data()->attached_view->height());
1466   }
1467 
1468   return gfx::Rect(tab_strip_point.x(), tab_strip_point.y(),
1469                    attached_context_->GetActiveTabWidth(),
1470                    GetLayoutConstant(TAB_HEIGHT));
1471 }
1472 
GetAttachedDragPoint(const gfx::Point & point_in_screen)1473 gfx::Point TabDragController::GetAttachedDragPoint(
1474     const gfx::Point& point_in_screen) {
1475   DCHECK(attached_context_);  // The tab must be attached.
1476 
1477   gfx::Point tab_loc(point_in_screen);
1478   views::View::ConvertPointFromScreen(attached_context_->AsView(), &tab_loc);
1479   const int x = attached_context_->AsView()->GetMirroredXInView(tab_loc.x()) -
1480                 mouse_offset_.x();
1481 
1482   const int max_x = attached_context_->GetTabDragAreaWidth() -
1483                     TabStrip::GetSizeNeededForViews(attached_views_);
1484   return gfx::Point(base::ClampToRange(x, 0, max_x), 0);
1485 }
1486 
GetViewsMatchingDraggedContents(TabDragContext * context)1487 std::vector<TabSlotView*> TabDragController::GetViewsMatchingDraggedContents(
1488     TabDragContext* context) {
1489   TabStripModel* model = attached_context_->GetTabStripModel();
1490   std::vector<TabSlotView*> views;
1491   for (size_t i = first_tab_index(); i < drag_data_.size(); ++i) {
1492     int model_index = model->GetIndexOfWebContents(drag_data_[i].contents);
1493     if (model_index == TabStripModel::kNoTab)
1494       return std::vector<TabSlotView*>();
1495     views.push_back(context->GetTabAt(model_index));
1496   }
1497   if (header_drag_)
1498     views.insert(views.begin(), context->GetTabGroupHeader(group_.value()));
1499   return views;
1500 }
1501 
EndDragImpl(EndDragType type)1502 void TabDragController::EndDragImpl(EndDragType type) {
1503   DragState previous_state = current_state_;
1504   current_state_ = DragState::kStopped;
1505   attached_context_tabs_closed_tracker_.reset();
1506 
1507   bring_to_front_timer_.Stop();
1508   move_stacked_timer_.Stop();
1509 
1510   if (type != TAB_DESTROYED) {
1511     // We only finish up the drag if we were actually dragging. If start_drag_
1512     // is false, the user just clicked and released and didn't move the mouse
1513     // enough to trigger a drag.
1514     if (previous_state != DragState::kNotStarted) {
1515       // After the drag ends, sometimes it shouldn't restore the focus, because
1516       // - if |attached_context_| is showing in overview mode, overview mode
1517       //   may be ended unexpectly because of the window activation.
1518       // - Some dragging gesture (like fling down) minimizes the window, but the
1519       //   window activation cancels minimized status. See
1520       //   https://crbug.com/902897
1521       if (!IsShowingInOverview(attached_context_) &&
1522           !attached_context_->AsView()->GetWidget()->IsMinimized()) {
1523         RestoreFocus();
1524       }
1525 
1526       GetAttachedBrowserWidget()->SetCanAppearInExistingFullscreenSpaces(false);
1527       if (type == CANCELED)
1528         RevertDrag();
1529       else
1530         CompleteDrag();
1531     }
1532   } else if (drag_data_.size() > 1) {
1533     initial_selection_model_.Clear();
1534     if (previous_state != DragState::kNotStarted)
1535       RevertDrag();
1536   }  // else case the only tab we were dragging was deleted. Nothing to do.
1537 
1538   // Clear tab dragging info after the complete/revert as CompleteDrag() may
1539   // need to use some of the properties.
1540   ClearTabDraggingInfo();
1541 
1542   // Clear out drag data so we don't attempt to do anything with it.
1543   drag_data_.clear();
1544 
1545   TabDragContext* owning_context =
1546       attached_context_ ? attached_context_ : source_context_;
1547   owning_context->DestroyDragController();
1548 }
1549 
PerformDeferredAttach()1550 void TabDragController::PerformDeferredAttach() {
1551 #if defined(OS_CHROMEOS)
1552   TabDragContext* deferred_target_context =
1553       deferred_target_context_observer_->deferred_target_context();
1554   if (!deferred_target_context)
1555     return;
1556 
1557   DCHECK_NE(deferred_target_context, attached_context_);
1558 
1559   // |is_dragging_new_browser_| needs to be reset here since after this function
1560   // is called, the browser window that was specially created for the dragged
1561   // tab(s) will be destroyed.
1562   is_dragging_new_browser_ = false;
1563   // |did_restore_window_| is only set to be true if the dragged window is the
1564   // source window and the source window was maximized or fullscreen before the
1565   // drag starts. It also needs to be reset to false here otherwise after this
1566   // function is called, the newly attached window may be maximized unexpectedly
1567   // after the drag ends.
1568   did_restore_window_ = false;
1569 
1570   // GetCursorScreenPoint() needs to be called before Detach() is called as
1571   // GetCursorScreenPoint() may use the current attached tabstrip to get the
1572   // touch event position but Detach() sets attached tabstrip to nullptr.
1573   // On ChromeOS, the gesture state is already cleared and so
1574   // GetCursorScreenPoint() will fail to obtain the last touch location.
1575   // Therefore it uses the last remembered location instead.
1576   const gfx::Point current_screen_point = (event_source_ == EVENT_SOURCE_TOUCH)
1577                                               ? last_point_in_screen_
1578                                               : GetCursorScreenPoint();
1579   Detach(DONT_RELEASE_CAPTURE);
1580   // If we're attaching the dragged tabs to an overview window's tabstrip, the
1581   // tabstrip should not have focus.
1582   Attach(deferred_target_context, current_screen_point, /*set_capture=*/false);
1583 
1584   SetDeferredTargetTabstrip(nullptr);
1585   deferred_target_context_observer_.reset();
1586 #endif
1587 }
1588 
RevertDrag()1589 void TabDragController::RevertDrag() {
1590   std::vector<TabSlotView*> views;
1591   if (header_drag_)
1592     views.push_back(drag_data_[0].attached_view);
1593   for (size_t i = first_tab_index(); i < drag_data_.size(); ++i) {
1594     if (drag_data_[i].contents) {
1595       // Contents is NULL if a tab was destroyed while the drag was under way.
1596       views.push_back(drag_data_[i].attached_view);
1597       RevertDragAt(i);
1598     }
1599   }
1600 
1601   if (attached_context_) {
1602     if (did_restore_window_)
1603       MaximizeAttachedWindow();
1604     if (attached_context_ == source_context_) {
1605       source_context_->StoppedDragging(views, initial_tab_positions_,
1606                                        move_behavior_ == MOVE_VISIBLE_TABS,
1607                                        false);
1608       if (header_drag_)
1609         source_context_->GetTabStripModel()->MoveTabGroup(group_.value());
1610     } else {
1611       attached_context_->DraggedTabsDetached();
1612     }
1613   }
1614 
1615   if (initial_selection_model_.empty())
1616     ResetSelection(source_context_->GetTabStripModel());
1617   else
1618     source_context_->GetTabStripModel()->SetSelectionFromModel(
1619         initial_selection_model_);
1620 
1621   if (source_context_)
1622     source_context_->AsView()->GetWidget()->Activate();
1623 }
1624 
ResetSelection(TabStripModel * model)1625 void TabDragController::ResetSelection(TabStripModel* model) {
1626   DCHECK(model);
1627   ui::ListSelectionModel selection_model;
1628   bool has_one_valid_tab = false;
1629   for (size_t i = 0; i < drag_data_.size(); ++i) {
1630     // |contents| is NULL if a tab was deleted out from under us.
1631     if (drag_data_[i].contents) {
1632       int index = model->GetIndexOfWebContents(drag_data_[i].contents);
1633       DCHECK_NE(-1, index);
1634       selection_model.AddIndexToSelection(index);
1635       if (!has_one_valid_tab || i == source_view_index_) {
1636         // Reset the active/lead to the first tab. If the source tab is still
1637         // valid we'll reset these again later on.
1638         selection_model.set_active(index);
1639         selection_model.set_anchor(index);
1640         has_one_valid_tab = true;
1641       }
1642     }
1643   }
1644   if (!has_one_valid_tab)
1645     return;
1646 
1647   model->SetSelectionFromModel(selection_model);
1648 }
1649 
RestoreInitialSelection()1650 void TabDragController::RestoreInitialSelection() {
1651   // First time detaching from the source tabstrip. Reset selection model to
1652   // initial_selection_model_. Before resetting though we have to remove all
1653   // the tabs from initial_selection_model_ as it was created with the tabs
1654   // still there.
1655   ui::ListSelectionModel selection_model = initial_selection_model_;
1656   for (DragData::const_reverse_iterator i(drag_data_.rbegin());
1657        i != drag_data_.rend(); ++i) {
1658     if (i->source_model_index != TabStripModel::kNoTab)
1659       selection_model.DecrementFrom(i->source_model_index);
1660   }
1661   // We may have cleared out the selection model. Only reset it if it
1662   // contains something.
1663   if (selection_model.empty())
1664     return;
1665 
1666   // The anchor/active may have been among the tabs that were dragged out. Force
1667   // the anchor/active to be valid.
1668   if (selection_model.anchor() == ui::ListSelectionModel::kUnselectedIndex)
1669     selection_model.set_anchor(selection_model.selected_indices()[0]);
1670   if (selection_model.active() == ui::ListSelectionModel::kUnselectedIndex)
1671     selection_model.set_active(selection_model.selected_indices()[0]);
1672   source_context_->GetTabStripModel()->SetSelectionFromModel(selection_model);
1673 }
1674 
RevertDragAt(size_t drag_index)1675 void TabDragController::RevertDragAt(size_t drag_index) {
1676   DCHECK_NE(current_state_, DragState::kNotStarted);
1677   DCHECK(source_context_);
1678 
1679   base::AutoReset<bool> setter(&is_mutating_, true);
1680   TabDragData* data = &(drag_data_[drag_index]);
1681   int target_index = data->source_model_index;
1682   if (attached_context_) {
1683     int index = attached_context_->GetTabStripModel()->GetIndexOfWebContents(
1684         data->contents);
1685     if (attached_context_ != source_context_) {
1686       // The Tab was inserted into another TabDragContext. We need to
1687       // put it back into the original one.
1688       std::unique_ptr<content::WebContents> detached_web_contents =
1689           attached_context_->GetTabStripModel()->DetachWebContentsAt(index);
1690       // TODO(beng): (Cleanup) seems like we should use Attach() for this
1691       //             somehow.
1692       source_context_->GetTabStripModel()->InsertWebContentsAt(
1693           target_index, std::move(detached_web_contents),
1694           (data->pinned ? TabStripModel::ADD_PINNED : 0));
1695     } else {
1696       // The Tab was moved within the TabDragContext where the drag
1697       // was initiated. Move it back to the starting location.
1698 
1699       // If the target index is to the right, then other unreverted tabs are
1700       // occupying indices between this tab and the target index. Those
1701       // unreverted tabs will later be reverted to the right of the target
1702       // index, so we skip those indices.
1703       if (target_index > index) {
1704         for (size_t i = drag_index + 1; i < drag_data_.size(); ++i) {
1705           if (drag_data_[i].contents)
1706             ++target_index;
1707         }
1708       }
1709       target_index = source_context_->GetTabStripModel()->MoveWebContentsAt(
1710           index, target_index, false);
1711     }
1712   } else {
1713     // The Tab was detached from the TabDragContext where the drag
1714     // began, and has not been attached to any other TabDragContext.
1715     // We need to put it back into the source TabDragContext.
1716     source_context_->GetTabStripModel()->InsertWebContentsAt(
1717         target_index, std::move(data->owned_contents),
1718         (data->pinned ? TabStripModel::ADD_PINNED : 0));
1719   }
1720   source_context_->GetTabStripModel()->UpdateGroupForDragRevert(
1721       target_index,
1722       data->tab_group_data.has_value()
1723           ? base::Optional<tab_groups::TabGroupId>{data->tab_group_data.value()
1724                                                        .group_id}
1725           : base::nullopt,
1726       data->tab_group_data.has_value()
1727           ? base::Optional<
1728                 tab_groups::TabGroupVisualData>{data->tab_group_data.value()
1729                                                     .group_visual_data}
1730           : base::nullopt);
1731 }
1732 
CompleteDrag()1733 void TabDragController::CompleteDrag() {
1734   DCHECK_NE(current_state_, DragState::kNotStarted);
1735 
1736   if (attached_context_) {
1737     if (is_dragging_new_browser_ || did_restore_window_) {
1738       if (IsSnapped(attached_context_)) {
1739         was_source_maximized_ = false;
1740         was_source_fullscreen_ = false;
1741       }
1742 
1743       // If source window was maximized - maximize the new window as well.
1744       if (was_source_maximized_ || was_source_fullscreen_)
1745         MaximizeAttachedWindow();
1746     }
1747     attached_context_->StoppedDragging(
1748         GetViewsMatchingDraggedContents(attached_context_),
1749         initial_tab_positions_, move_behavior_ == MOVE_VISIBLE_TABS, true);
1750   } else {
1751     // Compel the model to construct a new window for the detached
1752     // WebContentses.
1753     views::Widget* widget = source_context_->AsView()->GetWidget();
1754     gfx::Rect window_bounds(widget->GetRestoredBounds());
1755     window_bounds.set_origin(GetWindowCreatePoint(last_point_in_screen_));
1756 
1757     base::AutoReset<bool> setter(&is_mutating_, true);
1758 
1759     std::vector<TabStripModelDelegate::NewStripContents> contentses;
1760     for (size_t i = 0; i < drag_data_.size(); ++i) {
1761       TabStripModelDelegate::NewStripContents item;
1762       // We should have owned_contents here, this CHECK is used to gather data
1763       // for https://crbug.com/677806.
1764       CHECK(drag_data_[i].owned_contents);
1765       item.web_contents = std::move(drag_data_[i].owned_contents);
1766       item.add_types = drag_data_[i].pinned ? TabStripModel::ADD_PINNED
1767                                             : TabStripModel::ADD_NONE;
1768       contentses.push_back(std::move(item));
1769     }
1770 
1771     Browser* new_browser =
1772         source_context_->GetTabStripModel()
1773             ->delegate()
1774             ->CreateNewStripWithContents(std::move(contentses), window_bounds,
1775                                          widget->IsMaximized());
1776     ResetSelection(new_browser->tab_strip_model());
1777     new_browser->window()->Show();
1778   }
1779 
1780   if (header_drag_) {
1781     // Manually reset the selection to just the active tab in the group.
1782     // Otherwise, it's easy to accidentally delete the fully-selected group
1783     // by dragging on any of its still-selected members.
1784     TabStripModel* model = attached_context_
1785                                ? attached_context_->GetTabStripModel()
1786                                : source_context_->GetTabStripModel();
1787     ui::ListSelectionModel selection;
1788     int index = model->GetIndexOfWebContents(drag_data_[1].contents);
1789     DCHECK_NE(-1, index);
1790     selection.AddIndexToSelection(index);
1791     selection.set_active(index);
1792     selection.set_anchor(index);
1793     model->SetSelectionFromModel(selection);
1794   }
1795 }
1796 
MaximizeAttachedWindow()1797 void TabDragController::MaximizeAttachedWindow() {
1798   GetAttachedBrowserWidget()->Maximize();
1799 #if defined(OS_MAC)
1800   if (was_source_fullscreen_)
1801     GetAttachedBrowserWidget()->SetFullscreen(true);
1802 #endif
1803 #if defined(OS_CHROMEOS)
1804   if (was_source_fullscreen_) {
1805     // In fullscreen mode it is only possible to get here if the source
1806     // was in "immersive fullscreen" mode, so toggle it back on.
1807     BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow(
1808         GetAttachedBrowserWidget()->GetNativeWindow());
1809     DCHECK(browser_view);
1810     if (!browser_view->IsFullscreen())
1811       chrome::ToggleFullscreenMode(browser_view->browser());
1812   }
1813 #endif
1814 }
1815 
BringWindowUnderPointToFront(const gfx::Point & point_in_screen)1816 void TabDragController::BringWindowUnderPointToFront(
1817     const gfx::Point& point_in_screen) {
1818   gfx::NativeWindow window;
1819   if (GetLocalProcessWindow(point_in_screen, true, &window) ==
1820       Liveness::DELETED) {
1821     return;
1822   }
1823 
1824   // Only bring browser windows to front - only windows with a
1825   // TabDragContext can be tab drag targets.
1826   if (!CanAttachTo(window))
1827     return;
1828 
1829   if (window) {
1830     views::Widget* widget_window =
1831         views::Widget::GetWidgetForNativeWindow(window);
1832     if (!widget_window)
1833       return;
1834 
1835 #if defined(OS_CHROMEOS)
1836     // TODO(varkha): The code below ensures that the phantom drag widget
1837     // is shown on top of browser windows. The code should be moved to ash/
1838     // and the phantom should be able to assert its top-most state on its own.
1839     // One strategy would be for DragWindowController to
1840     // be able to observe stacking changes to the phantom drag widget's
1841     // siblings in order to keep it on top. One way is to implement a
1842     // notification that is sent to a window parent's observers when a
1843     // stacking order is changed among the children of that same parent.
1844     // Note that OnWindowStackingChanged is sent only to the child that is the
1845     // argument of one of the Window::StackChildX calls and not to all its
1846     // siblings affected by the stacking change.
1847     aura::Window* browser_window = widget_window->GetNativeView();
1848     // Find a topmost non-popup window and stack the recipient browser above
1849     // it in order to avoid stacking the browser window on top of the phantom
1850     // drag widget created by DragWindowController in a second display.
1851     for (aura::Window::Windows::const_reverse_iterator it =
1852              browser_window->parent()->children().rbegin();
1853          it != browser_window->parent()->children().rend(); ++it) {
1854       // If the iteration reached the recipient browser window then it is
1855       // already topmost and it is safe to return with no stacking change.
1856       if (*it == browser_window)
1857         return;
1858       if ((*it)->type() != aura::client::WINDOW_TYPE_POPUP) {
1859         widget_window->StackAbove(*it);
1860         break;
1861       }
1862     }
1863 #else
1864     widget_window->StackAtTop();
1865 #endif
1866 
1867     // The previous call made the window appear on top of the dragged window,
1868     // move the dragged window to the front.
1869     if (current_state_ == DragState::kDraggingWindow)
1870       attached_context_->AsView()->GetWidget()->StackAtTop();
1871   }
1872 }
1873 
GetAttachedBrowserWidget()1874 views::Widget* TabDragController::GetAttachedBrowserWidget() {
1875   return attached_context_->AsView()->GetWidget();
1876 }
1877 
AreTabsConsecutive()1878 bool TabDragController::AreTabsConsecutive() {
1879   for (size_t i = 1; i < drag_data_.size(); ++i) {
1880     if (drag_data_[i - 1].source_model_index + 1 !=
1881         drag_data_[i].source_model_index) {
1882       return false;
1883     }
1884   }
1885   return true;
1886 }
1887 
CalculateDraggedBrowserBounds(TabDragContext * source,const gfx::Point & point_in_screen,std::vector<gfx::Rect> * drag_bounds)1888 gfx::Rect TabDragController::CalculateDraggedBrowserBounds(
1889     TabDragContext* source,
1890     const gfx::Point& point_in_screen,
1891     std::vector<gfx::Rect>* drag_bounds) {
1892   gfx::Point center(0, source->AsView()->height() / 2);
1893   views::View::ConvertPointToWidget(source->AsView(), &center);
1894   gfx::Rect new_bounds(source->AsView()->GetWidget()->GetRestoredBounds());
1895 
1896   gfx::Rect work_area = display::Screen::GetScreen()
1897                             ->GetDisplayNearestPoint(last_point_in_screen_)
1898                             .work_area();
1899   if (new_bounds.size().width() >= work_area.size().width() &&
1900       new_bounds.size().height() >= work_area.size().height()) {
1901     new_bounds = work_area;
1902     new_bounds.Inset(kMaximizedWindowInset, kMaximizedWindowInset,
1903                      kMaximizedWindowInset, kMaximizedWindowInset);
1904     // Behave as if the |source| was maximized at the start of a drag since this
1905     // is consistent with a browser window creation logic in case of windows
1906     // that are as large as the |work_area|.
1907     was_source_maximized_ = true;
1908   }
1909 
1910   if (source->AsView()->GetWidget()->IsMaximized()) {
1911     // If the restore bounds is really small, we don't want to honor it
1912     // (dragging a really small window looks wrong), instead make sure the new
1913     // window is at least 50% the size of the old.
1914     const gfx::Size max_size(
1915         source->AsView()->GetWidget()->GetWindowBoundsInScreen().size());
1916     new_bounds.set_width(std::max(max_size.width() / 2, new_bounds.width()));
1917     new_bounds.set_height(std::max(max_size.height() / 2, new_bounds.height()));
1918   }
1919 
1920 #if defined(OS_CHROMEOS)
1921   if (ash::TabletMode::Get()->InTabletMode()) {
1922     new_bounds = GetDraggedBrowserBoundsInTabletMode(
1923         source->AsView()->GetWidget()->GetNativeWindow());
1924   }
1925 #endif
1926 
1927   new_bounds.set_y(point_in_screen.y() - center.y());
1928   switch (GetDetachPosition(point_in_screen)) {
1929     case DETACH_BEFORE:
1930       new_bounds.set_x(point_in_screen.x() - center.x());
1931       new_bounds.Offset(-mouse_offset_.x(), 0);
1932       break;
1933     case DETACH_AFTER: {
1934       gfx::Point right_edge(source->AsView()->width(), 0);
1935       views::View::ConvertPointToWidget(source->AsView(), &right_edge);
1936       new_bounds.set_x(point_in_screen.x() - right_edge.x());
1937       new_bounds.Offset(drag_bounds->back().right() - mouse_offset_.x(), 0);
1938       OffsetX(-drag_bounds->front().x(), drag_bounds);
1939       break;
1940     }
1941     default:
1942       break;  // Nothing to do for DETACH_ABOVE_OR_BELOW.
1943   }
1944 
1945   // Account for the extra space above the tabstrip on restored windows versus
1946   // maximized windows.
1947   if (source->AsView()->GetWidget()->IsMaximized()) {
1948     const auto* frame_view = static_cast<BrowserNonClientFrameView*>(
1949         source->AsView()->GetWidget()->non_client_view()->frame_view());
1950     new_bounds.Offset(
1951         0, frame_view->GetTopInset(false) - frame_view->GetTopInset(true));
1952   }
1953   return new_bounds;
1954 }
1955 
CalculateNonMaximizedDraggedBrowserBounds(views::Widget * widget,const gfx::Point & point_in_screen)1956 gfx::Rect TabDragController::CalculateNonMaximizedDraggedBrowserBounds(
1957     views::Widget* widget,
1958     const gfx::Point& point_in_screen) {
1959   gfx::Rect bounds = widget->GetWindowBoundsInScreen();
1960 #if defined(OS_CHROMEOS)
1961   if (ash::TabletMode::Get()->InTabletMode())
1962     bounds = GetDraggedBrowserBoundsInTabletMode(widget->GetNativeWindow());
1963 #endif
1964 
1965   // The user has to move the mouse some amount of pixels before the drag
1966   // starts. Offset the window by this amount so that the relative offset
1967   // of the initial location is consistent. See https://crbug.com/518740
1968   bounds.Offset(point_in_screen.x() - start_point_in_screen_.x(),
1969                 point_in_screen.y() - start_point_in_screen_.y());
1970   return bounds;
1971 }
1972 
AdjustBrowserAndTabBoundsForDrag(int tab_area_width,const gfx::Point & point_in_screen,gfx::Vector2d * drag_offset,std::vector<gfx::Rect> * drag_bounds)1973 void TabDragController::AdjustBrowserAndTabBoundsForDrag(
1974     int tab_area_width,
1975     const gfx::Point& point_in_screen,
1976     gfx::Vector2d* drag_offset,
1977     std::vector<gfx::Rect>* drag_bounds) {
1978   attached_context_->ForceLayout();
1979   const int dragged_context_width = attached_context_->GetTabDragAreaWidth();
1980 
1981   // If the new tabstrip region is smaller than the old, resize the tabs.
1982   if (dragged_context_width < tab_area_width) {
1983     const float leading_ratio =
1984         drag_bounds->front().x() / float{tab_area_width};
1985     *drag_bounds =
1986         attached_context_->CalculateBoundsForDraggedViews(attached_views_);
1987 
1988     if (drag_bounds->back().right() < dragged_context_width) {
1989       const int delta_x = std::min(
1990           int{(leading_ratio * dragged_context_width)},
1991           dragged_context_width -
1992               (drag_bounds->back().right() - drag_bounds->front().x()));
1993       OffsetX(delta_x, drag_bounds);
1994     }
1995 
1996     // Reposition the restored window such that the tab that was dragged remains
1997     // under the mouse cursor.
1998     gfx::Rect tab_bounds = (*drag_bounds)[source_view_index_];
1999     gfx::Point offset(
2000         base::ClampRound(tab_bounds.width() * offset_to_width_ratio_) +
2001             tab_bounds.x(),
2002         0);
2003     views::View::ConvertPointToWidget(attached_context_->AsView(), &offset);
2004     gfx::Rect bounds = GetAttachedBrowserWidget()->GetWindowBoundsInScreen();
2005     bounds.set_x(point_in_screen.x() - offset.x());
2006     GetAttachedBrowserWidget()->SetBounds(bounds);
2007     *drag_offset = point_in_screen - bounds.origin();
2008   }
2009   attached_context_->SetBoundsForDrag(attached_views_, *drag_bounds);
2010 }
2011 
CreateBrowserForDrag(TabDragContext * source,const gfx::Point & point_in_screen,gfx::Vector2d * drag_offset,std::vector<gfx::Rect> * drag_bounds)2012 Browser* TabDragController::CreateBrowserForDrag(
2013     TabDragContext* source,
2014     const gfx::Point& point_in_screen,
2015     gfx::Vector2d* drag_offset,
2016     std::vector<gfx::Rect>* drag_bounds) {
2017   gfx::Rect new_bounds(
2018       CalculateDraggedBrowserBounds(source, point_in_screen, drag_bounds));
2019   *drag_offset = point_in_screen - new_bounds.origin();
2020 
2021   Browser::CreateParams create_params =
2022       BrowserView::GetBrowserViewForNativeWindow(
2023           GetAttachedBrowserWidget()->GetNativeWindow())
2024           ->browser()
2025           ->create_params();
2026   create_params.user_gesture = true;
2027   create_params.in_tab_dragging = true;
2028   create_params.initial_bounds = new_bounds;
2029   // Do not copy attached window's show state as the attached window might be a
2030   // maximized or fullscreen window and we do not want the newly created browser
2031   // window is a maximized or fullscreen window since it will prevent window
2032   // moving/resizing on Chrome OS. See crbug.com/1023871 for details.
2033   create_params.initial_show_state = ui::SHOW_STATE_DEFAULT;
2034   // Don't copy the initial workspace since the *current* workspace might be
2035   // different and copying the workspace will move the tab to the initial one.
2036   create_params.initial_workspace = "";
2037   Browser* browser = Browser::Create(create_params);
2038   is_dragging_new_browser_ = true;
2039   // If the window is created maximized then the bounds we supplied are ignored.
2040   // We need to reset them again so they are honored.
2041   browser->window()->SetBounds(new_bounds);
2042 
2043   return browser;
2044 }
2045 
GetCursorScreenPoint()2046 gfx::Point TabDragController::GetCursorScreenPoint() {
2047 #if defined(OS_CHROMEOS)
2048   if (event_source_ == EVENT_SOURCE_TOUCH &&
2049       aura::Env::GetInstance()->is_touch_down()) {
2050     views::Widget* widget = GetAttachedBrowserWidget();
2051     DCHECK(widget);
2052     aura::Window* widget_window = widget->GetNativeWindow();
2053     DCHECK(widget_window->GetRootWindow());
2054     gfx::PointF touch_point_f;
2055     bool got_touch_point =
2056         widget->GetGestureRecognizer()->GetLastTouchPointForTarget(
2057             widget_window, &touch_point_f);
2058     CHECK(got_touch_point);
2059     gfx::Point touch_point = gfx::ToFlooredPoint(touch_point_f);
2060     wm::ConvertPointToScreen(widget_window->GetRootWindow(), &touch_point);
2061     return touch_point;
2062   }
2063 #endif
2064 
2065   return display::Screen::GetScreen()->GetCursorScreenPoint();
2066 }
2067 
GetWindowOffset(const gfx::Point & point_in_screen)2068 gfx::Vector2d TabDragController::GetWindowOffset(
2069     const gfx::Point& point_in_screen) {
2070   TabDragContext* owning_context =
2071       attached_context_ ? attached_context_ : source_context_;
2072   views::View* toplevel_view =
2073       owning_context->AsView()->GetWidget()->GetContentsView();
2074 
2075   gfx::Point point = point_in_screen;
2076   views::View::ConvertPointFromScreen(toplevel_view, &point);
2077   return point.OffsetFromOrigin();
2078 }
2079 
GetLocalProcessWindow(const gfx::Point & screen_point,bool exclude_dragged_view,gfx::NativeWindow * window)2080 TabDragController::Liveness TabDragController::GetLocalProcessWindow(
2081     const gfx::Point& screen_point,
2082     bool exclude_dragged_view,
2083     gfx::NativeWindow* window) {
2084   std::set<gfx::NativeWindow> exclude;
2085   if (exclude_dragged_view) {
2086     gfx::NativeWindow dragged_window =
2087         attached_context_->AsView()->GetWidget()->GetNativeWindow();
2088     if (dragged_window)
2089       exclude.insert(dragged_window);
2090   }
2091 #if (defined(OS_LINUX) && !defined(OS_CHROMEOS)) || defined(OS_BSD)
2092   // Exclude windows which are pending deletion via Browser::TabStripEmpty().
2093   // These windows can be returned in the Linux Aura port because the browser
2094   // window which was used for dragging is not hidden once all of its tabs are
2095   // attached to another browser window in DragBrowserToNewTabStrip().
2096   // TODO(pkotwicz): Fix this properly (crbug.com/358482)
2097   for (auto* browser : *BrowserList::GetInstance()) {
2098     if (browser->tab_strip_model()->empty())
2099       exclude.insert(browser->window()->GetNativeWindow());
2100   }
2101 #endif
2102   base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
2103   *window = window_finder_->GetLocalProcessWindowAtPoint(screen_point, exclude);
2104   return ref ? Liveness::ALIVE : Liveness::DELETED;
2105 }
2106 
SetTabDraggingInfo()2107 void TabDragController::SetTabDraggingInfo() {
2108 #if defined(OS_CHROMEOS)
2109   TabDragContext* dragged_context =
2110       attached_context_ ? attached_context_ : source_context_;
2111   DCHECK(dragged_context->IsDragSessionActive() &&
2112          current_state_ != DragState::kStopped);
2113 
2114   aura::Window* dragged_window =
2115       GetWindowForTabDraggingProperties(dragged_context);
2116   aura::Window* source_window =
2117       GetWindowForTabDraggingProperties(source_context_);
2118   dragged_window->SetProperty(ash::kIsDraggingTabsKey, true);
2119   if (source_window != dragged_window) {
2120     dragged_window->SetProperty(ash::kTabDraggingSourceWindowKey,
2121                                 source_window);
2122   }
2123 #endif
2124 }
2125 
ClearTabDraggingInfo()2126 void TabDragController::ClearTabDraggingInfo() {
2127 #if defined(OS_CHROMEOS)
2128   TabDragContext* dragged_context =
2129       attached_context_ ? attached_context_ : source_context_;
2130   DCHECK(!dragged_context->IsDragSessionActive() ||
2131          current_state_ == DragState::kStopped);
2132   // Do not clear the dragging info properties for a to-be-destroyed window.
2133   // They will be cleared later in Window's destructor. It's intentional as
2134   // ash::SplitViewController::TabDraggedWindowObserver listens to both
2135   // OnWindowDestroying() event and the window properties change event, and uses
2136   // the two events to decide what to do next.
2137   if (dragged_context->GetTabStripModel()->empty())
2138     return;
2139 
2140   aura::Window* dragged_window =
2141       GetWindowForTabDraggingProperties(dragged_context);
2142   dragged_window->ClearProperty(ash::kIsDraggingTabsKey);
2143   dragged_window->ClearProperty(ash::kTabDraggingSourceWindowKey);
2144 #endif
2145 }
2146 
UpdateGroupForDraggedTabs()2147 void TabDragController::UpdateGroupForDraggedTabs() {
2148   TabStripModel* attached_model = attached_context_->GetTabStripModel();
2149 
2150   const ui::ListSelectionModel::SelectedIndices& selected =
2151       attached_model->selection_model().selected_indices();
2152 
2153   // Pinned tabs cannot be grouped, so we only change the group membership of
2154   // unpinned tabs.
2155   std::vector<int> selected_unpinned;
2156   for (const int& selected_index : selected) {
2157     if (!attached_model->IsTabPinned(selected_index))
2158       selected_unpinned.push_back(selected_index);
2159   }
2160 
2161   if (selected_unpinned.empty())
2162     return;
2163 
2164   const base::Optional<tab_groups::TabGroupId> updated_group =
2165       GetTabGroupForTargetIndex(selected_unpinned);
2166 
2167   if (updated_group == attached_model->GetTabGroupForTab(selected_unpinned[0]))
2168     return;
2169 
2170   attached_model->MoveTabsAndSetGroup(selected_unpinned, selected_unpinned[0],
2171                                       updated_group);
2172 }
2173 
2174 base::Optional<tab_groups::TabGroupId>
GetTabGroupForTargetIndex(const std::vector<int> & selected)2175 TabDragController::GetTabGroupForTargetIndex(const std::vector<int>& selected) {
2176   // Indices in {selected} are always ordered in ascending order and should all
2177   // be consecutive.
2178   DCHECK_EQ(selected.back() - selected.front() + 1, int{selected.size()});
2179   const TabStripModel* attached_model = attached_context_->GetTabStripModel();
2180 
2181   const int left_tab_index = selected.front() - 1;
2182 
2183   const base::Optional<tab_groups::TabGroupId> left_group =
2184       attached_model->GetTabGroupForTab(left_tab_index);
2185   const base::Optional<tab_groups::TabGroupId> right_group =
2186       attached_model->GetTabGroupForTab(selected.back() + 1);
2187   const base::Optional<tab_groups::TabGroupId> current_group =
2188       attached_model->GetTabGroupForTab(selected[0]);
2189 
2190   if (left_group == right_group)
2191     return left_group;
2192 
2193   // If the tabs on the left and right have different group memberships,
2194   // including if one is ungrouped or nonexistent, change the group of the
2195   // dragged tab based on whether it is "leaning" toward the left or the
2196   // right of the gap. If the tab is centered in the gap, make the tab
2197   // ungrouped.
2198 
2199   const Tab* left_most_selected_tab =
2200       attached_context_->GetTabAt(selected.front());
2201 
2202   const int buffer = left_most_selected_tab->width() / 4;
2203 
2204   // The tab's bounds are larger than what visually appears in order to include
2205   // space for the rounded feet. Adding {tab_left_inset} to the horiztonal
2206   // bounds of the tab results in the x position that would be drawn when there
2207   // are no feet showing.
2208   const int tab_left_inset = TabStyle::GetTabOverlap() / 2;
2209 
2210   // Use the left edge for a reliable fallback, e.g. if this is the leftmost
2211   // tab or there is a group header to the immediate left.
2212   int left_edge =
2213       attached_model->ContainsIndex(left_tab_index)
2214           ? attached_context_->GetTabAt(left_tab_index)->bounds().right() -
2215                 tab_left_inset
2216           : tab_left_inset;
2217 
2218   // Extra polish: Prefer staying in an existing group, if any. This prevents
2219   // tabs at the edge of the group from flickering between grouped and
2220   // ungrouped. It also gives groups a slightly "sticky" feel while dragging.
2221   if (left_group.has_value() && left_group == current_group)
2222     left_edge += buffer;
2223   if (right_group.has_value() && right_group == current_group &&
2224       left_edge > tab_left_inset) {
2225     left_edge -= buffer;
2226   }
2227 
2228   int left_most_selected_x_position =
2229       left_most_selected_tab->x() + tab_left_inset;
2230 
2231   if ((left_most_selected_x_position <= left_edge - buffer) &&
2232       left_group.has_value() &&
2233       !attached_model->IsGroupCollapsed(left_group.value())) {
2234     return left_group;
2235   }
2236   if ((left_most_selected_x_position >= left_edge + buffer) &&
2237       right_group.has_value() &&
2238       !attached_model->IsGroupCollapsed(right_group.value())) {
2239     return right_group;
2240   }
2241   return base::nullopt;
2242 }
2243 
CanAttachTo(gfx::NativeWindow window)2244 bool TabDragController::CanAttachTo(gfx::NativeWindow window) {
2245   if (!window)
2246     return false;
2247 
2248   BrowserView* other_browser_view =
2249       BrowserView::GetBrowserViewForNativeWindow(window);
2250   if (!other_browser_view)
2251     return false;
2252   Browser* other_browser = other_browser_view->browser();
2253 
2254   // Do not allow dragging into a window with a modal dialog, it causes a
2255   // weird behavior.  See crbug.com/336691
2256 #if defined(USE_AURA)
2257   if (wm::GetModalTransient(window))
2258     return false;
2259 #else
2260   TabStripModel* model = other_browser->tab_strip_model();
2261   DCHECK(model);
2262   if (model->IsTabBlocked(model->active_index()))
2263     return false;
2264 #endif
2265 
2266   // We don't allow drops on windows that don't have tabstrips.
2267   if (!other_browser->SupportsWindowFeature(Browser::FEATURE_TABSTRIP))
2268     return false;
2269 
2270   Browser* browser = BrowserView::GetBrowserViewForNativeWindow(
2271                          GetAttachedBrowserWidget()->GetNativeWindow())
2272                          ->browser();
2273 
2274   // Profiles must be the same.
2275   if (other_browser->profile() != browser->profile())
2276     return false;
2277 
2278   // Ensure that browser types and app names are the same.
2279   if (other_browser->type() != browser->type() ||
2280       (browser->is_type_app() &&
2281        browser->app_name() != other_browser->app_name())) {
2282     return false;
2283   }
2284 
2285   return true;
2286 }
2287 
SetDeferredTargetTabstrip(TabDragContext * deferred_target_context)2288 void TabDragController::SetDeferredTargetTabstrip(
2289     TabDragContext* deferred_target_context) {
2290 #if defined(OS_CHROMEOS)
2291   if (!deferred_target_context_observer_) {
2292     deferred_target_context_observer_ =
2293         std::make_unique<DeferredTargetTabstripObserver>();
2294   }
2295   deferred_target_context_observer_->SetDeferredTargetTabstrip(
2296       deferred_target_context);
2297 #endif
2298 }
2299