File: wayland_window_drag_controller_unittest.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1845 lines) | stat: -rw-r--r-- 78,815 bytes parent folder | download | duplicates (4)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/ozone/platform/wayland/host/wayland_window_drag_controller.h"

#include <linux/input-event-codes.h>
#include <wayland-server-protocol.h>
#include <wayland-server.h>
#include <wayland-util.h>
#include <xdg-shell-server-protocol.h>

#include <cstdint>

#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/mock_callback.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/events/base_event_utils.h"
#include "ui/events/event.h"
#include "ui/events/types/event_type.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/ozone/platform/wayland/host/wayland_cursor_position.h"
#include "ui/ozone/platform/wayland/host/wayland_data_device.h"
#include "ui/ozone/platform/wayland/host/wayland_data_device_manager.h"
#include "ui/ozone/platform/wayland/host/wayland_data_drag_controller.h"
#include "ui/ozone/platform/wayland/host/wayland_event_source.h"
#include "ui/ozone/platform/wayland/host/wayland_output.h"
#include "ui/ozone/platform/wayland/host/wayland_output_manager.h"
#include "ui/ozone/platform/wayland/host/wayland_screen.h"
#include "ui/ozone/platform/wayland/host/wayland_serial_tracker.h"
#include "ui/ozone/platform/wayland/host/wayland_toplevel_window.h"
#include "ui/ozone/platform/wayland/host/wayland_window.h"
#include "ui/ozone/platform/wayland/host/wayland_window_manager.h"
#include "ui/ozone/platform/wayland/test/mock_pointer.h"
#include "ui/ozone/platform/wayland/test/mock_surface.h"
#include "ui/ozone/platform/wayland/test/mock_wayland_platform_window_delegate.h"
#include "ui/ozone/platform/wayland/test/scoped_wl_array.h"
#include "ui/ozone/platform/wayland/test/test_data_device.h"
#include "ui/ozone/platform/wayland/test/test_data_device_manager.h"
#include "ui/ozone/platform/wayland/test/test_data_offer.h"
#include "ui/ozone/platform/wayland/test/test_data_source.h"
#include "ui/ozone/platform/wayland/test/test_output.h"
#include "ui/ozone/platform/wayland/test/test_wayland_server_thread.h"
#include "ui/ozone/platform/wayland/test/wayland_drag_drop_test.h"
#include "ui/ozone/platform/wayland/test/wayland_test.h"
#include "ui/ozone/platform/wayland/test/wayland_window_drag_controller_test_api.h"
#include "ui/platform_window/extensions/wayland_extension.h"
#include "ui/platform_window/platform_window_delegate.h"
#include "ui/platform_window/wm/wm_move_loop_handler.h"

using testing::_;
using testing::Mock;
using testing::Values;

namespace ui {

using mojom::DragEventSource;
using TestApi = WaylandWindowDragControllerTestApi;

class WaylandWindowDragControllerTest : public WaylandDragDropTest {
 public:
  WaylandWindowDragControllerTest() = default;
  ~WaylandWindowDragControllerTest() override = default;

  void SetUp() override {
    WaylandDragDropTest::SetUp();
    TestApi(drag_controller()).set_extended_drag_available(true);

    EXPECT_FALSE(window_->HasPointerFocus());
    EXPECT_EQ(State::kIdle, drag_controller_state());
  }

  WaylandWindowDragController* drag_controller() {
    return connection_->window_drag_controller();
  }

  WaylandWindowDragController::State drag_controller_state() {
    return TestApi(drag_controller()).state();
  }

  WaylandPointer::Delegate* pointer_delegate() {
    return TestApi(drag_controller()).pointer_delegate();
  }

  WaylandTouch::Delegate* touch_delegate() {
    return TestApi(drag_controller()).touch_delegate();
  }

  wl::SerialTracker& serial_tracker() { return connection_->serial_tracker(); }

  MockWaylandPlatformWindowDelegate& delegate() { return delegate_; }
  WaylandWindow* window() { return window_.get(); }

  void SendPointerMotion(WaylandWindow* window,
                         MockPlatformWindowDelegate* delegate,
                         gfx::Point location,
                         bool ensure_dispatched = true) {
    if (ensure_dispatched) {
      EXPECT_CALL(*delegate, DispatchEvent(_)).WillOnce([](Event* event) {
        EXPECT_TRUE(event->IsMouseEvent());
        EXPECT_EQ(EventType::kMouseDragged, event->type());
      });
    }

    PostToServerAndWait([location](wl::TestWaylandServerThread* server) {
      wl_fixed_t x = wl_fixed_from_int(location.x());
      wl_fixed_t y = wl_fixed_from_int(location.y());
      ASSERT_TRUE(server->seat()->pointer());
      wl_resource* pointer_resource = server->seat()->pointer()->resource();
      wl_pointer_send_motion(pointer_resource, server->GetNextTime(), x, y);
      wl_pointer_send_frame(pointer_resource);
    });

    if (ensure_dispatched) {
      Mock::VerifyAndClearExpectations(delegate);
      EXPECT_EQ(window->GetWidget(),
                screen_->GetLocalProcessWidgetAtPoint(location, {}));
    }
  }

  void SendDndMotionForWindowDrag(const gfx::Point& location) {
    WaylandDragDropTest::SendDndMotion(location);
  }

  void SendDndDropAndFinished() {
    PostToServerAndWait([](wl::TestWaylandServerThread* server) {
      auto* data_source = server->data_device_manager()->data_source();
      ASSERT_TRUE(data_source);
      data_source->OnDndDropPerformed();
      data_source->OnFinished();
    });
  }

 protected:
  using State = WaylandWindowDragController::State;

  void SendPointerEnter(WaylandWindow* window,
                        MockPlatformWindowDelegate* delegate) override {
    EXPECT_CALL(*delegate, DispatchEvent(_)).Times(1);
    WaylandDragDropTest::SendPointerEnter(window, delegate);
    Mock::VerifyAndClearExpectations(delegate);
    EXPECT_EQ(window,
              window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  }

  void SendPointerLeave(WaylandWindow* window,
                        MockPlatformWindowDelegate* delegate) override {
    EXPECT_CALL(*delegate, DispatchEvent(_)).Times(1);
    WaylandDragDropTest::SendPointerLeave(window, delegate);
    Mock::VerifyAndClearExpectations(delegate);
    EXPECT_EQ(nullptr,
              window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  }

  void SendPointerPress(WaylandWindow* window,
                        MockPlatformWindowDelegate* delegate,
                        int button) {
    EXPECT_CALL(*delegate, DispatchEvent(_)).Times(1);
    WaylandDragDropTest::SendPointerButton(window, delegate, button,
                                           /*pressed=*/true);
    Mock::VerifyAndClearExpectations(delegate);
    EXPECT_EQ(window,
              window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  }

  // TODO(crbug.com/40711933): Support extended-drag in test compositor.

  void SendTouchDown(WaylandWindow* window,
                     MockPlatformWindowDelegate* delegate,
                     int id,
                     const gfx::Point& location) override {
    EXPECT_CALL(*delegate, DispatchEvent(_)).WillOnce([](Event* event) {
      EXPECT_EQ(EventType::kTouchPressed, event->type());
    });
    WaylandDragDropTest::SendTouchDown(window, delegate, id, location);
    Mock::VerifyAndClearExpectations(delegate);
    EXPECT_EQ(window,
              window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  }
  void SendTouchMotion(WaylandWindow* window,
                       MockPlatformWindowDelegate* delegate,
                       int id,
                       const gfx::Point& location) override {
    EXPECT_CALL(*delegate, DispatchEvent(_)).WillOnce([](Event* event) {
      EXPECT_EQ(EventType::kTouchMoved, event->type());
    });
    WaylandDragDropTest::SendTouchMotion(window, delegate, id, location);
    Mock::VerifyAndClearExpectations(delegate);
    EXPECT_EQ(window->GetWidget(),
              screen_->GetLocalProcessWidgetAtPoint(location, {}));
  }
};

// Check the following flow works as expected:
// 1. With a single 1 window open,
// 2. Move pointer into it, press left button, move cursor a bit (drag),
// 3. Run move loop, drag it within the window bounds and drop.
TEST_P(WaylandWindowDragControllerTest, DragInsideWindowAndDrop) {
  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  // Set up an "interaction flow", start the drag session and run move loop:
  //  - Event dispatching and bounds changes are monitored
  //  - At each event, emulates a new event at server side and proceeds to
  // the next test step.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);

  enum { kStarted, kDragging, kDropping, kDone } test_step = kStarted;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly([&](Event* event) {
    EXPECT_TRUE(event->IsMouseEvent());
    switch (test_step) {
      case kStarted:
        EXPECT_EQ(EventType::kMouseEntered, event->type());
        EXPECT_EQ(State::kDetached, drag_controller_state());
        // Ensure PlatformScreen keeps consistent.
        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));
        // Drag it a bit more. We are in the middle of OnDragEnter. Run this via
        // a task run. Otherwise, the data offer will be reset and
        // WaylandWindowDragController will crash.
        ScheduleTestTask(base::BindOnce(
            &WaylandWindowDragControllerTest::SendDndMotionForWindowDrag,
            base::Unretained(this), gfx::Point(20, 20)));
        test_step = kDragging;
        break;
      case kDropping: {
        EXPECT_EQ(EventType::kMouseReleased, event->type());
        EXPECT_EQ(State::kDropped, drag_controller_state());
        // Ensure PlatformScreen keeps consistent.
        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
        test_step = kDone;
        break;
      }
      case kDragging:
      default:
        FAIL() << " event=" << event->GetName()
               << " state=" << drag_controller_state()
               << " step=" << static_cast<int>(test_step);
    }
  });

  EXPECT_CALL(delegate_, OnBoundsChanged(_))
      .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
        EXPECT_EQ(kDragging, test_step);
        EXPECT_EQ(State::kDetached, drag_controller_state());
        EXPECT_EQ(gfx::Point(20, 20), window_->GetBoundsInDIP().origin());
        EXPECT_TRUE(change.origin_changed);
        test_step = kDropping;
        SendDndDropAndFinished();
      });

  // RunMoveLoop() blocks until the dragging session ends.
  EXPECT_TRUE(move_loop_handler->RunMoveLoop({}));

  // Verify expectations.
  Mock::VerifyAndClearExpectations(&delegate_);
  ASSERT_EQ(test_step, kDone);
  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_EQ(window_.get(), window_manager()->GetCurrentPointerFocusedWindow());
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Check the following flow works as expected:
// 1. With a single window open,
// 2. Touch down and move the touch point a bit (drag),
// 3. Run move loop, drag it within the window bounds and drop.
TEST_P(WaylandWindowDragControllerTest, DragInsideWindowAndDrop_TOUCH) {
  ASSERT_TRUE(GetWmMoveLoopHandler(*window_));
  ASSERT_TRUE(GetWaylandToplevelExtension(*window_));

  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendTouchDown(window_.get(), &delegate_, 0 /*point id*/, {0, 0} /*location*/);
  SendTouchMotion(window_.get(), &delegate_, 0 /*point id*/,
                  {10, 10} /*location*/);

  // Set up an "interaction flow", start the drag session and run move loop:
  //  - Event dispatching and bounds changes are monitored
  //  - At each event, emulates a new event at server side and proceeds to the
  //  next test step.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);

  // While in |kAttached| state, motion events are expected to be dispatched
  // plain EventType::kTouchMoved events.
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce([&](Event* event) {
    EXPECT_EQ(EventType::kTouchMoved, event->type());
    EXPECT_EQ(gfx::Point(10, 10), event->AsLocatedEvent()->root_location());
    EXPECT_EQ(State::kAttached, drag_controller_state());
    EXPECT_EQ(gfx::Point(10, 10), screen_->GetCursorScreenPoint());
  });
  SendDndMotionForWindowDrag({10, 10});

  enum TestStep { kDragging, kDropping, kDone } test_step = kDragging;

  EXPECT_CALL(delegate_, DispatchEvent(_))
      .WillOnce([&](Event* event) {
        EXPECT_EQ(EventType::kTouchReleased, event->type());
        ASSERT_EQ(kDropping, test_step);
        EXPECT_EQ(State::kDropped, drag_controller_state());
        gfx::Point expected_point{20, 20};
        expected_point += window_->GetBoundsInDIP().origin().OffsetFromOrigin();
        // Ensure PlatformScreen keeps consistent.
        EXPECT_EQ(expected_point, screen_->GetCursorScreenPoint());
        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
        test_step = kDone;
      });

  EXPECT_CALL(delegate_, OnBoundsChanged(_))
      .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
        EXPECT_EQ(State::kDetached, drag_controller_state());
        EXPECT_EQ(kDragging, test_step);
        EXPECT_EQ(gfx::Point(20, 20), window_->GetBoundsInDIP().origin());
        EXPECT_TRUE(change.origin_changed);

        test_step = kDropping;
        ScheduleTestTask(base::BindOnce(
            &WaylandWindowDragControllerTest::SendDndDropAndFinished,
            base::Unretained(this)));
      });

  // While in |kDetached| state, motion events are expected to be propagated
  // window bounds changed events.
  // Otherwise, we are not able to override the dispatcher and miss events.
  // This task must be scheduled so that move loop is able to be started before
  // this task is executed.
  ScheduleTestTask(base::BindOnce(
      &WaylandWindowDragControllerTest::SendDndMotionForWindowDrag,
      base::Unretained(this), gfx::Point({20, 20})));

  // RunMoveLoop() blocks until the dragging session ends, so resume test
  // server's run loop until it returns.
  EXPECT_TRUE(GetWmMoveLoopHandler(*window_)->RunMoveLoop({}));

  EXPECT_EQ(test_step, TestStep::kDone);

  SendPointerEnter(window_.get(), &delegate_);

  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Similar to DragInsideWindowAndDrop_TOUCH but with two fingers.
TEST_P(WaylandWindowDragControllerTest, DragInsideWindowAndDropTwoFingerTouch) {
  ASSERT_TRUE(GetWmMoveLoopHandler(*window_));
  ASSERT_TRUE(GetWaylandToplevelExtension(*window_));

  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  // Touch and then move with two fingers.
  SendTouchDown(window_.get(), &delegate_, 0 /*point id*/, {0, 0} /*location*/);
  SendTouchDown(window_.get(), &delegate_, 1 /*point id*/, {5, 0} /*location*/);
  SendTouchMotion(window_.get(), &delegate_, 0 /*point id*/,
                  {10, 10} /*location*/);
  SendTouchMotion(window_.get(), &delegate_, 1 /*point id*/,
                  {15, 10} /*location*/);

  // Set up an "interaction flow", start the drag session and run move loop:
  //  - Event dispatching and bounds changes are monitored
  //  - At each event, emulates a new event at server side and proceeds to the
  //  next test step.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);

  // While in |kAttached| state, motion events are expected to be dispatched
  // plain EventType::kTouchMoved events.
  EXPECT_CALL(delegate_, DispatchEvent(_))
      .WillOnce([&](Event* event) {
        EXPECT_EQ(EventType::kTouchMoved, event->type());
        EXPECT_EQ(0, event->AsTouchEvent()->pointer_details().id);
        EXPECT_EQ(gfx::Point(10, 10), event->AsLocatedEvent()->root_location());
        EXPECT_EQ(State::kAttached, drag_controller_state());
        EXPECT_EQ(gfx::Point(10, 10), screen_->GetCursorScreenPoint());
      })
      .WillOnce([&](Event* event) {
        EXPECT_EQ(EventType::kTouchMoved, event->type());
        EXPECT_EQ(1, event->AsTouchEvent()->pointer_details().id);
        EXPECT_EQ(gfx::Point(10, 10), event->AsLocatedEvent()->root_location());
        EXPECT_EQ(State::kAttached, drag_controller_state());
        EXPECT_EQ(gfx::Point(10, 10), screen_->GetCursorScreenPoint());
      });
  SendDndMotionForWindowDrag({10, 10});

  enum TestStep {
    kDragging,
    kDropping,
    kFirstFingerReleased,
    kDone
  } test_step = kDragging;

  EXPECT_CALL(delegate_, DispatchEvent(_))
      // delegate_ should receive two touch release events in a sequence.
      .WillOnce([&](Event* event) {
        ASSERT_EQ(kDropping, test_step);
        EXPECT_EQ(EventType::kTouchReleased, event->type());
        EXPECT_EQ(0, event->AsTouchEvent()->pointer_details().id);
        EXPECT_EQ(State::kDropped, drag_controller_state());

        // Ensure PlatformScreen keeps consistent.
        gfx::Point expected_point{20, 20};
        expected_point += window_->GetBoundsInDIP().origin().OffsetFromOrigin();
        EXPECT_EQ(expected_point, screen_->GetCursorScreenPoint());

        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
        test_step = kFirstFingerReleased;
      })
      .WillOnce([&](Event* event) {
        ASSERT_EQ(kFirstFingerReleased, test_step);
        EXPECT_EQ(EventType::kTouchReleased, event->type());
        EXPECT_EQ(1, event->AsTouchEvent()->pointer_details().id);
        EXPECT_EQ(State::kDropped, drag_controller_state());

        // Ensure PlatformScreen keeps consistent.
        gfx::Point expected_point{20, 20};
        expected_point += window_->GetBoundsInDIP().origin().OffsetFromOrigin();
        EXPECT_EQ(expected_point, screen_->GetCursorScreenPoint());

        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
        test_step = kDone;
      });

  EXPECT_CALL(delegate_, OnBoundsChanged(_))
      .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
        ASSERT_EQ(kDragging, test_step);
        EXPECT_EQ(State::kDetached, drag_controller_state());
        EXPECT_EQ(gfx::Point(20, 20), window_->GetBoundsInDIP().origin());
        EXPECT_TRUE(change.origin_changed);

        test_step = kDropping;
        ScheduleTestTask(base::BindOnce(
            &WaylandWindowDragControllerTest::SendDndDropAndFinished,
            base::Unretained(this)));
      });

  // While in |kDetached| state, motion events are expected to be propagated
  // window bounds changed events.
  // Otherwise, we are not able to override the dispatcher and miss events.
  // This task must be scheduled so that move loop is able to be started before
  // this task is executed.
  ScheduleTestTask(base::BindOnce(
      &WaylandWindowDragControllerTest::SendDndMotionForWindowDrag,
      base::Unretained(this), gfx::Point({20, 20})));

  // RunMoveLoop() blocks until the dragging session ends, so resume test
  // server's run loop until it returns.
  EXPECT_TRUE(GetWmMoveLoopHandler(*window_)->RunMoveLoop({}));

  EXPECT_EQ(test_step, TestStep::kDone);

  SendPointerEnter(window_.get(), &delegate_);

  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Check the following flow works as expected:
// 1. Start dragging  window_2 with touch.
// 2. Emulate |window_2| being closed manually by the user (eg control+w).
// 3. No crash observed.
TEST_P(WaylandWindowDragControllerTest, DestroyWindowDuringDragAndDrop_TOUCH) {
  // Init and open |window_2|.
  PlatformWindowInitProperties properties{gfx::Rect{80, 80}};
  properties.type = PlatformWindowType::kWindow;
  EXPECT_CALL(delegate_, OnAcceleratedWidgetAvailable(_)).Times(1);
  auto window_2 =
      delegate_.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_NE(gfx::kNullAcceleratedWidget, window_2->GetWidget());

  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  // Start a window dragging session and verify |window_2| is effectively being
  // dragged
  SendTouchDown(window_2.get(), &delegate_, 0 /*point id*/,
                {0, 0} /*location*/);

  auto* wayland_extension = GetWaylandToplevelExtension(*window_2);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);

  // Verify that the proper window is being dragged.
  EXPECT_EQ(window_2.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_2.get(), TestApi(drag_controller()).origin_window());
  Mock::VerifyAndClearExpectations(&delegate_);

  // Destroy the dragged window, and expect no crashes.
  window_2.reset();
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());

  SendTouchUp(0 /*touch id*/);
}

// Check the following flow works as expected:
// 1. With two windows open,
// 2. Touch down and start drag a window,
// 3. Emulate the compositor sending an unexpected `pointer enter` event
//   to another window, when the drag is ongoing.
//
// NOTE: This bug isn't noticed on DUT, but seems to be frequent on ash/chrome
// linux desktop builds (with ozone/x11 underneath).
TEST_P(WaylandWindowDragControllerTest,
       DragAndDropWithExtraneousPointerEnterEvent_TOUCH) {
  // Init and open |target_window|.
  PlatformWindowInitProperties properties{gfx::Rect{80, 80}};
  properties.type = PlatformWindowType::kWindow;
  EXPECT_CALL(delegate_, OnAcceleratedWidgetAvailable(_)).Times(1);
  auto window_2 =
      delegate_.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_NE(gfx::kNullAcceleratedWidget, window_2->GetWidget());

  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  ASSERT_TRUE(GetWmMoveLoopHandler(*window_2));
  ASSERT_TRUE(GetWaylandToplevelExtension(*window_2));

  // Start triggering a drag operation.
  SendTouchDown(window_2.get(), &delegate_, 0 /*point id*/,
                {0, 0} /*location*/);

  // This operation simulates bogus Wayland compositor that might send out
  // unexpected pointer enter events.
  SendPointerEnter(window_.get(), &delegate_);
  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_.get(), window_manager()->GetCurrentPointerFocusedWindow());
  EXPECT_EQ(window_2.get(), window_manager()->GetCurrentTouchFocusedWindow());

  // Set up an "interaction flow", start the drag session, run move loop
  // and verify the window effectively being dragged.
  GetWaylandToplevelExtension(*window_2)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);

  // Verify that the proper window is being dragged.
  EXPECT_EQ(window_2.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_2.get(), TestApi(drag_controller()).origin_window());

  SendTouchUp(0 /*touch id*/);
}

// Check the following flow works as expected:
// 1. With only 1 window open;
// 2. Move pointer into it, press left button, move cursor a bit (drag);
// 3. Run move loop,
// 4. Drag pointer to outside the window and release the mouse button, and make
//    sure RELEASE and EXIT mouse events are delivered even when the drop
//    happens outside the bounds of any surface.
TEST_P(WaylandWindowDragControllerTest, DragExitWindowAndDrop) {
  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  // Sets up an "interaction flow", start the drag session and run move loop:
  //  - Event dispatching and bounds changes are monitored
  //  - At each event, emulates a new event on server side and proceeds to the
  //  next test step.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);

  enum { kStarted, kDragging, kExitedDropping, kDone } test_step = kStarted;

  EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly([&](Event* event) {
    EXPECT_TRUE(event->IsMouseEvent());
    switch (test_step) {
      case kStarted:
        EXPECT_EQ(EventType::kMouseEntered, event->type());
        EXPECT_EQ(State::kDetached, drag_controller_state());
        // Ensure PlatformScreen keeps consistent.
        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));
        // Drag it a bit more. We are in the middle of OnDragEnter. Run this via
        // a task run. Otherwise, the data offer will be reset and
        // WaylandWindowDragController will crash.
        ScheduleTestTask(base::BindOnce(
            &WaylandWindowDragControllerTest::SendDndMotionForWindowDrag,
            base::Unretained(this), gfx::Point(20, 20)));
        test_step = kDragging;
        break;
      case kExitedDropping: {
        EXPECT_EQ(EventType::kMouseReleased, event->type());
        EXPECT_EQ(State::kDropped, drag_controller_state());
        // Ensure PlatformScreen keeps consistent.
        gfx::Point expected_point{20, 20};
        expected_point += window_->GetBoundsInDIP().origin().OffsetFromOrigin();
        EXPECT_EQ(expected_point, screen_->GetCursorScreenPoint());
        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
        test_step = kDone;
      } break;
      case kDragging:
      default:
        FAIL() << " event=" << event->GetName()
               << " state=" << drag_controller_state()
               << " step=" << static_cast<int>(test_step);
    }
  });

  EXPECT_CALL(delegate_, OnBoundsChanged(_))
      .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
        EXPECT_EQ(kDragging, test_step);
        EXPECT_EQ(State::kDetached, drag_controller_state());
        EXPECT_EQ(gfx::Point(20, 20), window_->GetBoundsInDIP().origin());
        EXPECT_TRUE(change.origin_changed);

        test_step = kExitedDropping;
        SendDndLeave();
        SendDndDropAndFinished();
      });

  // RunMoveLoop() blocks until the dragging sessions ends.
  EXPECT_TRUE(move_loop_handler->RunMoveLoop({}));

  // Verify expectations.
  Mock::VerifyAndClearExpectations(&delegate_);
  ASSERT_EQ(test_step, kDone);
  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Check the following flow works as expected:
// 1. With 2 windows open,
// 2. Focus window 1, starts dragging,
// 3. Run move loop,
// 4. Drag the pointer out of window 1 and then into window 2,
// 5. Drag it a bit more (within window 2) and then calls EndMoveLoop(),
//    emulating a window snap), and then
// 6. With the window in "snapped" state, drag it further and then drop.
// TODO(crbug.com/40886646): Test needs to be updated for 112.0.5570.0 to remove
// special handling logic in wayland_pointer.cc.
TEST_P(WaylandWindowDragControllerTest, DragToOtherWindowSnapDragDrop) {
  // Init and open |target_window|.
  PlatformWindowInitProperties properties{gfx::Rect{80, 80}};
  properties.type = PlatformWindowType::kWindow;
  EXPECT_CALL(delegate_, OnAcceleratedWidgetAvailable(_)).Times(1);
  auto window_2 =
      delegate_.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_NE(gfx::kNullAcceleratedWidget, window_2->GetWidget());

  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  auto* source_window = window_.get();
  auto* target_window = window_2.get();
  EXPECT_TRUE(source_window);
  EXPECT_TRUE(target_window);

  SendPointerEnter(source_window, &delegate_);
  SendPointerPress(source_window, &delegate_, BTN_LEFT);
  SendPointerMotion(source_window, &delegate_, {10, 10});

  // Sets up an "interaction flow", start the drag session and run move loop:
  //  - Event dispatching and bounds changes are monitored
  //  - At each event, emulates a new event on server side and proceeds to the
  //  next test step.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);

  enum {
    kStarted,
    kDragging,
    kEnteredTarget,
    kSnapped,
    kDone
  } test_step = kStarted;

  EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly([&](Event* event) {
    EXPECT_TRUE(event->IsMouseEvent());
    switch (test_step) {
      case kStarted:
        EXPECT_EQ(EventType::kMouseEntered, event->type());
        EXPECT_EQ(State::kDetached, drag_controller_state());
        // Ensure PlatformScreen keeps consistent.
        EXPECT_EQ(source_window->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));
        // Drag it a bit more. We are in the middle of
        // WaylandWindowDragController::OnDragEnter. Run this via a task run.
        // Otherwise, the data offer will be reset and
        // WaylandWindowDragController will crash.
        ScheduleTestTask(base::BindOnce(
            &WaylandWindowDragControllerTest::SendDndMotionForWindowDrag,
            base::Unretained(this), gfx::Point(50, 50)));
        test_step = kDragging;
        break;
      case kEnteredTarget:
        EXPECT_EQ(EventType::kMouseEntered, event->type());
        EXPECT_EQ(State::kDetached, drag_controller_state());
        // Ensure PlatformScreen keeps consistent.
        EXPECT_EQ(target_window->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

        move_loop_handler->EndMoveLoop();
        test_step = kSnapped;
        break;
      default:
        move_loop_handler->EndMoveLoop();
        FAIL() << " event=" << event->GetName()
               << " state=" << drag_controller_state()
               << " step=" << static_cast<int>(test_step);
    }
  });

  EXPECT_CALL(delegate_, OnBoundsChanged(_))
      .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
        EXPECT_EQ(State::kDetached, drag_controller_state());
        EXPECT_EQ(kDragging, test_step);
        EXPECT_EQ(gfx::Point(50, 50), window_->GetBoundsInDIP().origin());
        EXPECT_TRUE(change.origin_changed);

        // Exit |source_window| and enter the |target_window|.
        SendDndLeave();
        test_step = kEnteredTarget;
        SendDndEnter(target_window, {});
      });

  // RunMoveLoop() blocks until the dragging sessions ends.
  // TODO(nickdiego): Should succeed for this test case.
  EXPECT_FALSE(move_loop_handler->RunMoveLoop({}));

  // Continue the dragging session after "snapping" the window. At this point,
  // the DND session is expected to be still alive and responding normally to
  // data object events.
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_EQ(kSnapped, test_step);

  // Drag the pointer a bit more within |target_window| and then releases the
  // mouse button and ensures drag controller delivers the events properly and
  // exit gracefully.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(5);
  gfx::Point location(30, 30);
  for (size_t count = 1; count <= 5; ++count) {
    SendDndMotionForWindowDrag(location);
    location.Offset(0, 3);
  }

  EXPECT_EQ(gfx::Point(30, 42), screen_->GetCursorScreenPoint());
  EXPECT_EQ(target_window->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({50, 50}, {}));

  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce([&](Event* event) {
    EXPECT_TRUE(event->IsMouseEvent());
    switch (test_step) {
      case kSnapped:
        EXPECT_EQ(EventType::kMouseReleased, event->type());
        EXPECT_EQ(State::kDropped, drag_controller_state());
        EXPECT_EQ(target_window,
                  window_manager()->GetCurrentPointerOrTouchFocusedWindow());
        test_step = kDone;
        break;
      default:
        FAIL() << " event=" << event->GetName()
               << " state=" << drag_controller_state()
               << " step=" << static_cast<int>(test_step);
    }
  });

  SendDndDropAndFinished();
  SendPointerEnter(target_window, &delegate_);
  EXPECT_EQ(target_window,
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(target_window->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Check the following flow works as expected:
// 1. With 2 windows open,
// 2. Focus window 1, starts dragging,
// 3. Run move loop,
// 4. Drag the pointer out of window 1 and then into window 2,
// 5. Drag it a bit more (within window 2) and then calls EndMoveLoop(),
//    emulating a window snap), and then
// 6. With the window in "snapped" state, drag it further and then drop.
TEST_P(WaylandWindowDragControllerTest, DragToOtherWindowSnapDragDrop_TOUCH) {
  // Init and open |target_window|.
  PlatformWindowInitProperties properties{gfx::Rect{80, 80}};
  properties.type = PlatformWindowType::kWindow;
  EXPECT_CALL(delegate_, OnAcceleratedWidgetAvailable(_)).Times(1);
  auto window_2 =
      delegate_.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_NE(gfx::kNullAcceleratedWidget, window_2->GetWidget());

  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  auto* source_window = window_.get();
  auto* target_window = window_2.get();
  EXPECT_TRUE(source_window);
  EXPECT_TRUE(target_window);

  SendTouchDown(window_.get(), &delegate_, 0 /*point id*/, {0, 0} /*location*/);
  SendTouchMotion(window_.get(), &delegate_, 0 /*point id*/,
                  {10, 10} /*location*/);

  // Sets up an "interaction flow", start the drag session and run move loop:
  //  - Event dispatching and bounds changes are monitored
  //  - At each event, emulates a new event on server side and proceeds to the
  //  next test step.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_CALL(delegate_, DispatchEvent(_))
      .WillOnce([&](Event* event) {
        EXPECT_EQ(EventType::kTouchMoved, event->type());
        EXPECT_EQ(gfx::Point(10, 10), screen_->GetCursorScreenPoint());
      });
  SendDndMotionForWindowDrag({10, 10});

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);

  enum {
    kStarted,
    kDragging,
    kEnteredTarget,
    kSnapped,
    kDone
  } test_step = kStarted;

  EXPECT_CALL(delegate_, OnBoundsChanged(_))
      .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
        EXPECT_EQ(State::kDetached, drag_controller_state());
        EXPECT_EQ(kDragging, test_step);
        EXPECT_EQ(gfx::Point(50, 50), window_->GetBoundsInDIP().origin());
        EXPECT_TRUE(change.origin_changed);

        // Exit |source_window| and enter the |target_window|.
        SendDndLeave();
        test_step = kEnteredTarget;
        SendDndEnter(target_window, {20, 20});
        // Ensure the target window has focus.
        EXPECT_EQ(target_window,
                  window_manager()->GetCurrentPointerOrTouchFocusedWindow());
        EXPECT_EQ(target_window, static_cast<WaylandTouch::Delegate*>(
                                     connection_->event_source())
                                     ->GetTouchTarget(0 /*point id*/));
        move_loop_handler->EndMoveLoop();
      });

  // While in |kDetached| state, motion events are expected to be propagated
  // window bounds changed events.
  test_step = kDragging;
  ScheduleTestTask(base::BindOnce(
      &WaylandWindowDragControllerTest::SendDndMotionForWindowDrag,
      base::Unretained(this), gfx::Point(50, 50)));

  // RunMoveLoop() blocks until the window moving ends.
  // TODO(nickdiego): Should succeed for this test case.
  EXPECT_FALSE(move_loop_handler->RunMoveLoop({}));

  // Checks |target_window| is now "focused" and the states keep consistent.
  EXPECT_EQ(kEnteredTarget, test_step);
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_EQ(target_window->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));

  // Emulate |window_| snapping into |target_window|, and then continue the
  // dragging session after "snapping" process. At this point, the DND session
  // is expected to be still alive and responding normally to data object
  // events.
  window_.reset();
  test_step = kSnapped;
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // Drag the pointer a bit more within |target_window| and then releases the
  // mouse button and ensures drag controller delivers the events properly and
  // exit gracefully.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(5);
  gfx::Point location(30, 30);
  for (size_t count = 1; count <= 5; ++count) {
    SendDndMotionForWindowDrag(location);
    location.Offset(0, 3);
  }
  EXPECT_EQ(gfx::Point(30, 42), screen_->GetCursorScreenPoint());
  EXPECT_EQ(target_window->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({50, 50}, {}));

  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce([&](Event* event) {
    EXPECT_TRUE(event->IsTouchEvent());
    switch (test_step) {
      case kSnapped:
        EXPECT_EQ(EventType::kTouchReleased, event->type());
        EXPECT_EQ(State::kDropped, drag_controller_state());
        EXPECT_EQ(target_window,
                  window_manager()->GetCurrentPointerOrTouchFocusedWindow());
        test_step = kDone;
        break;
      default:
        FAIL() << " event=" << event->GetName()
               << " state=" << drag_controller_state()
               << " step=" << static_cast<int>(test_step);
    }
  });

  SendDndDropAndFinished();
  SendTouchUp(0 /*touch id*/);
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
}

// Verifies wl_data_device::leave events are properly handled and propagated
// while in window dragging "attached" mode.
TEST_P(WaylandWindowDragControllerTest, DragExitAttached) {
  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(1);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  WaylandTestBase::SyncDisplay();
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // Emulate a [motion => leave] event sequence and make sure the correct
  // ui::Events are dispatched in response.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(1);
  SendDndMotionForWindowDrag({50, 50});

  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce([&](Event* event) {
    EXPECT_EQ(EventType::kMouseDragged, event->type());
    EXPECT_EQ(gfx::Point(50, -1).ToString(),
              event->AsMouseEvent()->location().ToString());
  });
  SendDndLeave();

  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(1);
  SendDndDropAndFinished();

  SendPointerEnter(window_.get(), &delegate_);

  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Verifies wl_data_device::leave events are properly handled and propagated
// while in window dragging "attached" mode.
TEST_P(WaylandWindowDragControllerTest, DragExitAttached_TOUCH) {
  // Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendTouchDown(window_.get(), &delegate_, 0 /*point id*/, {0, 0} /*location*/);
  SendTouchMotion(window_.get(), &delegate_, 0 /*point id*/,
                  {10, 10} /*location*/);
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // Emulate a [motion => leave] event sequence and make sure the correct
  // ui::Events are dispatched in response.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(1);
  SendDndMotionForWindowDrag({50, 50});

  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce([&](Event* event) {
    EXPECT_EQ(EventType::kTouchMoved, event->type());
    EXPECT_EQ(gfx::Point(50, -10).ToString(),
              event->AsTouchEvent()->location().ToString());
  });
  SendDndLeave();

  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(1);
  SendDndDropAndFinished();
}

using BoundsChange = PlatformWindowDelegate::BoundsChange;

TEST_P(WaylandWindowDragControllerTest, RestoreDuringWindowDragSession) {
  const gfx::Rect original_bounds = window_->GetBoundsInDIP();
  wl::ScopedWlArray states({XDG_TOPLEVEL_STATE_ACTIVATED});

  // Maximize and check restored bounds is correctly set.
  constexpr gfx::Rect kMaximizedBounds{1024, 768};
  EXPECT_CALL(delegate_, OnBoundsChanged(testing::Eq(BoundsChange(false))));
  window_->Maximize();
  states.AddStateToWlArray(XDG_TOPLEVEL_STATE_MAXIMIZED);
  SendConfigureEvent(window_->root_surface()->get_surface_id(),
                     kMaximizedBounds.size(), states);

  EXPECT_EQ(kMaximizedBounds, window_->GetBoundsInDIP());

  auto restored_bounds = window_->GetRestoredBoundsInDIP();
  EXPECT_EQ(original_bounds, restored_bounds);

  // Start a window drag session.
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(WaylandWindowDragController::State::kAttached,
            drag_controller_state());

  // Call restore and ensure it's no-op.
  window_->Restore();
  EXPECT_EQ(PlatformWindowState::kMaximized, window_->GetPlatformWindowState());
}

// Regression test for https://crbug.com/1169446.
TEST_P(WaylandWindowDragControllerTest, MotionEventsSkippedWhileReattaching) {
  auto* dragged_window = window_.get();
  EXPECT_TRUE(dragged_window);

  SendPointerEnter(dragged_window, &delegate_);
  SendPointerPress(dragged_window, &delegate_, BTN_LEFT);
  SendPointerMotion(dragged_window, &delegate_, {10, 10});

  // Ensure the controller's state is updated accordingly and a MOUSE_ENTERED
  // event is dispatched in response to wl_data_device.enter.
  EXPECT_CALL(delegate(), DispatchEvent(_)).Times(1);
  // Start the drag session.
  GetWaylandToplevelExtension(*dragged_window)
      ->StartWindowDraggingSessionIfNeeded(DragEventSource::kMouse,
                                           /*allow_system_drag=*/false);
  WaylandTestBase::SyncDisplay();
  EXPECT_EQ(State::kAttached, drag_controller_state());

  auto* move_loop_handler = GetWmMoveLoopHandler(*dragged_window);
  ASSERT_TRUE(move_loop_handler);

  auto test = [](WaylandWindowDragControllerTest* self,
                 WmMoveLoopHandler* move_loop_handler) {
    // While in |kDetached| state, motion events are expected to be propagated
    // by window drag controller as bounds changes.
    EXPECT_EQ(State::kDetached, self->drag_controller_state());
    EXPECT_CALL(self->delegate(), OnBoundsChanged(_))
        .WillOnce([&](const PlatformWindowDelegate::BoundsChange& change) {
          EXPECT_EQ(gfx::Point(30, 30),
                    self->window()->GetBoundsInDIP().origin());
          EXPECT_TRUE(change.origin_changed);
        });
    self->SendDndMotionForWindowDrag({30, 30});

    move_loop_handler->EndMoveLoop();

    // Otherwise, after the move loop is requested to quit, but before it really
    // ends (ie. kAttaching state), motion events are **not** expected to be
    // propagated.
    EXPECT_EQ(State::kAttaching, self->drag_controller_state());
    EXPECT_CALL(self->delegate(), OnBoundsChanged(_)).Times(0);
    self->SendDndMotionForWindowDrag({31, 31});
  };
  ScheduleTestTask(base::BindOnce(test, base::Unretained(this),
                                  base::Unretained(move_loop_handler)));

  // Spins move loop for |window_1|.
  // TODO(nickdiego): Should succeed for this test case.
  EXPECT_FALSE(move_loop_handler->RunMoveLoop({}));

  // When the transition to |kAttached| state is finally done (ie. nested loop
  // quits), motion events are then expected to be propagated by window drag
  // controller as usual.
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_CALL(delegate(), DispatchEvent(_)).Times(1);
  SendDndMotionForWindowDrag({30, 30});

  EXPECT_CALL(delegate(), DispatchEvent(_)).Times(1);
  SendDndDropAndFinished();

  SendPointerEnter(window_.get(), &delegate_);

  EXPECT_EQ(State::kIdle, drag_controller_state());
}

// Test that cursor position is using DIP coordinates and is updated correctly
// on DragMotion event.
TEST_P(WaylandWindowDragControllerTest, CursorPositionIsUpdatedOnMotion) {
  constexpr gfx::Rect kOutputBounds(0, 0, 1920, 1080);
  PostToServerAndWait([&](wl::TestWaylandServerThread* server) {
    // Configure the first output with scale 1.
    wl::TestOutput* output1 = server->output();
    output1->SetPhysicalAndLogicalBounds(kOutputBounds);
    output1->Flush();

    // Creating a second output with scale 2.
    auto* output2 =
        server->CreateAndInitializeOutput(wl::TestOutputMetrics(kOutputBounds));
    output2->SetScale(2);
  });

  WaitForAllDisplaysReady();

  const std::vector<display::Display>& displays = screen_->GetAllDisplays();
  EXPECT_EQ(displays.size(), 2u);

  // Start a window drag session.
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  gfx::Point p0{10, 10};
  SendPointerMotion(window_.get(), &delegate_, p0);
  EXPECT_EQ(p0, screen_->GetCursorScreenPoint());

  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  EXPECT_CALL(delegate(), DispatchEvent(_)).Times(::testing::AtLeast(2));
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  WaylandTestBase::SyncDisplay();
  // Starting a DnD session results in a server sending a Enter event, which
  // enters the window at 0x0.
  EXPECT_EQ(gfx::Point(0, 0), screen_->GetCursorScreenPoint());
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // Now move the pointer to 10x10 location and start the test.
  SendDndMotionForWindowDrag(p0);
  EXPECT_EQ(p0, screen_->GetCursorScreenPoint());

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);
  auto test = [](WaylandWindowDragControllerTest* self, WaylandScreen* screen,
                 const WaylandOutputManager::OutputList* outputs,
                 wl::TestWaylandServerThread* server, WaylandWindow* window,
                 WmMoveLoopHandler* move_loop_handler) {
    ASSERT_TRUE(outputs);
    for (const auto& output : *outputs) {
      SCOPED_TRACE(
          base::StringPrintf("Output Scale=%f", output.second->scale_factor()));
      gfx::Point p0{10, 10};
      // Compute the expected point first as drag operation will move the
      // window.
      gfx::Point expected_point = p0;
      expected_point += window->GetBoundsInDIP().origin().OffsetFromOrigin();
      EXPECT_EQ(expected_point, screen->GetCursorScreenPoint());

      // Resetting cursor to the initial position.
      self->SendDndMotionForWindowDrag(p0);

      // Send the window to |output|.
      const uint32_t surface_id = window->root_surface()->get_surface_id();
      const uint32_t output_id = wl_proxy_get_id(
          reinterpret_cast<wl_proxy*>(output.second->get_output()));
      self->PostToServerAndWait([surface_id, output_id](
                                    wl::TestWaylandServerThread* server) {
        wl::MockSurface* surface =
            server->GetObject<wl::MockSurface>(surface_id);
        ASSERT_TRUE(surface);
        wl::TestOutput* output = server->GetObject<wl::TestOutput>(output_id);
        ASSERT_TRUE(output);
        wl_surface_send_enter(surface->resource(), output->resource());
      });
      EXPECT_EQ(output.second->scale_factor(),
                window->applied_state().window_scale);

      gfx::Point p1{20, 20};
      expected_point = p1;
      expected_point += window->GetBoundsInDIP().origin().OffsetFromOrigin();

      self->SendDndMotionForWindowDrag(p1);

      EXPECT_EQ(expected_point, screen->GetCursorScreenPoint());
      self->PostToServerAndWait([surface_id, output_id](
                                    wl::TestWaylandServerThread* server) {
        wl::MockSurface* surface =
            server->GetObject<wl::MockSurface>(surface_id);
        ASSERT_TRUE(surface);
        wl::TestOutput* output = server->GetObject<wl::TestOutput>(output_id);
        ASSERT_TRUE(output);

        wl_surface_send_leave(surface->resource(), output->resource());
      });
    }

    move_loop_handler->EndMoveLoop();
  };

  const WaylandOutputManager::OutputList* outputs =
      &connection_->wayland_output_manager()->GetAllOutputs();
  ScheduleTestTask(base::BindOnce(
      test, base::Unretained(this), base::Unretained(screen_.get()),
      base::Unretained(outputs), base::Unretained(&server_),
      base::Unretained(window_.get()), base::Unretained(move_loop_handler)));
  move_loop_handler->RunMoveLoop({});
}

// Ensure no memory issues happen when the dragged window is destroyed just
// after quitting the move loop. Regression test for crbug.com/1267791 and
// should be caught in both regular and ASAN builds, where more details about
// the actual memory issue is provided.
TEST_P(WaylandWindowDragControllerTest,
       HandleDraggedWindowDestructionAfterMoveLoop) {
  // 1. Ensure there is no window currently focused
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  // 2. Start the window drag session.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);
  ScheduleTestTask(
      base::BindLambdaForTesting([&]() { move_loop_handler->EndMoveLoop(); }));

  // 3. Run the move loop. The client should receive the data_device.data_offer
  // and data_device.data_enter events before the drag is halted. Ensure these
  // server events arrive at the client before proceeding to ensure tests are
  // asserting on a consistent expected ordering of events.
  EXPECT_FALSE(move_loop_handler->RunMoveLoop({}));
  WaylandTestBase::SyncDisplay();

  // 4. Destroy the dragged window just after quitting move loop.
  const auto* dangling_window_ptr = window_.get();
  window_.reset();
  EXPECT_NE(dangling_window_ptr, TestApi(drag_controller()).events_grabber());
  EXPECT_EQ(State::kIdle, drag_controller_state());

  // 5. Ensure no events are dispatched for drop. Which indirectly means that
  // drop handling code at window drag controller does not call into the above
  // destroyed dragged window.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  TestApi(drag_controller()).EmulateOnDragDrop(EventTimeForNow());

  // 6. Verifies that related state is correctly reset after drop.
  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Ensure no memory issues happen when the dragged and/or events grabber windows
// get destroyed while the move loop is running.
TEST_P(WaylandWindowDragControllerTest,
       HandleWindowsDestructionDuringMoveLoop) {
  // 1. Send some initial pointer events to |window_|.
  ASSERT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  // 2. Start the window drag session.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_TRUE(drag_controller()->IsActiveDragAndDropSession());

  // 3. Spawns a new toplevel |window_2| out of the origin |window_|. Similarly
  // to when a tab is detached in a Chrome's tab drag session.
  PlatformWindowInitProperties properties{gfx::Rect{80, 80}};
  properties.type = PlatformWindowType::kWindow;
  MockWaylandPlatformWindowDelegate delegate_2;
  EXPECT_CALL(delegate_2, OnAcceleratedWidgetAvailable(_)).Times(1);
  auto window_2 =
      delegate_2.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_NE(gfx::kNullAcceleratedWidget, window_2->GetWidget());
  window_2->Show(/*inactive=*/false);
  WaylandTestBase::SyncDisplay();

  // Spin the nested move loop and schedule a sequence of test steps to be
  // pefomed while it is running.
  ScheduleTestTask(base::BindLambdaForTesting([&]() {
    auto* cursor_tracker = connection_->wayland_cursor_position();
    ASSERT_TRUE(cursor_tracker);

    // Send a motion event and verify it is correctly propagated.
    EXPECT_CALL(delegate_2, OnBoundsChanged(_)).Times(1);
    SendDndMotionForWindowDrag({11, 10});
    EXPECT_EQ(gfx::Point(11, 10), cursor_tracker->GetCursorSurfacePoint());
    Mock::VerifyAndClearExpectations(&delegate_2);

    // Destroy the window being currently dragged. This will end the drag
    // session.
    window_2.reset();
    EXPECT_FALSE(drag_controller()->IsActiveDragAndDropSession());

    // Verify drag-and-drop events are not propagated after the drag ends.
    EXPECT_CALL(delegate_2, DispatchEvent(_)).Times(0);
    EXPECT_CALL(delegate_2, OnBoundsChanged(_)).Times(0);
    SendDndMotionForWindowDrag({12, 10});
    TestApi(drag_controller()).EmulateOnDragDrop(EventTimeForNow());
    Mock::VerifyAndClearExpectations(&delegate_2);

    // Verify that internal "last cursor position" is not updated after the
    // grab owner is destroyed.
    EXPECT_EQ(gfx::Point(11, 10), cursor_tracker->GetCursorSurfacePoint());
  }));

  ASSERT_TRUE(GetWmMoveLoopHandler(*window_2));
  EXPECT_FALSE(GetWmMoveLoopHandler(*window_2)->RunMoveLoop({}));

  // 4. Verifies that related state is correctly reset after the drag was
  // terminated. The remaining `window_` should remain under the pointer.
  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(window_->GetWidget(),
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));
}

// Ensures correct behavior when ext-drag protocol is not available, such as:
//
// 1. Returns 'success' even when wl_data_source.cancelled is sent by the
//    Wayland Compositor.
//
//  Regression test for https://crbug.com/1366504.
TEST_P(WaylandWindowDragControllerTest, ExtendedDragUnavailable) {
  ASSERT_TRUE(GetWmMoveLoopHandler(*window_));
  ASSERT_TRUE(GetWaylandToplevelExtension(*window_));
  TestApi(drag_controller()).set_extended_drag_available(false);

  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  auto* move_loop_handler = GetWmMoveLoopHandler(*window_);
  ASSERT_TRUE(move_loop_handler);

  enum { kStarted, kDropping, kDone } test_step = kStarted;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillRepeatedly([&](Event* event) {
    EXPECT_TRUE(event->IsMouseEvent());
    switch (test_step) {
      case kStarted:
        EXPECT_EQ(EventType::kMouseEntered, event->type());
        EXPECT_EQ(State::kDetached, drag_controller_state());

        // We are in the middle of
        // WaylandWindowDragController::OnDragEnter. Run this via a task run.
        // Otherwise, the data offer will be reset and
        // WaylandWindowDragController will crash.
        ScheduleTestTask(base::BindOnce(&WaylandDragDropTest::SendDndCancelled,
                                        base::Unretained(this)));
        test_step = kDropping;
        break;
      case kDropping: {
        EXPECT_EQ(EventType::kMouseReleased, event->type());
        EXPECT_EQ(State::kDropped, drag_controller_state());

        test_step = kDone;
        break;
      }
      case kDone:
        EXPECT_EQ(EventType::kMouseExited, event->type());
        EXPECT_EQ(window_->GetWidget(),
                  screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
        break;
    }
  });

  // RunMoveLoop() blocks until the dragging session ends, so resume test
  // server's run loop until it returns.
  bool succeeded = move_loop_handler->RunMoveLoop({});
  EXPECT_TRUE(succeeded);

  SendPointerEnter(window_.get(), &delegate_);

  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_EQ(window_.get(),
            window_manager()->GetCurrentPointerOrTouchFocusedWindow());
}

TEST_P(WaylandWindowDragControllerTest, GetSerial) {
  auto* origin = static_cast<WaylandToplevelWindow*>(window_.get());
  auto& window_manager = *connection_->window_manager();

  window_manager.SetPointerFocusedWindow(nullptr);
  window_manager.SetTouchFocusedWindow(nullptr);
  serial_tracker().ClearForTesting();
  {  // No serial, no window focused.
    auto serial =
        TestApi(drag_controller()).GetSerial(DragEventSource::kMouse, origin);
    EXPECT_FALSE(serial.has_value());
  }

  // Check cases where only pointer focus info is set.
  {  // Serial available, but no window focused.
    serial_tracker().UpdateSerial(wl::SerialType::kMousePress, 1u);
    auto serial =
        TestApi(drag_controller()).GetSerial(DragEventSource::kMouse, origin);
    EXPECT_FALSE(serial.has_value());
  }

  {  // Both serial and focused window available.
    window_manager.SetPointerFocusedWindow(window_.get());
    auto serial =
        TestApi(drag_controller()).GetSerial(DragEventSource::kMouse, origin);
    ASSERT_TRUE(serial.has_value());
    EXPECT_EQ(wl::SerialType::kMousePress, serial->type);
    EXPECT_EQ(1u, serial->value);
  }

  // Reset and check cases where only touch focus info is set.
  window_manager.SetPointerFocusedWindow(nullptr);
  window_manager.SetTouchFocusedWindow(nullptr);
  serial_tracker().ClearForTesting();
  {  // Serial available, but no window focused.
    serial_tracker().UpdateSerial(wl::SerialType::kTouchPress, 2u);
    auto serial =
        TestApi(drag_controller()).GetSerial(DragEventSource::kTouch, origin);
    EXPECT_FALSE(serial.has_value());
  }
  {  // Both serial and focused window available.
    window_manager.SetTouchFocusedWindow(window_.get());
    auto serial =
        TestApi(drag_controller()).GetSerial(DragEventSource::kTouch, origin);
    ASSERT_TRUE(serial.has_value());
    EXPECT_EQ(wl::SerialType::kTouchPress, serial->type);
    EXPECT_EQ(2u, serial->value);
  }
  // Reset focused window and serial information.
  window_manager.SetPointerFocusedWindow(nullptr);
  window_manager.SetTouchFocusedWindow(nullptr);
  serial_tracker().ClearForTesting();
}

TEST_P(WaylandWindowDragControllerTest, NoopUnlessPointerOrTouchPressed) {
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());

  // Press left mouse button within |window_|.
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);

  // Drag mustn't start for touch source while there is no active touch points.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);
  ASSERT_EQ(State::kIdle, drag_controller_state());
  ASSERT_FALSE(drag_controller()->drag_source().has_value());
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    ASSERT_FALSE(server->data_device_manager()->data_source());
  });
  SendPointerButton(window_.get(), &delegate_, BTN_LEFT, /*pressed=*/false);

  ASSERT_FALSE(serial_tracker().GetSerial(wl::SerialType::kTouchPress));

  // Now it should start successfully.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);
  ASSERT_EQ(State::kIdle, drag_controller_state());
}

ACTION_P(CloneEvent, ptr) {
  *ptr = arg0->Clone();
}

// Regression test for https://crbug.com/400486350.
TEST_P(WaylandWindowDragControllerTest,
       CancelIfPointerButtonIsReleasedBeforeFirstEnter) {
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());

  // Press left mouse button within |window_|.
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);

  // Ensure (at test compositor side) wl_data_device offer and enter are not
  // automatically sent when the next drag session is started.
  ASSERT_TRUE(connection_->data_device_manager()->GetDevice());
  PostToServerAndWait([](wl::TestWaylandServerThread* server) {
    ASSERT_FALSE(server->data_device_manager()->data_source());
    ASSERT_TRUE(server->data_device_manager()->data_device());
    server->data_device_manager()
        ->data_device()
        ->disable_auto_send_start_drag_events();
  });

  // Request the drag to start and ensure internal state is set as expected.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  ASSERT_EQ(State::kAttached, drag_controller_state());
  ASSERT_TRUE(drag_controller()->drag_source().has_value());

  // Now the edge case emulation: send a wl_pointer.button release before the
  // very first wl_data_device has been sent and ensure the drag session is
  // cancelled, internal state is reset and the corresponding mouse event
  // gets dispatched.
  std::unique_ptr<Event> event;
  EXPECT_CALL(delegate_, DispatchEvent(_)).WillOnce(CloneEvent(&event));
  SendPointerButton(window_.get(), &delegate_, BTN_LEFT, /*pressed=*/false);
  Mock::VerifyAndClearExpectations(&delegate_);
  ASSERT_TRUE(event->IsMouseEvent());
  EXPECT_TRUE(event->AsMouseEvent()->IsLeftMouseButton());
  EXPECT_EQ(event->type(), ui::EventType::kMouseReleased);
  ASSERT_EQ(State::kIdle, drag_controller_state());
  ASSERT_FALSE(drag_controller()->drag_source().has_value());
}

// Ensure events are handled appropriately when the target window is destroyed
// while the move loop is running (i.e. dragging in the detached state).
// Regression test for crbug.com/1433577.
TEST_P(WaylandWindowDragControllerTest,
       HandleTargetWindowDestruction_DetachedState) {
  // Send some initial pointer events to `window_`.
  ASSERT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  // Start the window drag session.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_TRUE(drag_controller()->IsActiveDragAndDropSession());

  // Spawns a new toplevel `window_2` out of the origin `window_`. Similarly to
  // when a tab is detached in a Chrome's tab drag session.
  PlatformWindowInitProperties properties{gfx::Rect{80, 80}};
  properties.type = PlatformWindowType::kWindow;
  MockWaylandPlatformWindowDelegate delegate_2;
  EXPECT_CALL(delegate_2, OnAcceleratedWidgetAvailable(_)).Times(1);
  auto window_2 =
      delegate_2.CreateWaylandWindow(connection_.get(), std::move(properties));
  ASSERT_NE(gfx::kNullAcceleratedWidget, window_2->GetWidget());
  window_2->Show(/*inactive=*/false);
  WaylandTestBase::SyncDisplay();

  // Spin the nested move loop and schedule a sequence of test steps to be
  // performed while it is running.
  ScheduleTestTask(base::BindLambdaForTesting([&]() {
    auto* cursor_tracker = connection_->wayland_cursor_position();
    ASSERT_TRUE(cursor_tracker);

    // Running the move loop will initiate dragging the window in the detached
    // state.
    EXPECT_EQ(State::kDetached, drag_controller_state());

    // Send a motion event and verify it is correctly propagated.
    EXPECT_CALL(delegate_2, OnBoundsChanged(_)).Times(1);
    SendDndMotionForWindowDrag({11, 10});
    EXPECT_EQ(gfx::Point(11, 10), cursor_tracker->GetCursorSurfacePoint());

    // Destroy the target window (which at this point should be the origin
    // window, grab owner and the target window).
    EXPECT_EQ(window_.get(), TestApi(drag_controller()).drag_target_window());
    EXPECT_EQ(window_.get(), TestApi(drag_controller()).events_grabber());
    EXPECT_EQ(window_.get(), TestApi(drag_controller()).origin_window());
    window_.reset();
    EXPECT_FALSE(drag_controller()->IsActiveDragAndDropSession());

    // Verify drag-and-drop events are not propagated for either the dragged
    // window or the origin windows after the drag ends.
    EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
    EXPECT_CALL(delegate_, OnBoundsChanged(_)).Times(0);
    EXPECT_CALL(delegate_2, DispatchEvent(_)).Times(0);
    EXPECT_CALL(delegate_2, OnBoundsChanged(_)).Times(0);
    SendDndMotionForWindowDrag({12, 10});
    TestApi(drag_controller()).EmulateOnDragDrop(EventTimeForNow());

    // Verify that internal "last cursor position" is not updated after the
    // grab owner is destroyed.
    EXPECT_EQ(gfx::Point(11, 10), cursor_tracker->GetCursorSurfacePoint());
  }));

  ASSERT_TRUE(GetWmMoveLoopHandler(*window_2));
  EXPECT_FALSE(GetWmMoveLoopHandler(*window_2)->RunMoveLoop({}));

  // Verifies that related state is correctly reset.
  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

// Ensure events are handled appropriately when the target window is destroyed
// while dragging a tab attached to the window (i.e. dragging in the attached
// state).
// Regression test for crbug.com/1433577.
TEST_P(WaylandWindowDragControllerTest,
       HandleTargetWindowDestruction_AttachedState) {
  // Send some initial pointer events to |window_|.
  ASSERT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, {10, 10});

  // Start the window drag session.
  auto* wayland_extension = GetWaylandToplevelExtension(*window_);
  wayland_extension->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());
  EXPECT_TRUE(drag_controller()->IsActiveDragAndDropSession());

  // Move the tab around in the tab strip and validate the cursor is tracked
  // correctly.
  auto* cursor_tracker = connection_->wayland_cursor_position();
  ASSERT_TRUE(cursor_tracker);

  SendDndMotionForWindowDrag({11, 10});
  EXPECT_EQ(gfx::Point(11, 10), cursor_tracker->GetCursorSurfacePoint());
  SendDndMotionForWindowDrag({12, 10});
  EXPECT_EQ(gfx::Point(12, 10), cursor_tracker->GetCursorSurfacePoint());

  // Destroy the target window (which at this point should be the origin window,
  // grab owner and the target window).
  EXPECT_EQ(window_.get(), TestApi(drag_controller()).drag_target_window());
  EXPECT_EQ(window_.get(), TestApi(drag_controller()).events_grabber());
  EXPECT_EQ(window_.get(), TestApi(drag_controller()).origin_window());
  window_.reset();
  EXPECT_FALSE(drag_controller()->IsActiveDragAndDropSession());

  // Verify drag-and-drop events are not propagated after the drag session has
  // ended.
  EXPECT_CALL(delegate_, DispatchEvent(_)).Times(0);
  SendDndMotionForWindowDrag({13, 10});
  TestApi(drag_controller()).EmulateOnDragDrop(EventTimeForNow());

  // Verifies that related state is correctly reset.
  EXPECT_EQ(State::kIdle, drag_controller_state());
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({20, 20}, {}));
}

TEST_P(WaylandWindowDragControllerTest,
       PointerReleaseBeforeServerAckCancellsDrag) {
  // Ensure there is no window currently focused.
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerMotion(window_.get(), &delegate_, /*location=*/{10, 10});

  // Start the drag session.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // Simulate a pointer release event arriving at the client before the server
  // has acknowledged the drag request. This should cancel the drag.
  pointer_delegate()->OnPointerButtonEvent(
      EventType::kMouseReleased, EF_LEFT_MOUSE_BUTTON, base::TimeTicks::Now(),
      window_.get(), wl::EventDispatchPolicy::kImmediate,
      /*allow_release_of_unpressed_button=*/false,
      /*is_synthesized=*/false);
  EXPECT_EQ(State::kIdle, drag_controller_state());
}

TEST_P(WaylandWindowDragControllerTest,
       TouchReleaseBeforeServerAckCancellsDrag) {
  // Ensure there is no window currently focused.
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());
  EXPECT_EQ(gfx::kNullAcceleratedWidget,
            screen_->GetLocalProcessWidgetAtPoint({10, 10}, {}));

  SendTouchDown(window_.get(), &delegate_, /*id=*/0, /*location=*/{0, 0});
  SendTouchMotion(window_.get(), &delegate_, /*id=*/0, /*location=*/{10, 10});

  // Start the drag session.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kTouch,
      /*allow_system_drag=*/false);
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // Simulate a touch release event arriving at the client before the server
  // has acknowledged the drag request. This should cancel the drag.
  touch_delegate()->OnTouchReleaseEvent(base::TimeTicks::Now(), /*id=*/0,
                                        wl::EventDispatchPolicy::kImmediate,
                                        /*is_synthesized=*/false);
  EXPECT_EQ(State::kIdle, drag_controller_state());
}

// Regression test for b/336321329. Ensures all pressed mouse buttons are
// released when the window drag ends.
TEST_P(WaylandWindowDragControllerTest, AllPointersReleasedAfterDragEnd) {
  EXPECT_FALSE(window_manager()->GetCurrentPointerOrTouchFocusedWindow());

  // Dispatch enter and press events for several mouse buttons.
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  SendPointerPress(window_.get(), &delegate_, BTN_RIGHT);
  SendPointerPress(window_.get(), &delegate_, BTN_MIDDLE);

  EXPECT_TRUE(pointer_delegate()->IsPointerButtonPressed(EF_LEFT_MOUSE_BUTTON));
  EXPECT_TRUE(
      pointer_delegate()->IsPointerButtonPressed(EF_RIGHT_MOUSE_BUTTON));
  EXPECT_TRUE(
      pointer_delegate()->IsPointerButtonPressed(EF_MIDDLE_MOUSE_BUTTON));

  // Start a drag with multiple mouse buttons pressed.
  GetWaylandToplevelExtension(*window_)->StartWindowDraggingSessionIfNeeded(
      DragEventSource::kMouse,
      /*allow_system_drag=*/false);
  ASSERT_EQ(State::kAttached, drag_controller_state());

  // End the drag, all pressed mouse buttons should have been released.
  SendDndDropAndFinished();
  EXPECT_EQ(State::kIdle, drag_controller_state());

  EXPECT_FALSE(
      pointer_delegate()->IsPointerButtonPressed(EF_LEFT_MOUSE_BUTTON));
  EXPECT_FALSE(
      pointer_delegate()->IsPointerButtonPressed(EF_RIGHT_MOUSE_BUTTON));
  EXPECT_FALSE(
      pointer_delegate()->IsPointerButtonPressed(EF_MIDDLE_MOUSE_BUTTON));
}

// Regression test for crbug.com/330274075. There are circumstances under which
// compositors will not send a send data_source.dnd_finish|cancelled for a
// wayland drag session. This can result in a data drag leaving the shared state
// in the data device in an inconsistent state. If a window drag session is
// requested while in such an inconsistent state this shared state must first be
// reset.
TEST_P(WaylandWindowDragControllerTest, OutgoingSessionWithoutDndFinished) {
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);

  // Once the drag session effectively starts at server-side, emulate a
  // data_source.dnd_drop_performed without its subsequent dnd_finished.
  ScheduleTestTask(
      base::BindLambdaForTesting([&]() { SendDndDropPerformed(); }));

  // Start the data drag session, which spins a nested message loop, and ensure
  // it quits even without wl_data_source.dnd_finished. In which case, the
  // expected side effect is drag controller's internal state left inconsistent,
  // ie: not reset to `kIdle`.
  OSExchangeData os_exchange_data;
  os_exchange_data.SetString(u"dnd-data");
  base::MockOnceCallback<void()> start_callback;
  base::MockOnceCallback<void(mojom::DragOperation)> completion_callback;
  window_->StartDrag(os_exchange_data,
                     DragDropTypes::DRAG_COPY | DragDropTypes::DRAG_MOVE,
                     DragEventSource::kMouse, /*cursor=*/{},
                     /*can_grab_pointer=*/true, start_callback.Get(),
                     completion_callback.Get(),
                     /*loation delegate=*/nullptr);
  EXPECT_NE(connection_->data_drag_controller()->state_,
            WaylandDataDragController::State::kIdle);

  // Attempt to start a window drag with the left mouse button. It should
  // succeed despite data device state not having been reset correctly.
  SendPointerEnter(window_.get(), &delegate_);
  SendPointerPress(window_.get(), &delegate_, BTN_LEFT);
  EXPECT_TRUE(drag_controller()->StartDragSession(
      window_->AsWaylandToplevelWindow(), DragEventSource::kMouse));
  EXPECT_EQ(State::kAttached, drag_controller_state());

  // End the drag.
  SendDndDropAndFinished();
  EXPECT_EQ(State::kIdle, drag_controller_state());
}

INSTANTIATE_TEST_SUITE_P(XdgVersionStableTest,
                         WaylandWindowDragControllerTest,
                         Values(wl::ServerConfig{}));

}  // namespace ui