File: tab_drag_controller_interactive_uitest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; 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,811; 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 (5744 lines) | stat: -rw-r--r-- 233,793 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
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif

#include "chrome/browser/ui/views/tabs/dragging/tab_drag_controller_interactive_uitest.h"

#include <stddef.h>

#include <algorithm>
#include <array>
#include <limits>
#include <memory>
#include <optional>
#include <set>
#include <utility>
#include <vector>

#include "base/command_line.h"
#include "base/dcheck_is_on.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/run_until.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/test_timeouts.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_tabstrip.h"
#include "chrome/browser/ui/tabs/features.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_observer.h"
#include "chrome/browser/ui/tabs/tab_style.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/frame/native_browser_frame_factory.h"
#include "chrome/browser/ui/views/frame/tab_strip_region_view.h"
#include "chrome/browser/ui/views/tabs/dragging/tab_drag_controller.h"
#include "chrome/browser/ui/views/tabs/dragging/tab_drag_controller_interactive_test_mixin.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/browser/ui/views/tabs/window_finder.h"
#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h"
#include "chrome/browser/web_applications/test/os_integration_test_override_impl.h"
#include "chrome/browser/web_applications/test/web_app_install_test_utils.h"
#include "chrome/browser/web_applications/web_app_provider.h"
#include "chrome/browser/web_applications/web_app_registrar.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "chromeos/ui/base/window_properties.h"
#include "components/constrained_window/constrained_window_views.h"
#include "components/tab_groups/tab_group_color.h"
#include "components/tab_groups/tab_group_id.h"
#include "components/tab_groups/tab_group_visual_data.h"
#include "components/tabs/public/split_tab_data.h"
#include "components/tabs/public/split_tab_id.h"
#include "components/tabs/public/tab_group.h"
#include "components/tabs/public/tab_interface.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/features.h"
#include "ui/aura/env.h"
#include "ui/base/mojom/ui_base_types.mojom-shared.h"
#include "ui/base/mojom/window_show_state.mojom.h"
#include "ui/base/test/ui_controls.h"
#include "ui/compositor/layer.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/animation/animation_test_api.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/test/widget_activation_waiter.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"

#if defined(USE_AURA)
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/test_windows.h"
#include "ui/aura/window_targeter.h"
#endif

#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/ui/views/frame/desktop_browser_frame_aura.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#endif

#if BUILDFLAG(IS_CHROMEOS)
#include "ash/public/cpp/split_view_test_api.h"
#include "ash/public/cpp/test/shell_test_api.h"
#include "ash/public/cpp/window_properties.h"
#include "ash/shell.h"
#include "ash/wm/window_state.h"
#include "base/test/simple_test_tick_clock.h"
#include "chrome/browser/ash/system_web_apps/test_support/test_system_web_app_installation.h"
#include "chrome/browser/ui/views/frame/browser_view_layout.h"
#include "chrome/browser/ui/views/frame/immersive_mode_controller.h"
#include "chrome/browser/ui/views/frame/immersive_mode_controller_chromeos.h"
#include "chromeos/ui/frame/immersive/immersive_fullscreen_controller_test_api.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/cursor_shape_client.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/cursor/cursor.h"
#include "ui/display/manager/display_manager.h"
#include "ui/display/test/display_manager_test_api.h"  // nogncheck
#include "ui/events/base_event_utils.h"
#include "ui/events/gesture_detection/gesture_configuration.h"
#endif

#if BUILDFLAG(IS_LINUX)
#include "chrome/browser/ui/views/frame/desktop_browser_frame_aura_linux.h"
#include "ui/ozone/public/ozone_platform.h"
#define DESKTOP_BROWSER_FRAME_AURA DesktopBrowserFrameAuraLinux
#else
#define DESKTOP_BROWSER_FRAME_AURA DesktopBrowserFrameAura
#endif

#if BUILDFLAG(IS_WIN)
#include "ui/base/ui_base_features.h"
#endif

using content::WebContents;
using display::Display;
using ui_test_utils::GetDisplays;

namespace test {

namespace {

const char kTabDragControllerInteractiveUITestUserDataKey[] =
    "TabDragControllerInteractiveUITestUserData";

class TabDragControllerInteractiveUITestUserData
    : public base::SupportsUserData::Data {
 public:
  explicit TabDragControllerInteractiveUITestUserData(int id) : id_(id) {}
  ~TabDragControllerInteractiveUITestUserData() override = default;
  int id() { return id_; }

 private:
  int id_;
};

#if BUILDFLAG(IS_CHROMEOS)
aura::Window* GetWindowForTabStrip(TabStrip* tab_strip) {
  return tab_strip ? tab_strip->GetWidget()->GetNativeWindow() : nullptr;
}
#endif

gfx::Point GetLeftCenterInScreenCoordinates(const views::View* view) {
  gfx::Point center = view->GetLocalBounds().CenterPoint();
  center.set_x(center.x() - view->GetLocalBounds().width() / 4);
  views::View::ConvertPointToScreen(view, &center);
  return center;
}

gfx::Point GetRightCenterInScreenCoordinates(const views::View* view) {
  gfx::Point center = view->GetLocalBounds().CenterPoint();
  center.set_x(center.x() + view->GetLocalBounds().width() / 4);
  views::View::ConvertPointToScreen(view, &center);
  return center;
}

Browser* WaitForActiveBrowser(const BrowserList* list, size_t num_browsers) {
  if (num_browsers != list->size()) {
    ADD_FAILURE() << "Unexpected browser count: expected " << num_browsers
                  << ", got " << list->size();
    return nullptr;
  }
  Browser* new_browser = list->get(num_browsers - 1);

  views::test::WaitForWidgetActive(
      BrowserView::GetBrowserViewForBrowser(new_browser)->GetWidget(), true);
  if (!new_browser->window()->IsActive()) {
    ADD_FAILURE() << "New browser window isn't active";
    return nullptr;
  }

  return new_browser;
}

}  // namespace

// Note: do not use this if the code that ends the drag session runs after
// QuitDraggingObserver::Wait() returns. This will make the test time out when
// using system-DnD-based tab dragging due to the limitations of
// TabDragController::SetDragLoopDoneCallbackForTesting().
//
// If you need to wait for dragged tabs to be attached to another browser, use
// BrowserChangeWaiter instead.
class QuitDraggingObserver {
 public:
  explicit QuitDraggingObserver(TabStrip* tab_strip) {
    tab_strip->GetDragContext()->SetDragControllerCallbackForTesting(
        base::BindOnce(&QuitDraggingObserver::OnDragControllerSet,
                       weak_ptr_factory_.GetWeakPtr()));
  }

  QuitDraggingObserver(const QuitDraggingObserver&) = delete;
  QuitDraggingObserver& operator=(const QuitDraggingObserver&) = delete;
  ~QuitDraggingObserver() = default;

  // The observer should be constructed prior to initiating the drag. To prevent
  // misuse via constructing a temporary object, Wait is marked lvalue-only.
  void Wait() & {
    timeout_warning_timer_.Start(
        FROM_HERE, TestTimeouts::action_max_timeout(),
        base::BindLambdaForTesting([]() {
          LOG(ERROR) << "QuitDraggingObserver::Wait() is taking a long time. "
                        "If this test times out, please check the comment for "
                        "QuitDraggingObserver to see if it should be using "
                        "BrowserChangeWaiter instead.";
          LOG(ERROR) << "Note: you might be using QuitDraggingObserver via "
                        "DragTabAndNotify() or "
                        "DragToDetachGroupAndNotify().";
        }));
    run_loop_.Run();
    timeout_warning_timer_.Stop();
  }

 private:
  void OnDragControllerSet(TabDragController* controller) {
    controller->SetDragLoopDoneCallbackForTesting(base::BindOnce(
        &QuitDraggingObserver::Quit, weak_ptr_factory_.GetWeakPtr()));
  }

  void Quit() { run_loop_.QuitWhenIdle(); }

  base::RunLoop run_loop_;
  base::OneShotTimer timeout_warning_timer_;

  base::WeakPtrFactory<QuitDraggingObserver> weak_ptr_factory_{this};
};

// Wait for a browser be added or removed, e.g. when a new browser is created to
// hold dragged tabs or when such a browser is closed after attaching to another
// browser.
//
// This is similar to ui_test_utils::BrowserChangeObserver, but with the option
// to run a closure in response to a change. This is needed because we might
// have nested `base::RunLoop`s:
// - when using system-DnD-based tab dragging, the system DnD code will spawn a
//   base::RunLoop. If we create a new RunLoop for a waiter before starting the
//   drag, we can't exit the waiter's RunLoop before the drag ends.
// - when using regular tab dragging, we have the same problem, but the nested
//   RunLoop already exits when attaching, even if the mouse is not yet
//   released.
// Therefore, the closure that will be run when a browser is added/removed must
// ensure the following:
// - if using system-DnD-based tab dragging, that the system DnD session ends,
//   by releasing the mouse or cancelling the DnD session;
// - else, that the move loop ends, i.e. attaching to an existing browser or
//   fully ending the tab drag.
class BrowserChangeWaiter : public BrowserListObserver {
 public:
  enum class ChangeType {
    kAdded,
    kRemoved,
  };

  explicit BrowserChangeWaiter(ChangeType type) : type_(type) {
    BrowserList::AddObserver(this);
  }
  BrowserChangeWaiter(const BrowserChangeWaiter&) = delete;
  BrowserChangeWaiter& operator=(const BrowserChangeWaiter&) = delete;
  ~BrowserChangeWaiter() override { BrowserList::RemoveObserver(this); }

  // The closure must ensure the system DnD session/move loop ends (see comment
  // above).
  void Wait(base::OnceClosure closure) {
    closure_ = std::move(closure);
    run_loop_.Run();
  }

  // BrowserListObserver:
  void OnBrowserAdded(Browser* browser) override {
    if (type_ == ChangeType::kAdded) {
      Quit();
    }
  }

  void OnBrowserRemoved(Browser* browser) override {
    if (type_ == ChangeType::kRemoved) {
      Quit();
    }
  }

 private:
  void Quit() {
    if (quit_called_) {
      return;
    }
    // Browser addition/removal callbacks can be called multiple times, calling
    // |Quit()| each time.
    // So make sure that the |closure_| still gets to run if multiple |Quit()|
    // calls happen in quick succession.
    quit_called_ = true;
    if (closure_) {
      // For ChangeType::kRemoved, the browser is still closing and
      // synchronously running the closure now can lead to reentrancy issues, so
      // we instead PostTask() it. We also need to make sure we only quit the
      // RunLoop after the closure has run.
      // It won't hurt to use the same approach for ChangeType::kAdded.
      base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
          FROM_HERE,
          base::BindOnce(
              [](base::OnceClosure closure, base::OnceClosure quit_closure) {
                std::move(closure).Run();
                std::move(quit_closure).Run();
              },
              std::move(closure_), run_loop_.QuitClosure()));
    } else {
      run_loop_.Quit();
    }
  }

  ChangeType type_;
  bool quit_called_ = false;
  base::OnceClosure closure_;
  base::RunLoop run_loop_{base::RunLoop::Type::kNestableTasksAllowed};
};

void SetID(WebContents* web_contents, int id) {
  web_contents->SetUserData(
      &kTabDragControllerInteractiveUITestUserDataKey,
      std::make_unique<TabDragControllerInteractiveUITestUserData>(id));
}

void ResetIDs(TabStripModel* model, int start) {
  for (int i = 0; i < model->count(); ++i) {
    SetID(model->GetWebContentsAt(i), start + i);
  }
}

std::string IDString(TabStripModel* model) {
  std::string result;
  for (int i = 0; i < model->count(); ++i) {
    if (i != 0) {
      result += " ";
    }
    WebContents* contents = model->GetWebContentsAt(i);
    TabDragControllerInteractiveUITestUserData* user_data =
        static_cast<TabDragControllerInteractiveUITestUserData*>(
            contents->GetUserData(
                &kTabDragControllerInteractiveUITestUserDataKey));
    if (user_data) {
      result += base::NumberToString(user_data->id());
    } else {
      result += "?";
    }
  }
  return result;
}

TabStrip* GetTabStripForBrowser(Browser* browser) {
  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
  return browser_view->tabstrip();
}

TabDragController* GetTabDragController(TabStrip* tab_strip) {
  return tab_strip->GetDragContext()->GetDragController();
}

// Resizes the given browser to the specified bounds by using ui_test_utils to
// generate mouse movements, similar to how a regular user would resize the
// window. This is used instead of BrowserWindow::SetBounds() on platforms where
// clients don't have complete control over window bounds (i.e., Wayland).
void ResizeUsingMouseEmulation(Browser* browser,
                               const gfx::Rect& target_bounds) {
#if BUILDFLAG(IS_LINUX)
  auto* window = browser->window()->GetNativeWindow();
  auto width_difference = window->bounds().width() - target_bounds.width();
  auto height_difference = window->bounds().height() - target_bounds.height();

  // Resize the window, if needed.
  if (width_difference != 0 || height_difference != 0) {
    // We use the container bounds because they don't include window
    // decorations.
    auto bottom_right = browser->tab_strip_model()
                            ->GetActiveWebContents()
                            ->GetContainerBounds()
                            .bottom_right();
    auto resize_target = gfx::Point(bottom_right.x() - width_difference,
                                    bottom_right.y() - height_difference);
    ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(bottom_right, window));
    ASSERT_TRUE(ui_test_utils::SendMouseEventsSync(
        ui_controls::MouseButton::LEFT, ui_controls::MouseButtonState::DOWN,
        window));
    ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(resize_target, window));
    ASSERT_TRUE(ui_test_utils::SendMouseEventsSync(
        ui_controls::MouseButton::LEFT, ui_controls::MouseButtonState::UP,
        window));
  }

  // Move the window.
  auto* grab_handle_space = BrowserView::GetBrowserViewForBrowser(browser)
                                ->tab_strip_region_view()
                                ->reserved_grab_handle_space_for_testing();
  auto grab_coordinates =
      ui_test_utils::GetCenterInScreenCoordinates(grab_handle_space);
  gfx::Vector2d grab_offset = {grab_coordinates.x(), grab_coordinates.y()};
  auto move_target = target_bounds.origin() + grab_offset;
  ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(grab_coordinates, window));
  ASSERT_TRUE(ui_test_utils::SendMouseEventsSync(
      ui_controls::MouseButton::LEFT, ui_controls::MouseButtonState::DOWN,
      window));

  // `move_target` is in screen coordinates.
  ui_controls::ForceUseScreenCoordinatesOnce();
  ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(move_target, window));

  ASSERT_TRUE(ui_test_utils::SendMouseEventsSync(
      ui_controls::MouseButton::LEFT, ui_controls::MouseButtonState::UP,
      window));
#endif  // BUILDFLAG(IS_LINUX)
}

// If this returns false, we must use ResizeUsingMouseEmulation() instead of
// BrowserWindow::SetBounds().
bool PlatformSupportsScreenCoordinates() {
#if BUILDFLAG(IS_LINUX)
  return ui::OzonePlatform::GetInstance()
      ->GetPlatformProperties()
      .supports_global_screen_coordinates;
#else
  return true;
#endif  // BUILDFLAG(IS_LINUX)
}

}  // namespace test

using test::GetTabDragController;
using test::GetTabStripForBrowser;
using test::IDString;
using test::ResetIDs;
using test::SetID;
using test::WaitForActiveBrowser;
using ui_test_utils::GetCenterInScreenCoordinates;

TabDragControllerTest::TabDragControllerTest()
    : browser_list_(BrowserList::GetInstance()) {}

TabDragControllerTest::~TabDragControllerTest() = default;

void TabDragControllerTest::StopAnimating(TabStrip* tab_strip) {
  tab_strip->StopAnimating(true);
}

void TabDragControllerTest::AddTabsAndResetBrowser(Browser* browser,
                                                   int additional_tabs,
                                                   const GURL& url) {
  for (int i = 0; i < additional_tabs; i++) {
    auto* contents = chrome::AddSelectedTabWithURL(
        browser, url, ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
    content::WaitForLoadStop(contents);
  }
  browser->window()->Show();
  StopAnimating(GetTabStripForBrowser(browser));
  // Perform any scheduled layouts so the tabstrip is in a steady state.
  BrowserView::GetBrowserViewForBrowser(browser)
      ->GetWidget()
      ->LayoutRootViewIfNecessary();
  ResetIDs(browser->tab_strip_model(), 0);
}

Browser* TabDragControllerTest::CreateAnotherBrowserAndResize() {
  // Resize the two windows so they're right next to each other.

  // If we're using test::ResizeUsingMouseEmulation(), it's important we resize
  // the first browser before creating the second one, else the second browser
  // might occlude the first browser's bottom right corner or tab strip grab
  // handle space, preventing us from resizing or moving it.
  const gfx::NativeWindow window = browser()->window()->GetNativeWindow();
  gfx::Rect work_area =
      display::Screen::GetScreen()->GetDisplayNearestWindow(window).work_area();
  const gfx::Size size(work_area.width() / 3, work_area.height() / 2);
  gfx::Rect browser_rect(work_area.origin() + gfx::Vector2d(50, 50), size);

  if (test::PlatformSupportsScreenCoordinates()) {
    ui_test_utils::SetAndWaitForBounds(*browser(), browser_rect);
    browser_rect.set_x(browser_rect.right());
  } else {
    test::ResizeUsingMouseEmulation(browser(), browser_rect);

    // `container_bounds` doesn't include window decorations, so we can use it
    // to calculate the window decorations' width by comparing its offset from
    // the browser window's bounds.
    auto container_bounds = browser()
                                ->tab_strip_model()
                                ->GetActiveWebContents()
                                ->GetContainerBounds();
    auto window_decoration_width =
        container_bounds.x() - browser()->window()->GetBounds().x();
    // We need to correct for the decorations drawn to the right of the first
    // window and to the left of the second window.
    browser_rect.set_x(browser_rect.right() - 2 * window_decoration_width);
  }

  Browser* browser2 = CreateBrowser(browser()->profile());
  ResetIDs(browser2->tab_strip_model(), 100);
  if (test::PlatformSupportsScreenCoordinates()) {
    ui_test_utils::SetAndWaitForBounds(*browser2, browser_rect);
  } else {
    test::ResizeUsingMouseEmulation(browser2, browser_rect);
  }
  return browser2;
}

void TabDragControllerTest::SetWindowFinderForTabStrip(
    TabStrip* tab_strip,
    std::unique_ptr<WindowFinder> window_finder) {
  ASSERT_TRUE(GetTabDragController(tab_strip));
  GetTabDragController(tab_strip)->window_finder_ = std::move(window_finder);
}

void TabDragControllerTest::HandleGestureEvent(TabStrip* tab_strip,
                                               ui::GestureEvent* event) {
  // Manually dispatch the event to the drag context (which has capture during
  // drags). Mouse/keyboard/touch events can be dispatched normally via test
  // machinery in ui_test_utils that have no direct gesture event equivalent.
  tab_strip->GetDragContext()->OnGestureEvent(event);
}

bool TabDragControllerTest::HasDragStarted(TabStrip* tab_strip) const {
  return GetTabDragController(tab_strip) &&
         GetTabDragController(tab_strip)->started_drag();
}

void TabDragControllerTest::SetUp() {
#if defined(USE_AURA)
  // This needs to be disabled as it can interfere with when events are
  // processed. In particular if input throttling is turned on, then when an
  // event ack runs the event may not have been processed.
  aura::Env::set_initial_throttle_input_on_resize_for_testing(false);
#endif
  InProcessBrowserTest::SetUp();
}

namespace {

int GetDetachY(TabStrip* tab_strip) {
  return std::max(TabDragController::kTouchVerticalDetachMagnetism,
                  TabDragController::kVerticalDetachMagnetism) +
         tab_strip->height() + 1;
}

bool GetIsDragged(Browser* browser) {
#if BUILDFLAG(IS_CHROMEOS)
  return ash::WindowState::Get(browser->window()->GetNativeWindow())
      ->is_dragged();
#else
  return false;
#endif
}

}  // namespace

#if !BUILDFLAG(IS_CHROMEOS) && defined(USE_AURA)

// Following classes verify a crash scenario. Specifically on Windows when focus
// changes it can trigger capture being lost. This was causing a crash in tab
// dragging as it wasn't set up to handle this scenario. These classes
// synthesize this scenario.

// Allows making ClearNativeFocus() invoke ReleaseCapture().
class TestDesktopBrowserFrameAura : public DESKTOP_BROWSER_FRAME_AURA {
 public:
  TestDesktopBrowserFrameAura(BrowserFrame* browser_frame,
                              BrowserView* browser_view)
      : DESKTOP_BROWSER_FRAME_AURA(browser_frame, browser_view) {}
  TestDesktopBrowserFrameAura(const TestDesktopBrowserFrameAura&) = delete;
  TestDesktopBrowserFrameAura& operator=(const TestDesktopBrowserFrameAura&) =
      delete;
  ~TestDesktopBrowserFrameAura() override = default;

  void ReleaseCaptureOnNextClear() { release_capture_ = true; }

  void ClearNativeFocus() override {
    views::DesktopNativeWidgetAura::ClearNativeFocus();
    if (release_capture_) {
      release_capture_ = false;
      GetWidget()->ReleaseCapture();
    }
  }

 private:
  // If true ReleaseCapture() is invoked in ClearNativeFocus().
  bool release_capture_ = false;
};

// Factory for creating a TestDesktopBrowserFrameAura.
class TestNativeBrowserFrameFactory : public NativeBrowserFrameFactory {
 public:
  TestNativeBrowserFrameFactory() = default;
  TestNativeBrowserFrameFactory(const TestNativeBrowserFrameFactory&) = delete;
  TestNativeBrowserFrameFactory& operator=(
      const TestNativeBrowserFrameFactory&) = delete;
  ~TestNativeBrowserFrameFactory() override = default;

  NativeBrowserFrame* Create(BrowserFrame* browser_frame,
                             BrowserView* browser_view) override {
    return new TestDesktopBrowserFrameAura(browser_frame, browser_view);
  }
};

class TabDragCaptureLostTest : public TabDragControllerTest {
 public:
  TabDragCaptureLostTest() {
    NativeBrowserFrameFactory::Set(new TestNativeBrowserFrameFactory);
  }
  TabDragCaptureLostTest(const TabDragCaptureLostTest&) = delete;
  TabDragCaptureLostTest& operator=(const TabDragCaptureLostTest&) = delete;
};

// See description above for details.
IN_PROC_BROWSER_TEST_F(TabDragCaptureLostTest, ReleaseCaptureOnDrag) {
  AddTabsAndResetBrowser(browser(), 1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  gfx::Point tab_1_center(GetCenterInScreenCoordinates(tab_strip->tab_at(1)));
  ASSERT_TRUE(
      ui_test_utils::SendMouseMoveSync(tab_1_center) &&
      ui_test_utils::SendMouseEventsSync(ui_controls::LEFT, ui_controls::DOWN));
  TestDesktopBrowserFrameAura* frame =
      static_cast<TestDesktopBrowserFrameAura*>(
          BrowserView::GetBrowserViewForBrowser(browser())
              ->GetWidget()
              ->native_widget_private());
  // Invoke ReleaseCaptureOnDrag() so that when the drag happens and focus
  // changes capture is released and the drag cancels.
  frame->ReleaseCaptureOnNextClear();
  ASSERT_TRUE(ui_test_utils::SendMouseMoveSync(
      GetCenterInScreenCoordinates(tab_strip->tab_at(0))));
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
}

#endif

IN_PROC_BROWSER_TEST_F(TabDragControllerTest, GestureEndShouldEndDragTest) {
  AddTabsAndResetBrowser(browser(), 1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  Tab* tab1 = tab_strip->tab_at(1);
  gfx::Point tab_1_center(tab1->width() / 2, tab1->height() / 2);

  ui::GestureEvent gesture_tap_down(
      tab_1_center.x(), tab_1_center.x(), 0, base::TimeTicks(),
      ui::GestureEventDetails(ui::EventType::kGestureTapDown));
  tab_strip->MaybeStartDrag(tab1, gesture_tap_down,
                            tab_strip->GetSelectionModel());
  EXPECT_TRUE(TabDragController::IsActive());

  ui::GestureEvent gesture_end(
      tab_1_center.x(), tab_1_center.x(), 0, base::TimeTicks(),
      ui::GestureEventDetails(ui::EventType::kGestureEnd));
  HandleGestureEvent(tab_strip, &gesture_end);
  EXPECT_FALSE(TabDragController::IsActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
}

class DetachToBrowserTabDragControllerTest
    : public TabDragControllerInteractiveTestMixin<TabDragControllerTest>,
      public ::testing::WithParamInterface<
          testing::tuple<bool, bool, const char*>> {
 public:
  DetachToBrowserTabDragControllerTest() {
    std::vector<base::test::FeatureRef> enabled_features = {
        features::kSideBySide};
    std::vector<base::test::FeatureRef> disabled_features = {
        features::kWebUITabStrip};

#if BUILDFLAG(IS_WIN)
    // Disable NativeWinOcclusion to avoid it interfering with test for dragging
    // over occluded browser window.
    disabled_features.push_back(features::kCalculateNativeWinOcclusion);
#endif  // BUILDFLAG(IS_WIN)

    if (std::get<0>(GetParam())) {
      enabled_features.push_back(tabs::kSplitTabStrip);
    }
    if (std::get<1>(GetParam())) {
      enabled_features.push_back(features::kTearOffWebAppTabOpensWebAppWindow);
    }
    scoped_feature_list_.InitWithFeatures(enabled_features, disabled_features);
  }
  DetachToBrowserTabDragControllerTest(
      const DetachToBrowserTabDragControllerTest&) = delete;
  DetachToBrowserTabDragControllerTest& operator=(
      const DetachToBrowserTabDragControllerTest&) = delete;

  void SetUpOnMainThread() override {
#if BUILDFLAG(IS_CHROMEOS)
    root_ = browser()->window()->GetNativeWindow()->GetRootWindow();

    // Disable flings which might otherwise inadvertently be generated from
    // tests' touch events.
    SetMinFlingVelocity(std::numeric_limits<float>::max());
#endif
#if BUILDFLAG(IS_MAC)
    // Currently MacViews' browser windows are shown in the background and could
    // be obscured by other windows if there are any. This should be fixed in
    // order to be consistent with other platforms.
    EXPECT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
#endif  // BUILDFLAG(IS_MAC)
  }

  InputSource input_source() override {
    return strstr(std::get<2>(GetParam()), "mouse")
               ? InputSource::INPUT_SOURCE_MOUSE
               : InputSource::INPUT_SOURCE_TOUCH;
  }

  bool DragInputToAsync(const gfx::Point& location,
                        const gfx::NativeWindow window_hint) {
    if (input_source() == InputSource::INPUT_SOURCE_MOUSE) {
      return ui_controls::SendMouseMove(location.x(), location.y(),
                                        window_hint);
    }
#if BUILDFLAG(IS_CHROMEOS)
    return ui_controls::SendTouchEvents(ui_controls::kTouchMove, 0,
                                        location.x(), location.y());
#else
    NOTREACHED();
#endif
  }

  // Like DragInputToCenter(), but for DragInputToAsync() instead of
  // DragInputTo().
  bool DragInputToCenterAsync(const views::View* view,
                              gfx::Vector2d offset = {}) {
    return DragInputToAsync(GetCenterInScreenCoordinates(view) + offset,
                            GetWindowHint(view));
  }

  bool DragInputToNotifyWhenDone(const gfx::Point& location,
                                 base::OnceClosure task,
                                 const gfx::NativeWindow window_hint) {
    if (input_source() == InputSource::INPUT_SOURCE_MOUSE) {
      return ui_controls::SendMouseMoveNotifyWhenDone(
          location.x(), location.y(), std::move(task), window_hint);
    }

#if BUILDFLAG(IS_CHROMEOS)
    return ui_controls::SendTouchEventsNotifyWhenDone(
        ui_controls::kTouchMove, 0, location.x(), location.y(),
        std::move(task));
#else
    NOTREACHED();
#endif
  }

  // Like DragInputToCenter(), but for DragInputToCenterNotifyWhenDone() instead
  // of DragInputTo().
  bool DragInputToCenterNotifyWhenDone(const views::View* view,
                                       base::OnceClosure task,
                                       gfx::Vector2d offset = {}) {
    gfx::Point location = GetCenterInScreenCoordinates(view) + offset;
    return DragInputToNotifyWhenDone(location, std::move(task),
                                     GetWindowHint(view));
  }

  void ReleaseInputAfterWindowDetached(int first_dragged_tab_width) {
    // On macOS, we want to avoid generating the input event [which requires
    // an associated window] until the window has been detached. Failure to do
    // so causes odd behavior [e.g. on macOS 10.10, the mouse-up will
    // reactivate the first window].
    if (browser_list()->size() != 2u) {
      base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
          FROM_HERE,
          base::BindOnce(&DetachToBrowserTabDragControllerTest::
                             ReleaseInputAfterWindowDetached,
                         base::Unretained(this), first_dragged_tab_width),
          base::Milliseconds(1));
      return;
    }
    // Only check tab width if dragging tabs between windows of the same type.
    if (browser_list()->get(0)->type() == browser_list()->get(1)->type()) {
      // The tab getting dragged into the new browser should have the same
      // width as before it was dragged.
      EXPECT_EQ(
          first_dragged_tab_width,
          GetTabStripForBrowser(browser_list()->get(1))->tab_at(0)->width());
    }
    // Windows hangs if you use a sync mouse event here.
    ASSERT_TRUE(ReleaseInput(0, true));
  }

  bool MoveInputTo(const gfx::Point& location) {
    aura::Env::GetInstance()->SetLastMouseLocation(location);
    if (input_source() == InputSource::INPUT_SOURCE_MOUSE) {
      return ui_test_utils::SendMouseMoveSync(location);
    }
#if BUILDFLAG(IS_CHROMEOS)
    return SendTouchEventsSync(ui_controls::kTouchMove, 0, location);
#else
    NOTREACHED();
#endif
  }

  void AddBlankTabAndShow(Browser* browser) {
    InProcessBrowserTest::AddBlankTabAndShow(browser);
  }

  // Returns true if the tab dragging info is correctly set on the attached
  // browser window.
  bool IsTabDraggingInfoSet(TabStrip* attached_tabstrip) {
    DCHECK(attached_tabstrip);
#if BUILDFLAG(IS_CHROMEOS)
    aura::Window* dragged_window =
        test::GetWindowForTabStrip(attached_tabstrip);
    attached_tabstrip->GetWidget()->GetNativeWindow();
    return dragged_window->GetProperty(ash::kIsDraggingTabsKey);
#else
    return true;
#endif
  }

  // Returns true if the tab dragging info is correctly cleared on the attached
  // browser window.
  bool IsTabDraggingInfoCleared(TabStrip* attached_tabstrip) {
    DCHECK(attached_tabstrip);
#if BUILDFLAG(IS_CHROMEOS)
    aura::Window* dragged_window =
        test::GetWindowForTabStrip(attached_tabstrip);
    return !dragged_window->GetProperty(ash::kIsDraggingTabsKey);
#else
    return true;
#endif
  }

  void DragTabAndNotify(TabStrip* tab_strip,
                        base::OnceClosure task,
                        int tab_index = 0,
                        int drag_x_offset = 0) {
    test::QuitDraggingObserver observer(tab_strip);
    // Move to the tab and drag it enough so that it detaches.
    Tab* tab = tab_strip->tab_at(tab_index);
    ASSERT_TRUE(PressInputAtCenter(tab));
    ASSERT_TRUE(DragInputToCenterNotifyWhenDone(
        tab, std::move(task),
        gfx::Vector2d(drag_x_offset, GetDetachY(tab_strip))));
    observer.Wait();
  }

  void DragToDetachGroupAndNotify(TabStrip* tab_strip,
                                  base::OnceClosure task,
                                  tab_groups::TabGroupId group,
                                  int drag_x_offset = 0) {
    test::QuitDraggingObserver observer(tab_strip);
    // Move to the tab and drag it enough so that it detaches.
    TabGroupHeader* group_header = tab_strip->group_header(group);
    ASSERT_TRUE(PressInputAtCenter(group_header));
    ASSERT_TRUE(DragInputToCenterNotifyWhenDone(
        group_header, std::move(task),
        gfx::Vector2d(drag_x_offset, GetDetachY(tab_strip))));
    observer.Wait();
  }

  // Helper method to click the first tab. Used to ensure no additional widgets
  // are in focus. For example, the tab editor bubble  is automatically opened
  // upon creating a new group.
  void EnsureFocusToTabStrip(TabStrip* tab_strip) {
    ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
    ASSERT_TRUE(ReleaseInput());
  }

  Browser* browser() const { return InProcessBrowserTest::browser(); }

 protected:
#if BUILDFLAG(IS_CHROMEOS)
  void SetMinFlingVelocity(float velocity) {
    ui::GestureConfiguration::GetInstance()->set_min_fling_velocity(velocity);
  }
#endif  // BUILDFLAG(IS_CHROMEOS)

 private:
#if BUILDFLAG(IS_CHROMEOS)
  // The root window for the event generator.
  raw_ptr<aura::Window, DanglingUntriaged> root_ = nullptr;
#endif
  base::test::ScopedFeatureList scoped_feature_list_;
  std::optional<webapps::AppId> tabbed_app_id_;

  // Some of these tests rely on animation being enabled. This forces
  // animation on even if it's turned off in the OS.
  gfx::AnimationTestApi::RenderModeResetter animation_mode_reset_{
      gfx::AnimationTestApi::SetRichAnimationRenderMode(
          gfx::Animation::RichAnimationRenderMode::FORCE_ENABLED)};
};

// Creates a browser with four tabs. The first three belong in the same Tab
// Group. Dragging the third tab to after the fourth tab will result in a
// removal of the dragged tab from its group. Then dragging the second tab to
// after the third tab will also result in a removal of that dragged tab from
// its group.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragRightToUngroupTab) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({0, 1, 2});
  StopAnimating(tab_strip);

  EXPECT_EQ(4, model->count());
  EXPECT_EQ(3u, model->group_model()->GetTabGroup(group)->ListTabs().length());

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(3)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Dragging the tab in the second index to the tab in the third index switches
  // the tabs and removes the dragged tab from the group.
  EXPECT_EQ("0 1 3 2", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 2));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(2));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(3));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Dragging the tab in the first index to the tab in the second index (tab 3)
  // switches the tabs and removes the dragged tab from the group.
  EXPECT_EQ("0 3 1 2", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 1));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(1));
}

// Creates a browser with four tabs. The last three belong in the same Tab
// Group. Dragging the second tab to before the first tab will result in a
// removal of the dragged tab from its group. Then dragging the third tab to
// before the second tab will also result in a removal of that dragged tab from
// its group.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragLeftToUngroupTab) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({1, 2, 3});
  StopAnimating(tab_strip);

  EXPECT_EQ(4, model->count());
  EXPECT_EQ(3u, model->group_model()->GetTabGroup(group)->ListTabs().length());
  EXPECT_EQ(group, model->GetTabGroupForTab(1).value());

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Dragging the tab in the first index to the tab in the zero-th index
  // switches the tabs and removes the dragged tab from the group.
  EXPECT_EQ("1 0 2 3", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(2, 4));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(0));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(1));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Dragging the tab in the second index to the tab in the first index switches
  // the tabs and removes the dragged tab from the group.
  EXPECT_EQ("1 2 0 3", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(3, 4));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(2));
}

// Creates a browser with four tabs. The first three belong in the same Tab
// Group. Dragging tabs in a tab group within the defined threshold does not
// modify the group of the dragged tab.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragTabWithinGroupDoesNotModifyGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({0, 1, 2});
  StopAnimating(tab_strip);

  EXPECT_EQ(4, model->count());
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 3));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Dragging the tab in the zero-th index to the tab in the first index
  // switches the tabs but group membership does not change.
  EXPECT_EQ("1 0 2 3", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 3));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Dragging the tab in the second index to the tab in the first index switches
  // the tabs but group membership does not change.
  EXPECT_EQ("1 2 0 3", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 3));
}

// Creates a browser with four tabs. The first tab is in a Tab Group. Dragging
// the only tab in that group will remove the group.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragOnlyTabInGroupRemovesGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({0});
  StopAnimating(tab_strip);

  EXPECT_EQ(4, model->count());
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 1));

  // Dragging the tab in the zero-th index to the tab in the first index
  // switches the tabs and removes the group of the zero-th tab.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 0 2 3", IDString(model));
  EXPECT_FALSE(model->group_model()->ContainsTabGroup(group));
}

// Creates a browser with four tabs. The first tab is in Tab Group 1. The
// third tab is in Tab Group 2. Dragging the second tab over one to the left
// will result in the second tab joining Tab Group 1. Then dragging the third
// tab over one to the left will result in the tab joining Tab Group 1. Then
// dragging the fourth tab over one to the left will result in the tab joining
// Tab Group 1 as well.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragSingleTabLeftIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({0});
  model->AddToNewGroup({2});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  // Dragging the tab in the first index toward the tab in the zero-th index
  // switches the tabs and adds the dragged tab to the group.
  // Drag only half the tab length, to ensure that the tab in the first index
  // lands in the slot between the tab in the zero-th index and the group
  // header to the left of the zero-th index.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(
      DragInputToCenter(tab_strip->tab_at(1),
                        gfx::Vector2d(-tab_strip->tab_at(0)->width() / 2, 0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 0 2 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 2));

  // Dragging the tab in the second index to the tab in the first index switches
  // the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 2 0 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 3));

  // Dragging the tab in the third index to the tab in the second index switches
  // the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(3)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 2 3 0", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 4));
}

// Creates a browser with five tabs. The fourth tab is in Tab Group 1. The
// second tab is in Tab Group 2. Dragging the third tab over one to the right
// will result in the tab joining Tab Group 1. Then dragging the second tab
// over one to the right will result in the tab joining Tab Group 1. Then
// dragging the first tab over one to the right will result in the tab joining
// Tab Group 1 as well.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragSingleTabRightIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 4);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({3});
  model->AddToNewGroup({1});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  // Dragging the tab in the second index to the tab in the third index switches
  // the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(3)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("0 1 3 2 4", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(2, 4));

  // Dragging the tab in the first index to the tab in the second index switches
  // the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("0 3 1 2 4", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(1, 4));

  // Dragging the tab in the zero-th index to the tab in the first index
  // switches the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("3 0 1 2 4", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 4));
}

// Creates a browser with five tabs. The last two tabs are in a Tab Group.
// Dragging the first tab past the last slot should allow it to exit the group.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragSingleTabRightOfRightmostGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 4);
  tab_groups::TabGroupId group = model->AddToNewGroup({3, 4});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  // Dragging the first tab past the last slot brings it to the end of the
  // tabstrip, where it should not be in a group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(4), gfx::Vector2d(1, 0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 2 3 4 0", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group)->ListTabs(), gfx::Range(2, 4));
}

// Creates a browser with four tabs each in its own group. Selecting and
// dragging the first and third tabs right at the first tab will result in the
// tabs joining the same group as the tab in the second position. Then dragging
// the tabs over two to the right will result in the tabs joining the same group
// as the last tab.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragMultipleTabsRightIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  // Create a browser with four tabs total, and put each tab into its own
  // single-tab group.
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  model->AddToNewGroup({0});
  tab_groups::TabGroupId group2 = model->AddToNewGroup({1});
  model->AddToNewGroup({2});
  tab_groups::TabGroupId group4 = model->AddToNewGroup({3});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  // Click the first tab and select third tab so both first and third tabs are
  // selected.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  browser()->tab_strip_model()->SelectTabAt(2);

  // Drag the first tab from its left edge toward the right. This should make
  // the two selected tabs join the start of Tab Group 2 (which previously held
  // only the second tab).
  ASSERT_TRUE(
      PressInput(test::GetLeftCenterInScreenCoordinates(tab_strip->tab_at(0)),
                 GetWindowHint(tab_strip)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("0 2 1 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group4)->ListTabs(), gfx::Range(3, 4));
  EXPECT_EQ(group_model->GetTabGroup(group2)->ListTabs(), gfx::Range(0, 3));

  // Dragging the center of the first tab to the center of the third tab will
  // result in the tabs joining the end of Tab Group 4.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 3 0 2", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group2)->ListTabs(), gfx::Range(0, 1));
  EXPECT_EQ(group_model->GetTabGroup(group4)->ListTabs(), gfx::Range(1, 4));
}

// Creates a browser with four tabs each in its own group. Selecting and
// dragging the second and fourth tabs left at the fourth tab will result in the
// tabs joining the same group as the tab in the third position.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragMultipleTabsLeftIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({0});
  model->AddToNewGroup({1});
  tab_groups::TabGroupId group3 = model->AddToNewGroup({2});
  model->AddToNewGroup({3});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  // Click the second tab and select fourth tab so both second and fourth tabs
  // are selected.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  browser()->tab_strip_model()->SelectTabAt(3);

  // Dragging the fourth tab slightly to the left will result in the two
  // selected tabs joining the end of Tab Group 3.
  const gfx::Point left_center_fourth_tab =
      test::GetLeftCenterInScreenCoordinates(tab_strip->tab_at(3));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(3)));
  ASSERT_TRUE(DragInputTo(left_center_fourth_tab, GetWindowHint(tab_strip)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("0 2 1 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 1));
  EXPECT_EQ(group_model->GetTabGroup(group3)->ListTabs(), gfx::Range(1, 4));
}

// Creates a browser with four tabs with third and fourth in a group.
// Selecting and  dragging the second and third tabs towards left out
// of the group will result in the tabs being ungrouped.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragUngroupedTabGroupedTabOutsideGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({2, 3});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  // Click the second tab and select third tab so both second and third tabs
  // are selected.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  browser()->tab_strip_model()->SelectTabAt(2);

  // Dragging the third tab slightly to the left will result in the two
  // selected tabs leaving the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 2 0 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(3, 4));
}

// TODO(crbug.com/333085989): Re-enable flaky tests
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_RevertDragSplitTab DISABLED_RevertDragSplitTab
#else
#define MAYBE_RevertDragSplitTab RevertDragSplitTab
#endif

// Drag a split tab within a tabstrip and cancel the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_RevertDragSplitTab) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 3);
  model->ActivateTabAt(0);
  split_tabs::SplitTabId split_id =
      model->AddToNewSplit({1}, split_tabs::SplitTabVisualData());
  StopAnimating(tab_strip);

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(3)));

  EXPECT_EQ("2 3 0 1", IDString(model));
  EXPECT_EQ(model->GetSplitData(split_id)->ListTabs(),
            std::vector<tabs::TabInterface*>(
                {model->GetTabAtIndex(2), model->GetTabAtIndex(3)}));

  ASSERT_TRUE(TabDragController::IsActive());

  // Pressing escape will revert the tabs to original state before the drag.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_ESCAPE, false,
                                              false, false, false));
  EXPECT_EQ("0 1 2 3", IDString(model));
  EXPECT_EQ(model->GetSplitData(split_id)->ListTabs(),
            std::vector<tabs::TabInterface*>(
                {model->GetTabAtIndex(0), model->GetTabAtIndex(1)}));
}

// Creates a browser with four tabs. The first two tabs are in Tab Group 1.
// Dragging the third tab over one to the left will result in the tab joining
// Tab Group 1. While this drag is still in session, pressing escape will revert
// group of the tab to before the drag session started.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertDragSingleTabIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({0, 1});
  StopAnimating(tab_strip);

  // Dragging the tab in the second index to the tab in the first index switches
  // the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));

  EXPECT_EQ("0 2 1 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 3));

  ASSERT_TRUE(TabDragController::IsActive());

  // Pressing escape will revert the tabs to original state before the drag.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_ESCAPE, false,
                                              false, false, false));
  EXPECT_EQ("0 1 2 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 2));
}

// Creates a browser with four tabs. The last two tabs are in Tab Group 1. The
// second tab is in Tab Group 2. Dragging the second tab over one to the right
// will result in the tab joining Tab Group 1. While this drag is still in
// session, pressing escape will revert group of the tab, but will not recreate
// the group because the group was closed during dragging.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertDragSingleTabGroupIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({2, 3});
  tab_groups::TabGroupId group2 = model->AddToNewGroup({1});
  const tab_groups::TabGroupVisualData new_data(
      u"Foo", tab_groups::TabGroupColorId::kCyan);
  model->ChangeTabGroupVisuals(group2, new_data);
  StopAnimating(tab_strip);

  // Dragging the tab in the first index to the tab in the second index switches
  // the tabs and adds the dragged tab to the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));

  EXPECT_EQ("0 2 1 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(1, 4));

  ASSERT_TRUE(TabDragController::IsActive());

  // Reverting the drag (by pressing escape) will not rebuild the group because
  // saved group information is not saved in the tab drag controller, so the
  // group would be duplicated.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_ESCAPE, false,
                                              false, false, false));
  EXPECT_EQ("0 1 2 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(2, 4));
  EXPECT_FALSE(group_model->ContainsTabGroup(group2));
}

// Creates a browser with four tabs. The middle two belong in the same Tab
// Group. Dragging the group header will result in both the grouped tabs moving
// together.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragGroupHeaderDragsGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({1, 2});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  ASSERT_EQ(4, model->count());
  ASSERT_EQ(2u, group_model->GetTabGroup(group)->ListTabs().length());

  // Drag the entire group right by its header.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(3)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("0 3 1 2", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group)->ListTabs(), gfx::Range(2, 4));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(0));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(1));

  // Drag the entire group left by its header.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 2 0 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group)->ListTabs(), gfx::Range(0, 2));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(2));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(3));
}

// Creates a browser with four tabs. The first two belong in Tab Group 1, and
// the last two belong in Tab Group 2. Dragging the group header of Tab Group 1
// right will result in Tab Group 1 moving but avoiding Tab Group 2.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragGroupHeaderRightAvoidsOtherGroups) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({0, 1});
  tab_groups::TabGroupId group2 = model->AddToNewGroup({2, 3});
  StopAnimating(tab_strip);

  ASSERT_EQ(4, model->count());
  ASSERT_EQ(2u, group_model->GetTabGroup(group1)->ListTabs().length());
  ASSERT_EQ(2u, group_model->GetTabGroup(group2)->ListTabs().length());

  // Drag group1 right, but not far enough to get to the other side of group2.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Expect group1 to "snap back" to its current position, avoiding group2.
  EXPECT_EQ("0 1 2 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 2));
  EXPECT_EQ(group_model->GetTabGroup(group2)->ListTabs(), gfx::Range(2, 4));

  // Drag group1 right, far enough to get to the other side of group2.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Expect group1 to "snap to" the other side of group2 and not land in the
  // middle.
  EXPECT_EQ("2 3 0 1", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(2, 4));
  EXPECT_EQ(group_model->GetTabGroup(group2)->ListTabs(), gfx::Range(0, 2));
}

// Creates a browser with four tabs. The first two belong in Tab Group 1, and
// the last two belong in Tab Group 2. Dragging the group header of Tab Group 2
// left will result in Tab Group 2 moving but avoiding Tab Group 1.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragGroupHeaderLeftAvoidsOtherGroups) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group1 = model->AddToNewGroup({0, 1});
  tab_groups::TabGroupId group2 = model->AddToNewGroup({2, 3});
  StopAnimating(tab_strip);

  ASSERT_EQ(4, model->count());
  ASSERT_EQ(2u, group_model->GetTabGroup(group1)->ListTabs().length());
  ASSERT_EQ(2u, group_model->GetTabGroup(group2)->ListTabs().length());

  // Drag group2 left, but not far enough to get to the other side of group1.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Expect group2 to "snap back" to its current position, avoiding group1.
  EXPECT_EQ("0 1 2 3", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(0, 2));
  EXPECT_EQ(group_model->GetTabGroup(group2)->ListTabs(), gfx::Range(2, 4));

  // Drag group2 left, far enough to get to the other side of group1.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group2)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Expect group2 to "snap to" the other side of group1 and not land in the
  // middle.
  EXPECT_EQ("2 3 0 1", IDString(model));
  EXPECT_EQ(group_model->GetTabGroup(group1)->ListTabs(), gfx::Range(2, 4));
  EXPECT_EQ(group_model->GetTabGroup(group2)->ListTabs(), gfx::Range(0, 2));
}

// Creates a browser with four tabs. The first tab is pinned, and the last
// three belong in the same Tab Group. Dragging the pinned tab to the middle
// of the group will not result in the pinned tab getting grouped or moving
// into the group.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragPinnedTabDoesNotGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  model->SetTabPinned(0, true);
  tab_groups::TabGroupId group = model->AddToNewGroup({1, 2, 3});
  StopAnimating(tab_strip);

  ASSERT_EQ(4, model->count());
  ASSERT_EQ(3u, model->group_model()->GetTabGroup(group)->ListTabs().length());

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // The pinned tab should not have moved or joined the group.
  EXPECT_EQ("0 1 2 3", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(1, 4));
  EXPECT_EQ(std::nullopt, model->GetTabGroupForTab(0));
}

// Drags a tab within the window (without dragging the whole window) then
// pressing a key ends the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       KeyPressShouldEndDragTest) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));

  ASSERT_TRUE(TabDragController::IsActive());

  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser(), ui::VKEY_TAB, false,
                                              false, false, false));
  StopAnimating(tab_strip);

  EXPECT_EQ("1 0", IDString(browser()->tab_strip_model()));
  EXPECT_FALSE(TabDragController::IsActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
}

// Flaky. https://crbug.com/343188577
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_StartDragWhileEndingPreviousDragDoesNothingTest \
  DISABLED_StartDragWhileEndingPreviousDragDoesNothingTest
#else
#define MAYBE_StartDragWhileEndingPreviousDragDoesNothingTest \
  StartDragWhileEndingPreviousDragDoesNothingTest
#endif

// Can't start another drag session while the previous one is still ending.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_StartDragWhileEndingPreviousDragDoesNothingTest) {
  AddTabsAndResetBrowser(browser(), 2);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  const gfx::Point tab_0_center_screen =
      GetCenterInScreenCoordinates(tab_strip->tab_at(0));
  const gfx::Point tab_2_center_screen =
      GetCenterInScreenCoordinates(tab_strip->tab_at(2));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));

  ASSERT_TRUE(TabDragController::IsActive());
  StopAnimating(tab_strip);

  ASSERT_TRUE(ReleaseInput());

  // The drag is over...
  ASSERT_FALSE(TabDragController::IsActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());

  // But the tab is still animating and still belongs to the TabDragContext.
  ASSERT_TRUE(tab_strip->IsAnimatingInTabStrip());
  ASSERT_TRUE(tab_strip->tab_at(0)->dragging());
  ASSERT_EQ(tab_strip->tab_at(0)->parent(), tab_strip->GetDragContext());

  ASSERT_EQ("1 0 2", IDString(browser()->tab_strip_model()));

  // Attempt to start *another* drag session while the animation is still going.
  ASSERT_TRUE(PressInput(tab_2_center_screen, GetWindowHint(tab_strip)));
  ASSERT_TRUE(DragInputTo(tab_0_center_screen, GetWindowHint(tab_strip)));

  // This should not actually start.
  EXPECT_FALSE(TabDragController::IsActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_EQ("1 0 2", IDString(browser()->tab_strip_model()));

  ASSERT_TRUE(ReleaseInput());
}

#if defined(USE_AURA)
bool SubtreeShouldBeExplored(aura::Window* window,
                             const gfx::Point& local_point) {
  gfx::Point point_in_parent = local_point;
  aura::Window::ConvertPointToTarget(window, window->parent(),
                                     &point_in_parent);
  gfx::Point point_in_root = local_point;
  aura::Window::ConvertPointToTarget(window, window->GetRootWindow(),
                                     &point_in_root);
  ui::MouseEvent event(ui::EventType::kMouseMoved, point_in_parent,
                       point_in_root, base::TimeTicks::Now(), 0, 0);
  return window->targeter()->SubtreeShouldBeExploredForEvent(window, event);
}

// The logic to find the target tabstrip should take the window mask into
// account. This test hangs without the fix. crbug.com/473080.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragWithMaskedWindows) {
  AddTabsAndResetBrowser(browser(), 1);

  aura::Window* browser_window = browser()->window()->GetNativeWindow();
  const gfx::Rect bounds = browser_window->GetBoundsInScreen();
  aura::test::TestWindowDelegate masked_window_delegate;
  masked_window_delegate.set_can_focus(false);
  std::unique_ptr<aura::Window> masked_window(
      aura::test::CreateTestWindowWithDelegate(
          &masked_window_delegate, 10, bounds, browser_window->parent()));
  masked_window->SetProperty(aura::client::kZOrderingKey,
                             ui::ZOrderLevel::kFloatingWindow);
  auto targeter = std::make_unique<aura::WindowTargeter>();
  targeter->SetInsets(gfx::Insets::TLBR(0, bounds.width() - 10, 0, 0));
  masked_window->SetEventTargeter(std::move(targeter));

  ASSERT_FALSE(SubtreeShouldBeExplored(masked_window.get(),
                                       gfx::Point(bounds.width() - 11, 0)));
  ASSERT_TRUE(SubtreeShouldBeExplored(masked_window.get(),
                                      gfx::Point(bounds.width() - 9, 0)));
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 0", IDString(model));
  EXPECT_FALSE(TabDragController::IsActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
}
#endif  // USE_AURA

namespace {

// Invoked from the nested run loop.
void DragToSeparateWindowStep2(DetachToBrowserTabDragControllerTest* test,
                               TabStrip* not_attached_tab_strip,
                               TabStrip* target_tab_strip) {
  EXPECT_FALSE(not_attached_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_FALSE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());

  // Test that after the tabs are detached from the source tabstrip (in this
  // case `not_attached_tab_strip`), the tab dragging info should be properly
  // cleared on the source tabstrip.
  EXPECT_TRUE(test->IsTabDraggingInfoCleared(not_attached_tab_strip));
  // At this moment there should be a new browser window for the dragged tabs.
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(3u, num_browsers);
  Browser* new_browser = test->browser_list()->get(num_browsers - 1);
  TabStrip* new_tab_strip = GetTabStripForBrowser(new_browser);
  EXPECT_TRUE(new_tab_strip->GetDragContext()->IsDragSessionActive());
  // Test that the tab dragging info should be correctly set on the new window.
  EXPECT_TRUE(test->IsTabDraggingInfoSet(new_tab_strip));

  // Drag to target_tab_strip. This should stop the nested loop from dragging
  // the window.
  //
  // Note: It's possible on small screens for the windows to overlap, so we want
  // to pick a point squarely within the second tab strip and not in the
  // starting window. This only works if the platform supports global screen
  // coordinates; on platforms without this support the test environment must
  // ensure a large enough screen (e.g. xvfb.py for Linux) to make sure that the
  // windows don't overlap.
  if (test::PlatformSupportsScreenCoordinates()) {
    const gfx::Rect old_window_bounds =
        not_attached_tab_strip->GetWidget()->GetWindowBoundsInScreen();
    const gfx::Rect target_bounds = target_tab_strip->GetBoundsInScreen();
    gfx::Point target_point = target_bounds.CenterPoint();
    target_point.set_x(
        std::max(target_point.x(), old_window_bounds.right() + 1));
    EXPECT_TRUE(target_bounds.Contains(target_point));
    EXPECT_TRUE(test->DragInputToAsync(target_point,
                                       test->GetWindowHint(target_tab_strip)));
  } else {
    EXPECT_TRUE(test->DragInputToCenterAsync(target_tab_strip));
  }
}

}  // namespace

// Flaky. https://crbug.com/1176998
#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
#define MAYBE_DragToSeparateWindow DISABLED_DragToSeparateWindow
#else
#define MAYBE_DragToSeparateWindow DragToSeparateWindow
#endif

// Creates two browsers, drags from first into second.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragToSeparateWindow) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  Tab* tab = tab_strip->tab_at(0);
  ASSERT_TRUE(PressInputAtCenter(tab));
  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  ASSERT_TRUE(DragInputToCenterNotifyWhenDone(
      tab,
      base::BindOnce(&DragToSeparateWindowStep2, this, tab_strip, tab_strip2),
      gfx::Vector2d(0, GetDetachY(tab_strip))));

  // Wait for the browser containing the dragged tabs to be removed when
  // attaching to browser2.
  test::BrowserChangeWaiter(test::BrowserChangeWaiter::ChangeType::kRemoved)
      .Wait(base::BindLambdaForTesting([=, this]() {
        // Should now be attached to tab_strip2.
        ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
        ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
        ASSERT_TRUE(TabDragController::IsActive());
        EXPECT_FALSE(GetIsDragged(browser()));
        EXPECT_TRUE(IsTabDraggingInfoCleared(tab_strip));
        EXPECT_TRUE(IsTabDraggingInfoSet(tab_strip2));

        // Drag to the trailing end of the tabstrip to ensure we're in a
        // predictable spot within the strip.
        StopAnimating(tab_strip2);
        ASSERT_TRUE(DragInputToCenter(tab_strip2->tab_at(1)));

        // Release mouse or touch, stopping the drag session.
        ASSERT_TRUE(ReleaseInput());
      }));

  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_TRUE(IsTabDraggingInfoCleared(tab_strip2));
  EXPECT_EQ("100 0", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));
  EXPECT_FALSE(GetIsDragged(browser2));

  // Both windows should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_FALSE(browser2->window()->IsMaximized());

  // The tab strip should no longer have capture because the drag was ended and
  // mouse/touch was released.
  EXPECT_FALSE(tab_strip->GetWidget()->HasCapture());
  EXPECT_FALSE(tab_strip2->GetWidget()->HasCapture());
}

// Test is based on DragToSeparateWindow. https://crbug.com/1176998
#if (BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64)) || BUILDFLAG(IS_CHROMEOS)
#define MAYBE_DragToSeparateWindowDuringDragEnd \
  DISABLED_DragToSeparateWindowDuringDragEnd
#else
#define MAYBE_DragToSeparateWindowDuringDragEnd \
  DragToSeparateWindowDuringDragEnd
#endif

// Creates two browsers, starts and end a drag in the target browser, then drags
// from source to target before the target browser finishes ending drags.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragToSeparateWindowDuringDragEnd) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  AddTabsAndResetBrowser(browser2, 1);
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  ASSERT_TRUE(PressInputAtCenter(tab_strip2->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip2->tab_at(1)));

  StopAnimating(tab_strip2);
  ASSERT_TRUE(ReleaseInput());

  // We should be doing the post-drag animation.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsAnimatingDragEnd());
  // The tab should still be considered as dragging.
  ASSERT_TRUE(tab_strip2->tab_at(1)->dragging());

  Tab* tab = tab_strip->tab_at(0);
  ASSERT_TRUE(PressInputAtCenter(tab));
  // Drag from `tab_strip` to `tab_strip2`.
  ASSERT_TRUE(DragInputToCenterNotifyWhenDone(
      tab,
      base::BindOnce(&DragToSeparateWindowStep2, this, tab_strip, tab_strip2),
      gfx::Vector2d(0, GetDetachY(tab_strip))));

  test::BrowserChangeWaiter(test::BrowserChangeWaiter::ChangeType::kRemoved)
      .Wait(base::BindLambdaForTesting([=, this]() {
        // Should now be attached to `tab_strip2`.
        ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
        ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
        ASSERT_TRUE(TabDragController::IsActive());
        EXPECT_FALSE(GetIsDragged(browser()));
        EXPECT_TRUE(IsTabDraggingInfoCleared(tab_strip));
        EXPECT_TRUE(IsTabDraggingInfoSet(tab_strip2));

        // Release mouse or touch, stopping the drag session.
        ASSERT_TRUE(ReleaseInput());
      }));

  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
}

#if BUILDFLAG(IS_WIN)

// Create two browsers, with the second one occluded, and drag from first over
// second. This should create a third browser, w/o bringing forward the second
// browser, because it's occluded.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragToOccludedWindow) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  // Mark the second browser as occluded. NativeWindow occlusion calculation has
  // been disabled in test constructor, so we don't need an actual occluding
  // window.
  browser2->window()
      ->GetNativeWindow()
      ->GetHost()
      ->SetNativeWindowOcclusionState(aura::Window::OcclusionState::OCCLUDED,
                                      {});

  // Drag a tab from first browser to middle of first tab of the second,
  // occluded browser, and drop. This should create a third browser window.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenterAsync(tab_strip2->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());

  EXPECT_EQ(3u, browser_list()->size());
}

#endif  // BUILDFLAG(IS_WIN)

namespace {

// WindowFinder that calls OnMouseCaptureLost() from
// GetLocalProcessWindowAtPoint().
class CaptureLoseWindowFinder : public WindowFinder {
 public:
  explicit CaptureLoseWindowFinder(TabStrip* tab_strip)
      : tab_strip_(tab_strip) {}
  CaptureLoseWindowFinder(const CaptureLoseWindowFinder&) = delete;
  CaptureLoseWindowFinder& operator=(const CaptureLoseWindowFinder&) = delete;
  ~CaptureLoseWindowFinder() override = default;

  // WindowFinder:
  gfx::NativeWindow GetLocalProcessWindowAtPoint(
      const gfx::Point& screen_point,
      const std::set<gfx::NativeWindow>& ignore) override {
    static_cast<views::View*>(tab_strip_->GetDragContext())
        ->OnMouseCaptureLost();
    return gfx::NativeWindow();
  }

 private:
  raw_ptr<TabStrip> tab_strip_;
};

}  // namespace

// Calls OnMouseCaptureLost() from WindowFinder::GetLocalProcessWindowAtPoint()
// and verifies we don't crash. This simulates a crash seen on windows.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       CaptureLostDuringDrag) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Press on first tab so drag is active. Reset WindowFinder to one that causes
  // capture to be lost from within GetLocalProcessWindowAtPoint(), then
  // continue drag. The capture lost should trigger the drag to cancel.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive());
  SetWindowFinderForTabStrip(
      tab_strip, base::WrapUnique(new CaptureLoseWindowFinder(tab_strip)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
}

namespace {

#if BUILDFLAG(IS_CHROMEOS)
bool IsWindowPositionManaged(aura::Window* window) {
  return window->GetProperty(ash::kWindowPositionManagedTypeKey);
}
bool HasUserChangedWindowPositionOrSize(aura::Window* window) {
  return ash::WindowState::Get(window)->bounds_changed_by_user();
}
#else
bool IsWindowPositionManaged(gfx::NativeWindow window) {
  return true;
}
bool HasUserChangedWindowPositionOrSize(gfx::NativeWindow window) {
  return false;
}
#endif

}  // namespace

// Drags from browser to separate window and releases mouse.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DetachToOwnWindow) {
  const gfx::Rect initial_bounds(browser()->window()->GetBounds());
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  tabs::TabHandle dragged_tab =
      browser()->tab_strip_model()->GetTabAtIndex(0)->GetHandle();

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_0_width));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  EXPECT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));
  EXPECT_EQ(0,
            new_browser->tab_strip_model()->GetIndexOfTab(dragged_tab.Get()));
  EXPECT_EQ(new_browser->tab_strip_model(),
            dragged_tab.Get()->GetBrowserWindowInterface()->GetTabStripModel());

  // The bounds of the initial window should not have changed.
  EXPECT_EQ(initial_bounds.ToString(),
            browser()->window()->GetBounds().ToString());

  EXPECT_FALSE(GetIsDragged(browser()));
  EXPECT_FALSE(GetIsDragged(new_browser));
  // After this both windows should still be manageable.
  EXPECT_TRUE(IsWindowPositionManaged(browser()->window()->GetNativeWindow()));
  EXPECT_TRUE(
      IsWindowPositionManaged(new_browser->window()->GetNativeWindow()));

  // Both windows should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_FALSE(new_browser->window()->IsMaximized());

  // The tab strip should no longer have capture because the drag was ended and
  // mouse/touch was released.
  EXPECT_FALSE(tab_strip->GetWidget()->HasCapture());
  EXPECT_FALSE(tab_strip2->GetWidget()->HasCapture());
}

class TabDragControllerTestDialog : public views::DialogDelegateView {
 public:
  TabDragControllerTestDialog() {
    SetFocusBehavior(FocusBehavior::ALWAYS);
    SetModalType(ui::mojom::ModalType::kChild);
    // Dialogs that take focus must have a name and role to pass accessibility
    // checks.
    GetViewAccessibility().SetRole(ax::mojom::Role::kDialog);
    GetViewAccessibility().SetName("Test dialog",
                                   ax::mojom::NameFrom::kAttribute);
  }

  TabDragControllerTestDialog(const TabDragControllerTestDialog&) = delete;
  TabDragControllerTestDialog& operator=(const TabDragControllerTestDialog&) =
      delete;

  ~TabDragControllerTestDialog() override = default;

  views::View* GetInitiallyFocusedView() override { return this; }
};

// Drags from browser that has a web dialog to separate window.
// The dialog should follow the new browser window.
// TODO(crbug.com/40934892): Expectations are sometimes off by one pixel on
// Windows. Reenable once deflaked.
#if BUILDFLAG(IS_WIN)
#define MAYBE_DetachToOwnWindowWithDialog DISABLED_DetachToOwnWindowWithDialog
#else
#define MAYBE_DetachToOwnWindowWithDialog DetachToOwnWindowWithDialog
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DetachToOwnWindowWithDialog) {
  const gfx::Rect initial_bounds(browser()->window()->GetBounds());
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Create a web modal dialog on the first tab.
  views::Widget* dialog = constrained_window::ShowWebModalDialogViews(
      new TabDragControllerTestDialog,
      browser()->tab_strip_model()->GetWebContentsAt(0));

  // Capture the initial offset of the dialog relative to the browser before
  // dragging.
  gfx::Point dialog_initial_position = dialog->GetRestoredBounds().origin();
  gfx::Vector2d initial_offset =
      dialog_initial_position - initial_bounds.origin();

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  gfx::Point initial_drag_position =
      GetCenterInScreenCoordinates(tab_strip->tab_at(0));
  int detach_y = GetDetachY(tab_strip);
  DragTabAndNotify(
      tab_strip,
      base::BindOnce(base::IgnoreResult(base::BindOnce(
                         // Drags further.
                         &DetachToBrowserTabDragControllerTest::DragInputTo,
                         base::Unretained(this),
                         initial_drag_position + gfx::Vector2d(0, 2 * detach_y),
                         gfx::NativeWindow())))
          .Then(base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                   ReleaseInputAfterWindowDetached,
                               base::Unretained(this), tab_0_width)));

  // There should now be another browser.
  ASSERT_EQ(2u, browser_list()->size());

  // The dialog should be attached to the new browser.
  Browser* new_browser = browser_list()->get(1);

  // Check that the dialog's parent window is the new browser's window.
  EXPECT_EQ(dialog->parent(), views::Widget::GetWidgetForNativeWindow(
                                  new_browser->window()->GetNativeWindow()));

  // The relative offset from the new browser to the dialog should remain
  // unchanged after dragging.
  gfx::Point dialog_position = dialog->GetRestoredBounds().origin();
  gfx::Point browser_position = new_browser->window()->GetBounds().origin();
  gfx::Vector2d offset = dialog_position - browser_position;

  EXPECT_EQ(initial_offset, offset);

  // The bounds of the initial window should not have changed.
  EXPECT_EQ(initial_bounds.ToString(),
            browser()->window()->GetBounds().ToString());
}

#if BUILDFLAG(IS_CHROMEOS)
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DetachToOwnWindowWithNonVisibleOnAllWorkspaceState) {
  // Set the source browser to be visible on all workspace.
  ASSERT_EQ(1u, browser_list()->size());
  Browser* source_browser = browser_list()->get(0);
  auto* source_window = source_browser->window()->GetNativeWindow();
  source_window->SetProperty(
      aura::client::kWindowWorkspaceKey,
      aura::client::kWindowWorkspaceVisibleOnAllWorkspaces);

  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_0_width));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  EXPECT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  EXPECT_FALSE(GetIsDragged(browser()));
  EXPECT_FALSE(GetIsDragged(new_browser));
  // After this both windows should still be manageable.
  EXPECT_TRUE(IsWindowPositionManaged(browser()->window()->GetNativeWindow()));
  EXPECT_TRUE(
      IsWindowPositionManaged(new_browser->window()->GetNativeWindow()));

  auto* new_window = new_browser->window()->GetNativeWindow();
  // The new window should not be visible on all workspace.
  ASSERT_FALSE(new_window->GetProperty(aura::client::kWindowWorkspaceKey) ==
               aura::client::kWindowWorkspaceVisibleOnAllWorkspaces);
}
#endif  // BUILDFLAG(IS_CHROMEOS)

// Tests that a tab can be dragged from a browser window that is resized to full
// screen.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DetachFromFullsizeWindow) {
  // Resize the browser window so that it is as big as the work area.
  gfx::Rect work_area =
      display::Screen::GetScreen()
          ->GetDisplayNearestWindow(browser()->window()->GetNativeWindow())
          .work_area();
  ui_test_utils::SetAndWaitForBounds(*browser(), work_area);
  const gfx::Rect initial_bounds(browser()->window()->GetBounds());
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_0_width));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // The bounds of the initial window should not have changed.
  EXPECT_EQ(initial_bounds.ToString(),
            browser()->window()->GetBounds().ToString());

  EXPECT_FALSE(GetIsDragged(browser()));
  EXPECT_FALSE(GetIsDragged(new_browser));
  // After this both windows should still be manageable.
  EXPECT_TRUE(IsWindowPositionManaged(browser()->window()->GetNativeWindow()));
  EXPECT_TRUE(
      IsWindowPositionManaged(new_browser->window()->GetNativeWindow()));

  // The tab strip should no longer have capture because the drag was ended and
  // mouse/touch was released.
  EXPECT_FALSE(tab_strip->GetWidget()->HasCapture());
  EXPECT_FALSE(tab_strip2->GetWidget()->HasCapture());
}

// This test doesn't make sense on Mac, since it has no concept of "maximized".
#if !BUILDFLAG(IS_MAC)

// Drags from browser to a separate window and releases mouse.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DetachToOwnWindowFromMaximizedWindow) {
  // Maximize the initial browser window.
  {
    auto waiter = ui_test_utils::CreateAsyncWidgetRequestWaiter(*browser());
    browser()->window()->Maximize();
    ASSERT_TRUE(base::test::RunUntil(
        [&]() { return browser()->window()->IsMaximized(); }));
    waiter.Wait();
  }

  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_0_width));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // The bounds of the initial window should not have changed.
  EXPECT_TRUE(browser()->window()->IsMaximized());

  EXPECT_FALSE(GetIsDragged(browser()));
  EXPECT_FALSE(GetIsDragged(new_browser));
  // After this both windows should still be manageable.
  EXPECT_TRUE(IsWindowPositionManaged(browser()->window()->GetNativeWindow()));
  EXPECT_TRUE(
      IsWindowPositionManaged(new_browser->window()->GetNativeWindow()));

  const bool kMaximizedStateRetainedOnTabDrag =
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)
      false;
#else
      true;
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX)

  if (kMaximizedStateRetainedOnTabDrag) {
    ASSERT_TRUE(base::test::RunUntil(
        [&]() { return new_browser->window()->IsMaximized(); }));
  }
  EXPECT_EQ(new_browser->window()->IsMaximized(),
            kMaximizedStateRetainedOnTabDrag);
}
#endif  // !BUILDFLAG(IS_MAC)

#if BUILDFLAG(IS_CHROMEOS)

// This test makes sense only on Chrome OS where we have the immersive
// fullscreen mode. The detached tab to a new browser window should remain in
// immersive fullscreen mode.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DetachToOwnWindowWhileInImmersiveFullscreenMode) {
  // Toggle the immersive fullscreen mode for the initial browser.
  chrome::ToggleFullscreenMode(browser());
  ImmersiveModeController* controller =
      BrowserView::GetBrowserViewForBrowser(browser())
          ->immersive_mode_controller();
  ASSERT_TRUE(controller->IsEnabled());

  // Forcively reveal the tabstrip immediately.
  std::unique_ptr<ImmersiveRevealedLock> lock =
      controller->GetRevealedLock(ImmersiveModeController::ANIMATE_REVEAL_NO);

  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_0_width));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // The bounds of the initial window should not have changed.
  EXPECT_TRUE(browser()->window()->IsFullscreen());
  ASSERT_TRUE(BrowserView::GetBrowserViewForBrowser(browser())
                  ->immersive_mode_controller()
                  ->IsEnabled());

  EXPECT_FALSE(GetIsDragged(browser()));
  EXPECT_FALSE(GetIsDragged(new_browser));
  // After this both windows should still be manageable.
  EXPECT_TRUE(IsWindowPositionManaged(browser()->window()->GetNativeWindow()));
  EXPECT_TRUE(
      IsWindowPositionManaged(new_browser->window()->GetNativeWindow()));

  // The new browser should be in immersive fullscreen mode.
  ASSERT_TRUE(BrowserView::GetBrowserViewForBrowser(new_browser)
                  ->immersive_mode_controller()
                  ->IsEnabled());
  EXPECT_TRUE(new_browser->window()->IsFullscreen());
}

#endif  // BUILDFLAG(IS_CHROMEOS)

// Deletes a tab being dragged before the user moved enough to start a drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DeleteBeforeStartedDragging) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Click on the first tab, but don't move it.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));

  // Should be dragging.
  ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // Delete the tab being dragged.
  browser()->tab_strip_model()->DetachAndDeleteWebContentsAt(0);

  // Should have canceled dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));
  EXPECT_FALSE(GetIsDragged(browser()));
}

// Replaces a tab being dragged before the user moved enough to start a drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       ReplaceBeforeStartedDragging) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Click on the first tab, but don't move it.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));

  // A drag session should exist, but the drag should not have started.
  ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_FALSE(HasDragStarted(tab_strip));

  // Replace the tab being dragged.
  std::unique_ptr<content::WebContents> new_web_contents =
      content::WebContents::Create(
          content::WebContents::CreateParams(browser()->profile()));
  browser()->tab_strip_model()->DiscardWebContentsAt(
      0, std::move(new_web_contents));

  // The drag session should still exist, and still not be started.
  ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_FALSE(HasDragStarted(tab_strip));

  // Move the mouse enough to start the drag.  It doesn't matter whether this
  // is enough to create a window or not.
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0), gfx::Vector2d(40, 0)));

  // Drag should now have started.
  ASSERT_TRUE(HasDragStarted(tab_strip));

  // The replaced webcontents should not have an id character.
  EXPECT_EQ("? 1", IDString(browser()->tab_strip_model()));

  EXPECT_TRUE(ReleaseInput());
}

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragDoesntStartFromClick) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Click on the first tab, but don't move it.
  EXPECT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));

  // A drag session should exist, but the drag should not have started.
  EXPECT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());
  EXPECT_FALSE(HasDragStarted(tab_strip));

  // Move the mouse enough to start the drag.  It doesn't matter whether this
  // is enough to create a window or not.
  EXPECT_TRUE(DragInputToCenter(tab_strip->tab_at(0), gfx::Vector2d(20, 0)));

  // Drag should now have started.
  EXPECT_TRUE(HasDragStarted(tab_strip));

  EXPECT_TRUE(ReleaseInput());
}

// Deletes a tab being dragged while still attached.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DeleteTabWhileAttached) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Click on the first tab and move it enough so that it starts dragging but is
  // still attached.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0), gfx::Vector2d(20, 0)));

  // Should be dragging.
  ASSERT_TRUE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // Delete the tab being dragged.
  browser()->tab_strip_model()->DetachAndDeleteWebContentsAt(0);

  // Should have canceled dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  EXPECT_FALSE(GetIsDragged(browser()));
}

// Selects 1 tab out of 4, drags it out and closes the new browser window while
// dragging.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DeleteTabsWhileDetached) {
  AddTabsAndResetBrowser(browser(), 3);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  EXPECT_EQ("0 1 2 3", IDString(browser()->tab_strip_model()));

  ui_test_utils::BrowserChangeObserver removed_observer(
      nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kRemoved);
  // Drag the third tab out of its browser window, request to close the detached
  // tab and verify its owning window gets properly closed.
  DragTabAndNotify(
      tab_strip, base::BindLambdaForTesting([&]() {
        ASSERT_EQ(2u, browser_list()->size());
        Browser* old_browser = browser_list()->get(0);
        EXPECT_EQ("0 1 3", IDString(old_browser->tab_strip_model()));
        Browser* new_browser = browser_list()->get(1);
        EXPECT_EQ("2", IDString(new_browser->tab_strip_model()));
        chrome::CloseTab(new_browser);
        // Ensure that the newly created tab strip is "closeable" just after
        // requesting to close it, even if we are still waiting for the nested
        // move loop to exit. Regression test for https://crbug.com/1309461.
        EXPECT_TRUE(GetTabStripForBrowser(new_browser)->IsTabStripCloseable());
      }),
      2);
  // Ensure completion of asynchronous browser closure.
  removed_observer.Wait();

  // Should no longer be dragging.
  ASSERT_EQ(1u, browser_list()->size());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // Dragged out tab (and its owning window) should get closed.
  EXPECT_EQ("0 1 3", IDString(browser()->tab_strip_model()));

  // No longer dragging.
  EXPECT_FALSE(GetIsDragged(browser()));
}

namespace {

void PressEscapeWhileDetachedStep2(DetachToBrowserTabDragControllerTest* test) {
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(2u, num_browsers);
  Browser* new_browser = test->browser_list()->get(num_browsers - 1);
  EXPECT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
      new_browser->window()->GetNativeWindow(), ui::VKEY_ESCAPE, false, false,
      false, false));
}

}  // namespace

// Detaches a tab and while detached presses escape to revert the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertDragWhileDetached) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  tabs::TabHandle dragged_tab =
      browser()->tab_strip_model()->GetTabAtIndex(0)->GetHandle();

  ui_test_utils::BrowserChangeObserver removed_observer(
      nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kRemoved);
  // Move to the first tab and drag it enough so that it detaches.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&PressEscapeWhileDetachedStep2, this));
  // Ensure completion of asynchronous browser closure.
  removed_observer.Wait();

  // Should not be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // And there should only be one window.
  EXPECT_EQ(1u, browser_list()->size());

  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));
  EXPECT_NE(nullptr, dragged_tab.Get());
  EXPECT_EQ(0, browser()->tab_strip_model()->GetIndexOfTab(dragged_tab.Get()));
  EXPECT_EQ(browser()->tab_strip_model(),
            dragged_tab.Get()->GetBrowserWindowInterface()->GetTabStripModel());

  // Remaining browser window should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());

  // The tab strip should no longer have capture because the drag was ended and
  // mouse/touch was released.
  EXPECT_FALSE(tab_strip->GetWidget()->HasCapture());
}

// Creates a browser with two tabs, drags the second to the first.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, DragInSameWindow) {
  AddTabsAndResetBrowser(browser(), 1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  // Test that the dragging info is correctly set on `tab_strip`.
  EXPECT_TRUE(IsTabDraggingInfoSet(tab_strip));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 0", IDString(model));
  EXPECT_FALSE(TabDragController::IsActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  // Test that the dragging info is properly cleared after dragging.
  EXPECT_TRUE(IsTabDraggingInfoCleared(tab_strip));

  // The tab strip should no longer have capture because the drag was ended and
  // mouse/touch was released.
  EXPECT_FALSE(tab_strip->GetWidget()->HasCapture());
}

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       TabDragContextOwnsDraggedTabs) {
  AddTabsAndResetBrowser(browser(), 1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabDragContext* drag_context = tab_strip->GetDragContext();
  Tab* dragged_tab = tab_strip->tab_at(1);

  // Tabs are not in the TabDragContext when they aren't being dragged.
  ASSERT_FALSE(drag_context->Contains(dragged_tab));

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  EXPECT_FALSE(drag_context->Contains(dragged_tab));

  // TabDragContext gets them only after the drag truly begins.
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  EXPECT_TRUE(drag_context->Contains(dragged_tab));

  // TabDragContext keeps them after the drag ends...
  ASSERT_TRUE(ReleaseInput());
  EXPECT_TRUE(drag_context->Contains(dragged_tab));

  // Until they animate back into place.
  StopAnimating(tab_strip);
  EXPECT_FALSE(drag_context->Contains(dragged_tab));

  EXPECT_FALSE(TabDragController::IsActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
}

#if BUILDFLAG(IS_LINUX)
#define MAYBE_TabDragContextOwnsClosingDraggedTabs \
  DISABLED_TabDragContextOwnsClosingDraggedTabs
#else
#define MAYBE_TabDragContextOwnsClosingDraggedTabs \
  TabDragContextOwnsClosingDraggedTabs
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_TabDragContextOwnsClosingDraggedTabs) {
  AddTabsAndResetBrowser(browser(), 1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabDragContext* drag_context = tab_strip->GetDragContext();
  Tab* dragged_tab = tab_strip->tab_at(1);

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));

  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));

  // Delete the tab being dragged.
  browser()->tab_strip_model()->DetachAndDeleteWebContentsAt(0);

  // Should have canceled dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // TabDragContext still owns the tab while it's closing.
  ASSERT_TRUE(dragged_tab->closing());
  EXPECT_TRUE(drag_context->Contains(dragged_tab));

  // Completing the close animation destroys the tab.
  views::ViewTracker dragged_tab_tracker(dragged_tab);
  StopAnimating(tab_strip);
  EXPECT_EQ(dragged_tab_tracker.view(), nullptr);
}

namespace {

void DragAllStep2(DetachToBrowserTabDragControllerTest* test) {
  // Should only be one window.
  EXPECT_EQ(1u, test->browser_list()->size());

  // Windows hangs if you use a sync mouse event here.
  EXPECT_TRUE(test->ReleaseInput(0, true));
}

}  // namespace

// Selects multiple tabs and starts dragging the window.
// TODO(crbug.com/40934892): Expectations are sometimes off by one pixel on
// Windows. Reenable once deflaked.
#if BUILDFLAG(IS_WIN)
#define MAYBE_DragAll DISABLED_DragAll
#else
#define MAYBE_DragAll DragAll
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest, MAYBE_DragAll) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  browser()->tab_strip_model()->SelectTabAt(0);
  const gfx::Rect initial_bounds = browser()->window()->GetBounds();

  // Move to the first tab and drag it enough so that it would normally
  // detach.
  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllStep2, this));

  // Should not be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // And there should only be one window.
  EXPECT_EQ(1u, browser_list()->size());

  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));

  EXPECT_FALSE(GetIsDragged(browser()));

  // Remaining browser window should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());

  const gfx::Rect final_bounds = browser()->window()->GetBounds();

  // The following expectations might not hold on platforms where we can't
  // control the browser's bounds.
  if (test::PlatformSupportsScreenCoordinates()) {
    // Size unchanged, but it should have moved down.
    EXPECT_EQ(initial_bounds.size(), final_bounds.size());
    EXPECT_EQ(initial_bounds.origin().x(), final_bounds.origin().x());
    EXPECT_EQ(initial_bounds.origin().y() + GetDetachY(tab_strip),
              final_bounds.origin().y());
  }
}

namespace {

// Invoked from the nested run loop.
void DragAllToSeparateWindowStep2(DetachToBrowserTabDragControllerTest* test,
                                  TabStrip* attached_tab_strip,
                                  TabStrip* target_tab_strip) {
  EXPECT_TRUE(attached_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_FALSE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());
  EXPECT_EQ(2u, test->browser_list()->size());

  // Drag to target_tab_strip. This should stop the nested loop from dragging
  // the window.
  EXPECT_TRUE(test->DragInputToCenterAsync(target_tab_strip));
}

}  // namespace

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// Flaky on Mac10.14 and Linux: https://crbug.com/1213345
#define MAYBE_DragPinnedAndUnpinnedToSeparateWindow \
  DISABLED_DragPinnedAndUnpinnedToSeparateWindow
#else
#define MAYBE_DragPinnedAndUnpinnedToSeparateWindow \
  DragPinnedAndUnpinnedToSeparateWindow
#endif

// Creates two browsers, then drags a combination of pinned and unpinned tabs
// from one to the other.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragPinnedAndUnpinnedToSeparateWindow) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  AddTabsAndResetBrowser(browser(), 1);
  browser()->tab_strip_model()->SetTabPinned(0, true);
  StopAnimating(tab_strip);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  TabStripModel* model2 = browser2->tab_strip_model();
  AddTabsAndResetBrowser(browser2, 1);
  ResetIDs(model2, 100);
  StopAnimating(tab_strip2);

  // Click the first tab and select the second tab so they are the only ones
  // selected.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  browser()->tab_strip_model()->SelectTabAt(1);

  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2,
                                             this, tab_strip, tab_strip2));

  // Drag to the trailing end of the tabstrip to ensure we're in a
  // predictable spot within the strip.
  StopAnimating(tab_strip2);
  ASSERT_TRUE(DragInputToCenter(tab_strip2->tab_at(3)));
  // Release mouse or touch, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());

  EXPECT_EQ("0 100 101 1", IDString(model2));
  EXPECT_TRUE(browser2->tab_strip_model()->IsTabPinned(0));
  EXPECT_FALSE(browser2->tab_strip_model()->IsTabPinned(1));
}

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// Flaky on Mac10.14 and Linux: https://crbug.com/1213345
#define MAYBE_DragSplitTabToSeparateWindow DISABLED_DragSplitTabToSeparateWindow
#else
#define MAYBE_DragSplitTabToSeparateWindow DragSplitTabToSeparateWindow
#endif

// Creates two browsers, then drags a split tab from one to the other.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragSplitTabToSeparateWindow) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  AddTabsAndResetBrowser(browser(), 1);
  browser()->tab_strip_model()->ActivateTabAt(0);
  split_tabs::SplitTabId split_id = browser()->tab_strip_model()->AddToNewSplit(
      {1}, split_tabs::SplitTabVisualData());
  StopAnimating(tab_strip);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  TabStripModel* model2 = browser2->tab_strip_model();
  AddTabsAndResetBrowser(browser2, 1);
  ResetIDs(model2, 100);
  StopAnimating(tab_strip2);

  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2,
                                             this, tab_strip, tab_strip2));

  // Drag to the trailing end of the tabstrip to ensure we're in a
  // predictable spot within the strip.
  StopAnimating(tab_strip2);
  ASSERT_TRUE(DragInputToCenter(tab_strip2->tab_at(3)));
  // Release mouse or touch, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());

  EXPECT_EQ("100 101 0 1", IDString(model2));
  EXPECT_EQ(
      browser2->tab_strip_model()->GetSplitData(split_id)->ListTabs().size(),
      2u);
}

// Flaky. http://crbug.com/1128774
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
// These were flaking on all macs, so commented out ARCH_ above for
// crbug.com/1160917 too.
#define MAYBE_DragAllToSeparateWindow DISABLED_DragAllToSeparateWindow
#else
#define MAYBE_DragAllToSeparateWindow DragAllToSeparateWindow
#endif

// Creates two browsers, selects all tabs in first and drags into second.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragAllToSeparateWindow) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  browser()->tab_strip_model()->SelectTabAt(0);

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2,
                                             this, tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_EQ(1u, browser_list()->size());

  // Drag to the trailing end of the tabstrip to ensure we're in a
  // predictable spot within the strip.
  StopAnimating(tab_strip2);
  ASSERT_TRUE(DragInputToCenter(tab_strip2->tab_at(1)));
  // Release mouse or touch, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());

  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("100 0 1", IDString(browser2->tab_strip_model()));

  EXPECT_FALSE(GetIsDragged(browser2));

  // Remaining browser window should not be maximized
  EXPECT_FALSE(browser2->window()->IsMaximized());
}

// Based on DragAllToSeparateWindow, which is flaky.
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
#define MAYBE_DragAllToSeparateWindowThenDrop \
  DISABLED_DragAllToSeparateWindowThenDrop
#else
#define MAYBE_DragAllToSeparateWindowThenDrop DragAllToSeparateWindowThenDrop
#endif

// Creates two browsers, selects all tabs in first, drags into second, then
// drags out again and drops the new browser.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragAllToSeparateWindowThenDrop) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  browser()->tab_strip_model()->SelectTabAt(0);

  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2,
                                             this, tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_EQ(1u, browser_list()->size());

  // Drag out of tab_strip2 again.
  EXPECT_TRUE(DragInputToCenterAsync(tab_strip2,
                                     /*offset=*/{0, GetDetachY(tab_strip2)}));

  // A new browser should open to hold the dragged tabs.
  Browser* new_browser;
  TabStrip* new_tab_strip;
  test::BrowserChangeWaiter(test::BrowserChangeWaiter::ChangeType::kAdded)
      .Wait(
          base::BindLambdaForTesting([=, &new_browser, &new_tab_strip, this]() {
            new_browser = ui_test_utils::GetBrowserNotInSet({browser2});
            new_tab_strip = GetTabStripForBrowser(new_browser);
            ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
            ASSERT_TRUE(new_tab_strip->GetDragContext()->IsDragSessionActive());
            ASSERT_TRUE(TabDragController::IsActive());

            // Release the mouse, stopping the drag session.
            ASSERT_TRUE(ReleaseInput());
          }));

  ASSERT_FALSE(new_tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("100", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("0 1", IDString(new_browser->tab_strip_model()));
  EXPECT_FALSE(GetIsDragged(new_browser));
}

namespace {

// Invoked from the nested run loop.
void DoubleNestedRunLoopStep2(DetachToBrowserTabDragControllerTest* test,
                              TabStrip* attached_tab_strip,
                              TabStrip* target_tab_strip) {
  EXPECT_TRUE(attached_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_FALSE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());
  EXPECT_TRUE(
      TabDragController::IsAttachedTo(attached_tab_strip->GetDragContext()));
  EXPECT_EQ(2u, test->browser_list()->size());

  TabDragController* const drag_controller =
      attached_tab_strip->GetDragContext()->GetDragController();
  const gfx::Point target_center =
      GetCenterInScreenCoordinates(target_tab_strip);

  // Drag to target_tab_strip. This should cause TabDragController to ask to end
  // the nested run loop. Normally, we'd return from here to allow the nested
  // loop to exit, but to reproduce the conditions for the crash, we won't.
  ASSERT_EQ(drag_controller->Drag(target_center),
            TabDragController::Liveness::ALIVE);

  // Call Drag directly - still on the nested run loop! - in a way that would
  // spawn a nested run loop if processed.
  ASSERT_EQ(drag_controller->Drag(
                target_center + gfx::Vector2d(0, GetDetachY(target_tab_strip))),
            TabDragController::Liveness::ALIVE);

  // Release input to ensure the nested run loop does actually exit.
  EXPECT_TRUE(test->ReleaseInput(0, /*async=*/true));
}

}  // namespace

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragToSeparateWindowAttemptToSpawnDoubleNestedRunLoop) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Wayland doesn't necessarily support window move loops; this test doesn't
  // make sense in that case.
  if (!tab_strip->GetWidget()->IsMoveLoopSupported()) {
    return;
  }

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  browser()->tab_strip_model()->SelectTabAt(0);

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip, base::BindOnce(&DoubleNestedRunLoopStep2, this,
                                             tab_strip, tab_strip2));

  // The drag should have ended.
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
}

#if BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
#define MAYBE_DragWindowIntoGroup DISABLED_DragWindowIntoGroup
#else
#define MAYBE_DragWindowIntoGroup DragWindowIntoGroup
#endif

// Creates two browser with two tabs each. The first browser has one tab in a
// group and the second tab not in a group. The second browser {browser2} has
// two tabs in another group {group1}. Dragging the two tabs in the first
// browser into the middle of the second browser will insert the two dragged
// tabs into the {group1}} after the first tab.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragWindowIntoGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 1);
  model->AddToNewGroup({0});
  StopAnimating(tab_strip);

  // Set up the second browser with two tabs in a group with distinct IDs.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  TabStripModel* model2 = browser2->tab_strip_model();
  AddTabsAndResetBrowser(browser2, 1);
  ResetIDs(model2, 100);
  tab_groups::TabGroupId group1 = model2->AddToNewGroup({0, 1});
  StopAnimating(tab_strip2);

  // Click the first tab and select the second tab so they are the only ones
  // selected.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(ReleaseInput());
  browser()->tab_strip_model()->SelectTabAt(1);

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2,
                                             this, tab_strip, tab_strip2));

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());

  EXPECT_EQ("100 0 1 101", IDString(model2));
  EXPECT_EQ(model2->group_model()->GetTabGroup(group1)->ListTabs(),
            gfx::Range(0, 4));
}

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
// Flaky on Mac10.14 and Linux: https://crbug.com/1213345
#define MAYBE_DragGroupHeaderToSeparateWindow \
  DISABLED_DragGroupHeaderToSeparateWindow
#else
#define MAYBE_DragGroupHeaderToSeparateWindow DragGroupHeaderToSeparateWindow
#endif

// Creates two browsers, then drags a group from one to the other.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragGroupHeaderToSeparateWindow) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 1);
  tab_groups::TabGroupId group = model->AddToNewGroup({0, 1});
  tab_groups::TabGroupColorId group_color = tab_strip->GetGroupColorId(group);
  StopAnimating(tab_strip);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  TabStripModel* model2 = browser2->tab_strip_model();
  StopAnimating(tab_strip2);

  // Drag the group by its header into the second browser.
  DragToDetachGroupAndNotify(tab_strip,
                             base::BindOnce(&DragAllToSeparateWindowStep2, this,
                                            tab_strip, tab_strip2),
                             group);
  ASSERT_TRUE(ReleaseInput());

  // Expect the group to be in browser2, but with a new tab_groups::TabGroupId.
  EXPECT_EQ("100 0 1", IDString(model2));
  EXPECT_EQ(model2->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(1, 3));
  EXPECT_EQ(tab_strip2->GetGroupColorId(group), group_color);
}

#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
// Flaky on Mac10.14 and Linux: https://crbug.com/1213345
#define MAYBE_DragGroupHeaderWithSplitToSeparateWindow \
  DISABLED_DragGroupHeaderWithSplitToSeparateWindow
#else
#define MAYBE_DragGroupHeaderWithSplitToSeparateWindow \
  DragGroupHeaderWithSplitToSeparateWindow
#endif

// Creates two browsers, then drags a group from one to the other.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragGroupHeaderWithSplitToSeparateWindow) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 1);
  tab_groups::TabGroupId group = model->AddToNewGroup({0, 1});

  model->ActivateTabAt(0);
  model->AddToNewSplit({1}, split_tabs::SplitTabVisualData());

  tab_groups::TabGroupColorId group_color = tab_strip->GetGroupColorId(group);
  StopAnimating(tab_strip);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  TabStripModel* model2 = browser2->tab_strip_model();
  StopAnimating(tab_strip2);

  // Drag the group by its header into the second browser.
  DragToDetachGroupAndNotify(tab_strip,
                             base::BindOnce(&DragAllToSeparateWindowStep2, this,
                                            tab_strip, tab_strip2),
                             group);
  ASSERT_TRUE(ReleaseInput());

  // Expect the group to be in browser2.
  EXPECT_EQ("100 0 1", IDString(model2));
  EXPECT_EQ(model2->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(1, 3));
  EXPECT_EQ(tab_strip2->GetGroupColorId(group), group_color);
}

// Drags a tab group by the header to a new position toward the right and
// presses escape to revert the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertHeaderDragRight) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({0, 1});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  TabGroupHeader* group_header = tab_strip->group_header(group);
  EXPECT_FALSE(group_header->dragging());
  ASSERT_TRUE(PressInputAtCenter(group_header));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(group_header->dragging());

  ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
      browser()->window()->GetNativeWindow(), ui::VKEY_ESCAPE, false, false,
      false, false));
  StopAnimating(tab_strip);

  EXPECT_EQ(1u, browser_list()->size());
  EXPECT_FALSE(group_header->dragging());
  EXPECT_EQ("0 1 2 3", IDString(browser()->tab_strip_model()));
  std::vector<tab_groups::TabGroupId> groups =
      model->group_model()->ListTabGroups();
  EXPECT_EQ(1u, groups.size());
  EXPECT_EQ(model->group_model()->GetTabGroup(groups[0])->ListTabs(),
            gfx::Range(0, 2));
}

// Drags a tab group by the header to a new position toward the left and presses
// escape to revert the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertHeaderDragLeft) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({2, 3});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  TabGroupHeader* group_header = tab_strip->group_header(group);
  EXPECT_FALSE(group_header->dragging());
  ASSERT_TRUE(PressInputAtCenter(group_header));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(group_header->dragging());

  ASSERT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
      browser()->window()->GetNativeWindow(), ui::VKEY_ESCAPE, false, false,
      false, false));

  StopAnimating(tab_strip);
  EXPECT_EQ(1u, browser_list()->size());
  EXPECT_FALSE(group_header->dragging());
  EXPECT_EQ("0 1 2 3", IDString(browser()->tab_strip_model()));
  std::vector<tab_groups::TabGroupId> groups =
      model->group_model()->ListTabGroups();
  EXPECT_EQ(1u, groups.size());
  EXPECT_EQ(model->group_model()->GetTabGroup(groups[0])->ListTabs(),
            gfx::Range(2, 4));
}

namespace {

void PressEscapeWhileDetachedHeaderStep2(
    DetachToBrowserTabDragControllerTest* test) {
  // At this moment there should be a new browser window for the dragged tabs.
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(2u, num_browsers);
  Browser* new_browser = test->browser_list()->get(num_browsers - 1);
  std::vector<tab_groups::TabGroupId> new_browser_groups =
      new_browser->tab_strip_model()->group_model()->ListTabGroups();
  EXPECT_EQ(1u, new_browser_groups.size());
  EXPECT_EQ(0u, test->browser()
                    ->tab_strip_model()
                    ->group_model()
                    ->ListTabGroups()
                    .size());

  TabGroupHeader* new_group_header =
      GetTabStripForBrowser(new_browser)->group_header(new_browser_groups[0]);
  EXPECT_TRUE(new_group_header->dragging());

  EXPECT_TRUE(ui_test_utils::SendKeyPressToWindowSync(
      new_browser->window()->GetNativeWindow(), ui::VKEY_ESCAPE, false, false,
      false, false));
}

}  // namespace

// Drags a tab group by the header and while detached presses escape to revert
// the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertHeaderDragWhileDetached) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 1);
  tab_groups::TabGroupId group = model->AddToNewGroup({0});
  StopAnimating(tab_strip);
  EnsureFocusToTabStrip(tab_strip);

  ui_test_utils::BrowserChangeObserver removed_observer(
      nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kRemoved);
  DragToDetachGroupAndNotify(
      tab_strip, base::BindOnce(&PressEscapeWhileDetachedHeaderStep2, this),
      group);
  // Ensure completion of asynchronous browser closure.
  removed_observer.Wait();

  EXPECT_FALSE(tab_strip->group_header(group)->dragging());

  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ(1u, browser_list()->size());
  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));
  std::vector<tab_groups::TabGroupId> groups =
      model->group_model()->ListTabGroups();
  EXPECT_EQ(1u, groups.size());
  EXPECT_EQ(model->group_model()->GetTabGroup(groups[0])->ListTabs(),
            gfx::Range(0, 1));
}

// Creates a browser with four tabs where the second and third tab is in a
// collapsed group. Drag the fourth tab to the left past the group header. The
// fourth tab should swap places with the collapsed group header.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragTabLeftPastCollapsedGroupHeader) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({1, 2});
  StopAnimating(tab_strip);

  EXPECT_EQ(4, model->count());
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(1, 3));
  EXPECT_FALSE(model->IsGroupCollapsed(group));
  tab_strip->ToggleTabGroupCollapsedState(group);
  StopAnimating(tab_strip);
  EXPECT_TRUE(model->IsGroupCollapsed(group));

  // Dragging the last tab to the left should cause it to swap places with the
  // collapsed group header.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(3)));
  ASSERT_TRUE(
      DragInputTo(test::GetLeftCenterInScreenCoordinates(tab_strip->tab_at(3)),
                  GetWindowHint(tab_strip)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("0 3 1 2", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(2, 4));
  EXPECT_TRUE(model->IsGroupCollapsed(group));
}

// Creates a browser with four tabs where the second and third tab is in a
// collapsed group. Drag the first tab to the right past the group header. The
// first tab should swap places with the collapsed group header.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragTabRightPastCollapsedGroupHeader) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({1, 2});
  StopAnimating(tab_strip);

  EXPECT_EQ(4, model->count());
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(1, 3));
  EXPECT_FALSE(model->IsGroupCollapsed(group));
  tab_strip->ToggleTabGroupCollapsedState(group);
  StopAnimating(tab_strip);
  EXPECT_TRUE(model->IsGroupCollapsed(group));

  // Dragging the first tab to the right should cause it to swap places with the
  // collapsed group header.
  const gfx::NativeWindow window_hint = GetWindowHint(tab_strip);
  ASSERT_TRUE(
      PressInput(test::GetLeftCenterInScreenCoordinates(tab_strip->tab_at(0)),
                 window_hint));
  ASSERT_TRUE(
      DragInputTo(test::GetRightCenterInScreenCoordinates(tab_strip->tab_at(0)),
                  window_hint));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  EXPECT_EQ("1 2 0 3", IDString(model));
  EXPECT_EQ(model->group_model()->GetTabGroup(group)->ListTabs(),
            gfx::Range(0, 2));
  EXPECT_TRUE(model->IsGroupCollapsed(group));
}

// Drags a tab group by the header and while detached presses escape to revert
// the drag.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       RevertCollapsedHeaderDragWhileDetached) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 1);
  tab_groups::TabGroupId group = model->AddToNewGroup({0});
  EXPECT_FALSE(model->IsGroupCollapsed(group));
  EnsureFocusToTabStrip(tab_strip);

  tab_strip->ToggleTabGroupCollapsedState(group);
  StopAnimating(tab_strip);
  EXPECT_TRUE(model->IsGroupCollapsed(group));

  ui_test_utils::BrowserChangeObserver removed_observer(
      nullptr, ui_test_utils::BrowserChangeObserver::ChangeType::kRemoved);
  DragToDetachGroupAndNotify(
      tab_strip, base::BindOnce(&PressEscapeWhileDetachedHeaderStep2, this),
      group);
  // Ensure completion of asynchronous browser closure.
  removed_observer.Wait();

  EXPECT_FALSE(tab_strip->group_header(group)->dragging());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ(1u, browser_list()->size());
  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));
  std::vector<tab_groups::TabGroupId> groups =
      model->group_model()->ListTabGroups();
  EXPECT_EQ(1u, groups.size());
  EXPECT_EQ(model->group_model()->GetTabGroup(groups[0])->ListTabs(),
            gfx::Range(0, 1));
  EXPECT_TRUE(tab_strip->IsGroupCollapsed(group));
}

// Creates a browser with four tabs. The first two tabs belong in Tab Group 1.
// Dragging the collapsed group header of Tab Group 1 will result in Tab Group 1
// expanding.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragCollapsedGroupHeaderExpandsGroup) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  TabGroupModel* group_model = model->group_model();

  AddTabsAndResetBrowser(browser(), 3);
  tab_groups::TabGroupId group = model->AddToNewGroup({2, 3});
  ASSERT_FALSE(model->IsGroupCollapsed(group));
  tab_strip->ToggleTabGroupCollapsedState(group);
  StopAnimating(tab_strip);
  ASSERT_TRUE(model->IsGroupCollapsed(group));
  EnsureFocusToTabStrip(tab_strip);

  ASSERT_EQ(4, model->count());
  ASSERT_EQ(2u, group_model->GetTabGroup(group)->ListTabs().length());

  // Drag group1, this should expand the group.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->group_header(group)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(TabDragController::IsActive());
  EXPECT_FALSE(model->IsGroupCollapsed(group));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);
  EXPECT_FALSE(model->IsGroupCollapsed(group));
}

#if BUILDFLAG(IS_MAC)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
// Test is flaky on Mac: https://crbug.com/1167249
#define MAYBE_DragCollapsedGroupHeaderToSeparateWindow \
  DISABLED_DragCollapsedGroupHeaderToSeparateWindow
#else
#define MAYBE_DragCollapsedGroupHeaderToSeparateWindow \
  DragCollapsedGroupHeaderToSeparateWindow
#endif

// Creates two browsers, then drags a collapsed group from one to the other.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragCollapsedGroupHeaderToSeparateWindow) {
  ASSERT_TRUE(browser()->tab_strip_model()->SupportsTabGroups());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  TabStripModel* model = browser()->tab_strip_model();
  AddTabsAndResetBrowser(browser(), 2);
  tab_groups::TabGroupId group = model->AddToNewGroup({0, 1});
  EXPECT_FALSE(model->IsGroupCollapsed(group));
  tab_strip->ToggleTabGroupCollapsedState(group);
  StopAnimating(tab_strip);
  EXPECT_TRUE(model->IsGroupCollapsed(group));

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  TabStripModel* model2 = browser2->tab_strip_model();
  StopAnimating(tab_strip2);

  // Drag the group by its header into the second browser.
  TabGroupHeader* group_header = tab_strip->group_header(group);
  ASSERT_TRUE(PressInputAtCenter(group_header));
  ASSERT_TRUE(DragInputToCenterNotifyWhenDone(
      group_header,
      base::BindOnce(&DragToSeparateWindowStep2, this, tab_strip, tab_strip2),
      gfx::Vector2d(0, GetDetachY(tab_strip))));
  test::BrowserChangeWaiter(test::BrowserChangeWaiter::ChangeType::kRemoved)
      .Wait(base::BindLambdaForTesting(
          [this]() { ASSERT_TRUE(ReleaseInput()); }));

  // Expect the group to be in browser2, but with a new tab_groups::TabGroupId
  // and not collapsed.
  EXPECT_EQ("100 0 1", IDString(model2));
  std::vector<tab_groups::TabGroupId> browser2_groups =
      model2->group_model()->ListTabGroups();
  EXPECT_EQ(1u, browser2_groups.size());
  EXPECT_EQ(model2->group_model()->GetTabGroup(browser2_groups[0])->ListTabs(),
            gfx::Range(1, 3));
  ASSERT_FALSE(tab_strip->IsGroupCollapsed(browser2_groups[0]));
  EXPECT_EQ(browser2_groups[0], group);
}

// Detachable tabs are not supported for PWAs on Mac so these tests don't apply.
#if !BUILDFLAG(IS_MAC)
using DetachTabWithUrlControlledByWebApp = DetachToBrowserTabDragControllerTest;
// Test tearing off a tab displaying a url controlled by a web app.
// The kTearOffWebAppTabOpensWebAppWindow experiment determines whether the new
// browser window will be a normal browser window or an app window.
IN_PROC_BROWSER_TEST_P(DetachTabWithUrlControlledByWebApp, TearOffWebApp) {
  // OS integration is needed to be able to launch web applications. This
  // override ensures OS integration doesn't leave any traces.
  std::unique_ptr<web_app::OsIntegrationTestOverrideImpl::BlockingRegistration>
      override_registration;

  {
    base::ScopedAllowBlockingForTesting allow_blocking;
    override_registration =
        web_app::OsIntegrationTestOverrideImpl::OverrideForTesting();
  }

  // Install tabbed web app.
  auto web_app_info = web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(
      GURL("https://www.example.com"));
  web_app_info->title = u"A tabbed web app";
  web_app_info->user_display_mode =
      web_app::mojom::UserDisplayMode::kStandalone;
  webapps::AppId app_id = web_app::test::InstallWebApp(browser()->profile(),
                                                       std::move(web_app_info));

  // Load URL controlled by installed web app.
  AddTabsAndResetBrowser(browser(), 1, GURL("https://www.example.com/"));

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  EXPECT_EQ(browser()->tab_strip_model()->count(), 2);

  // Move to the second tab and drag it enough that it detaches.
  DragTabAndNotify(
      tab_strip,
      base::BindOnce(&DetachToBrowserTabDragControllerTest::
                         ReleaseInputAfterWindowDetached,
                     base::Unretained(this), tab_strip->tab_at(1)->width()),
      1);

  EXPECT_EQ(2u, browser_list()->size());

  // Expect first window is left with just the start tab.
  TabStripModel* source_tab_strip_model =
      browser_list()->get(0)->tab_strip_model();
  EXPECT_EQ(source_tab_strip_model->count(), 1);
  EXPECT_FALSE(source_tab_strip_model->IsTabPinned(0));
  EXPECT_EQ(source_tab_strip_model->GetWebContentsAt(0)->GetVisibleURL(),
            GURL("about:blank"));

  // Expect the newly created window has the dragged tab.
  TabStripModel* dest_tab_strip_model =
      browser_list()->get(1)->tab_strip_model();
  EXPECT_EQ(dest_tab_strip_model->count(), 1);
  EXPECT_EQ(dest_tab_strip_model->GetWebContentsAt(0)->GetVisibleURL(),
            web_app::WebAppProvider::GetForTest(browser()->profile())
                ->registrar_unsafe()
                .GetAppStartUrl(app_id));
  EXPECT_EQ(dest_tab_strip_model->active_index(), 0);

  // Check that right type of browser window is opened, depending on the value
  // of kTearOffWebAppTabOpensWebAppWindow experiment.
  EXPECT_EQ(browser_list()->get(1)->type(),
            std::get<1>(GetParam()) ? Browser::TYPE_APP : Browser::TYPE_NORMAL);
}

INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachTabWithUrlControlledByWebApp,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Bool(),
        /*input_source=*/::testing::Values("mouse")));

class DetachToBrowserTabDragControllerTestWithTabbedWebApp
    : public DetachToBrowserTabDragControllerTest {
 public:
  DetachToBrowserTabDragControllerTestWithTabbedWebApp() {
    scoped_feature_list_.InitWithFeatures(
        {blink::features::kDesktopPWAsTabStrip}, {});
  }

  webapps::AppId InstallMockApp(bool add_home_tab) {
    auto web_app_info =
        web_app::WebAppInstallInfo::CreateWithStartUrlForTesting(
            GURL("https://www.example.com"));
    web_app_info->title = u"A tabbed web app";
    web_app_info->user_display_mode =
        web_app::mojom::UserDisplayMode::kStandalone;
    web_app_info->display_override = {blink::mojom::DisplayMode::kTabbed};
    if (add_home_tab) {
      blink::Manifest::TabStrip manifest_tab_strip;
      manifest_tab_strip.home_tab = blink::Manifest::HomeTabParams();
      web_app_info->tab_strip = std::move(manifest_tab_strip);
    }

    return web_app::test::InstallWebApp(browser()->profile(),
                                        std::move(web_app_info));
  }

 private:
  web_app::OsIntegrationTestOverrideBlockingRegistration faked_os_integration_;
  base::test::ScopedFeatureList scoped_feature_list_;
};

// Tabbed web apps with the home tab cannot have detachable tabs.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithTabbedWebApp,
                       HomeTabAddedToEveryWindow) {
  // Install tabbed web app.
  webapps::AppId app_id = InstallMockApp(/*add_home_tab=*/true);
  Browser* app_browser =
      web_app::LaunchWebAppBrowser(browser()->profile(), app_id);
  ASSERT_EQ(2u, browser_list()->size());

  // Close normal browser since other code expects only 1 browser to start.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(1u, browser_list()->size());

  SelectFirstBrowser();
  ASSERT_EQ(app_browser, browser());

  AddTabsAndResetBrowser(browser(), 1, GURL("https://www.example.com/newpage"));

  TabStrip* tab_strip = GetTabStripForBrowser(app_browser);
  EXPECT_EQ(browser()->tab_strip_model()->count(), 2);

  // Move to the second tab and drag it enough that it detaches.
  int tab_1_width = tab_strip->tab_at(1)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_1_width),
                   1);

  EXPECT_EQ(2u, browser_list()->size());

  // Expect first window is left with just the home tab.
  TabStripModel* source_tab_strip_model =
      browser_list()->get(0)->tab_strip_model();
  EXPECT_EQ(source_tab_strip_model->count(), 1);
  EXPECT_TRUE(source_tab_strip_model->IsTabPinned(0));
  EXPECT_EQ(source_tab_strip_model->GetWebContentsAt(0)->GetVisibleURL(),
            web_app::WebAppProvider::GetForTest(browser()->profile())
                ->registrar_unsafe()
                .GetAppStartUrl(app_id));

  // Expect the newly created window has the dragged tab and a home tab.
  TabStripModel* dest_tab_strip_model =
      browser_list()->get(1)->tab_strip_model();
  EXPECT_EQ(dest_tab_strip_model->count(), 2);
  EXPECT_TRUE(dest_tab_strip_model->IsTabPinned(0));
  EXPECT_EQ(dest_tab_strip_model->GetWebContentsAt(0)->GetVisibleURL(),
            source_tab_strip_model->GetWebContentsAt(0)->GetVisibleURL());
  EXPECT_EQ(dest_tab_strip_model->GetWebContentsAt(1)->GetVisibleURL(),
            GURL("https://www.example.com/newpage"));
  EXPECT_EQ(dest_tab_strip_model->active_index(), 1);
}

// Home tab can't be detached.
// TODO(crbug.com/40245163): Enable this test for Linux.
#if BUILDFLAG(IS_LINUX)
#define MAYBE_CantDragHomeTab DISABLED_CantDragHomeTab
#else
#define MAYBE_CantDragHomeTab CantDragHomeTab
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithTabbedWebApp,
                       MAYBE_CantDragHomeTab) {
  // Install tabbed web app.
  webapps::AppId app_id = InstallMockApp(/*add_home_tab=*/true);
  Browser* app_browser =
      web_app::LaunchWebAppBrowser(browser()->profile(), app_id);
  ASSERT_EQ(2u, browser_list()->size());

  // Close normal browser since other code expects only 1 browser to start.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(1u, browser_list()->size());

  SelectFirstBrowser();
  ASSERT_EQ(app_browser, browser());

  AddTabsAndResetBrowser(browser(), 1, GURL("https://www.example.com/newpage"));

  TabStrip* tab_strip = GetTabStripForBrowser(app_browser);
  EXPECT_EQ(browser()->tab_strip_model()->count(), 2);

  // Try dragging the home tab enough that it would usually detach.
  const Tab* tab = tab_strip->tab_at(0);
  ASSERT_TRUE(PressInputAtCenter(tab));
  ASSERT_TRUE(DragInputToCenter(tab, gfx::Vector2d(0, GetDetachY(tab_strip))));

  ASSERT_TRUE(TabDragController::IsActive());

  ASSERT_TRUE(ReleaseInput());

  // There should only be one browser window containing two tabs.
  EXPECT_EQ(1u, browser_list()->size());
  EXPECT_EQ(browser()->tab_strip_model()->count(), 2);
}

// Tabbed web apps without a home tab do not have home tab added.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithTabbedWebApp,
                       NoHomeTab) {
  // Install tabbed web app.
  webapps::AppId app_id = InstallMockApp(/*add_home_tab=*/false);
  Browser* app_browser =
      web_app::LaunchWebAppBrowser(browser()->profile(), app_id);
  ASSERT_EQ(2u, browser_list()->size());

  // Close normal browser since other code expects only 1 browser to start.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(1u, browser_list()->size());

  SelectFirstBrowser();
  ASSERT_EQ(app_browser, browser());

  AddTabsAndResetBrowser(browser(), 1, GURL("https://www.example.com/newpage"));

  TabStrip* tab_strip = GetTabStripForBrowser(app_browser);
  EXPECT_EQ(browser()->tab_strip_model()->count(), 2);

  // Move to the second tab and drag it enough that it detaches.
  int tab_1_width = tab_strip->tab_at(1)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_1_width),
                   1);

  // Expect 2 app windows with 1 tab each.
  ASSERT_EQ(2u, browser_list()->size());
  EXPECT_EQ(browser_list()->get(0)->tab_strip_model()->count(), 1);
  EXPECT_EQ(browser_list()->get(1)->tab_strip_model()->count(), 1);
}
#endif  // !BUILDFLAG(IS_MAC)

class DetachToBrowserTabDragControllerTestWithScrollableTabStripEnabled
    : public DetachToBrowserTabDragControllerTest {
 public:
  DetachToBrowserTabDragControllerTestWithScrollableTabStripEnabled() {
    scoped_feature_list_.InitWithFeatures({tabs::kScrollableTabStrip}, {});
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_;
};

// Disabling on macOS due to DCHECK crashes; see https://crbug.com/1183043.
#if BUILDFLAG(IS_LINUX) || (BUILDFLAG(IS_MAC) && DCHECK_IS_ON())
#define MAYBE_DraggingRightExpandsTabStripSize \
  DISABLED_DraggingRightExpandsTabStripSize
#else
#define MAYBE_DraggingRightExpandsTabStripSize DraggingRightExpandsTabStripSize
#endif
// Creates a browser with two tabs and drags the rightmost tab. Given the
// browser window is large enough, the tabstrip should expand to accommodate
// this tab. Note: There must be at least two tabs because dragging a singular
// tab will drag the window.
// Disabled for Linux due to test dragging flakiness.
IN_PROC_BROWSER_TEST_P(
    DetachToBrowserTabDragControllerTestWithScrollableTabStripEnabled,
    MAYBE_DraggingRightExpandsTabStripSize) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  const TabStyle* tab_style = TabStyle::Get();
  // We must ensure that we set the bounds of the browser window such that it is
  // wide enough to allow the tab strip to expand to accommodate this tab.
  browser()->window()->SetBounds(gfx::Rect(
      0, 0, tab_style->GetStandardWidth(/*is_split*/ false) * 5, 400));

  const int tab_strip_width = tab_strip->width();
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(
      tab_strip->tab_at(1),
      gfx::Vector2d(tab_style->GetStandardWidth(/*is_split*/ false), 0)));
  BrowserView::GetBrowserViewForBrowser(browser())
      ->GetWidget()
      ->LayoutRootViewIfNecessary();
  EXPECT_EQ(tab_strip_width + tab_style->GetStandardWidth(/*is_split*/ false),
            tab_strip->width());
  ASSERT_TRUE(ReleaseInput());
}

namespace {

// Invoked from the nested run loop.
void DragAllToSeparateWindowAndCancelStep2(
    DetachToBrowserTabDragControllerTest* test,
    TabStrip* attached_tab_strip,
    TabStrip* target_tab_strip) {
  EXPECT_TRUE(attached_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_FALSE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());
  EXPECT_EQ(2u, test->browser_list()->size());

  // Drag to target_tab_strip. This should stop the nested loop from dragging
  // the window.
  EXPECT_TRUE(test->DragInputToCenterAsync(target_tab_strip));
}

}  // namespace

#if BUILDFLAG(IS_MAC) /* && defined(ARCH_CPU_ARM64) */
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
// These were flaking on all macs, so commented out ARCH_ above for
// crbug.com/1160917 too.
#define MAYBE_DragAllToSeparateWindowAndCancel \
  DISABLED_DragAllToSeparateWindowAndCancel
#else
// TODO(crbug.com/40740354): Flaky on Windows and Linux.
#define MAYBE_DragAllToSeparateWindowAndCancel \
  DISABLED_DragAllToSeparateWindowAndCancel
#endif

// Creates two browsers, selects all tabs in first, drags into second, then hits
// escape.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragAllToSeparateWindowAndCancel) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  browser()->tab_strip_model()->SelectTabAt(0);

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DragAllToSeparateWindowAndCancelStep2, this,
                                  tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_EQ(1u, browser_list()->size());

  // Cancel the drag.
  ASSERT_TRUE(ui_test_utils::SendKeyPressSync(browser2, ui::VKEY_ESCAPE, false,
                                              false, false, false));

  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("100 0 1", IDString(browser2->tab_strip_model()));

  // browser() will have been destroyed, but browser2 should remain.
  ASSERT_EQ(1u, browser_list()->size());

  EXPECT_FALSE(GetIsDragged(browser2));

  // Remaining browser window should not be maximized
  EXPECT_FALSE(browser2->window()->IsMaximized());
}

#if BUILDFLAG(IS_MAC) /* && defined(ARCH_CPU_ARM64) */
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
// These were flaking on all macs, so commented out ARCH_ above for
// crbug.com/1160917 too.
#define MAYBE_DragAllToSeparateWindowWithPinnedTabs \
  DISABLED_DragAllToSeparateWindowWithPinnedTabs
#else
// TODO(crbug.com/40740354): Flaky on Windows and Linux.
#define MAYBE_DragAllToSeparateWindowWithPinnedTabs \
  DISABLED_DragAllToSeparateWindowWithPinnedTabs
#endif

// Creates two browsers, selects all tabs in first, drags into second, then hits
// escape.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragAllToSeparateWindowWithPinnedTabs) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Open a second tab.
  AddTabsAndResetBrowser(browser(), 1);
  // Re-select the first one.
  browser()->tab_strip_model()->SelectTabAt(0);

  // Create another browser.
  Browser* target_browser = CreateAnotherBrowserAndResize();
  TabStrip* target_tab_strip = GetTabStripForBrowser(target_browser);

  // Pin the tab in the target tabstrip.
  target_browser->tab_strip_model()->SetTabPinned(0, true);

  // Drag the selected tabs to `target_tab_strip`.
  DragTabAndNotify(
      tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2, this, tab_strip,
                                target_tab_strip));

  // Should now be attached to `target_tab_strip`.
  ASSERT_TRUE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_EQ(1u, browser_list()->size());

  // Drag to the trailing end of the tabstrip to ensure we're in a consistent
  // spot within the strip.
  StopAnimating(target_tab_strip);
  ASSERT_TRUE(DragInputToCenter(target_tab_strip->tab_at(1)));

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  ASSERT_FALSE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("100 0 1", IDString(target_browser->tab_strip_model()));

  EXPECT_FALSE(GetIsDragged(target_browser));

  // Remaining browser window should not be maximized
  EXPECT_FALSE(target_browser->window()->IsMaximized());
}

// Creates two browsers, drags from first into the second in such a way that
// no detaching should happen.
// TODO(crbug.com/41482323): Reenable flaky test.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DISABLED_DragDirectlyToSecondWindow) {
  // TODO(pkasting): Crashes when detaching browser.  https://crbug.com/918733
  if (input_source() == InputSource::INPUT_SOURCE_TOUCH) {
    VLOG(1) << "Test is DISABLED for touch input.";
    return;
  }

  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  const gfx::Rect initial_bounds(browser2->window()->GetBounds());

  // Place the first browser directly below the second in such a way that
  // dragging a tab upwards will drag it directly into the second browser's
  // tabstrip.
  const BrowserView* const browser_view2 =
      BrowserView::GetBrowserViewForBrowser(browser2);
  const gfx::Rect tabstrip_region2_bounds =
      browser_view2->frame()->GetBoundsForTabStripRegion(
          browser_view2->tab_strip_region_view()->GetMinimumSize());
  gfx::Rect bounds = initial_bounds;
  bounds.Offset(0, tabstrip_region2_bounds.bottom());
  browser()->window()->SetBounds(bounds);

  // Ensure the first browser is on top so clicks go to it.
  ui_test_utils::BrowserActivationWaiter activation_waiter(browser());
  browser()->window()->Activate();
  activation_waiter.WaitForActivation();

  // Move to the first tab and drag it to browser2.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));

  const views::View* tab = tab_strip2->tab_at(0);
  ASSERT_TRUE(DragInputToCenter(tab, gfx::Vector2d(-tab->width() / 4, 0)));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 100", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // Make sure that the window is still managed and not user moved.
  EXPECT_TRUE(IsWindowPositionManaged(browser2->window()->GetNativeWindow()));
  EXPECT_FALSE(HasUserChangedWindowPositionOrSize(
      browser2->window()->GetNativeWindow()));

  // Also make sure that the drag to window position has not changed.
  EXPECT_EQ(initial_bounds.ToString(),
            browser2->window()->GetBounds().ToString());
}

// Flaky. https://crbug.com/1176998
#if (BUILDFLAG(IS_MAC) && defined(ARCH_CPU_ARM64)) || BUILDFLAG(IS_LINUX)
// Bulk-disabled for arm64 bot stabilization: https://crbug.com/1154345
#define MAYBE_DragSingleTabToSeparateWindow \
  DISABLED_DragSingleTabToSeparateWindow
#else
#define MAYBE_DragSingleTabToSeparateWindow DragSingleTabToSeparateWindow
#endif

// Creates two browsers, the first browser has a single tab and drags into the
// second browser.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_DragSingleTabToSeparateWindow) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  ResetIDs(browser()->tab_strip_model(), 0);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip, base::BindOnce(&DragAllToSeparateWindowStep2,
                                             this, tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_EQ(1u, browser_list()->size());

  // Drag to the trailing end of the tabstrip to ensure we're in a consistent
  // spot within the strip.
  StopAnimating(tab_strip2);
  ASSERT_TRUE(DragInputToCenter(tab_strip2->tab_at(1)));

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("100 0", IDString(browser2->tab_strip_model()));

  EXPECT_FALSE(GetIsDragged(browser2));

  // Remaining browser window should not be maximized
  EXPECT_FALSE(browser2->window()->IsMaximized());
}

#if !BUILDFLAG(IS_MAC)
namespace {

// Invoked from the nested run loop.
void CancelOnNewTabWhenDraggingStep2(DetachToBrowserTabDragControllerTest* test,
                                     const Browser* default_browser,
                                     base::OnceClosure quit_closure,
                                     WebContents** contents_out) {
  EXPECT_TRUE(TabDragController::IsActive());
  EXPECT_EQ(2u, test->browser_list()->size());

  // Finds the new browser opened by the test, and waits until it becomes
  // the last active one.
  Browser* new_browser = nullptr;
  for (Browser* browser : *test->browser_list()) {
    if (browser != default_browser) {
      new_browser = browser;
      break;
    }
  }
  CHECK(new_browser);
  ui_test_utils::WaitForBrowserSetLastActive(new_browser);

  *contents_out =
      chrome::AddAndReturnTabAt(test->browser_list()->GetLastActive(),
                                GURL(url::kAboutBlankURL), 0, false);
  std::move(quit_closure).Run();
}

}  // namespace

// Adds another tab, detaches into separate window, adds another tab and
// verifies the run loop ends.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       CancelOnNewTabWhenDragging) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Skip this test for fallback tab dragging, see the note in
  // TabDragController::TabWasAdded() for more context.
  views::Widget* widget = tab_strip->GetDragContext()->GetWidget();
  if (base::FeatureList::IsEnabled(
          features::kAllowWindowDragUsingSystemDragDrop) &&
      !widget->IsMoveLoopSupported()) {
    GTEST_SKIP() << "Not relevant for fallback tab dragging";
  }

  AddTabsAndResetBrowser(browser(), 1);

  // Move to the first tab and drag it enough so that it detaches.
  const Tab* tab = tab_strip->tab_at(0);
  ASSERT_TRUE(PressInputAtCenter(tab));

  base::RunLoop run_loop;
  auto quit_closure = run_loop.QuitClosure();
  WebContents* web_contents = nullptr;
  // Add another tab. This should trigger exiting the nested loop. Add at the
  // beginning to exercise past crash when model/tabstrip got out of sync.
  // crbug.com/474082
  ASSERT_TRUE(DragInputToCenterNotifyWhenDone(
      tab,
      base::BindOnce(&CancelOnNewTabWhenDraggingStep2, this, browser(),
                     std::move(quit_closure), base::Unretained(&web_contents)),
      gfx::Vector2d(0, GetDetachY(tab_strip))));
  run_loop.Run();
  ASSERT_TRUE(!!web_contents);
  content::WaitForLoadStop(web_contents);

  // Should be two windows and not dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  ASSERT_EQ(2u, browser_list()->size());
  for (Browser* browser : *BrowserList::GetInstance()) {
    EXPECT_FALSE(GetIsDragged(browser));
    // Should not be maximized
    EXPECT_FALSE(browser->window()->IsMaximized());
  }
}
#endif  // !BUILDFLAG(IS_MAC)

namespace {

TabStrip* GetAttachedTabstrip() {
  for (Browser* browser : *BrowserList::GetInstance()) {
    BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
    if (TabDragController::IsAttachedTo(
            browser_view->tabstrip()->GetDragContext())) {
      return browser_view->tabstrip();
    }
  }
  return nullptr;
}

void DragWindowAndVerifyOffset(DetachToBrowserTabDragControllerTest* test,
                               TabStrip* tab_strip,
                               int tab_index) {
  test::QuitDraggingObserver observer(tab_strip);
  // Move to the tab and drag it enough so that it detaches.
  const gfx::Point tab_center =
      GetCenterInScreenCoordinates(tab_strip->tab_at(tab_index));
  // The expected offset; the horizontal position should be relative to the
  // pressed tab. The vertical position should be relative to the window itself
  // since the top margin can be different between the existing browser and
  // the dragged one.
  const gfx::Vector2d press_offset(
      tab_center.x() - tab_strip->tab_at(tab_index)->GetBoundsInScreen().x(),
      tab_center.y() - tab_strip->GetWidget()->GetWindowBoundsInScreen().y());
  const gfx::Point initial_move =
      tab_center + gfx::Vector2d(0, GetDetachY(tab_strip));
  const gfx::Point second_move = initial_move + gfx::Vector2d(20, 20);
  const gfx::NativeWindow window_hint = test->GetWindowHint(tab_strip);
  ASSERT_TRUE(test->PressInput(tab_center, window_hint));
  ASSERT_TRUE(test->DragInputToNotifyWhenDone(
      initial_move, base::BindLambdaForTesting([&]() {
        // Moves slightly to cause the actual dragging effect on the system and
        // makes sure the window is positioned correctly.
        ASSERT_TRUE(test->DragInputToNotifyWhenDone(
            second_move, base::BindLambdaForTesting([&]() {
              TabStrip* attached = GetAttachedTabstrip();
              // Same computation for drag offset. This operation drags a single
              // tab, so the target tab index should be always 0.
              gfx::Vector2d drag_offset(
                  second_move.x() -
                      attached->tab_at(0)->GetBoundsInScreen().x(),
                  second_move.y() -
                      attached->GetWidget()->GetWindowBoundsInScreen().y());
              EXPECT_EQ(press_offset, drag_offset);
              ASSERT_TRUE(test->ReleaseInput());
            }),
            window_hint));
      }),
      window_hint));
  observer.Wait();
}

}  // namespace

#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_MAC)
// TODO(mukai): enable this test on Windows and Linux.
// TODO(crbug.com/41468034): flaky on Mac
#define MAYBE_OffsetForDraggingTab DISABLED_OffsetForDraggingTab
#else
#define MAYBE_OffsetForDraggingTab OffsetForDraggingTab
#endif

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       MAYBE_OffsetForDraggingTab) {
  DragWindowAndVerifyOffset(this, GetTabStripForBrowser(browser()), 0);
  ASSERT_FALSE(TabDragController::IsActive());
}

// TODO(crbug.com/41457552): fix flakiness and re-enable this test on mac/linux.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DISABLED_OffsetForDraggingDetachedTab) {
  AddTabsAndResetBrowser(browser(), 1);

  DragWindowAndVerifyOffset(this, GetTabStripForBrowser(browser()), 1);
  ASSERT_FALSE(TabDragController::IsActive());
}

#if BUILDFLAG(IS_CHROMEOS)
namespace {

void DragInMaximizedWindowStep2(DetachToBrowserTabDragControllerTest* test,
                                Browser* browser,
                                TabStrip* tab_strip) {
  // There should be another browser.
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(2u, num_browsers);
  Browser* new_browser = test->browser_list()->get(num_browsers - 1);
  EXPECT_NE(browser, new_browser);
  ui_test_utils::BrowserActivationWaiter activation_waiter(new_browser);
  activation_waiter.WaitForActivation();
  EXPECT_TRUE(new_browser->window()->IsActive());
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);

  EXPECT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());

  // Both windows should be visible.
  EXPECT_TRUE(tab_strip->GetWidget()->IsVisible());
  EXPECT_TRUE(tab_strip2->GetWidget()->IsVisible());

  // Stops dragging.
  EXPECT_TRUE(test->ReleaseInput());
}

}  // namespace

// Creates a browser with two tabs, maximizes it, drags the tab out.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DragInMaximizedWindow) {
  {
    auto waiter = ui_test_utils::CreateAsyncWidgetRequestWaiter(*browser());
    browser()->window()->Maximize();
    waiter.Wait();
  }
  ASSERT_TRUE(browser()->window()->IsMaximized());
  AddTabsAndResetBrowser(browser(), 1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  DragTabAndNotify(tab_strip, base::BindOnce(&DragInMaximizedWindowStep2, this,
                                             browser(), tab_strip));

  ASSERT_FALSE(TabDragController::IsActive());

  // Should be two browsers.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);

  EXPECT_TRUE(browser()->window()->GetNativeWindow()->IsVisible());
  EXPECT_TRUE(new_browser->window()->GetNativeWindow()->IsVisible());

  EXPECT_FALSE(GetIsDragged(browser()));
  EXPECT_FALSE(GetIsDragged(new_browser));

  // The source window should be maximized.
  EXPECT_TRUE(browser()->window()->IsMaximized());
  // The new window should be maximized.
  EXPECT_TRUE(new_browser->window()->IsMaximized());
}

namespace {

void NewBrowserWindowStateStep2(DetachToBrowserTabDragControllerTest* test,
                                TabStrip* tab_strip) {
  // There should be two browser windows, including the newly created one for
  // the dragged tab.
  EXPECT_EQ(3u, test->browser_list()->size());

  // Get this new created window for the dragged tab.
  Browser* new_browser = test->browser_list()->get(2);
  aura::Window* window = new_browser->window()->GetNativeWindow();
  EXPECT_NE(window->GetProperty(aura::client::kShowStateKey),
            ui::mojom::WindowShowState::kMaximized);
  EXPECT_EQ(window->GetProperty(aura::client::kShowStateKey),
            ui::mojom::WindowShowState::kDefault);

  EXPECT_TRUE(test->ReleaseInput());
}

}  // namespace

// Test that tab dragging can work on a browser window with its initial show
// state is MAXIMIZED.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       NewBrowserWindowState) {
  // Create a browser window whose initial show state is MAXIMIZED.
  Browser::CreateParams params(browser()->profile(), /*user_gesture=*/false);
  params.initial_show_state = ui::mojom::WindowShowState::kMaximized;
  Browser* browser = Browser::Create(params);
  AddBlankTabAndShow(browser);
  TabStrip* tab_strip = GetTabStripForBrowser(browser);
  AddTabsAndResetBrowser(browser, 1);

  // Maximize the browser window.
  browser->window()->Maximize();
  EXPECT_EQ(browser->window()->GetNativeWindow()->GetProperty(
                aura::client::kShowStateKey),
            ui::mojom::WindowShowState::kMaximized);

  // Drag it far enough that the first tab detaches.
  DragTabAndNotify(
      tab_strip, base::BindOnce(&NewBrowserWindowStateStep2, this, tab_strip));
}

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       OffsetForDraggingInMaximizedWindow) {
  AddTabsAndResetBrowser(browser(), 1);
  // Moves the browser window slightly to ensure that the browser's restored
  // bounds are different from the maximized bound's origin.
  browser()->window()->SetBounds(browser()->window()->GetBounds() +
                                 gfx::Vector2d(100, 50));
  browser()->window()->Maximize();

  DragWindowAndVerifyOffset(this, GetTabStripForBrowser(browser()), 0);
  ASSERT_FALSE(TabDragController::IsActive());
}

namespace {

// A window observer that observes the dragged window's property
// ash::kIsDraggingTabsKey.
class DraggedWindowObserver : public aura::WindowObserver {
 public:
  DraggedWindowObserver(DetachToBrowserTabDragControllerTest* test,
                        aura::Window* window,
                        const gfx::Rect& bounds,
                        const gfx::Point& end_point)
      : test_(test), end_bounds_(bounds), end_point_(end_point) {}
  DraggedWindowObserver(const DraggedWindowObserver&) = delete;
  DraggedWindowObserver& operator=(const DraggedWindowObserver&) = delete;
  ~DraggedWindowObserver() override {
    if (window_) {
      window_->RemoveObserver(this);
    }
  }

  void StartObserving(aura::Window* window) {
    DCHECK(!window_);
    window_ = window;
    window_->AddObserver(this);
  }

  // aura::WindowObserver:
  void OnWindowDestroying(aura::Window* window) override {
    DCHECK_EQ(window_, window);
    window_->RemoveObserver(this);
    window_ = nullptr;
  }

  void OnWindowPropertyChanged(aura::Window* window,
                               const void* key,
                               intptr_t old) override {
    DCHECK_EQ(window_, window);
    if (key == ash::kIsDraggingTabsKey) {
      if (!window_->GetProperty(ash::kIsDraggingTabsKey)) {
        // It should be triggered by TabDragController::ClearTabDraggingInfo()
        // from TabDragController::EndDragImpl(). Theoretically at this point
        // TabDragController should have removed itself as an observer of the
        // dragged tabstrip's widget. So changing its bounds should do nothing.

        // It's to ensure the current cursor location is within the bounds of
        // another browser's tabstrip.
        test_->MoveInputTo(end_point_);

        // Change window's bounds to simulate what might happen in ash. If
        // TabDragController is still an observer of the dragged tabstrip's
        // widget, OnWidgetBoundsChanged() will calls into ContinueDragging()
        // to attach the dragged tabstrip into another browser, which might
        // cause chrome crash.
        window_->SetBounds(end_bounds_);
      }
    }
  }

 private:
  raw_ptr<DetachToBrowserTabDragControllerTest> test_;
  // The dragged window.
  raw_ptr<aura::Window> window_ = nullptr;
  // The bounds that `window_` will change to when the drag ends.
  gfx::Rect end_bounds_;
  // The position that the mouse/touch event will move to when the drag ends.
  gfx::Point end_point_;
};

void DoNotObserveDraggedWidgetAfterDragEndsStep2(
    DetachToBrowserTabDragControllerTest* test,
    DraggedWindowObserver* observer,
    TabStrip* attached_tab_strip) {
  EXPECT_TRUE(attached_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());

  // Start observe the dragged window.
  observer->StartObserving(attached_tab_strip->GetWidget()->GetNativeWindow());

  EXPECT_TRUE(test->ReleaseInput());
}

}  // namespace

// Test that after the drag ends, TabDragController is no longer an observer of
// the dragged widget, so that if the bounds of the dragged widget change,
// TabDragController won't be put into dragging process again.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       DoNotObserveDraggedWidgetAfterDragEnds) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  EXPECT_EQ(2u, browser_list()->size());

  // Create an window observer to observe the dragged window.
  std::unique_ptr<DraggedWindowObserver> observer(new DraggedWindowObserver(
      this, test::GetWindowForTabStrip(tab_strip),
      tab_strip2->GetWidget()->GetNativeWindow()->bounds(),
      GetCenterInScreenCoordinates(tab_strip2)));

  // Drag the tab long enough so that it moves.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DoNotObserveDraggedWidgetAfterDragEndsStep2,
                                  this, observer.get(), tab_strip));

  // There should be still two browsers at this moment. `tab_strip` should not
  // be merged into `tab_strip2`.
  EXPECT_EQ(2u, browser_list()->size());

  ASSERT_FALSE(TabDragController::IsActive());
}

namespace {

// Returns true if the web contents that's associated with `browser` is using
// fast resize.
bool WebContentsIsFastResized(Browser* browser) {
  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser);
  ContentsWebView* contents_web_view =
      static_cast<ContentsWebView*>(browser_view->GetContentsView());
  return contents_web_view->holder()->fast_resize();
}

void FastResizeDuringDraggingStep2(DetachToBrowserTabDragControllerTest* test,
                                   TabStrip* not_attached_tab_strip,
                                   TabStrip* target_tab_strip) {
  // There should be three browser windows, including the newly created one for
  // the dragged tab.
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(3u, num_browsers);

#if !BUILDFLAG(IS_LINUX)
  // Get this new created window for the drag. It should have fast resize set.
  Browser* new_browser = test->browser_list()->get(num_browsers - 1);
  EXPECT_TRUE(WebContentsIsFastResized(new_browser));
  // The source window should also have fast resize set.
  EXPECT_TRUE(WebContentsIsFastResized(test->browser()));
#endif

  // Now drag to target_tab_strip.
  EXPECT_TRUE(test->DragInputToCenter(target_tab_strip));

  EXPECT_TRUE(test->ReleaseInput());
}

}  // namespace

// Tests that we use fast resize to resize the web contents of the dragged
// window and the source window during tab dragging process, and don't use fast
// resize after tab dragging ends.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       FastResizeDuringDragging) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  AddTabsAndResetBrowser(browser(), 1);

  // Create another browser.
  Browser* browser2 = CreateAnotherBrowserAndResize();
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  EXPECT_EQ(2u, browser_list()->size());

  EXPECT_FALSE(WebContentsIsFastResized(browser()));
  EXPECT_FALSE(WebContentsIsFastResized(browser2));

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip, base::BindOnce(&FastResizeDuringDraggingStep2,
                                             this, tab_strip, tab_strip2));

  EXPECT_FALSE(WebContentsIsFastResized(browser()));
  EXPECT_FALSE(WebContentsIsFastResized(browser2));
}

class DetachToBrowserTabDragControllerTestWithTabbedSystemApp
    : public DetachToBrowserTabDragControllerTest {
 public:
  DetachToBrowserTabDragControllerTestWithTabbedSystemApp()
      : test_system_web_app_installation_(
            ash::TestSystemWebAppInstallation::SetUpTabbedMultiWindowApp()) {}

  webapps::AppId InstallMockApp() {
    test_system_web_app_installation_->WaitForAppInstall();
    return test_system_web_app_installation_->GetAppId();
  }

  Browser* LaunchWebAppBrowser(webapps::AppId app_id) {
    return web_app::LaunchWebAppBrowser(browser()->profile(), app_id);
  }

  const GURL& GetAppUrl() {
    return test_system_web_app_installation_->GetAppUrl();
  }

 private:
  std::unique_ptr<ash::TestSystemWebAppInstallation>
      test_system_web_app_installation_;
};

// Move tab from TYPE_APP Browser to create new TYPE_APP Browser.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithTabbedSystemApp,
                       DragAppToOwnWindow) {
  // Install and get a tabbed system app.
  webapps::AppId tabbed_app_id = InstallMockApp();
  Browser* app_browser = LaunchWebAppBrowser(tabbed_app_id);
  ASSERT_EQ(2u, browser_list()->size());

  // Close normal browser since other code expects only 1 browser to start.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(1u, browser_list()->size());
  SelectFirstBrowser();
  ASSERT_EQ(app_browser, browser());
  EXPECT_EQ(Browser::Type::TYPE_APP, browser_list()->get(0)->type());
  AddTabsAndResetBrowser(browser(), 1, GetAppUrl());
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  int tab_0_width = tab_strip->tab_at(0)->width();
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DetachToBrowserTabDragControllerTest::
                                      ReleaseInputAfterWindowDetached,
                                  base::Unretained(this), tab_0_width));

  // New browser should be TYPE_APP.
  ASSERT_EQ(2u, browser_list()->size());
  EXPECT_EQ(Browser::Type::TYPE_APP, browser_list()->get(1)->type());
}

// TODO (crbug.com/1521327): Test fails after migrating to ChromeRefresh2023.
// Move tab from TYPE_APP Browser to another TYPE_APP Browser.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithTabbedSystemApp,
                       DISABLED_DragAppToAppWindow) {
  // Install and get 2 browsers with tabbed system app.
  webapps::AppId tabbed_app_id = InstallMockApp();
  Browser* app_browser1 = LaunchWebAppBrowser(tabbed_app_id);
  Browser* app_browser2 = LaunchWebAppBrowser(tabbed_app_id);
  ASSERT_EQ(3u, browser_list()->size());
  ResetIDs(app_browser2->tab_strip_model(), 100);

  gfx::Rect work_area =
      display::Screen::GetScreen()
          ->GetDisplayNearestWindow(app_browser1->window()->GetNativeWindow())
          .work_area();
  const gfx::Size size(work_area.width() / 3, work_area.height() / 2);
  gfx::Rect browser_rect(work_area.origin(), size);
  app_browser1->window()->SetBounds(browser_rect);
  browser_rect.set_x(browser_rect.right());
  app_browser2->window()->SetBounds(browser_rect);

  // Close normal browser since other code expects only 1 browser to start.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(2u, browser_list()->size());
  SelectFirstBrowser();
  ASSERT_EQ(app_browser1, browser());

  AddTabsAndResetBrowser(browser(), 1, GetAppUrl());
  TabStrip* tab_strip1 = GetTabStripForBrowser(app_browser1);
  TabStrip* tab_strip2 = GetTabStripForBrowser(app_browser2);

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip1, base::BindOnce(&DragToSeparateWindowStep2, this,
                                              tab_strip1, tab_strip2));

  // Should now be attached to tab_strip2.
  // Release mouse or touch, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  EXPECT_EQ("100 0", IDString(app_browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(app_browser1->tab_strip_model()));
}

// Subclass of DetachToBrowserTabDragControllerTest that
// creates multiple displays.
class DetachToBrowserInSeparateDisplayTabDragControllerTest
    : public DetachToBrowserTabDragControllerTest {
 public:
  DetachToBrowserInSeparateDisplayTabDragControllerTest() = default;
  DetachToBrowserInSeparateDisplayTabDragControllerTest(
      const DetachToBrowserInSeparateDisplayTabDragControllerTest&) = delete;
  DetachToBrowserInSeparateDisplayTabDragControllerTest& operator=(
      const DetachToBrowserInSeparateDisplayTabDragControllerTest&) = delete;
  virtual ~DetachToBrowserInSeparateDisplayTabDragControllerTest() = default;

  void SetUpOnMainThread() override {
    DetachToBrowserTabDragControllerTest::SetUpOnMainThread();
    // Make screens sufficiently wide to host 2 browsers side by side.
    // 1280x800 is the default resolution for the main display in tests.
    // We stick to it, as opposed to a smaller one, to avoid the browser
    // window being shrunk and maximized when calling UpdateDisplay.
    const std::string display_specs = "1280x800,1280x800";
    display::test::DisplayManagerTestApi(ash::Shell::Get()->display_manager())
        .UpdateDisplay(display_specs);
  }
};

namespace {

void DragSingleTabToSeparateWindowInSecondDisplayStep3(
    DetachToBrowserTabDragControllerTest* test) {
  EXPECT_TRUE(test->ReleaseInput());
}

void DragSingleTabToSeparateWindowInSecondDisplayStep2(
    DetachToBrowserTabDragControllerTest* test,
    const gfx::Point& target_point,
    gfx::NativeWindow window_hint) {
  EXPECT_TRUE(test->DragInputToNotifyWhenDone(
      target_point,
      base::BindOnce(&DragSingleTabToSeparateWindowInSecondDisplayStep3, test),
      window_hint));
}

}  // namespace

// Drags from browser to a second display and releases input.
// TODO(crbug.com/40940016): Test is flaky on multiple bots.
IN_PROC_BROWSER_TEST_P(DetachToBrowserInSeparateDisplayTabDragControllerTest,
                       DISABLED_DragSingleTabToSeparateWindowInSecondDisplay) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move to the first tab and drag it enough so that it detaches.
  // Then drag it to the final destination on the second screen.
  display::Screen* const screen = display::Screen::GetScreen();
  display::Display second_display = ui_test_utils::GetSecondaryDisplay(screen);
  const gfx::Point start = GetCenterInScreenCoordinates(tab_strip->tab_at(0));
  ASSERT_FALSE(second_display.bounds().Contains(start));
  const gfx::Point target(second_display.bounds().x() + 1,
                          start.y() + GetDetachY(tab_strip));
  ASSERT_TRUE(second_display.bounds().Contains(target));

  // TODO(crbug.com/40638870): Unit tests should be able to simulate mouse input
  // without having to call `CursorManager::SetDisplay`.
  ash::Shell::Get()->cursor_manager()->SetDisplay(second_display);
  DragTabAndNotify(
      tab_strip,
      base::BindOnce(&DragSingleTabToSeparateWindowInSecondDisplayStep2, this,
                     target, GetWindowHint(tab_strip)));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  // This other browser should be on the second screen (with mouse drag)
  // With the touch input the browser cannot be dragged from one screen
  // to another and the window stays on the first screen.
  if (input_source() == InputSource::INPUT_SOURCE_MOUSE) {
    EXPECT_EQ(
        ui_test_utils::GetSecondaryDisplay(screen).id(),
        screen
            ->GetDisplayNearestWindow(new_browser->window()->GetNativeWindow())
            .id());
  }

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // Both windows should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_FALSE(new_browser->window()->IsMaximized());
}

namespace {

// Invoked from the nested run loop.
void DragTabToWindowInSeparateDisplayStep2(
    DetachToBrowserTabDragControllerTest* test,
    TabStrip* not_attached_tab_strip,
    TabStrip* target_tab_strip) {
  EXPECT_FALSE(not_attached_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_FALSE(target_tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());

  // Drag to target_tab_strip. This should stop the nested loop from dragging
  // the window.
  // Move it closer to the beginning of the tab so it will drop before that tab.
  EXPECT_TRUE(test->DragInputToCenterAsync(target_tab_strip->tab_at(0),
                                           gfx::Vector2d(-20, 0)));
}

}  // namespace

// Drags from browser to another browser on a second display and releases input.
// TODO(crbug.com/329747667): Test is flaky on "Linux ChromiumOS MSan Tests"
#if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER)
#define MAYBE_DragTabToWindowInSeparateDisplay \
  DISABLED_DragTabToWindowInSeparateDisplay
#else
#define MAYBE_DragTabToWindowInSeparateDisplay DragTabToWindowInSeparateDisplay
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserInSeparateDisplayTabDragControllerTest,
                       MAYBE_DragTabToWindowInSeparateDisplay) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Create another browser.
  Browser* browser2 = CreateBrowser(browser()->profile());
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  ResetIDs(browser2->tab_strip_model(), 100);

  // Move the second browser to the second display.
  display::Screen* screen = display::Screen::GetScreen();
  Display second_display = ui_test_utils::GetSecondaryDisplay(screen);
  ui_test_utils::SetAndWaitForBounds(*browser2, second_display.work_area());
  EXPECT_EQ(
      second_display.id(),
      screen->GetDisplayNearestWindow(browser2->window()->GetNativeWindow())
          .id());

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DragTabToWindowInSeparateDisplayStep2, this,
                                  tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 100", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // Both windows should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_FALSE(browser2->window()->IsMaximized());
}

// Crashes on ChromeOS. crbug.com/1003288
IN_PROC_BROWSER_TEST_P(
    DetachToBrowserInSeparateDisplayTabDragControllerTest,
    DISABLED_DragBrowserWindowWhenMajorityOfBoundsInSecondDisplay) {
  // Set the browser's window bounds such that the majority of its bounds
  // resides in the second display.
  const std::pair<Display, Display> displays =
      GetDisplays(display::Screen::GetScreen());

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  {
    // Moves the browser window through dragging so that the majority of its
    // bounds are in the secondary display but it's still be in the primary
    // display. Do not use SetBounds() or related, it may move the browser
    // window to the secondary display in some configurations like Mash.
    int target_x = displays.first.bounds().right() -
                   browser()->window()->GetBounds().width() / 2 + 20;
    const gfx::Point target_point =
        GetCenterInScreenCoordinates(tab_strip->tab_at(0)) +
        gfx::Vector2d(target_x - browser()->window()->GetBounds().x(),
                      GetDetachY(tab_strip));
    DragTabAndNotify(
        tab_strip,
        base::BindOnce(&DragSingleTabToSeparateWindowInSecondDisplayStep2, this,
                       target_point, GetWindowHint(tab_strip)));
    StopAnimating(tab_strip);
  }
  EXPECT_EQ(displays.first.id(),
            browser()->window()->GetNativeWindow()->GetHost()->GetDisplayId());

  // Start dragging the window by the tab strip, and move it only to the edge
  // of the first display. Expect at that point mouse would warp and the window
  // will therefore reside in the second display when mouse is released.
  const gfx::Point tab_0_center =
      GetCenterInScreenCoordinates(tab_strip->tab_at(0));
  const int offset_x = tab_0_center.x() - browser()->window()->GetBounds().x();
  const int detach_y = tab_0_center.y() + GetDetachY(tab_strip);
  const int first_display_warp_edge_x = displays.first.bounds().right() - 1;
  const gfx::Point warped_point(displays.second.bounds().x() + 1, detach_y);

  DragTabAndNotify(
      tab_strip, base::BindLambdaForTesting([&]() {
        // This makes another event on the warped location because the test
        // system does not create it automatically as the result of pointer
        // warp.
        const gfx::NativeWindow window_hint = GetWindowHint(tab_strip);
        ASSERT_TRUE(DragInputToNotifyWhenDone(
            gfx::Point(first_display_warp_edge_x, detach_y),
            base::BindOnce(&DragSingleTabToSeparateWindowInSecondDisplayStep2,
                           this, warped_point, window_hint),
            window_hint));
      }));

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should only be a single browser.
  WaitForActiveBrowser(browser_list(), 1);
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());

  // Browser now resides in display 2.
  EXPECT_EQ(warped_point.x() - offset_x, browser()->window()->GetBounds().x());
  EXPECT_EQ(displays.second.id(),
            browser()->window()->GetNativeWindow()->GetHost()->GetDisplayId());
}

// Drags from browser to another browser on a second display and releases input.
#if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER)
// TODO(crbug.com/333006829):
#define MAYBE_DragTabToWindowOnSecondDisplay \
  DISABLED_DragTabToWindowOnSecondDisplay
#else
#define MAYBE_DragTabToWindowOnSecondDisplay DragTabToWindowOnSecondDisplay
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserInSeparateDisplayTabDragControllerTest,
                       MAYBE_DragTabToWindowOnSecondDisplay) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Create another browser.
  Browser* browser2 = CreateBrowser(browser()->profile());
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  ResetIDs(browser2->tab_strip_model(), 100);

  // Move both browsers to be side by side on the second display.
  display::Screen* screen = display::Screen::GetScreen();
  Display second_display = ui_test_utils::GetSecondaryDisplay(screen);
  gfx::Rect work_area = second_display.work_area();
  work_area.set_width(work_area.width() / 2);
  ui_test_utils::SetAndWaitForBounds(*browser(), work_area);
  // It's possible the window will not fit in half the screen, in which case we
  // will position the windows as well as we can.
  work_area.set_x(browser()->window()->GetBounds().right());
  // Sanity check: second browser should still be on the second display.
  ASSERT_LT(work_area.x(), second_display.work_area().right());
  ui_test_utils::SetAndWaitForBounds(*browser2, work_area);
  EXPECT_EQ(
      second_display.id(),
      screen->GetDisplayNearestWindow(browser()->window()->GetNativeWindow())
          .id());
  EXPECT_EQ(
      second_display.id(),
      screen->GetDisplayNearestWindow(browser2->window()->GetNativeWindow())
          .id());

  // Sanity check: make sure the target position is also within in the screen
  // bounds:
  ASSERT_LT(GetCenterInScreenCoordinates(tab_strip2->tab_at(0)).x(),
            second_display.work_area().right());

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DragTabToWindowInSeparateDisplayStep2, this,
                                  tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 100", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // Both windows should not be maximized
  EXPECT_FALSE(browser()->window()->IsMaximized());
  EXPECT_FALSE(browser2->window()->IsMaximized());
}

// Drags from a maximized browser to another non-maximized browser on a second
// display and releases input.
#if BUILDFLAG(IS_CHROMEOS) && defined(MEMORY_SANITIZER)
// TODO(crbug.com/333006829):
#define MAYBE_DragMaxTabToNonMaxWindowInSeparateDisplay \
  DISABLED_DragMaxTabToNonMaxWindowInSeparateDisplay
#else
#define MAYBE_DragMaxTabToNonMaxWindowInSeparateDisplay \
  DragMaxTabToNonMaxWindowInSeparateDisplay
#endif
IN_PROC_BROWSER_TEST_P(DetachToBrowserInSeparateDisplayTabDragControllerTest,
                       MAYBE_DragMaxTabToNonMaxWindowInSeparateDisplay) {
  AddTabsAndResetBrowser(browser(), 1);
  ASSERT_TRUE(ui_test_utils::MaximizeAndWaitUntilUIUpdateDone(*browser()));
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Create another browser on the second display.
  display::Screen* screen = display::Screen::GetScreen();
  ASSERT_EQ(2, screen->GetNumDisplays());
  const std::pair<Display, Display> displays = GetDisplays(screen);
  gfx::Rect work_area = displays.second.work_area();
  work_area.Inset(gfx::Insets::TLBR(20, 20, 60, 20));
  Browser::CreateParams params(browser()->profile(), true);
  params.initial_show_state = ui::mojom::WindowShowState::kNormal;
  params.initial_bounds = work_area;
  Browser* browser2 = Browser::Create(params);
  AddBlankTabAndShow(browser2);

  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  ResetIDs(browser2->tab_strip_model(), 100);

  EXPECT_EQ(
      displays.second.id(),
      screen->GetDisplayNearestWindow(browser2->window()->GetNativeWindow())
          .id());
  EXPECT_EQ(
      displays.first.id(),
      screen->GetDisplayNearestWindow(browser()->window()->GetNativeWindow())
          .id());
  EXPECT_EQ(2, tab_strip->GetTabCount());
  EXPECT_EQ(1, tab_strip2->GetTabCount());

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DragTabToWindowInSeparateDisplayStep2, this,
                                  tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());

  // tab should have moved
  EXPECT_EQ(1, tab_strip->GetTabCount());
  EXPECT_EQ(2, tab_strip2->GetTabCount());

  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 100", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // Source browser should still be maximized, target should not
  EXPECT_TRUE(browser()->window()->IsMaximized());
  EXPECT_FALSE(browser2->window()->IsMaximized());
}

// Drags from a restored browser to an immersive fullscreen browser on a
// second display and releases input.
// TODO(pkasting) https://crbug.com/910782 Hangs.
IN_PROC_BROWSER_TEST_P(DetachToBrowserInSeparateDisplayTabDragControllerTest,
                       DISABLED_DragTabToImmersiveBrowserOnSeparateDisplay) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Create another browser.
  Browser* browser2 = CreateBrowser(browser()->profile());
  TabStrip* tab_strip2 = GetTabStripForBrowser(browser2);
  ResetIDs(browser2->tab_strip_model(), 100);

  // Move the second browser to the second display.
  display::Screen* screen = display::Screen::GetScreen();
  const std::pair<Display, Display> displays = GetDisplays(screen);
  ui_test_utils::SetAndWaitForBounds(*browser2, displays.second.work_area());
  EXPECT_EQ(
      displays.second.id(),
      screen->GetDisplayNearestWindow(browser2->window()->GetNativeWindow())
          .id());

  // Put the second browser into immersive fullscreen.
  BrowserView* browser_view2 = BrowserView::GetBrowserViewForBrowser(browser2);
  ImmersiveModeController* immersive_controller2 =
      browser_view2->immersive_mode_controller();
  chromeos::ImmersiveFullscreenControllerTestApi(
      static_cast<ImmersiveModeControllerChromeos*>(immersive_controller2)
          ->controller())
      .SetupForTest();
  chrome::ToggleFullscreenMode(browser2);
  // For MD, the browser's top chrome is completely offscreen, with tabstrip
  // visible.
  ASSERT_TRUE(immersive_controller2->IsEnabled());
  ASSERT_FALSE(immersive_controller2->IsRevealed());
  ASSERT_TRUE(tab_strip2->GetVisible());

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough that it attaches to browser2.
  DragTabAndNotify(tab_strip,
                   base::BindOnce(&DragTabToWindowInSeparateDisplayStep2, this,
                                  tab_strip, tab_strip2));

  // Should now be attached to tab_strip2.
  ASSERT_TRUE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  // browser2's top chrome should be revealed and the tab strip should be
  // at normal height while user is dragging tabs_strip2's tabs.
  ASSERT_TRUE(immersive_controller2->IsRevealed());
  ASSERT_TRUE(tab_strip2->GetVisible());

  // Release the mouse, stopping the drag session.
  ASSERT_TRUE(ReleaseInput());
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 100", IDString(browser2->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));

  // Move the mouse off of browser2's top chrome.
  ASSERT_TRUE(
      ui_test_utils::SendMouseMoveSync(displays.first.bounds().CenterPoint()));

  // The first browser window should not be in immersive fullscreen.
  // browser2 should still be in immersive fullscreen, but the top chrome should
  // no longer be revealed.
  BrowserView* browser_view = BrowserView::GetBrowserViewForBrowser(browser());
  EXPECT_FALSE(browser_view->immersive_mode_controller()->IsEnabled());

  EXPECT_TRUE(immersive_controller2->IsEnabled());
  EXPECT_FALSE(immersive_controller2->IsRevealed());
  EXPECT_TRUE(tab_strip2->GetVisible());
}

// Subclass of DetachToBrowserTabDragControllerTest that
// creates multiple displays with different device scale factors.
class DifferentDeviceScaleFactorDisplayTabDragControllerTest
    : public DetachToBrowserTabDragControllerTest {
 public:
  DifferentDeviceScaleFactorDisplayTabDragControllerTest() = default;
  DifferentDeviceScaleFactorDisplayTabDragControllerTest(
      const DifferentDeviceScaleFactorDisplayTabDragControllerTest&) = delete;
  DifferentDeviceScaleFactorDisplayTabDragControllerTest& operator=(
      const DifferentDeviceScaleFactorDisplayTabDragControllerTest&) = delete;
  virtual ~DifferentDeviceScaleFactorDisplayTabDragControllerTest() = default;

  void SetUpOnMainThread() override {
    DetachToBrowserTabDragControllerTest::SetUpOnMainThread();
    display::test::DisplayManagerTestApi(ash::Shell::Get()->display_manager())
        .UpdateDisplay("1280x800,1280x800*2");
  }

  float GetCursorDeviceScaleFactor() const {
    auto* cursor_client = aura::client::GetCursorClient(
        browser()->window()->GetNativeWindow()->GetRootWindow());
    const auto& cursor_shape_client = aura::client::GetCursorShapeClient();
    return cursor_shape_client.GetCursorData(cursor_client->GetCursor())
        ->scale_factor;
  }
};

namespace {

// The points where a tab is dragged in CursorDeviceScaleFactorStep.
constexpr auto kDragPoints = std::to_array<gfx::Point>({
    {300, 200},
    {399, 200},
    {500, 200},
    {400, 200},
    {300, 200},
});

// The expected device scale factors after the cursor is moved to the
// corresponding kDragPoints in CursorDeviceScaleFactorStep.
constexpr std::array kDeviceScaleFactorExpectations = {
    1.0f, 1.0f, 2.0f, 2.0f, 1.0f,
};

static_assert(
    kDragPoints.size() == kDeviceScaleFactorExpectations.size(),
    "kDragPoints and kDeviceScaleFactorExpectations must have the same "
    "number of elements");

// Drags tab to `kDragPoints[index]`, then calls the next step function.
void CursorDeviceScaleFactorStep(
    DifferentDeviceScaleFactorDisplayTabDragControllerTest* test,
    TabStrip* not_attached_tab_strip,
    size_t index) {
  SCOPED_TRACE(index);
  ASSERT_FALSE(not_attached_tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());

  if (index > 0) {
    EXPECT_EQ(kDragPoints[index - 1],
              aura::Env::GetInstance()->last_mouse_location());
    EXPECT_EQ(kDeviceScaleFactorExpectations[index - 1],
              test->GetCursorDeviceScaleFactor());
  }

  if (index < std::size(kDragPoints)) {
    ASSERT_TRUE(test->DragInputToNotifyWhenDone(
        kDragPoints[index],
        base::BindOnce(&CursorDeviceScaleFactorStep, test,
                       not_attached_tab_strip, index + 1),
        // The window hint isn't used on Ash.
        gfx::NativeWindow()));
  } else {
    // Finishes a series of CursorDeviceScaleFactorStep calls and ends drag.
    ASSERT_TRUE(
        ui_test_utils::SendMouseEventsSync(ui_controls::LEFT, ui_controls::UP));
  }
}

}  // namespace

// Verifies cursor's device scale factor is updated when a tab is moved across
// displays with different device scale factors (http://crbug.com/154183).
// TODO(pkasting): In interactive_ui_tests, scale factor never changes to 2.
// https://crbug.com/918731
// TODO(pkasting): In non_single_process_mash_interactive_ui_tests, pointer is
// warped during the drag (which results in changing to scale factor 2 early),
// and scale factor doesn't change back to 1 at the end.
// https://crbug.com/918732
IN_PROC_BROWSER_TEST_P(DifferentDeviceScaleFactorDisplayTabDragControllerTest,
                       DISABLED_CursorDeviceScaleFactor) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  // Move the second browser to the second display.
  ASSERT_EQ(2, display::Screen::GetScreen()->GetNumDisplays());

  // Move to the first tab and drag it enough so that it detaches.
  DragTabAndNotify(tab_strip, base::BindOnce(&CursorDeviceScaleFactorStep, this,
                                             tab_strip, 0));
}

class DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest
    : public DetachToBrowserTabDragControllerTest {
 public:
  DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest() = default;
  DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest(
      const DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest&) =
      delete;
  DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest& operator=(
      const DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest&) =
      delete;

  void SetUpOnMainThread() override {
    DetachToBrowserTabDragControllerTest::SetUpOnMainThread();
    display::test::DisplayManagerTestApi(ash::Shell::Get()->display_manager())
        .UpdateDisplay("1280x800,1280x800");
  }
};

namespace {

// Invoked from the nested run loop.
void CancelDragTabToWindowInSeparateDisplayStep3(
    DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest* test,
    TabStrip* tab_strip) {
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_TRUE(TabDragController::IsActive());
  ASSERT_EQ(2u, test->browser_list()->size());

  // Switching display mode should cancel the drag operation.
  ash::ShellTestApi().AddRemoveDisplay();
}

// Invoked from the nested run loop.
void CancelDragTabToWindowInSeparateDisplayStep2(
    DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest* test,
    TabStrip* tab_strip,
    Display current_display,
    gfx::Point final_destination) {
  EXPECT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  EXPECT_TRUE(TabDragController::IsActive());
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(2u, num_browsers);

  Browser* new_browser = test->browser_list()->get(num_browsers - 1);
  EXPECT_EQ(
      current_display.id(),
      display::Screen::GetScreen()
          ->GetDisplayNearestWindow(new_browser->window()->GetNativeWindow())
          .id());

  EXPECT_TRUE(test->DragInputToNotifyWhenDone(
      final_destination,
      base::BindOnce(&CancelDragTabToWindowInSeparateDisplayStep3, test,
                     tab_strip),
      // The window hint isn't used on Ash.
      gfx::NativeWindow()));
}

}  // namespace

// TODO(crbug.com/333085989): Re-enable flaky tests
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_CancelDragTabToWindowIn2ndDisplay \
  DISABLED_CancelDragTabToWindowIn2ndDisplay
#else
#define MAYBE_CancelDragTabToWindowIn2ndDisplay \
  CancelDragTabToWindowIn2ndDisplay
#endif

// Drags from browser to a second display and releases input.
IN_PROC_BROWSER_TEST_P(
    DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest,
    MAYBE_CancelDragTabToWindowIn2ndDisplay) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));

  // Move the second browser to the second display.
  const std::pair<Display, Display> displays =
      GetDisplays(display::Screen::GetScreen());
  gfx::Point final_destination = displays.second.work_area().CenterPoint();

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough to move to another display.
  DragTabAndNotify(
      tab_strip,
      base::BindOnce(&CancelDragTabToWindowInSeparateDisplayStep2, this,
                     tab_strip, displays.first, final_destination));

  ASSERT_EQ(1u, browser_list()->size());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));

  // Release the mouse
  ASSERT_TRUE(
      ui_test_utils::SendMouseEventsSync(ui_controls::LEFT, ui_controls::UP));
}

// TODO(crbug.com/333085989): Re-enable flaky tests on ChromeOS
#if BUILDFLAG(IS_CHROMEOS)
#define MAYBE_CancelDragTabToWindowIn1stDisplay \
  DISABLED_CancelDragTabToWindowIn1stDisplay
#else
#define MAYBE_CancelDragTabToWindowIn1stDisplay \
  CancelDragTabToWindowIn1stDisplay
#endif

// Drags from browser from a second display to primary and releases input.
IN_PROC_BROWSER_TEST_P(
    DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest,
    MAYBE_CancelDragTabToWindowIn1stDisplay) {
  display::Screen* screen = display::Screen::GetScreen();
  const std::pair<Display, Display> displays = GetDisplays(screen);

  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));
  EXPECT_EQ(
      displays.first.id(),
      screen->GetDisplayNearestWindow(browser()->window()->GetNativeWindow())
          .id());

  browser()->window()->SetBounds(displays.second.work_area());
  EXPECT_EQ(
      displays.second.id(),
      screen->GetDisplayNearestWindow(browser()->window()->GetNativeWindow())
          .id());

  // Move the second browser to the display.
  gfx::Point final_destination = displays.first.work_area().CenterPoint();

  // Move to the first tab and drag it enough so that it detaches, but not
  // enough to move to another display.
  DragTabAndNotify(
      tab_strip,
      base::BindOnce(&CancelDragTabToWindowInSeparateDisplayStep2, this,
                     tab_strip, displays.second, final_destination));

  ASSERT_EQ(1u, browser_list()->size());
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));

  // Release the mouse
  ASSERT_TRUE(
      ui_test_utils::SendMouseEventsSync(ui_controls::LEFT, ui_controls::UP));
}

// Subclass of DetachToBrowserTabDragControllerTest that runs tests only with
// touch input.
class DetachToBrowserTabDragControllerTestTouch
    : public DetachToBrowserTabDragControllerTest {
 public:
  DetachToBrowserTabDragControllerTestTouch() = default;
  DetachToBrowserTabDragControllerTestTouch(
      const DetachToBrowserTabDragControllerTestTouch&) = delete;
  DetachToBrowserTabDragControllerTestTouch& operator=(
      const DetachToBrowserTabDragControllerTestTouch&) = delete;
  virtual ~DetachToBrowserTabDragControllerTestTouch() = default;

  void TearDown() override {
    ui::SetEventTickClockForTesting(nullptr);
    clock_.reset();
  }

 protected:
  std::unique_ptr<base::SimpleTestTickClock> clock_;
};

namespace {
void PressSecondFingerWhileDetachedStep3(
    DetachToBrowserTabDragControllerTest* test) {
  EXPECT_TRUE(TabDragController::IsActive());
  EXPECT_EQ(2u, test->browser_list()->size());
  EXPECT_TRUE(test->browser_list()->get(1)->window()->IsActive());

  EXPECT_TRUE(test->ReleaseInput());
  EXPECT_TRUE(test->ReleaseInput(1));
}

void PressSecondFingerWhileDetachedStep2(
    DetachToBrowserTabDragControllerTest* test,
    const gfx::Point& target_point) {
  EXPECT_TRUE(TabDragController::IsActive());
  size_t num_browsers = test->browser_list()->size();
  EXPECT_EQ(2u, num_browsers);
  EXPECT_TRUE(
      test->browser_list()->get(num_browsers - 1)->window()->IsActive());

  // The window hint isn't used on Ash.
  gfx::NativeWindow window_hint = gfx::NativeWindow();
  // Continue dragging after adding a second finger.
  EXPECT_TRUE(test->PressInput(gfx::Point(), window_hint, 1));
  EXPECT_TRUE(test->DragInputToNotifyWhenDone(
      target_point, base::BindOnce(&PressSecondFingerWhileDetachedStep3, test),
      window_hint));
}

}  // namespace

// Detaches a tab and while detached presses a second finger.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestTouch,
                       PressSecondFingerWhileDetached) {
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  EXPECT_EQ("0 1", IDString(browser()->tab_strip_model()));

  // Move to the first tab and drag it enough so that it detaches. Drag it
  // slightly more horizontally so that it does not generate a swipe down
  // gesture that minimizes the detached browser window.
  const int touch_move_delta = GetDetachY(tab_strip);
  const gfx::Point target = GetCenterInScreenCoordinates(tab_strip->tab_at(0)) +
                            gfx::Vector2d(0, 2 * touch_move_delta);
  DragTabAndNotify(
      tab_strip,
      base::BindOnce(&PressSecondFingerWhileDetachedStep2, this, target), 0,
      touch_move_delta + 5);

  // Should no longer be dragging.
  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());

  // There should now be another browser.
  Browser* new_browser = WaitForActiveBrowser(browser_list(), 2);
  TabStrip* tab_strip2 = GetTabStripForBrowser(new_browser);
  ASSERT_FALSE(tab_strip2->GetDragContext()->IsDragSessionActive());

  EXPECT_EQ("0", IDString(new_browser->tab_strip_model()));
  EXPECT_EQ("1", IDString(browser()->tab_strip_model()));
}

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestTouch,
                       LeftSnapShouldntCauseMergeAtEnd) {
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  AddTabsAndResetBrowser(browser(), 1);

  // Set the last mouse location at the center of tab 0. This shouldn't affect
  // the touch behavior below. See https://crbug.com/914527#c1 for the details
  // of how this can affect the result.
  gfx::Point tab_0_center(GetCenterInScreenCoordinates(tab_strip->tab_at(0)));
  base::RunLoop run_loop;
  ui_controls::SendMouseMoveNotifyWhenDone(tab_0_center.x(), tab_0_center.y(),
                                           run_loop.QuitClosure());
  run_loop.Run();

  // Drag the tab 1 to left-snapping.
  DragTabAndNotify(
      tab_strip, base::BindLambdaForTesting([&]() {
        const gfx::Rect display_bounds =
            display::Screen::GetScreen()->GetPrimaryDisplay().bounds();
        const gfx::Point target(display_bounds.x(),
                                display_bounds.CenterPoint().y());
        ASSERT_TRUE(DragInputToNotifyWhenDone(
            target,
            base::BindLambdaForTesting([&]() { ASSERT_TRUE(ReleaseInput()); }),
            // The window hint isn't used on Ash.
            gfx::NativeWindow()));
      }),
      1);

  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ(2u, browser_list()->size());
}

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestTouch,
                       FlingDownAtEndOfDrag) {
  // Reduce the minimum fling velocity for this specific test case to cause the
  // fling-down gesture in the middle of tab-dragging. This should end up with
  // minimizing the window. See https://crbug.com/902897 for the details.
  SetMinFlingVelocity(1);

  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  test::QuitDraggingObserver observer(tab_strip);
  const gfx::Point tab_0_center =
      GetCenterInScreenCoordinates(tab_strip->tab_at(0));
  const gfx::Vector2d detach(0, GetDetachY(tab_strip));
  const gfx::NativeWindow window_hint = GetWindowHint(tab_strip);
  clock_ = std::make_unique<base::SimpleTestTickClock>();
  clock_->SetNowTicks(base::TimeTicks::Now());
  ui::SetEventTickClockForTesting(clock_.get());
  ASSERT_TRUE(PressInput(tab_0_center, window_hint));
  clock_->Advance(base::Milliseconds(5));
  ASSERT_TRUE(DragInputToNotifyWhenDone(
      tab_0_center + detach, base::BindLambdaForTesting([&]() {
        // Drag down again; this should cause a fling-down event.
        clock_->Advance(base::Milliseconds(5));
        ASSERT_TRUE(DragInputToNotifyWhenDone(
            tab_0_center + detach + detach, base::BindLambdaForTesting([&]() {
              clock_->Advance(base::Milliseconds(5));
              ASSERT_TRUE(ReleaseInput());
            }),
            window_hint));
      }),
      window_hint));
  observer.Wait();

  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_TRUE(browser()->window()->IsMinimized());
  EXPECT_FALSE(browser()->window()->IsVisible());
}

// TODO(http://crbug/343503164) This test seems to be attempting to induce a
// fling gesture event, but it currently fails to do so. If a fling gesture
// event was produced, the detached window should end up minimized.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestTouch,
                       DISABLED_FlingOnStartingDrag) {
  SetMinFlingVelocity(1);
  AddTabsAndResetBrowser(browser(), 1);
  TabStrip* tab_strip = GetTabStripForBrowser(browser());
  const gfx::Point tab_0_center =
      GetCenterInScreenCoordinates(tab_strip->tab_at(0));
  const gfx::Vector2d detach(0, GetDetachY(tab_strip));
  const gfx::NativeWindow window_hint = GetWindowHint(tab_strip);

  // Sends events to the server without waiting for its reply, which will cause
  // extra touch events before PerformWindowMove starts handling events.
  test::QuitDraggingObserver observer(tab_strip);
  clock_ = std::make_unique<base::SimpleTestTickClock>();
  clock_->SetNowTicks(base::TimeTicks::Now());
  ui::SetEventTickClockForTesting(clock_.get());
  ASSERT_TRUE(PressInput(tab_0_center, window_hint));
  clock_->Advance(base::Milliseconds(5));
  ASSERT_TRUE(DragInputToAsync(tab_0_center + detach, window_hint));
  clock_->Advance(base::Milliseconds(5));
  ASSERT_TRUE(DragInputToAsync(tab_0_center + detach + detach, window_hint));
  clock_->Advance(base::Milliseconds(2));
  ASSERT_TRUE(ReleaseInput());
  observer.Wait();

  ASSERT_FALSE(tab_strip->GetDragContext()->IsDragSessionActive());
  ASSERT_FALSE(TabDragController::IsActive());
  EXPECT_EQ(2u, browser_list()->size());
  auto* browser2 = browser_list()->get(1);
  EXPECT_TRUE(browser2->window()->IsMinimized());
  EXPECT_FALSE(browser2->window()->IsVisible());
}

#endif  // BUILDFLAG(IS_CHROMEOS)

namespace {

class SelectTabDuringDragObserver : public TabStripModelObserver {
 public:
  SelectTabDuringDragObserver() = default;
  ~SelectTabDuringDragObserver() override = default;
  void OnTabStripModelChanged(
      TabStripModel* tab_strip_model,
      const TabStripModelChange& change,
      const TabStripSelectionChange& selection) override {
    if (change.type() != TabStripModelChange::kMoved) {
      return;
    }
    const TabStripModelChange::Move* move = change.GetMove();
    int index_to_select = move->to_index == 0 ? 1 : 0;
    tab_strip_model->SelectTabAt(index_to_select);
  }
};

}  // namespace

// Bug fix for crbug.com/1196309. Don't change tab selection while dragging.
IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTest,
                       SelectTabDuringDrag) {
  TabStripModel* model = browser()->tab_strip_model();
  TabStrip* tab_strip = GetTabStripForBrowser(browser());

  SelectTabDuringDragObserver observer;
  model->AddObserver(&observer);

  AddTabsAndResetBrowser(browser(), 1);
  ASSERT_EQ(2, model->count());

  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(0)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1)));
  {
    gfx::Rect tab_bounds = tab_strip->tab_at(1)->GetLocalBounds();
    views::View::ConvertRectToScreen(tab_strip->tab_at(1), &tab_bounds);
    ASSERT_TRUE(
        DragInputTo(tab_bounds.right_center(), GetWindowHint(tab_strip)));
  }
  ASSERT_TRUE(ReleaseInput());
}

#if BUILDFLAG(IS_CHROMEOS)
// Runs tests with a tabbed system web app that is locked for OnTask. This is
// not related to normal web browsers.
using DetachToBrowserTabDragControllerTestWithOnTaskLocked =
    DetachToBrowserTabDragControllerTestWithTabbedSystemApp;

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithOnTaskLocked,
                       MoveTabOnDrag) {
  // Install and launch mock app that can be locked for OnTask.
  const webapps::AppId tabbed_app_id = InstallMockApp();
  Browser* const app_browser = LaunchWebAppBrowser(tabbed_app_id);
  ASSERT_EQ(2u, browser_list()->size());

  // Close normal browser.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(1u, browser_list()->size());
  SelectFirstBrowser();
  ASSERT_EQ(app_browser, browser());
  EXPECT_EQ(Browser::Type::TYPE_APP, browser_list()->get(0)->type());

  // Lock the app for OnTask and set up app for testing drag behavior.
  browser()->SetLockedForOnTask(true);
  AddTabsAndResetBrowser(browser(), /*additional_tabs=*/3, GetAppUrl());
  TabStripModel* const tab_strip_model = browser()->tab_strip_model();
  ASSERT_EQ("0 1 2 3", IDString(tab_strip_model));

  // Drag tab in the second index to the tab in the third index to switch tab
  // positioning.
  TabStrip* const tab_strip = GetTabStripForBrowser(browser());
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // Verify tab is not detached and its position is updated.
  ASSERT_EQ(1u, browser_list()->size());
  EXPECT_EQ("0 2 1 3", IDString(tab_strip_model));
}

IN_PROC_BROWSER_TEST_P(DetachToBrowserTabDragControllerTestWithOnTaskLocked,
                       TabDoesNotDetachOnDrag) {
  // Install and launch mock app that can be locked for OnTask.
  const webapps::AppId tabbed_app_id = InstallMockApp();
  Browser* const app_browser = LaunchWebAppBrowser(tabbed_app_id);
  ASSERT_EQ(2u, browser_list()->size());

  // Close normal browser.
  CloseBrowserSynchronously(browser());
  ASSERT_EQ(1u, browser_list()->size());
  SelectFirstBrowser();
  ASSERT_EQ(app_browser, browser());
  EXPECT_EQ(Browser::Type::TYPE_APP, browser_list()->get(0)->type());

  // Lock the app for OnTask and set up app for testing drag behavior.
  browser()->SetLockedForOnTask(true);
  AddTabsAndResetBrowser(browser(), /*additional_tabs=*/3, GetAppUrl());

  // Drag tab away from tab strip and verify it is not detached.
  TabStrip* const tab_strip = GetTabStripForBrowser(browser());
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(1)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(1),
                                gfx::Vector2d(0, GetDetachY(tab_strip) + 1)));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);
  EXPECT_EQ(1u, browser_list()->size());
}

INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTest,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse", "touch")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestWithScrollableTabStripEnabled,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse", "touch")));
#else
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTest,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Bool(),
        /*input_source=*/::testing::Values("mouse")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestWithScrollableTabStripEnabled,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Bool(),
        /*input_source=*/::testing::Values("mouse")));
#endif  // BUILDFLAG(IS_CHROMEOS)

#if BUILDFLAG(IS_CHROMEOS)
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserInSeparateDisplayTabDragControllerTest,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestTouch,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("touch")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DifferentDeviceScaleFactorDisplayTabDragControllerTest,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserInSeparateDisplayAndCancelTabDragControllerTest,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestWithTabbedSystemApp,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse", "touch")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestWithOnTaskLocked,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse", "touch")));
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestWithTabbedWebApp,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse", "touch")));
#elif !BUILDFLAG(IS_MAC)
INSTANTIATE_TEST_SUITE_P(
    TabDragging,
    DetachToBrowserTabDragControllerTestWithTabbedWebApp,
    ::testing::Combine(
        /*kSplitTabStrip=*/::testing::Bool(),
        /*kTearOffWebAppTabOpensWebAppWindow=*/::testing::Values(false),
        /*input_source=*/::testing::Values("mouse")));
#endif

// TODO(crbug.com/409577362) : Fix test flakiness
#if !BUILDFLAG(IS_CHROMEOS)
class SideBySideTabDragControllerTest
    : public TabDragControllerInteractiveTestMixin<TabDragControllerTest> {
 public:
  bool IsTabInSplit(int index) {
    return GetTabStripForBrowser(browser())->tab_at(index)->split().has_value();
  }

  void AddTabs(Browser* browser, int additional_tabs) {
    for (int i = 0; i < additional_tabs; i++) {
      chrome::AddSelectedTabWithURL(browser, GURL(url::kAboutBlankURL),
                                    ui::PAGE_TRANSITION_AUTO_TOPLEVEL);
    }
  }

 private:
  base::test::ScopedFeatureList scoped_feature_list_{features::kSideBySide};
};

// Flaky. https://crbug.com/40748225
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
#define MAYBE_DragBetweenSplitTab DISABLED_DragBetweenSplitTab
#else
#define MAYBE_DragBetweenSplitTab DragBetweenSplitTab
#endif
IN_PROC_BROWSER_TEST_F(SideBySideTabDragControllerTest,
                       MAYBE_DragBetweenSplitTab) {
  TabStrip* const tab_strip = GetTabStripForBrowser(browser());

  AddTabs(browser(), 2);

  split_tabs::SplitTabId id = split_tabs::SplitTabId::GenerateNew();
  tab_strip->OnSplitCreated({0, 1}, id);
  StopAnimating(tab_strip);

  Tab* const last_split_tab = tab_strip->tab_at(1);

  EXPECT_TRUE(IsTabInSplit(0));
  EXPECT_TRUE(IsTabInSplit(1));
  EXPECT_FALSE(IsTabInSplit(2));

  // Drag the last tab to the middle of the split tab.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(DragInputToCenter(last_split_tab));
  ASSERT_TRUE(ReleaseInput());
  StopAnimating(tab_strip);

  // The last tab should return to where it was since we can't drag a tab in
  // between a split.
  EXPECT_FALSE(IsTabInSplit(0));
  EXPECT_TRUE(IsTabInSplit(1));
  EXPECT_TRUE(IsTabInSplit(2));
}

// Flaky. https://crbug.com/40748225
#if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX)
#define MAYBE_DragBetweenMultipleSplitTabs DISABLED_DragBetweenMultipleSplitTabs
#else
#define MAYBE_DragBetweenMultipleSplitTabs DragBetweenMultipleSplitTabs
#endif
IN_PROC_BROWSER_TEST_F(SideBySideTabDragControllerTest,
                       MAYBE_DragBetweenMultipleSplitTabs) {
  TabStrip* const tab_strip = GetTabStripForBrowser(browser());

  AddTabs(browser(), 4);

  split_tabs::SplitTabId first_id = split_tabs::SplitTabId::GenerateNew();
  tab_strip->OnSplitCreated({0, 1}, first_id);

  split_tabs::SplitTabId second_id = split_tabs::SplitTabId::GenerateNew();
  tab_strip->OnSplitCreated({2, 3}, second_id);

  StopAnimating(tab_strip);

  EXPECT_TRUE(IsTabInSplit(0));
  EXPECT_TRUE(IsTabInSplit(1));
  EXPECT_TRUE(IsTabInSplit(2));
  EXPECT_TRUE(IsTabInSplit(3));
  EXPECT_FALSE(IsTabInSplit(4));

  // Drag the last tab in between the two sets of split tabs.
  ASSERT_TRUE(PressInputAtCenter(tab_strip->tab_at(4)));
  ASSERT_TRUE(DragInputToCenter(tab_strip->tab_at(2)));
  ASSERT_TRUE(ReleaseInput());

  StopAnimating(tab_strip);

  // The single tab should be able to go in between the two sets of split tabs
  // since they belong to different splits.
  EXPECT_TRUE(IsTabInSplit(0));
  EXPECT_TRUE(IsTabInSplit(1));
  EXPECT_FALSE(IsTabInSplit(2));
  EXPECT_TRUE(IsTabInSplit(3));
  EXPECT_TRUE(IsTabInSplit(4));
}
#endif  // !BUILDFLAG(IS_CHROMEOS)