-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathtab_drag_controller.cc
2317 lines (2033 loc) · 90.2 KB
/
tab_drag_controller.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tabs/tab_drag_controller.h"
#include <algorithm>
#include <limits>
#include <set>
#include <utility>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/containers/contains.h"
#include "base/i18n/rtl.h"
#include "base/numerics/ranges.h"
#include "base/numerics/safe_conversions.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/layout_constants.h"
#include "chrome/browser/ui/sad_tab_helper.h"
#include "chrome/browser/ui/tabs/tab_group.h"
#include "chrome/browser/ui/tabs/tab_group_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/tabs/tab_strip_model_delegate.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/frame/browser_non_client_frame_view.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_slot_view.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/browser/ui/views/tabs/tab_strip_layout_helper.h"
#include "chrome/browser/ui/views/tabs/tab_style_views.h"
#include "chrome/browser/ui/views/tabs/window_finder.h"
#include "components/tab_groups/tab_group_id.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/views/event_monitor.h"
#include "ui/views/view_tracker.h"
#include "ui/views/widget/root_view.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "ash/public/cpp/ash_features.h"
#include "ash/public/cpp/tablet_mode.h"
#include "ash/public/cpp/window_properties.h" // nogncheck
#include "chromeos/ui/base/window_properties.h"
#include "chromeos/ui/base/window_state_type.h" // nogncheck
#include "ui/aura/window_delegate.h"
#include "ui/wm/core/coordinate_conversion.h"
#endif
#if defined(USE_AURA)
#include "ui/aura/env.h" // nogncheck
#include "ui/aura/window.h" // nogncheck
#include "ui/wm/core/window_modality_controller.h" // nogncheck
#endif
using content::OpenURLParams;
using content::WebContents;
// If non-null there is a drag underway.
static TabDragController* g_tab_drag_controller = nullptr;
namespace {
// Initial delay before moving tabs when the dragged tab is close to the edge of
// the stacked tabs.
constexpr auto kMoveAttachedInitialDelay =
base::TimeDelta::FromMilliseconds(600);
// Delay for moving tabs after the initial delay has passed.
constexpr auto kMoveAttachedSubsequentDelay =
base::TimeDelta::FromMilliseconds(300);
// A dragged window is forced to be a bit smaller than maximized bounds during a
// drag. This prevents the dragged browser widget from getting maximized at
// creation and makes it easier to drag tabs out of a restored window that had
// maximized size.
constexpr int kMaximizedWindowInset = 10; // DIPs.
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Returns the aura::Window which stores the window properties for tab-dragging.
aura::Window* GetWindowForTabDraggingProperties(const TabDragContext* context) {
return context ? context->AsView()->GetWidget()->GetNativeWindow() : nullptr;
}
// Returns true if |context| browser window is snapped.
bool IsSnapped(const TabDragContext* context) {
DCHECK(context);
chromeos::WindowStateType type =
GetWindowForTabDraggingProperties(context)->GetProperty(
chromeos::kWindowStateTypeKey);
return type == chromeos::WindowStateType::kLeftSnapped ||
type == chromeos::WindowStateType::kRightSnapped;
}
// In Chrome OS tablet mode, when dragging a tab/tabs around, the desired
// browser size during dragging is one-fourth of the workspace size or the
// window's minimum size.
gfx::Rect GetDraggedBrowserBoundsInTabletMode(aura::Window* window) {
const gfx::Rect work_area =
display::Screen::GetScreen()->GetDisplayNearestWindow(window).work_area();
gfx::Size mininum_size;
if (window->delegate())
mininum_size = window->delegate()->GetMinimumSize();
gfx::Rect bounds(window->GetBoundsInScreen());
bounds.set_width(std::max(work_area.width() / 2, mininum_size.width()));
bounds.set_height(std::max(work_area.height() / 2, mininum_size.height()));
return bounds;
}
// Store the current window bounds if we're in Chrome OS tablet mode and tab
// dragging is allowed on browser windows.
void StoreCurrentDraggedBrowserBoundsInTabletMode(
aura::Window* window,
const gfx::Rect& bounds_in_screen) {
if (ash::TabletMode::Get()->InTabletMode()) {
// The bounds that is stored in ash::kRestoreBoundsOverrideKey will be used
// by DragDetails to calculate the window bounds during dragging in tablet
// mode.
window->SetProperty(ash::kRestoreBoundsOverrideKey,
new gfx::Rect(bounds_in_screen));
}
}
// Returns true if |context| is currently showing in overview mode in Chrome
// OS.
bool IsShowingInOverview(TabDragContext* context) {
return context && GetWindowForTabDraggingProperties(context)->GetProperty(
chromeos::kIsShowingInOverviewKey);
}
// Returns true if we should attach the dragged tabs into |target_context|
// after the drag ends. Currently it only happens on Chrome OS, when the dragged
// tabs are dragged over an overview window, we should not try to attach it
// to the overview window during dragging, but should wait to do so until the
// drag ends.
bool ShouldAttachOnEnd(TabDragContext* target_context) {
return IsShowingInOverview(target_context);
}
// Returns true if |context| can detach from the current context and attach
// into another eligible browser window's context.
bool CanDetachFromTabStrip(TabDragContext* context) {
return context && GetWindowForTabDraggingProperties(context)->GetProperty(
ash::kCanAttachToAnotherWindowKey);
}
#else
bool IsSnapped(const TabDragContext* context) {
return false;
}
bool IsShowingInOverview(TabDragContext* context) {
return false;
}
bool ShouldAttachOnEnd(TabDragContext* target_context) {
return false;
}
bool CanDetachFromTabStrip(TabDragContext* context) {
return true;
}
#endif // #if BUILDFLAG(IS_CHROMEOS_ASH)
void SetCapture(TabDragContext* context) {
context->AsView()->GetWidget()->SetCapture(context->AsView());
}
gfx::Rect GetTabstripScreenBounds(const TabDragContext* context) {
const views::View* view = context->AsView();
gfx::Point view_topleft;
views::View::ConvertPointToScreen(view, &view_topleft);
gfx::Rect view_screen_bounds = view->GetLocalBounds();
view_screen_bounds.Offset(view_topleft.x(), view_topleft.y());
return view_screen_bounds;
}
// Returns true if |bounds| contains the y-coordinate |y|. The y-coordinate
// of |bounds| is adjusted by |vertical_adjustment|.
bool DoesRectContainVerticalPointExpanded(const gfx::Rect& bounds,
int vertical_adjustment,
int y) {
int upper_threshold = bounds.bottom() + vertical_adjustment;
int lower_threshold = bounds.y() - vertical_adjustment;
return y >= lower_threshold && y <= upper_threshold;
}
// Adds |x_offset| to all the rectangles in |rects|.
void OffsetX(int x_offset, std::vector<gfx::Rect>* rects) {
if (x_offset == 0)
return;
for (size_t i = 0; i < rects->size(); ++i)
(*rects)[i].set_x((*rects)[i].x() + x_offset);
}
} // namespace
// KeyEventTracker installs an event monitor and runs a callback to end the drag
// when it receives any key event.
class KeyEventTracker : public ui::EventObserver {
public:
KeyEventTracker(base::OnceClosure end_drag_callback,
base::OnceClosure revert_drag_callback,
gfx::NativeWindow context)
: end_drag_callback_(std::move(end_drag_callback)),
revert_drag_callback_(std::move(revert_drag_callback)) {
event_monitor_ = views::EventMonitor::CreateApplicationMonitor(
this, context, {ui::ET_KEY_PRESSED});
}
KeyEventTracker(const KeyEventTracker&) = delete;
KeyEventTracker& operator=(const KeyEventTracker&) = delete;
~KeyEventTracker() override = default;
private:
// ui::EventObserver:
void OnEvent(const ui::Event& event) override {
if (event.AsKeyEvent()->key_code() == ui::VKEY_ESCAPE &&
revert_drag_callback_) {
std::move(revert_drag_callback_).Run();
} else if (event.AsKeyEvent()->key_code() != ui::VKEY_ESCAPE &&
end_drag_callback_) {
std::move(end_drag_callback_).Run();
}
}
base::OnceClosure end_drag_callback_;
base::OnceClosure revert_drag_callback_;
std::unique_ptr<views::EventMonitor> event_monitor_;
};
class TabDragController::SourceTabStripEmptinessTracker
: public TabStripModelObserver {
public:
explicit SourceTabStripEmptinessTracker(TabStripModel* tabstrip,
TabDragController* parent)
: tab_strip_(tabstrip), parent_(parent) {
tab_strip_->AddObserver(this);
}
private:
void TabStripEmpty() override {
tab_strip_->RemoveObserver(this);
parent_->OnSourceTabStripEmpty();
}
TabStripModel* const tab_strip_;
TabDragController* const parent_;
};
class TabDragController::DraggedTabsClosedTracker
: public TabStripModelObserver {
public:
DraggedTabsClosedTracker(TabStripModel* tabstrip, TabDragController* parent)
: parent_(parent) {
tabstrip->AddObserver(this);
}
void OnTabStripModelChanged(
TabStripModel* model,
const TabStripModelChange& change,
const TabStripSelectionChange& selection) override {
if (change.type() != TabStripModelChange::Type::kRemoved)
return;
for (const auto& contents : change.GetRemove()->contents)
parent_->OnActiveStripWebContentsRemoved(contents.contents);
}
private:
TabDragController* const parent_;
};
TabDragController::TabDragData::TabDragData()
: contents(nullptr),
source_model_index(TabStripModel::kNoTab),
attached_view(nullptr),
pinned(false) {}
TabDragController::TabDragData::~TabDragData() {}
TabDragController::TabDragData::TabDragData(TabDragData&&) = default;
#if BUILDFLAG(IS_CHROMEOS_ASH)
// The class to track the current deferred target tabstrip and also to observe
// its native window's property ash::kIsDeferredTabDraggingTargetWindowKey.
// The reason we need to observe the window property is the property might be
// cleared outside of TabDragController (i.e. by ash), and we should update the
// tracked deferred target tabstrip in this case.
class TabDragController::DeferredTargetTabstripObserver
: public aura::WindowObserver {
public:
DeferredTargetTabstripObserver() = default;
DeferredTargetTabstripObserver(const DeferredTargetTabstripObserver&) =
delete;
DeferredTargetTabstripObserver& operator=(
const DeferredTargetTabstripObserver&) = delete;
~DeferredTargetTabstripObserver() override {
if (deferred_target_context_) {
GetWindowForTabDraggingProperties(deferred_target_context_)
->RemoveObserver(this);
deferred_target_context_ = nullptr;
}
}
void SetDeferredTargetTabstrip(TabDragContext* deferred_target_context) {
if (deferred_target_context_ == deferred_target_context)
return;
// Clear the window property on the previous |deferred_target_context_|.
if (deferred_target_context_) {
aura::Window* old_window =
GetWindowForTabDraggingProperties(deferred_target_context_);
old_window->RemoveObserver(this);
old_window->ClearProperty(ash::kIsDeferredTabDraggingTargetWindowKey);
}
deferred_target_context_ = deferred_target_context;
// Set the window property on the new |deferred_target_context_|.
if (deferred_target_context_) {
aura::Window* new_window =
GetWindowForTabDraggingProperties(deferred_target_context_);
new_window->SetProperty(ash::kIsDeferredTabDraggingTargetWindowKey, true);
new_window->AddObserver(this);
}
}
// aura::WindowObserver:
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override {
DCHECK_EQ(window,
GetWindowForTabDraggingProperties(deferred_target_context_));
if (key == ash::kIsDeferredTabDraggingTargetWindowKey &&
!window->GetProperty(ash::kIsDeferredTabDraggingTargetWindowKey)) {
SetDeferredTargetTabstrip(nullptr);
}
// else do nothing. currently it's only possible that ash clears the window
// property, but doesn't set the window property.
}
void OnWindowDestroying(aura::Window* window) override {
DCHECK_EQ(window,
GetWindowForTabDraggingProperties(deferred_target_context_));
SetDeferredTargetTabstrip(nullptr);
}
TabDragContext* deferred_target_context() { return deferred_target_context_; }
private:
TabDragContext* deferred_target_context_ = nullptr;
};
#endif
///////////////////////////////////////////////////////////////////////////////
// TabDragController, public:
// static
const int TabDragController::kTouchVerticalDetachMagnetism = 50;
// static
const int TabDragController::kVerticalDetachMagnetism = 15;
TabDragController::TabDragController()
: current_state_(DragState::kNotStarted),
event_source_(EVENT_SOURCE_MOUSE),
source_context_(nullptr),
attached_context_(nullptr),
can_release_capture_(true),
offset_to_width_ratio_(0),
old_focused_view_tracker_(std::make_unique<views::ViewTracker>()),
last_move_screen_loc_(0),
source_view_index_(std::numeric_limits<size_t>::max()),
initial_move_(true),
detach_behavior_(DETACHABLE),
move_behavior_(REORDER),
mouse_has_ever_moved_left_(false),
mouse_has_ever_moved_right_(false),
is_dragging_new_browser_(false),
was_source_maximized_(false),
was_source_fullscreen_(false),
did_restore_window_(false),
tab_strip_to_attach_to_after_exit_(nullptr),
move_loop_widget_(nullptr),
is_mutating_(false),
attach_x_(-1),
attach_index_(-1) {
g_tab_drag_controller = this;
}
TabDragController::~TabDragController() {
if (g_tab_drag_controller == this)
g_tab_drag_controller = nullptr;
widget_observation_.Reset();
if (is_dragging_window())
GetAttachedBrowserWidget()->EndMoveLoop();
if (event_source_ == EVENT_SOURCE_TOUCH) {
TabDragContext* capture_context =
attached_context_ ? attached_context_ : source_context_;
capture_context->AsView()->GetWidget()->ReleaseCapture();
}
CHECK(!IsInObserverList());
}
void TabDragController::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) {
DCHECK(!dragging_views.empty());
DCHECK(base::Contains(dragging_views, source_view));
source_context_ = source_context;
was_source_maximized_ = source_context->AsView()->GetWidget()->IsMaximized();
was_source_fullscreen_ =
source_context->AsView()->GetWidget()->IsFullscreen();
// Do not release capture when transferring capture between widgets on:
// - Desktop Linux
// Mouse capture is not synchronous on desktop Linux. Chrome makes
// transferring capture between widgets without releasing capture appear
// synchronous on desktop Linux, so use that.
// - Chrome OS
// Releasing capture on Ash cancels gestures so avoid it.
#if defined(OS_LINUX) || defined(OS_CHROMEOS)
can_release_capture_ = false;
#endif
start_point_in_screen_ = gfx::Point(source_view_offset, mouse_offset.y());
views::View::ConvertPointToScreen(source_view, &start_point_in_screen_);
event_source_ = event_source;
mouse_offset_ = mouse_offset;
move_behavior_ = move_behavior;
last_point_in_screen_ = start_point_in_screen_;
last_move_screen_loc_ = start_point_in_screen_.x();
initial_tab_positions_ = source_context->GetTabXCoordinates();
source_context_emptiness_tracker_ =
std::make_unique<SourceTabStripEmptinessTracker>(
source_context_->GetTabStripModel(), this);
header_drag_ = source_view->GetTabSlotViewType() ==
TabSlotView::ViewType::kTabGroupHeader;
if (header_drag_)
group_ = source_view->group();
drag_data_.resize(dragging_views.size());
for (size_t i = 0; i < dragging_views.size(); ++i)
InitDragData(dragging_views[i], &(drag_data_[i]));
source_view_index_ =
std::find(dragging_views.begin(), dragging_views.end(), source_view) -
dragging_views.begin();
// Listen for Esc key presses.
key_event_tracker_ = std::make_unique<KeyEventTracker>(
base::BindOnce(&TabDragController::EndDrag, base::Unretained(this),
END_DRAG_COMPLETE),
base::BindOnce(&TabDragController::EndDrag, base::Unretained(this),
END_DRAG_CANCEL),
source_context_->AsView()->GetWidget()->GetNativeWindow());
if (source_view->width() > 0) {
offset_to_width_ratio_ =
float{source_view->GetMirroredXInView(source_view_offset)} /
float{source_view->width()};
}
InitWindowCreatePoint();
initial_selection_model_ = std::move(initial_selection_model);
// Gestures don't automatically do a capture. We don't allow multiple drags at
// the same time, so we explicitly capture.
if (event_source == EVENT_SOURCE_TOUCH) {
// Taking capture may cause capture to be lost, ending the drag and
// destroying |this|.
base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
SetCapture(source_context_);
if (!ref)
return;
}
window_finder_ = std::make_unique<WindowFinder>();
}
// static
bool TabDragController::IsAttachedTo(const TabDragContext* context) {
return (g_tab_drag_controller && g_tab_drag_controller->active() &&
g_tab_drag_controller->attached_context() == context);
}
// static
bool TabDragController::IsActive() {
return g_tab_drag_controller && g_tab_drag_controller->active();
}
// static
TabDragContext* TabDragController::GetSourceContext() {
return g_tab_drag_controller ? g_tab_drag_controller->source_context_
: nullptr;
}
void TabDragController::SetMoveBehavior(MoveBehavior behavior) {
if (current_state_ == DragState::kNotStarted)
move_behavior_ = behavior;
}
bool TabDragController::IsDraggingTab(content::WebContents* contents) {
for (auto& drag_data : drag_data_) {
if (drag_data.contents == contents)
return true;
}
return false;
}
void TabDragController::Drag(const gfx::Point& point_in_screen) {
TRACE_EVENT1("views", "TabDragController::Drag", "point_in_screen",
point_in_screen.ToString());
bring_to_front_timer_.Stop();
move_stacked_timer_.Stop();
if (current_state_ == DragState::kWaitingToDragTabs ||
current_state_ == DragState::kWaitingToStop ||
current_state_ == DragState::kStopped)
return;
if (current_state_ == DragState::kNotStarted) {
if (!CanStartDrag(point_in_screen))
return; // User hasn't dragged far enough yet.
// On windows SaveFocus() may trigger a capture lost, which destroys us.
{
base::WeakPtr<TabDragController> ref(weak_factory_.GetWeakPtr());
SaveFocus();
if (!ref)
return;
}
current_state_ = DragState::kDraggingTabs;
Attach(source_context_, gfx::Point());
if (num_dragging_tabs() == source_context_->GetTabStripModel()->count()) {
views::Widget* widget = GetAttachedBrowserWidget();
gfx::Rect new_bounds;
gfx::Vector2d drag_offset;
if (was_source_maximized_ || was_source_fullscreen_) {
did_restore_window_ = true;
// When all tabs in a maximized browser are dragged the browser gets
// restored during the drag and maximized back when the drag ends.
const int tab_area_width = attached_context_->GetTabDragAreaWidth();
std::vector<gfx::Rect> drag_bounds =
attached_context_->CalculateBoundsForDraggedViews(attached_views_);
OffsetX(GetAttachedDragPoint(point_in_screen).x(), &drag_bounds);
new_bounds = CalculateDraggedBrowserBounds(
source_context_, point_in_screen, &drag_bounds);
new_bounds.Offset(-widget->GetRestoredBounds().x() +
point_in_screen.x() - mouse_offset_.x(),
0);
widget->SetVisibilityChangedAnimationsEnabled(false);
widget->Restore();
widget->SetBounds(new_bounds);
drag_offset = GetWindowOffset(point_in_screen);
AdjustBrowserAndTabBoundsForDrag(tab_area_width, point_in_screen,
&drag_offset, &drag_bounds);
widget->SetVisibilityChangedAnimationsEnabled(true);
} else {
new_bounds =
CalculateNonMaximizedDraggedBrowserBounds(widget, point_in_screen);
widget->SetBounds(new_bounds);
drag_offset = GetWindowOffset(point_in_screen);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
StoreCurrentDraggedBrowserBoundsInTabletMode(widget->GetNativeWindow(),
new_bounds);
#endif
RunMoveLoop(drag_offset);
return;
}
}
if (ContinueDragging(point_in_screen) == Liveness::DELETED)
return;
}
void TabDragController::EndDrag(EndDragReason reason) {
TRACE_EVENT0("views", "TabDragController::EndDrag");
// If we're dragging a window ignore capture lost since it'll ultimately
// trigger the move loop to end and we'll revert the drag when RunMoveLoop()
// finishes.
if (reason == END_DRAG_CAPTURE_LOST &&
current_state_ == DragState::kDraggingWindow) {
return;
}
// If we're dragging a window, end the move loop, returning control to
// RunMoveLoop() which will end the drag.
if (current_state_ == DragState::kDraggingWindow) {
current_state_ = DragState::kWaitingToStop;
GetAttachedBrowserWidget()->EndMoveLoop();
return;
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// It's possible that in Chrome OS we defer the windows that are showing in
// overview to attach into during dragging. If so we need to attach the
// dragged tabs to it first.
if (reason == END_DRAG_COMPLETE && deferred_target_context_observer_)
PerformDeferredAttach();
// It's also possible that we need to merge the dragged tabs back into the
// source window even if the dragged tabs is dragged away from the source
// window.
if (source_context_ &&
GetWindowForTabDraggingProperties(source_context_)
->GetProperty(ash::kIsDeferredTabDraggingTargetWindowKey)) {
GetWindowForTabDraggingProperties(source_context_)
->ClearProperty(ash::kIsDeferredTabDraggingTargetWindowKey);
reason = END_DRAG_CANCEL;
}
#endif
EndDragImpl(reason != END_DRAG_COMPLETE && source_context_ ? CANCELED
: NORMAL);
}
void TabDragController::InitDragData(TabSlotView* view,
TabDragData* drag_data) {
TRACE_EVENT0("views", "TabDragController::InitDragData");
const int source_model_index = source_context_->GetIndexOf(view);
drag_data->source_model_index = source_model_index;
if (source_model_index != TabStripModel::kNoTab) {
drag_data->contents = source_context_->GetTabStripModel()->GetWebContentsAt(
drag_data->source_model_index);
drag_data->pinned = source_context_->IsTabPinned(static_cast<Tab*>(view));
}
base::Optional<tab_groups::TabGroupId> tab_group_id = view->group();
if (tab_group_id.has_value()) {
drag_data->tab_group_data = TabDragData::TabGroupData{
tab_group_id.value(), *source_context_->GetTabStripModel()
->group_model()
->GetTabGroup(tab_group_id.value())
->visual_data()};
}
}
void TabDragController::OnWidgetBoundsChanged(views::Widget* widget,
const gfx::Rect& new_bounds) {
TRACE_EVENT1("views", "TabDragController::OnWidgetBoundsChanged",
"new_bounds", new_bounds.ToString());
// Detaching and attaching can be suppresed temporarily to suppress attaching
// to incorrect window on changing bounds. We should prevent Drag() itself,
// otherwise it can clear deferred attaching tab.
if (!CanDetachFromTabStrip(attached_context_))
return;
#if defined(USE_AURA)
aura::Env* env = aura::Env::GetInstance();
// WidgetBoundsChanged happens as a step of ending a drag, but Drag() doesn't
// have to be called -- GetCursorScreenPoint() may return an incorrect
// location in such case and causes a weird effect. See
// https://crbug.com/914527 for the details.
if (!env->IsMouseButtonDown() && !env->is_touch_down())
return;
#endif
Drag(GetCursorScreenPoint());
}
void TabDragController::OnWidgetDestroyed(views::Widget* widget) {
widget_observation_.Reset();
}
void TabDragController::OnSourceTabStripEmpty() {
// NULL out source_context_ so that we don't attempt to add back to it (in
// the case of a revert).
source_context_ = nullptr;
#if BUILDFLAG(IS_CHROMEOS_ASH)
// Also update the source window info for the current dragged window.
if (attached_context_) {
GetWindowForTabDraggingProperties(attached_context_)
->ClearProperty(ash::kTabDraggingSourceWindowKey);
}
#endif
}
void TabDragController::OnActiveStripWebContentsRemoved(
content::WebContents* contents) {
// Mark closed tabs as destroyed so we don't try to manipulate them later.
for (auto it = drag_data_.begin(); it != drag_data_.end(); it++) {
if (it->contents == contents) {
it->contents = nullptr;
break;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// TabDragController, private:
void TabDragController::InitWindowCreatePoint() {
// window_create_point_ is only used in CompleteDrag() (through
// GetWindowCreatePoint() to get the start point of the docked window) when
// the attached_context_ is NULL and all the window's related bound
// information are obtained from source_context_. So, we need to get the
// first_tab based on source_context_, not attached_context_. Otherwise,
// the window_create_point_ is not in the correct coordinate system. Please
// refer to http://crbug.com/6223 comment #15 for detailed information.
views::View* first_tab = source_context_->GetTabAt(0);
views::View::ConvertPointToWidget(first_tab, &first_source_tab_point_);
window_create_point_ = first_source_tab_point_;
window_create_point_.Offset(mouse_offset_.x(), mouse_offset_.y());
}
gfx::Point TabDragController::GetWindowCreatePoint(
const gfx::Point& origin) const {
// If the cursor is outside the monitor area, move it inside. For example,
// dropping a tab onto the task bar on Windows produces this situation.
gfx::Rect work_area =
display::Screen::GetScreen()->GetDisplayNearestPoint(origin).work_area();
gfx::Point create_point(origin);
if (!work_area.IsEmpty()) {
if (create_point.x() < work_area.x())
create_point.set_x(work_area.x());
else if (create_point.x() > work_area.right())
create_point.set_x(work_area.right());
if (create_point.y() < work_area.y())
create_point.set_y(work_area.y());
else if (create_point.y() > work_area.bottom())
create_point.set_y(work_area.bottom());
}
return gfx::Point(create_point.x() - window_create_point_.x(),
create_point.y() - window_create_point_.y());
}
void TabDragController::SaveFocus() {
DCHECK(source_context_);
old_focused_view_tracker_->SetView(
source_context_->AsView()->GetFocusManager()->GetFocusedView());
source_context_->AsView()->GetFocusManager()->ClearFocus();
// WARNING: we may have been deleted.
}
void TabDragController::RestoreFocus() {
if (attached_context_ != source_context_) {
if (is_dragging_new_browser_) {
content::WebContents* active_contents = source_dragged_contents();
if (active_contents && !active_contents->FocusLocationBarByDefault())
active_contents->Focus();
}
return;
}
views::View* old_focused_view = old_focused_view_tracker_->view();
if (!old_focused_view)
return;
old_focused_view->GetFocusManager()->SetFocusedView(old_focused_view);
}
bool TabDragController::CanStartDrag(const gfx::Point& point_in_screen) const {
// Determine if the mouse has moved beyond a minimum elasticity distance in
// any direction from the starting point.
static const int kMinimumDragDistance = 10;
int x_offset = abs(point_in_screen.x() - start_point_in_screen_.x());
int y_offset = abs(point_in_screen.y() - start_point_in_screen_.y());
return sqrt(pow(float{x_offset}, 2) + pow(float{y_offset}, 2)) >
kMinimumDragDistance;
}
TabDragController::Liveness TabDragController::ContinueDragging(
const gfx::Point& point_in_screen) {
TRACE_EVENT1("views", "TabDragController::ContinueDragging",
"point_in_screen", point_in_screen.ToString());
DCHECK(attached_context_);
TabDragContext* target_context = source_context_;
if (detach_behavior_ == DETACHABLE &&
GetTargetTabStripForPoint(point_in_screen, &target_context) ==
Liveness::DELETED) {
return Liveness::DELETED;
}
// The dragged tabs may not be able to attach into |target_context| during
// dragging if the window accociated with |target_context| is currently
// showing in overview mode in Chrome OS, in this case we defer attaching into
// it till the drag ends and reset |target_context| here.
if (ShouldAttachOnEnd(target_context)) {
SetDeferredTargetTabstrip(target_context);
target_context = current_state_ == DragState::kDraggingWindow
? attached_context_
: nullptr;
} else {
SetDeferredTargetTabstrip(nullptr);
}
bool tab_strip_changed = (target_context != attached_context_);
if (attached_context_) {
int move_delta = point_in_screen.x() - last_point_in_screen_.x();
if (move_delta > 0)
mouse_has_ever_moved_right_ = true;
else if (move_delta < 0)
mouse_has_ever_moved_left_ = true;
}
last_point_in_screen_ = point_in_screen;
if (tab_strip_changed) {
is_dragging_new_browser_ = false;
did_restore_window_ = false;
if (DragBrowserToNewTabStrip(target_context, point_in_screen) ==
DRAG_BROWSER_RESULT_STOP) {
return Liveness::ALIVE;
}
}
if (current_state_ == DragState::kDraggingWindow) {
bring_to_front_timer_.Start(
FROM_HERE, base::TimeDelta::FromMilliseconds(750),
base::BindOnce(&TabDragController::BringWindowUnderPointToFront,
base::Unretained(this), point_in_screen));
}
if (current_state_ == DragState::kDraggingTabs) {
if (move_only()) {
DragActiveTabStacked(point_in_screen);
} else {
MoveAttached(point_in_screen, false);
if (tab_strip_changed) {
// Move the corresponding window to the front. We do this after the
// move as on windows activate triggers a synchronous paint.
attached_context_->AsView()->GetWidget()->Activate();
}
}
}
return Liveness::ALIVE;
}
TabDragController::DragBrowserResultType
TabDragController::DragBrowserToNewTabStrip(TabDragContext* target_context,
const gfx::Point& point_in_screen) {
TRACE_EVENT1("views", "TabDragController::DragBrowserToNewTabStrip",
"point_in_screen", point_in_screen.ToString());
if (!target_context) {
DetachIntoNewBrowserAndRunMoveLoop(point_in_screen);
return DRAG_BROWSER_RESULT_STOP;
}
#if defined(USE_AURA)
// Only Aura windows are gesture consumers.
gfx::NativeView attached_native_view =
GetAttachedBrowserWidget()->GetNativeView();
GetAttachedBrowserWidget()->GetGestureRecognizer()->TransferEventsTo(
attached_native_view,
target_context->AsView()->GetWidget()->GetNativeView(),
ui::TransferTouchesBehavior::kDontCancel);
#endif
if (current_state_ == DragState::kDraggingWindow) {
// ReleaseCapture() is going to result in calling back to us (because it
// results in a move). That'll cause all sorts of problems. Reset the
// observer so we don't get notified and process the event.
#if BUILDFLAG(IS_CHROMEOS_ASH)
widget_observation_.Reset();
move_loop_widget_ = nullptr;
#endif // BUILDFLAG(IS_CHROMEOS_ASH)
views::Widget* browser_widget = GetAttachedBrowserWidget();
// Need to release the drag controller before starting the move loop as it's
// going to trigger capture lost, which cancels drag.
attached_context_->ReleaseDragController();
target_context->OwnDragController(this);
// Disable animations so that we don't see a close animation on aero.
browser_widget->SetVisibilityChangedAnimationsEnabled(false);
if (can_release_capture_)
browser_widget->ReleaseCapture();
else
SetCapture(target_context);
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if !(defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
// EndMoveLoop is going to snap the window back to its original location.
// Hide it so users don't see this. Hiding a window in Linux aura causes
// it to lose capture so skip it.
browser_widget->Hide();
#endif
browser_widget->EndMoveLoop();
// Ideally we would always swap the tabs now, but on non-ash Windows, it
// seems that running the move loop implicitly activates the window when
// done, leading to all sorts of flicker. So, on non-ash Windows, instead
// we process the move after the loop completes. But on chromeos, we can
// do tab swapping now to avoid the tab flashing issue
// (crbug.com/116329).
if (can_release_capture_) {
tab_strip_to_attach_to_after_exit_ = target_context;
current_state_ = DragState::kWaitingToDragTabs;
} else {
Detach(DONT_RELEASE_CAPTURE);
Attach(target_context, point_in_screen);
current_state_ = DragState::kDraggingTabs;
// Move the tabs into position.
MoveAttached(point_in_screen, true);
attached_context_->AsView()->GetWidget()->Activate();
}
return DRAG_BROWSER_RESULT_STOP;
}
Detach(DONT_RELEASE_CAPTURE);
Attach(target_context, point_in_screen);
MoveAttached(point_in_screen, true);
return DRAG_BROWSER_RESULT_CONTINUE;
}
void TabDragController::DragActiveTabStacked(
const gfx::Point& point_in_screen) {
if (attached_context_->GetTabCount() != int{initial_tab_positions_.size()})
return; // TODO: should cancel drag if this happens.
int delta = point_in_screen.x() - start_point_in_screen_.x();
attached_context_->DragActiveTabStacked(initial_tab_positions_, delta);
}
void TabDragController::MoveAttachedToNextStackedIndex(
const gfx::Point& point_in_screen) {
int index = *attached_context_->GetActiveTouchIndex();
if (index + 1 >= attached_context_->GetTabCount())
return;
attached_context_->GetTabStripModel()->MoveSelectedTabsTo(index + 1);
StartMoveStackedTimerIfNecessary(point_in_screen,
kMoveAttachedSubsequentDelay);
}
void TabDragController::MoveAttachedToPreviousStackedIndex(
const gfx::Point& point_in_screen) {
int index = *attached_context_->GetActiveTouchIndex();
if (index <= attached_context_->GetPinnedTabCount())
return;
attached_context_->GetTabStripModel()->MoveSelectedTabsTo(index - 1);
StartMoveStackedTimerIfNecessary(point_in_screen,
kMoveAttachedSubsequentDelay);
}
void TabDragController::MoveAttached(const gfx::Point& point_in_screen,
bool just_attached) {
DCHECK(attached_context_);
DCHECK_EQ(current_state_, DragState::kDraggingTabs);
gfx::Point dragged_view_point = GetAttachedDragPoint(point_in_screen);
const int threshold = attached_context_->GetHorizontalDragThreshold();
std::vector<TabSlotView*> views(drag_data_.size());
for (size_t i = 0; i < drag_data_.size(); ++i)
views[i] = drag_data_[i].attached_view;
bool did_layout = false;
// Update the model, moving the WebContents from one index to another. Do this
// only if we have moved a minimum distance since the last reorder (to prevent
// jitter), or if this the first move and the tabs are not consecutive, or if
// we have just attached to a new tabstrip and need to move to the correct
// initial position.
if (just_attached ||
(abs(point_in_screen.x() - last_move_screen_loc_) > threshold) ||
(initial_move_ && !AreTabsConsecutive())) {
TabStripModel* attached_model = attached_context_->GetTabStripModel();
int to_index = attached_context_->GetInsertionIndexForDraggedBounds(
GetDraggedViewTabStripBounds(dragged_view_point),
GetViewsMatchingDraggedContents(attached_context_), num_dragging_tabs(),
mouse_has_ever_moved_left_, mouse_has_ever_moved_right_, group_);
bool do_move = true;
// While dragging within a tabstrip the expectation is the insertion index
// is based on the left edge of the tabs being dragged. OTOH when dragging
// into a new tabstrip (attaching) the expectation is the insertion index is
// based on the cursor. This proves problematic as insertion may change the
// size of the tabs, resulting in the index calculated before the insert
// differing from the index calculated after the insert. To alleviate this
// the index is chosen before insertion, and subsequently a new index is