summaryrefslogtreecommitdiffstats
path: root/src/widgets/widgets/qmainwindowlayout.cpp
blob: db17e50d5c28e2f61186e5087eda50dc69988c78 (plain)
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
// Copyright (C) 2016 The Qt Company Ltd.
// Copyright (C) 2015 Olivier Goffart <ogoffart@woboq.com>
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qmainwindowlayout_p.h"

#if QT_CONFIG(dockwidget)
#include "qdockarealayout_p.h"
#include "qdockwidget.h"
#include "qdockwidget_p.h"
#endif
#if QT_CONFIG(toolbar)
#include "qtoolbar_p.h"
#include "qtoolbar.h"
#include "qtoolbarlayout_p.h"
#endif
#include "qmainwindow.h"
#include "qwidgetanimator_p.h"
#if QT_CONFIG(rubberband)
#include "qrubberband.h"
#endif
#if QT_CONFIG(tabbar)
#include "qtabbar_p.h"
#endif

#include <qapplication.h>
#if QT_CONFIG(draganddrop)
#include <qdrag.h>
#endif
#include <qmimedata.h>
#if QT_CONFIG(statusbar)
#include <qstatusbar.h>
#endif
#include <qstring.h>
#include <qstyle.h>
#include <qstylepainter.h>
#include <qvarlengtharray.h>
#include <qstack.h>
#include <qmap.h>
#include <qtimer.h>
#include <qpointer.h>

#ifndef QT_NO_DEBUG_STREAM
#  include <qdebug.h>
#  include <qtextstream.h>
#endif

#include <private/qmenu_p.h>
#include <private/qapplication_p.h>
#include <private/qlayoutengine_p.h>
#include <private/qwidgetresizehandler_p.h>

#include <QScopedValueRollback>

QT_BEGIN_NAMESPACE

using namespace Qt::StringLiterals;

extern QMainWindowLayout *qt_mainwindow_layout(const QMainWindow *window);

/******************************************************************************
** debug
*/

#if QT_CONFIG(dockwidget) && !defined(QT_NO_DEBUG_STREAM)

static void dumpLayout(QTextStream &qout, const QDockAreaLayoutInfo &layout, QString indent);

static void dumpLayout(QTextStream &qout, const QDockAreaLayoutItem &item, QString indent)
{
    qout << indent << "QDockAreaLayoutItem: "
            << "pos: " << item.pos << " size:" << item.size
            << " gap:" << (item.flags & QDockAreaLayoutItem::GapItem)
            << " keepSize:" << (item.flags & QDockAreaLayoutItem::KeepSize) << '\n';
    indent += "  "_L1;
    if (item.widgetItem != nullptr) {
        qout << indent << "widget: "
            << item.widgetItem->widget()->metaObject()->className()
            << " \"" << item.widgetItem->widget()->windowTitle() << "\"\n";
    } else if (item.subinfo != nullptr) {
        qout << indent << "subinfo:\n";
        dumpLayout(qout, *item.subinfo, indent + "  "_L1);
    } else if (item.placeHolderItem != nullptr) {
        QRect r = item.placeHolderItem->topLevelRect;
        qout << indent << "placeHolder: "
            << "pos: " << item.pos << " size:" << item.size
            << " gap:" << (item.flags & QDockAreaLayoutItem::GapItem)
            << " keepSize:" << (item.flags & QDockAreaLayoutItem::KeepSize)
            << " objectName:" << item.placeHolderItem->objectName
            << " hidden:" << item.placeHolderItem->hidden
            << " window:" << item.placeHolderItem->window
            << " rect:" << r.x() << ',' << r.y() << ' '
            << r.width() << 'x' << r.height() << '\n';
    }
}

static void dumpLayout(QTextStream &qout, const QDockAreaLayoutInfo &layout, QString indent)
{
    const QSize minSize = layout.minimumSize();
    qout << indent << "QDockAreaLayoutInfo: "
            << layout.rect.left() << ','
            << layout.rect.top() << ' '
            << layout.rect.width() << 'x'
            << layout.rect.height()
            << " min size: " << minSize.width() << ',' << minSize.height()
            << " orient:" << layout.o
#if QT_CONFIG(tabbar)
            << " tabbed:" << layout.tabbed
            << " tbshape:" << layout.tabBarShape
#endif
            << '\n';

    indent += "  "_L1;

    for (int i = 0; i < layout.item_list.size(); ++i) {
        qout << indent << "Item: " << i << '\n';
        dumpLayout(qout, layout.item_list.at(i), indent + "  "_L1);
    }
}

static void dumpLayout(QTextStream &qout, const QDockAreaLayout &layout)
{
    qout << "QDockAreaLayout: "
            << layout.rect.left() << ','
            << layout.rect.top() << ' '
            << layout.rect.width() << 'x'
            << layout.rect.height() << '\n';

    qout << "TopDockArea:\n";
    dumpLayout(qout, layout.docks[QInternal::TopDock], "  "_L1);
    qout << "LeftDockArea:\n";
    dumpLayout(qout, layout.docks[QInternal::LeftDock], "  "_L1);
    qout << "RightDockArea:\n";
    dumpLayout(qout, layout.docks[QInternal::RightDock], "  "_L1);
    qout << "BottomDockArea:\n";
    dumpLayout(qout, layout.docks[QInternal::BottomDock], "  "_L1);
}

QDebug operator<<(QDebug debug, const QDockAreaLayout &layout)
{
    QString s;
    QTextStream str(&s);
    dumpLayout(str, layout);
    debug << s;
    return debug;
}

QDebug operator<<(QDebug debug, const QMainWindowLayout *layout)
{
    debug << layout->layoutState.dockAreaLayout;
    return debug;
}

// Use this to dump item lists of all populated main window docks.
// Use DUMP macro inside QMainWindowLayout
#if 0
static void dumpItemLists(const QMainWindowLayout *layout, const char *function, const char *comment)
{
    for (int i = 0; i < QInternal::DockCount; ++i) {
        const auto &list = layout->layoutState.dockAreaLayout.docks[i].item_list;
        if (list.isEmpty())
            continue;
        qDebug() << function << comment << "Dock" << i << list;
    }
}
#define DUMP(comment) dumpItemLists(this, __FUNCTION__, comment)
#endif // 0

#endif // QT_CONFIG(dockwidget) && !defined(QT_NO_DEBUG)


/*!
    \internal
    QDockWidgetGroupWindow is a floating window, containing several QDockWidgets floating together.
    This requires QMainWindow::GroupedDragging to be enabled.
    QDockWidgets floating jointly in a QDockWidgetGroupWindow are considered to be docked.
    Their \c isFloating property is \c false.
    QDockWidget children of a QDockWidgetGroupWindow are either:
    \list
    \li tabbed (as long as Qt is compiled with the \c tabbar feature), or
    \li arranged next to each other, equivalent to the default on a main window dock.
    \endlist

    QDockWidgetGroupWindow uses QDockWidgetGroupLayout to lay out its QDockWidget children.
    It stores layout information in a QDockAreaLayoutInfo, including temporary spacer items
    and rubber bands.

    If its QDockWidget children are tabbed, the QDockWidgetGroupWindow shows the active QDockWidget's
    title as its own window title.

    QDockWidgetGroupWindow is designed to hold more than one QDockWidget.
    A QDockWidgetGroupWindow with only one QDockWidget child may occur only temporarily
    \list
    \li in its construction phase, or
    \li during a hover: While QDockWidget A is hovered over B, B is converted into a QDockWidgetGroupWindow.
    \endlist

    A QDockWidgetGroupWindow with only one QDockWidget child must never get focus, be dragged or dropped.
    To enforce this restriction, QDockWidgetGrouWindow will remove itself after its second QDockWidget
    child has been removed. It will make its last QDockWidget child a single, floating QDockWidget.
    Eventually, the empty QDockWidgetGroupWindow will call deleteLater() on itself.
*/


#if QT_CONFIG(dockwidget)
class QDockWidgetGroupLayout : public QLayout,
                               public QMainWindowLayoutSeparatorHelper<QDockWidgetGroupLayout>
{
    QWidgetResizeHandler *resizer;
public:
    QDockWidgetGroupLayout(QDockWidgetGroupWindow* parent) : QLayout(parent) {
        setSizeConstraint(QLayout::SetMinAndMaxSize);
        resizer = new QWidgetResizeHandler(parent);
    }
    ~QDockWidgetGroupLayout() {
        layoutState.deleteAllLayoutItems();
    }

    void addItem(QLayoutItem*) override { Q_UNREACHABLE(); }
    int count() const override { return 0; }
    QLayoutItem* itemAt(int index) const override
    {
        int x = 0;
        return layoutState.itemAt(&x, index);
    }
    QLayoutItem* takeAt(int index) override
    {
        int x = 0;
        QLayoutItem *ret = layoutState.takeAt(&x, index);
        if (savedState.rect.isValid() && ret->widget()) {
            // we need to remove the item also from the saved state to prevent crash
            QList<int> path = savedState.indexOf(ret->widget());
            if (!path.isEmpty())
                savedState.remove(path);
            // Also, the item may be contained several times as a gap item.
            path = layoutState.indexOf(ret->widget());
            if (!path.isEmpty())
                layoutState.remove(path);
        }
        return ret;
    }
    QSize sizeHint() const override
    {
        int fw = frameWidth();
        return layoutState.sizeHint() + QSize(fw, fw);
    }
    QSize minimumSize() const override
    {
        int fw = frameWidth();
        return layoutState.minimumSize() + QSize(fw, fw);
    }
    QSize maximumSize() const override
    {
        int fw = frameWidth();
        return layoutState.maximumSize() + QSize(fw, fw);
    }
    void setGeometry(const QRect&r) override
    {
        groupWindow()->destroyOrHideIfEmpty();
        QDockAreaLayoutInfo *li = dockAreaLayoutInfo();
        if (li->isEmpty())
            return;
        int fw = frameWidth();
#if QT_CONFIG(tabbar)
        li->reparentWidgets(parentWidget());
#endif
        li->rect = r.adjusted(fw, fw, -fw, -fw);
        li->fitItems();
        li->apply(false);
        if (savedState.rect.isValid())
            savedState.rect = li->rect;
        resizer->setEnabled(!nativeWindowDeco());
    }

    QDockAreaLayoutInfo *dockAreaLayoutInfo() { return &layoutState; }

    bool nativeWindowDeco() const
    {
        return groupWindow()->hasNativeDecos();
    }

    int frameWidth() const
    {
        return nativeWindowDeco() ? 0 :
            parentWidget()->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, nullptr, parentWidget());
    }

    QDockWidgetGroupWindow *groupWindow() const
    {
        return static_cast<QDockWidgetGroupWindow *>(parent());
    }

    QDockAreaLayoutInfo layoutState;
    QDockAreaLayoutInfo savedState;
};

bool QDockWidgetGroupWindow::event(QEvent *e)
{
    auto lay = static_cast<QDockWidgetGroupLayout *>(layout());
    if (lay && lay->windowEvent(e))
        return true;

    switch (e->type()) {
    case QEvent::Close:
#if QT_CONFIG(tabbar)
        // Forward the close to the QDockWidget just as if its close button was pressed
        if (QDockWidget *dw = activeTabbedDockWidget()) {
            dw->close();
            adjustFlags();
        }
#endif
        return true;
    case QEvent::Move:
#if QT_CONFIG(tabbar)
        // Let QDockWidgetPrivate::moseEvent handle the dragging
        if (QDockWidget *dw = activeTabbedDockWidget())
            static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(dw))->moveEvent(static_cast<QMoveEvent*>(e));
#endif
        return true;
    case QEvent::NonClientAreaMouseMove:
    case QEvent::NonClientAreaMouseButtonPress:
    case QEvent::NonClientAreaMouseButtonRelease:
    case QEvent::NonClientAreaMouseButtonDblClick:
#if QT_CONFIG(tabbar)
        // Let the QDockWidgetPrivate of the currently visible dock widget handle the drag and drop
        if (QDockWidget *dw = activeTabbedDockWidget())
            static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(dw))->nonClientAreaMouseEvent(static_cast<QMouseEvent*>(e));
#endif
        return true;
    case QEvent::ChildAdded:
        if (qobject_cast<QDockWidget *>(static_cast<QChildEvent*>(e)->child()))
            adjustFlags();
        break;
    case QEvent::LayoutRequest:
        // We might need to show the widget again
        destroyOrHideIfEmpty();
        break;
    case QEvent::Resize:
        updateCurrentGapRect();
        emit resized();
        break;
    default:
        break;
    }
    return QWidget::event(e);
}

void QDockWidgetGroupWindow::paintEvent(QPaintEvent *)
{
    QDockWidgetGroupLayout *lay = static_cast<QDockWidgetGroupLayout *>(layout());
    bool nativeDeco = lay->nativeWindowDeco();

    if (!nativeDeco) {
        QStyleOptionFrame framOpt;
        framOpt.initFrom(this);
        QStylePainter p(this);
        p.drawPrimitive(QStyle::PE_FrameDockWidget, framOpt);
    }
}

QDockAreaLayoutInfo *QDockWidgetGroupWindow::layoutInfo() const
{
    return static_cast<QDockWidgetGroupLayout *>(layout())->dockAreaLayoutInfo();
}

#if QT_CONFIG(tabbar)
/*! \internal
    If this is a floating tab bar returns the currently the QDockWidgetGroupWindow that contains
    tab, otherwise, return nullptr;
    \note: if there is only one QDockWidget, it's still considered as a floating tab
 */
const QDockAreaLayoutInfo *QDockWidgetGroupWindow::tabLayoutInfo() const
{
    const QDockAreaLayoutInfo *info = layoutInfo();
    while (info && !info->tabbed) {
        // There should be only one tabbed subinfo otherwise we are not a floating tab but a real
        // window
        const QDockAreaLayoutInfo *next = nullptr;
        bool isSingle = false;
        for (const auto &item : info->item_list) {
            if (item.skip() || (item.flags & QDockAreaLayoutItem::GapItem))
                continue;
            if (next || isSingle) // Two visible things
                return nullptr;
            if (item.subinfo)
                next = item.subinfo;
            else if (item.widgetItem)
                isSingle = true;
        }
        if (isSingle)
            return info;
        info = next;
    }
    return info;
}

/*! \internal
    If this is a floating tab bar returns the currently active QDockWidget, otherwise nullptr
 */
QDockWidget *QDockWidgetGroupWindow::activeTabbedDockWidget() const
{
    QDockWidget *dw = nullptr;
    const QDockAreaLayoutInfo *info = tabLayoutInfo();
    if (!info)
        return nullptr;
    if (info->tabBar && info->tabBar->currentIndex() >= 0) {
        int i = info->tabIndexToListIndex(info->tabBar->currentIndex());
        if (i >= 0) {
            const QDockAreaLayoutItem &item = info->item_list.at(i);
            if (item.widgetItem)
                dw = qobject_cast<QDockWidget *>(item.widgetItem->widget());
        }
    }
    if (!dw) {
        for (int i = 0; !dw && i < info->item_list.size(); ++i) {
            const QDockAreaLayoutItem &item = info->item_list.at(i);
            if (item.skip())
                continue;
            if (!item.widgetItem)
                continue;
            dw = qobject_cast<QDockWidget *>(item.widgetItem->widget());
        }
    }
    return dw;
}
#endif // QT_CONFIG(tabbar)

/*! \internal
    Destroy or hide this window if there is no more QDockWidget in it.
    Otherwise make sure it is shown.
 */
void QDockWidgetGroupWindow::destroyOrHideIfEmpty()
{
    const QDockAreaLayoutInfo *info = layoutInfo();
    if (!info->isEmpty()) {
        show(); // It might have been hidden,
        return;
    }
    // There might still be placeholders
    if (!info->item_list.isEmpty()) {
        hide();
        return;
    }

    // Make sure to reparent the possibly floating or hidden QDockWidgets to the parent
    const auto dockWidgetsList = dockWidgets();
    for (QDockWidget *dw : dockWidgetsList) {
        const bool wasFloating = dw->isFloating();
        const bool wasHidden = dw->isHidden();
        dw->setParent(parentWidget());
        qCDebug(lcQpaDockWidgets) << "Reparented:" << dw << "to" << parentWidget() << "by" << this;
        if (wasFloating) {
            dw->setFloating(true);
        } else {
            // maybe it was hidden, we still have to put it back in the main layout.
            QMainWindowLayout *ml =
                qt_mainwindow_layout(static_cast<QMainWindow *>(parentWidget()));
            Qt::DockWidgetArea area = ml->dockWidgetArea(this);
            if (area == Qt::NoDockWidgetArea)
                area = Qt::LeftDockWidgetArea; // FIXME: DockWidget doesn't save original docking area
            static_cast<QMainWindow *>(parentWidget())->addDockWidget(area, dw);
            qCDebug(lcQpaDockWidgets) << "Redocked to Mainwindow:" << area << dw << "by" << this;
        }
        if (!wasHidden)
            dw->show();
    }
    deleteLater();
}

/*!
   \internal
   \return \c true if the group window has at least one visible QDockWidget child,
   otherwise false.
 */
bool QDockWidgetGroupWindow::hasVisibleDockWidgets() const
{
    const auto &children = findChildren<QDockWidget *>(Qt::FindChildrenRecursively);
    for (auto child : children) {
        // WA_WState_Visible is set on the dock widget, associated to the active tab
        // and unset on all others.
        // WA_WState_Hidden is set if the dock widgets have been explicitly hidden.
        // This is the relevant information to check (equivalent to !child->isHidden()).
        if (!child->testAttribute(Qt::WA_WState_Hidden))
            return true;
    }
    return false;
}

/*! \internal
    Sets the flags of this window in accordance to the capabilities of the dock widgets
 */
void QDockWidgetGroupWindow::adjustFlags()
{
    Qt::WindowFlags oldFlags = windowFlags();
    Qt::WindowFlags flags = oldFlags;

#if QT_CONFIG(tabbar)
    QDockWidget *top = activeTabbedDockWidget();
#else
    QDockWidget *top = nullptr;
#endif
    if (!top) { // nested tabs, show window decoration
        flags =
            ((oldFlags & ~Qt::FramelessWindowHint) | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    } else if (static_cast<QDockWidgetGroupLayout *>(layout())->nativeWindowDeco()) {
        flags |= Qt::CustomizeWindowHint | Qt::WindowTitleHint;
        flags.setFlag(Qt::WindowCloseButtonHint, top->features() & QDockWidget::DockWidgetClosable);
        flags &= ~Qt::FramelessWindowHint;
    } else {
        flags &= ~(Qt::WindowCloseButtonHint | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
        flags |= Qt::FramelessWindowHint;
    }

    if (oldFlags != flags) {
        if (!windowHandle())
            create(); // The desired geometry is forgotten if we call setWindowFlags before having a window
        setWindowFlags(flags);
        const bool gainedNativeDecos = (oldFlags & Qt::FramelessWindowHint) && !(flags & Qt::FramelessWindowHint);
        const bool lostNativeDecos = !(oldFlags & Qt::FramelessWindowHint) && (flags & Qt::FramelessWindowHint);

        // Adjust the geometry after gaining/losing decos, so that the client area appears always
        // at the same place when tabbing
        if (lostNativeDecos) {
            QRect newGeometry = geometry();
            newGeometry.setTop(frameGeometry().top());
            const int bottomFrame = geometry().top() - frameGeometry().top();
            m_removedFrameSize = QSize((frameSize() - size()).width(), bottomFrame);
            setGeometry(newGeometry);
        } else if (gainedNativeDecos && m_removedFrameSize.isValid()) {
            QRect r = geometry();
            r.adjust(-m_removedFrameSize.width() / 2, 0,
                     -m_removedFrameSize.width() / 2, -m_removedFrameSize.height());
            setGeometry(r);
            m_removedFrameSize = QSize();
        }

        setVisible(hasVisibleDockWidgets());
    }

    QWidget *titleBarOf = top ? top : parentWidget();
    setWindowTitle(titleBarOf->windowTitle());
    setWindowIcon(titleBarOf->windowIcon());
}

bool QDockWidgetGroupWindow::hasNativeDecos() const
{
#if QT_CONFIG(tabbar)
    QDockWidget *dw = activeTabbedDockWidget();
    if (!dw) // We have a group of nested QDockWidgets (not just floating tabs)
        return true;

    if (!QDockWidgetLayout::wmSupportsNativeWindowDeco())
        return false;

    return dw->titleBarWidget() == nullptr;
#else
    return true;
#endif
}

/*
    The given widget is hovered over this floating group.
    This function will save the state and create a gap in the actual state.
    currentGapRect and currentGapPos will be set.
    One must call restore() or apply() after this function.
    Returns true if there was any change in the currentGapPos
 */
bool QDockWidgetGroupWindow::hover(QLayoutItem *widgetItem, const QPoint &mousePos)
{
    QDockAreaLayoutInfo &savedState = static_cast<QDockWidgetGroupLayout *>(layout())->savedState;
    if (savedState.isEmpty())
        savedState = *layoutInfo();

    QMainWindow::DockOptions opts = static_cast<QMainWindow *>(parentWidget())->dockOptions();
    QDockAreaLayoutInfo newState = savedState;
    bool nestingEnabled =
        (opts & QMainWindow::AllowNestedDocks) && !(opts & QMainWindow::ForceTabbedDocks);
    QDockAreaLayoutInfo::TabMode tabMode =
#if !QT_CONFIG(tabbar)
        QDockAreaLayoutInfo::NoTabs;
#else
        nestingEnabled ? QDockAreaLayoutInfo::AllowTabs : QDockAreaLayoutInfo::ForceTabs;
    if (auto group = qobject_cast<QDockWidgetGroupWindow *>(widgetItem->widget())) {
        if (!group->tabLayoutInfo())
            tabMode = QDockAreaLayoutInfo::NoTabs;
    }
    if (newState.tabbed) {
        // insertion into a top-level tab
        newState.item_list = { QDockAreaLayoutItem(new QDockAreaLayoutInfo(newState)) };
        newState.item_list.first().size = pick(savedState.o, savedState.rect.size());
        newState.tabbed = false;
        newState.tabBar = nullptr;
    }
#endif

    auto newGapPos = newState.gapIndex(mousePos, nestingEnabled, tabMode);
    Q_ASSERT(!newGapPos.isEmpty());

    // Do not insert a new gap item, if the current position already is a gap,
    // or if the group window contains one
    if (newGapPos == currentGapPos || newState.hasGapItem(newGapPos))
        return false;

    currentGapPos = newGapPos;
    newState.insertGap(currentGapPos, widgetItem);
    newState.fitItems();
    *layoutInfo() = std::move(newState);
    updateCurrentGapRect();
    layoutInfo()->apply(opts & QMainWindow::AnimatedDocks);
    return true;
}

void QDockWidgetGroupWindow::updateCurrentGapRect()
{
    if (!currentGapPos.isEmpty())
        currentGapRect = layoutInfo()->info(currentGapPos)->itemRect(currentGapPos.last(), true);
}

/*
    Remove the gap that was created by hover()
 */
void QDockWidgetGroupWindow::restore()
{
    QDockAreaLayoutInfo &savedState = static_cast<QDockWidgetGroupLayout *>(layout())->savedState;
    if (!savedState.isEmpty()) {
        *layoutInfo() = savedState;
        savedState = QDockAreaLayoutInfo();
    }
    currentGapRect = QRect();
    currentGapPos.clear();
    adjustFlags();
    layoutInfo()->fitItems();
    layoutInfo()->apply(static_cast<QMainWindow *>(parentWidget())->dockOptions()
                        & QMainWindow::AnimatedDocks);
}

/*
    Apply the state  that was created by hover
 */
void QDockWidgetGroupWindow::apply()
{
    static_cast<QDockWidgetGroupLayout *>(layout())->savedState.clear();
    currentGapRect = QRect();
    layoutInfo()->plug(currentGapPos);
    currentGapPos.clear();
    adjustFlags();
    layoutInfo()->apply(false);
}

void QDockWidgetGroupWindow::childEvent(QChildEvent *event)
{
    switch (event->type()) {
    case QEvent::ChildRemoved:
        if (auto *dockWidget = qobject_cast<QDockWidget *>(event->child()))
            dockWidget->removeEventFilter(this);
        destroyIfSingleItemLeft();
        break;
    case QEvent::ChildAdded:
        if (auto *dockWidget = qobject_cast<QDockWidget *>(event->child()))
            dockWidget->installEventFilter(this);
        break;
    default:
        break;
    }
}

bool QDockWidgetGroupWindow::eventFilter(QObject *obj, QEvent *event)
{
    auto *dockWidget = qobject_cast<QDockWidget *>(obj);
    if (!dockWidget)
        return QWidget::eventFilter(obj, event);

    switch (event->type()) {
    case QEvent::Close:
        // We don't want closed dock widgets in a floating tab
        // => dock it to the main dock, before closing;
        reparent(dockWidget);
        dockWidget->setFloating(false);
        break;

    case QEvent::Hide:
        // if the dock widget is not an active tab, it is hidden anyway.
        // if it is the active tab, hide the whole group.
        if (dockWidget->isVisible())
            hide();
        break;

    default:
        break;
    }
    return QWidget::eventFilter(obj, event);
}

void QDockWidgetGroupWindow::destroyIfSingleItemLeft()
{
    const auto &dockWidgets = this->dockWidgets();

    // Handle only the last dock
    if (dockWidgets.count() != 1)
        return;

    auto *lastDockWidget = dockWidgets.at(0);

    // If the last remaining dock widget is not in the group window's item_list,
    // a group window is being docked on a main window docking area.
    // => don't interfere
    if (layoutInfo()->indexOf(lastDockWidget).isEmpty())
        return;

    auto *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
    QMainWindowLayout *mwLayout = qt_mainwindow_layout(mainWindow);

    // Unplug the last remaining dock widget and hide the group window, to avoid flickering
    mwLayout->unplug(lastDockWidget, QDockWidgetPrivate::DragScope::Widget);
    lastDockWidget->setGeometry(geometry());
    hide();

    // Get the layout info for the main window dock, where dock widgets need to go
    QDockAreaLayoutInfo &parentInfo = mwLayout->layoutState.dockAreaLayout.docks[layoutInfo()->dockPos];

    // Re-parent last dock widget
    reparent(lastDockWidget);

    // the group window could still have placeholder items => clear everything
    layoutInfo()->item_list.clear();

    // remove the group window and the dock's item_list pointing to it.
    parentInfo.remove(this);
    destroyOrHideIfEmpty();
}

void QDockWidgetGroupWindow::reparent(QDockWidget *dockWidget)
{
    // reparent a dockWidget to the main window
    // - remove it from the floating dock's layout info
    // - insert it to the main dock's layout info
    // Finally, set draggingDock to nullptr, since the drag is finished.
    auto *mainWindow = qobject_cast<QMainWindow *>(parentWidget());
    Q_ASSERT(mainWindow);
    QMainWindowLayout *mwLayout = qt_mainwindow_layout(mainWindow);
    Q_ASSERT(mwLayout);
    QDockAreaLayoutInfo &parentInfo = mwLayout->layoutState.dockAreaLayout.docks[layoutInfo()->dockPos];
    dockWidget->removeEventFilter(this);
    parentInfo.add(dockWidget);
    layoutInfo()->remove(dockWidget);
    const bool wasFloating = dockWidget->isFloating();
    const bool wasVisible = dockWidget->isVisible();
    dockWidget->setParent(mainWindow);
    dockWidget->setFloating(wasFloating);
    dockWidget->setVisible(wasVisible);
}
#endif

/******************************************************************************
** QMainWindowLayoutState
*/

// we deal with all the #ifndefferry here so QMainWindowLayout code is clean

QMainWindowLayoutState::QMainWindowLayoutState(QMainWindow *win)
    :
#if QT_CONFIG(toolbar)
    toolBarAreaLayout(win),
#endif
#if QT_CONFIG(dockwidget)
    dockAreaLayout(win)
#else
    centralWidgetItem(0)
#endif

{
    mainWindow = win;
}

QSize QMainWindowLayoutState::sizeHint() const
{

    QSize result(0, 0);

#if QT_CONFIG(dockwidget)
    result = dockAreaLayout.sizeHint();
#else
    if (centralWidgetItem)
        result = centralWidgetItem->sizeHint();
#endif

#if QT_CONFIG(toolbar)
    result = toolBarAreaLayout.sizeHint(result);
#endif // QT_CONFIG(toolbar)

    return result;
}

QSize QMainWindowLayoutState::minimumSize() const
{
    QSize result(0, 0);

#if QT_CONFIG(dockwidget)
    result = dockAreaLayout.minimumSize();
#else
    if (centralWidgetItem)
        result = centralWidgetItem->minimumSize();
#endif

#if QT_CONFIG(toolbar)
    result = toolBarAreaLayout.minimumSize(result);
#endif // QT_CONFIG(toolbar)

    return result;
}

/*!
    \internal

    Returns whether the layout fits into the main window.
*/
bool QMainWindowLayoutState::fits() const
{
    Q_ASSERT(mainWindow);

    QSize size;

#if QT_CONFIG(dockwidget)
    size = dockAreaLayout.minimumStableSize();
#endif

#if QT_CONFIG(toolbar)
    size.rwidth() += toolBarAreaLayout.docks[QInternal::LeftDock].rect.width();
    size.rwidth() += toolBarAreaLayout.docks[QInternal::RightDock].rect.width();
    size.rheight() += toolBarAreaLayout.docks[QInternal::TopDock].rect.height();
    size.rheight() += toolBarAreaLayout.docks[QInternal::BottomDock].rect.height();
#endif

    return size.width() <= mainWindow->width() && size.height() <= mainWindow->height();
}

void QMainWindowLayoutState::apply(bool animated)
{
#if QT_CONFIG(toolbar)
    toolBarAreaLayout.apply(animated);
#endif

#if QT_CONFIG(dockwidget)
//    dumpLayout(dockAreaLayout, QString());
    dockAreaLayout.apply(animated);
#else
    if (centralWidgetItem) {
        QMainWindowLayout *layout = qt_mainwindow_layout(mainWindow);
        Q_ASSERT(layout);
        layout->widgetAnimator.animate(centralWidgetItem->widget(), centralWidgetRect, animated);
    }
#endif
}

void QMainWindowLayoutState::fitLayout()
{
    QRect r;
#if !QT_CONFIG(toolbar)
    r = rect;
#else
    toolBarAreaLayout.rect = rect;
    r = toolBarAreaLayout.fitLayout();
#endif // QT_CONFIG(toolbar)

#if QT_CONFIG(dockwidget)
    dockAreaLayout.rect = r;
    dockAreaLayout.fitLayout();
#else
    centralWidgetRect = r;
#endif
}

void QMainWindowLayoutState::deleteAllLayoutItems()
{
#if QT_CONFIG(toolbar)
    toolBarAreaLayout.deleteAllLayoutItems();
#endif

#if QT_CONFIG(dockwidget)
    dockAreaLayout.deleteAllLayoutItems();
#endif
}

void QMainWindowLayoutState::deleteCentralWidgetItem()
{
#if QT_CONFIG(dockwidget)
    delete dockAreaLayout.centralWidgetItem;
    dockAreaLayout.centralWidgetItem = nullptr;
#else
    delete centralWidgetItem;
    centralWidgetItem = 0;
#endif
}

QLayoutItem *QMainWindowLayoutState::itemAt(int index, int *x) const
{
#if QT_CONFIG(toolbar)
    if (QLayoutItem *ret = toolBarAreaLayout.itemAt(x, index))
        return ret;
#endif

#if QT_CONFIG(dockwidget)
    if (QLayoutItem *ret = dockAreaLayout.itemAt(x, index))
        return ret;
#else
    if (centralWidgetItem  && (*x)++ == index)
        return centralWidgetItem;
#endif

    return nullptr;
}

QLayoutItem *QMainWindowLayoutState::takeAt(int index, int *x)
{
#if QT_CONFIG(toolbar)
    if (QLayoutItem *ret = toolBarAreaLayout.takeAt(x, index))
        return ret;
#endif

#if QT_CONFIG(dockwidget)
    if (QLayoutItem *ret = dockAreaLayout.takeAt(x, index))
        return ret;
#else
    if (centralWidgetItem && (*x)++ == index) {
        QLayoutItem *ret = centralWidgetItem;
        centralWidgetItem = nullptr;
        return ret;
    }
#endif

    return nullptr;
}

QList<int> QMainWindowLayoutState::indexOf(QWidget *widget) const
{
    QList<int> result;

#if QT_CONFIG(toolbar)
    // is it a toolbar?
    if (QToolBar *toolBar = qobject_cast<QToolBar*>(widget)) {
        result = toolBarAreaLayout.indexOf(toolBar);
        if (!result.isEmpty())
            result.prepend(0);
        return result;
    }
#endif

#if QT_CONFIG(dockwidget)
    // is it a dock widget?
    if (qobject_cast<QDockWidget *>(widget) || qobject_cast<QDockWidgetGroupWindow *>(widget)) {
        result = dockAreaLayout.indexOf(widget);
        if (!result.isEmpty())
            result.prepend(1);
        return result;
    }
#endif // QT_CONFIG(dockwidget)

    return result;
}

bool QMainWindowLayoutState::contains(QWidget *widget) const
{
#if QT_CONFIG(dockwidget)
    if (dockAreaLayout.centralWidgetItem != nullptr && dockAreaLayout.centralWidgetItem->widget() == widget)
        return true;
    if (!dockAreaLayout.indexOf(widget).isEmpty())
        return true;
#else
    if (centralWidgetItem && centralWidgetItem->widget() == widget)
        return true;
#endif

#if QT_CONFIG(toolbar)
    if (!toolBarAreaLayout.indexOf(widget).isEmpty())
        return true;
#endif
    return false;
}

void QMainWindowLayoutState::setCentralWidget(QWidget *widget)
{
    QLayoutItem *item = nullptr;
    //make sure we remove the widget
    deleteCentralWidgetItem();

    if (widget != nullptr)
        item = new QWidgetItemV2(widget);

#if QT_CONFIG(dockwidget)
    dockAreaLayout.centralWidgetItem = item;
#else
    centralWidgetItem = item;
#endif
}

QWidget *QMainWindowLayoutState::centralWidget() const
{
    QLayoutItem *item = nullptr;

#if QT_CONFIG(dockwidget)
    item = dockAreaLayout.centralWidgetItem;
#else
    item = centralWidgetItem;
#endif

    if (item != nullptr)
        return item->widget();
    return nullptr;
}

QList<int> QMainWindowLayoutState::gapIndex(QWidget *widget,
                                            const QPoint &pos) const
{
    QList<int> result;

#if QT_CONFIG(toolbar)
    // is it a toolbar?
    if (qobject_cast<QToolBar*>(widget) != nullptr) {
        result = toolBarAreaLayout.gapIndex(pos);
        if (!result.isEmpty())
            result.prepend(0);
        return result;
    }
#endif

#if QT_CONFIG(dockwidget)
    // is it a dock widget?
    if (qobject_cast<QDockWidget *>(widget) != nullptr
            || qobject_cast<QDockWidgetGroupWindow *>(widget)) {
        bool disallowTabs = false;
#if QT_CONFIG(tabbar)
        if (auto *group = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
            if (!group->tabLayoutInfo()) // Disallow to drop nested docks as a tab
                disallowTabs = true;
        }
#endif
        result = dockAreaLayout.gapIndex(pos, disallowTabs);
        if (!result.isEmpty())
            result.prepend(1);
        return result;
    }
#endif // QT_CONFIG(dockwidget)

    return result;
}

bool QMainWindowLayoutState::insertGap(const QList<int> &path, QLayoutItem *item)
{
    if (path.isEmpty())
        return false;

    int i = path.first();

#if QT_CONFIG(toolbar)
    if (i == 0) {
        Q_ASSERT(qobject_cast<QToolBar*>(item->widget()) != nullptr);
        return toolBarAreaLayout.insertGap(path.mid(1), item);
    }
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1) {
        Q_ASSERT(qobject_cast<QDockWidget*>(item->widget()) || qobject_cast<QDockWidgetGroupWindow*>(item->widget()));
        return dockAreaLayout.insertGap(path.mid(1), item);
    }
#endif // QT_CONFIG(dockwidget)

    return false;
}

void QMainWindowLayoutState::remove(const QList<int> &path)
{
    int i = path.first();

#if QT_CONFIG(toolbar)
    if (i == 0)
        toolBarAreaLayout.remove(path.mid(1));
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1)
        dockAreaLayout.remove(path.mid(1));
#endif // QT_CONFIG(dockwidget)
}

void QMainWindowLayoutState::remove(QLayoutItem *item)
{
#if QT_CONFIG(toolbar)
    toolBarAreaLayout.remove(item);
#endif

#if QT_CONFIG(dockwidget)
    // is it a dock widget?
    if (QDockWidget *dockWidget = qobject_cast<QDockWidget *>(item->widget())) {
        QList<int> path = dockAreaLayout.indexOf(dockWidget);
        if (!path.isEmpty())
            dockAreaLayout.remove(path);
    }
#endif // QT_CONFIG(dockwidget)
}

void QMainWindowLayoutState::clear()
{
#if QT_CONFIG(toolbar)
    toolBarAreaLayout.clear();
#endif

#if QT_CONFIG(dockwidget)
    dockAreaLayout.clear();
#else
    centralWidgetRect = QRect();
#endif

    rect = QRect();
}

bool QMainWindowLayoutState::isValid() const
{
    return rect.isValid();
}

QLayoutItem *QMainWindowLayoutState::item(const QList<int> &path)
{
    int i = path.first();

#if QT_CONFIG(toolbar)
    if (i == 0) {
        const QToolBarAreaLayoutItem *tbItem = toolBarAreaLayout.item(path.mid(1));
        Q_ASSERT(tbItem);
        return tbItem->widgetItem;
    }
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1)
        return dockAreaLayout.item(path.mid(1)).widgetItem;
#endif // QT_CONFIG(dockwidget)

    return nullptr;
}

QRect QMainWindowLayoutState::itemRect(const QList<int> &path) const
{
    int i = path.first();

#if QT_CONFIG(toolbar)
    if (i == 0)
        return toolBarAreaLayout.itemRect(path.mid(1));
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1)
        return dockAreaLayout.itemRect(path.mid(1));
#endif // QT_CONFIG(dockwidget)

    return QRect();
}

QRect QMainWindowLayoutState::gapRect(const QList<int> &path) const
{
    int i = path.first();

#if QT_CONFIG(toolbar)
    if (i == 0)
        return toolBarAreaLayout.itemRect(path.mid(1));
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1)
        return dockAreaLayout.gapRect(path.mid(1));
#endif // QT_CONFIG(dockwidget)

    return QRect();
}

QLayoutItem *QMainWindowLayoutState::plug(const QList<int> &path)
{
    int i = path.first();

#if QT_CONFIG(toolbar)
    if (i == 0)
        return toolBarAreaLayout.plug(path.mid(1));
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1)
        return dockAreaLayout.plug(path.mid(1));
#endif // QT_CONFIG(dockwidget)

    return nullptr;
}

QLayoutItem *QMainWindowLayoutState::unplug(const QList<int> &path, QMainWindowLayoutState *other)
{
    int i = path.first();

#if !QT_CONFIG(toolbar)
    Q_UNUSED(other);
#else
    if (i == 0)
        return toolBarAreaLayout.unplug(path.mid(1), other ? &other->toolBarAreaLayout : nullptr);
#endif

#if QT_CONFIG(dockwidget)
    if (i == 1)
        return dockAreaLayout.unplug(path.mid(1));
#endif // QT_CONFIG(dockwidget)

    return nullptr;
}

void QMainWindowLayoutState::saveState(QDataStream &stream) const
{
#if QT_CONFIG(dockwidget)
    dockAreaLayout.saveState(stream);
#if QT_CONFIG(tabbar)
    const QList<QDockWidgetGroupWindow *> floatingTabs =
        mainWindow->findChildren<QDockWidgetGroupWindow *>(Qt::FindDirectChildrenOnly);

    for (QDockWidgetGroupWindow *floating : floatingTabs) {
        if (floating->layoutInfo()->isEmpty())
            continue;
        stream << uchar(QDockAreaLayout::FloatingDockWidgetTabMarker) << floating->geometry();
        floating->layoutInfo()->saveState(stream);
    }
#endif
#endif
#if QT_CONFIG(toolbar)
    toolBarAreaLayout.saveState(stream);
#endif
}

template <typename T>
static QList<T> findChildrenHelper(const QObject *o)
{
    const QObjectList &list = o->children();
    QList<T> result;

    for (int i=0; i < list.size(); ++i) {
        if (T t = qobject_cast<T>(list[i])) {
            result.append(t);
        }
    }

    return result;
}

#if QT_CONFIG(dockwidget)
static QList<QDockWidget*> allMyDockWidgets(const QWidget *mainWindow)
{
    QList<QDockWidget*> result;
    for (QObject *c : mainWindow->children()) {
        if (auto *dw = qobject_cast<QDockWidget*>(c)) {
            result.append(dw);
        } else if (auto *gw = qobject_cast<QDockWidgetGroupWindow*>(c)) {
            for (QObject *c : gw->children()) {
                if (auto *dw = qobject_cast<QDockWidget*>(c))
                    result.append(dw);
            }
        }
    }

    return result;
}
#endif // QT_CONFIG(dockwidget)

//pre4.3 tests the format that was used before 4.3
bool QMainWindowLayoutState::checkFormat(QDataStream &stream)
{
    while (!stream.atEnd()) {
        uchar marker;
        stream >> marker;
        switch(marker)
        {
#if QT_CONFIG(toolbar)
            case QToolBarAreaLayout::ToolBarStateMarker:
            case QToolBarAreaLayout::ToolBarStateMarkerEx:
                {
                    QList<QToolBar *> toolBars = findChildrenHelper<QToolBar*>(mainWindow);
                    if (!toolBarAreaLayout.restoreState(stream, toolBars, marker, true /*testing*/)) {
                            return false;
                    }
                }
                break;
#endif // QT_CONFIG(toolbar)

#if QT_CONFIG(dockwidget)
            case QDockAreaLayout::DockWidgetStateMarker:
                {
                    const auto dockWidgets = allMyDockWidgets(mainWindow);
                    if (!dockAreaLayout.restoreState(stream, dockWidgets, true /*testing*/)) {
                        return false;
                    }
                }
                break;
#if QT_CONFIG(tabbar)
            case QDockAreaLayout::FloatingDockWidgetTabMarker:
                {
                    QRect geom;
                    stream >> geom;
                    QDockAreaLayoutInfo info;
                    auto dockWidgets = allMyDockWidgets(mainWindow);
                    if (!info.restoreState(stream, dockWidgets, true /* testing*/))
                        return false;
                }
                break;
#endif // QT_CONFIG(tabbar)
#endif // QT_CONFIG(dockwidget)
            default:
                //there was an error during the parsing
                return false;
        }// switch
    } //while

    //everything went fine: it must be a pre-4.3 saved state
    return true;
}

bool QMainWindowLayoutState::restoreState(QDataStream &_stream,
                                        const QMainWindowLayoutState &oldState)
{
    //make a copy of the data so that we can read it more than once
    QByteArray copy;
    while(!_stream.atEnd()) {
        int length = 1024;
        QByteArray ba(length, '\0');
        length = _stream.readRawData(ba.data(), ba.size());
        ba.resize(length);
        copy += ba;
    }

    QDataStream ds(copy);
    ds.setVersion(_stream.version());
    if (!checkFormat(ds))
        return false;

    QDataStream stream(copy);
    stream.setVersion(_stream.version());

    while (!stream.atEnd()) {
        uchar marker;
        stream >> marker;
        switch(marker)
        {
#if QT_CONFIG(dockwidget)
            case QDockAreaLayout::DockWidgetStateMarker:
                {
                    const auto dockWidgets = allMyDockWidgets(mainWindow);
                    if (!dockAreaLayout.restoreState(stream, dockWidgets))
                        return false;

                    for (int i = 0; i < dockWidgets.size(); ++i) {
                        QDockWidget *w = dockWidgets.at(i);
                        QList<int> path = dockAreaLayout.indexOf(w);
                        if (path.isEmpty()) {
                            QList<int> oldPath = oldState.dockAreaLayout.indexOf(w);
                            if (oldPath.isEmpty()) {
                                continue;
                            }
                            QDockAreaLayoutInfo *info = dockAreaLayout.info(oldPath);
                            if (info == nullptr) {
                                continue;
                            }
                            info->add(w);
                        }
                    }
                }
                break;
#if QT_CONFIG(tabwidget)
            case QDockAreaLayout::FloatingDockWidgetTabMarker:
            {
                auto dockWidgets = allMyDockWidgets(mainWindow);
                QDockWidgetGroupWindow* floatingTab = qt_mainwindow_layout(mainWindow)->createTabbedDockWindow();
                *floatingTab->layoutInfo() = QDockAreaLayoutInfo(
                    &dockAreaLayout.sep, QInternal::LeftDock, // FIXME: DockWidget doesn't save original docking area
                    Qt::Horizontal, QTabBar::RoundedSouth, mainWindow);
                QRect geometry;
                stream >> geometry;
                QDockAreaLayoutInfo *info = floatingTab->layoutInfo();
                if (!info->restoreState(stream, dockWidgets, false))
                    return false;
                geometry = QDockAreaLayout::constrainedRect(geometry, floatingTab);
                floatingTab->move(geometry.topLeft());
                floatingTab->resize(geometry.size());

                // Don't show an empty QDockWidgetGroupWindow if no dock widget is available yet.
                // reparentWidgets() would be triggered by show(), so do it explicitly here.
                if (info->onlyHasPlaceholders())
                    info->reparentWidgets(floatingTab);
                else
                    floatingTab->show();
            }
            break;
#endif // QT_CONFIG(tabwidget)
#endif // QT_CONFIG(dockwidget)

#if QT_CONFIG(toolbar)
            case QToolBarAreaLayout::ToolBarStateMarker:
            case QToolBarAreaLayout::ToolBarStateMarkerEx:
                {
                    QList<QToolBar *> toolBars = findChildrenHelper<QToolBar*>(mainWindow);
                    if (!toolBarAreaLayout.restoreState(stream, toolBars, marker))
                        return false;

                    for (int i = 0; i < toolBars.size(); ++i) {
                        QToolBar *w = toolBars.at(i);
                        QList<int> path = toolBarAreaLayout.indexOf(w);
                        if (path.isEmpty()) {
                            QList<int> oldPath = oldState.toolBarAreaLayout.indexOf(w);
                            if (oldPath.isEmpty()) {
                                continue;
                            }
                            toolBarAreaLayout.docks[oldPath.at(0)].insertToolBar(nullptr, w);
                        }
                    }
                }
                break;
#endif // QT_CONFIG(toolbar)
            default:
                return false;
        }// switch
    } //while


    return true;
}

/******************************************************************************
** QMainWindowLayoutState - toolbars
*/

#if QT_CONFIG(toolbar)

static constexpr Qt::ToolBarArea validateToolBarArea(Qt::ToolBarArea area)
{
    switch (area) {
    case Qt::LeftToolBarArea:
    case Qt::RightToolBarArea:
    case Qt::TopToolBarArea:
    case Qt::BottomToolBarArea:
        return area;
    default:
        break;
    }
    return Qt::TopToolBarArea;
}

static QInternal::DockPosition toDockPos(Qt::ToolBarArea area)
{
    switch (area) {
        case Qt::LeftToolBarArea: return QInternal::LeftDock;
        case Qt::RightToolBarArea: return QInternal::RightDock;
        case Qt::TopToolBarArea: return QInternal::TopDock;
        case Qt::BottomToolBarArea: return QInternal::BottomDock;
        default:
            break;
    }

    return QInternal::DockCount;
}

static Qt::ToolBarArea toToolBarArea(QInternal::DockPosition pos)
{
    switch (pos) {
        case QInternal::LeftDock:   return Qt::LeftToolBarArea;
        case QInternal::RightDock:  return Qt::RightToolBarArea;
        case QInternal::TopDock:    return Qt::TopToolBarArea;
        case QInternal::BottomDock: return Qt::BottomToolBarArea;
        default: break;
    }
    return Qt::NoToolBarArea;
}

static inline Qt::ToolBarArea toToolBarArea(int pos)
{
    return toToolBarArea(static_cast<QInternal::DockPosition>(pos));
}

void QMainWindowLayout::addToolBarBreak(Qt::ToolBarArea area)
{
    area = validateToolBarArea(area);

    layoutState.toolBarAreaLayout.addToolBarBreak(toDockPos(area));
    if (savedState.isValid())
        savedState.toolBarAreaLayout.addToolBarBreak(toDockPos(area));

    invalidate();
}

void QMainWindowLayout::insertToolBarBreak(QToolBar *before)
{
    layoutState.toolBarAreaLayout.insertToolBarBreak(before);
    if (savedState.isValid())
        savedState.toolBarAreaLayout.insertToolBarBreak(before);
    invalidate();
}

void QMainWindowLayout::removeToolBarBreak(QToolBar *before)
{
    layoutState.toolBarAreaLayout.removeToolBarBreak(before);
    if (savedState.isValid())
        savedState.toolBarAreaLayout.removeToolBarBreak(before);
    invalidate();
}

void QMainWindowLayout::moveToolBar(QToolBar *toolbar, int pos)
{
    layoutState.toolBarAreaLayout.moveToolBar(toolbar, pos);
    if (savedState.isValid())
        savedState.toolBarAreaLayout.moveToolBar(toolbar, pos);
    invalidate();
}

/* Removes the toolbar from the mainwindow so that it can be added again. Does not
   explicitly hide the toolbar. */
void QMainWindowLayout::removeToolBar(QToolBar *toolbar)
{
    if (toolbar) {
        QObject::disconnect(parentWidget(), SIGNAL(iconSizeChanged(QSize)),
                   toolbar, SLOT(_q_updateIconSize(QSize)));
        QObject::disconnect(parentWidget(), SIGNAL(toolButtonStyleChanged(Qt::ToolButtonStyle)),
                   toolbar, SLOT(_q_updateToolButtonStyle(Qt::ToolButtonStyle)));

        removeWidget(toolbar);
    }
}

/*!
    Adds \a toolbar to \a area, continuing the current line.
*/
void QMainWindowLayout::addToolBar(Qt::ToolBarArea area,
                                   QToolBar *toolbar,
                                   bool)
{
    area = validateToolBarArea(area);
    // let's add the toolbar to the layout
    addChildWidget(toolbar);
    QLayoutItem *item = layoutState.toolBarAreaLayout.addToolBar(toDockPos(area), toolbar);
    if (savedState.isValid() && item) {
        // copy the toolbar also in the saved state
        savedState.toolBarAreaLayout.insertItem(toDockPos(area), item);
    }
    invalidate();

    // this ensures that the toolbar has the right window flags (not floating any more)
    toolbar->d_func()->updateWindowFlags(false /*floating*/);
}

/*!
    Adds \a toolbar before \a before
*/
void QMainWindowLayout::insertToolBar(QToolBar *before, QToolBar *toolbar)
{
    addChildWidget(toolbar);
    QLayoutItem *item = layoutState.toolBarAreaLayout.insertToolBar(before, toolbar);
    if (savedState.isValid() && item) {
        // copy the toolbar also in the saved state
        savedState.toolBarAreaLayout.insertItem(before, item);
    }
    if (!currentGapPos.isEmpty() && currentGapPos.constFirst() == 0) {
        currentGapPos = layoutState.toolBarAreaLayout.currentGapIndex();
        if (!currentGapPos.isEmpty()) {
            currentGapPos.prepend(0);
            currentGapRect = layoutState.itemRect(currentGapPos);
        }
    }
    invalidate();
}

Qt::ToolBarArea QMainWindowLayout::toolBarArea(const QToolBar *toolbar) const
{
    QInternal::DockPosition pos = layoutState.toolBarAreaLayout.findToolBar(toolbar);
    switch (pos) {
        case QInternal::LeftDock:   return Qt::LeftToolBarArea;
        case QInternal::RightDock:  return Qt::RightToolBarArea;
        case QInternal::TopDock:    return Qt::TopToolBarArea;
        case QInternal::BottomDock: return Qt::BottomToolBarArea;
        default: break;
    }
    return Qt::NoToolBarArea;
}

bool QMainWindowLayout::toolBarBreak(QToolBar *toolBar) const
{
    return layoutState.toolBarAreaLayout.toolBarBreak(toolBar);
}

void QMainWindowLayout::getStyleOptionInfo(QStyleOptionToolBar *option, QToolBar *toolBar) const
{
    option->toolBarArea = toolBarArea(toolBar);
    layoutState.toolBarAreaLayout.getStyleOptionInfo(option, toolBar);
}

void QMainWindowLayout::toggleToolBarsVisible()
{
    layoutState.toolBarAreaLayout.visible = !layoutState.toolBarAreaLayout.visible;
    if (!layoutState.mainWindow->isMaximized()) {
        QPoint topLeft = parentWidget()->geometry().topLeft();
        QRect r = parentWidget()->geometry();
        r = layoutState.toolBarAreaLayout.rectHint(r);
        r.moveTo(topLeft);
        parentWidget()->setGeometry(r);
    } else {
        update();
    }
}

#endif // QT_CONFIG(toolbar)

/******************************************************************************
** QMainWindowLayoutState - dock areas
*/

#if QT_CONFIG(dockwidget)

static QInternal::DockPosition toDockPos(Qt::DockWidgetArea area)
{
    switch (area) {
        case Qt::LeftDockWidgetArea: return QInternal::LeftDock;
        case Qt::RightDockWidgetArea: return QInternal::RightDock;
        case Qt::TopDockWidgetArea: return QInternal::TopDock;
        case Qt::BottomDockWidgetArea: return QInternal::BottomDock;
        default:
            break;
    }

    return QInternal::DockCount;
}

inline static Qt::DockWidgetArea toDockWidgetArea(int pos)
{
    return QDockWidgetPrivate::toDockWidgetArea(static_cast<QInternal::DockPosition>(pos));
}

// Checks if QDockWidgetGroupWindow or QDockWidget can be plugged the area indicated by path.
// Returns false if called with invalid widget type or if compiled without dockwidget support.
static bool isAreaAllowed(QWidget *widget, const QList<int> &path)
{
    Q_ASSERT_X((path.size() > 1), "isAreaAllowed", "invalid path size");
    const Qt::DockWidgetArea area = toDockWidgetArea(path[1]);

    // Read permissions directly from a single dock widget
    if (QDockWidget *dw = qobject_cast<QDockWidget *>(widget)) {
        const bool allowed = dw->isAreaAllowed(area);
        if (!allowed)
            qCDebug(lcQpaDockWidgets) << "No permission for single DockWidget" << widget << "to dock on" << area;
        return allowed;
    }

    // Read permissions from a DockWidgetGroupWindow depending on its DockWidget children
    if (QDockWidgetGroupWindow *dwgw = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
        const QList<QDockWidget *> children = dwgw->findChildren<QDockWidget *>(QString(), Qt::FindDirectChildrenOnly);

        if (children.size() == 1) {
            // Group window has a single child => read its permissions
            const bool allowed = children.at(0)->isAreaAllowed(area);
            if (!allowed)
                qCDebug(lcQpaDockWidgets) << "No permission for DockWidgetGroupWindow" << widget << "to dock on" << area;
            return allowed;
        } else {
            // Group window has more than one or no children => dock it anywhere
            qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "has" << children.size() << "children:";
            qCDebug(lcQpaDockWidgets) << children;
            qCDebug(lcQpaDockWidgets) << "DockWidgetGroupWindow" << widget << "can dock at" << area << "and anywhere else.";
            return true;
        }
    }
    qCDebug(lcQpaDockWidgets) << "Docking requested for invalid widget type (coding error)." << widget << area;
    return false;
}

void QMainWindowLayout::setCorner(Qt::Corner corner, Qt::DockWidgetArea area)
{
    if (layoutState.dockAreaLayout.corners[corner] == area)
        return;
    layoutState.dockAreaLayout.corners[corner] = area;
    if (savedState.isValid())
        savedState.dockAreaLayout.corners[corner] = area;
    invalidate();
}

Qt::DockWidgetArea QMainWindowLayout::corner(Qt::Corner corner) const
{
    return layoutState.dockAreaLayout.corners[corner];
}

// Returns the rectangle of a dockWidgetArea
// if max is true, the maximum possible rectangle for dropping is returned
// the current visible rectangle otherwise
QRect QMainWindowLayout::dockWidgetAreaRect(const Qt::DockWidgetArea area, DockWidgetAreaSize size) const
{
    const QInternal::DockPosition dockPosition = toDockPos(area);

    // Called with invalid dock widget area
    if (dockPosition == QInternal::DockCount) {
        qCDebug(lcQpaDockWidgets) << "QMainWindowLayout::dockWidgetAreaRect called with" << area;
        return QRect();
    }

    const QDockAreaLayout dl = layoutState.dockAreaLayout;

    // Return maximum or visible rectangle
    return (size == Maximum) ? dl.gapRect(dockPosition) : dl.docks[dockPosition].rect;
}

void QMainWindowLayout::addDockWidget(Qt::DockWidgetArea area,
                                             QDockWidget *dockwidget,
                                             Qt::Orientation orientation)
{
    addChildWidget(dockwidget);

    // If we are currently moving a separator, then we need to abort the move, since each
    // time we move the mouse layoutState is replaced by savedState modified by the move.
    if (!movingSeparator.isEmpty())
        endSeparatorMove(movingSeparatorPos);

    layoutState.dockAreaLayout.addDockWidget(toDockPos(area), dockwidget, orientation);
    emit dockwidget->dockLocationChanged(area);
    invalidate();
}

bool QMainWindowLayout::restoreDockWidget(QDockWidget *dockwidget)
{
    addChildWidget(dockwidget);
    if (!layoutState.dockAreaLayout.restoreDockWidget(dockwidget))
        return false;
    emit dockwidget->dockLocationChanged(dockWidgetArea(dockwidget));
    invalidate();
    return true;
}

#if QT_CONFIG(tabbar)
void QMainWindowLayout::tabifyDockWidget(QDockWidget *first, QDockWidget *second)
{
    applyRestoredState();
    addChildWidget(second);
    layoutState.dockAreaLayout.tabifyDockWidget(first, second);
    emit second->dockLocationChanged(dockWidgetArea(first));
    invalidate();
}

bool QMainWindowLayout::documentMode() const
{
    return _documentMode;
}

void QMainWindowLayout::setDocumentMode(bool enabled)
{
    if (_documentMode == enabled)
        return;

    _documentMode = enabled;

    // Update the document mode for all tab bars
    for (QTabBar *bar : std::as_const(usedTabBars))
        bar->setDocumentMode(_documentMode);
    for (QTabBar *bar : std::as_const(unusedTabBars))
        bar->setDocumentMode(_documentMode);
}

void QMainWindowLayout::setVerticalTabsEnabled(bool enabled)
{
    if (verticalTabsEnabled == enabled)
        return;

    verticalTabsEnabled = enabled;

    updateTabBarShapes();
}

#if QT_CONFIG(tabwidget)
QTabWidget::TabShape QMainWindowLayout::tabShape() const
{
    return _tabShape;
}

void QMainWindowLayout::setTabShape(QTabWidget::TabShape tabShape)
{
    if (_tabShape == tabShape)
        return;

    _tabShape = tabShape;

    updateTabBarShapes();
}

QTabWidget::TabPosition QMainWindowLayout::tabPosition(Qt::DockWidgetArea area) const
{
    const QInternal::DockPosition dockPos = toDockPos(area);
    if (dockPos < QInternal::DockCount)
        return tabPositions[dockPos];
    qWarning("QMainWindowLayout::tabPosition called with out-of-bounds value '%d'", int(area));
    return QTabWidget::North;
}

void QMainWindowLayout::setTabPosition(Qt::DockWidgetAreas areas, QTabWidget::TabPosition tabPosition)
{
    const Qt::DockWidgetArea dockWidgetAreas[] = {
        Qt::TopDockWidgetArea,
        Qt::LeftDockWidgetArea,
        Qt::BottomDockWidgetArea,
        Qt::RightDockWidgetArea
    };
    const QInternal::DockPosition dockPositions[] = {
        QInternal::TopDock,
        QInternal::LeftDock,
        QInternal::BottomDock,
        QInternal::RightDock
    };

    for (int i = 0; i < QInternal::DockCount; ++i)
        if (areas & dockWidgetAreas[i])
            tabPositions[dockPositions[i]] = tabPosition;

    updateTabBarShapes();
}

QTabBar::Shape _q_tb_tabBarShapeFrom(QTabWidget::TabShape shape, QTabWidget::TabPosition position);
#endif // QT_CONFIG(tabwidget)

void QMainWindowLayout::updateTabBarShapes()
{
#if QT_CONFIG(tabwidget)
    const QTabWidget::TabPosition vertical[] = {
        QTabWidget::West,
        QTabWidget::East,
        QTabWidget::North,
        QTabWidget::South
    };
#else
    const QTabBar::Shape vertical[] = {
        QTabBar::RoundedWest,
        QTabBar::RoundedEast,
        QTabBar::RoundedNorth,
        QTabBar::RoundedSouth
    };
#endif

    QDockAreaLayout &layout = layoutState.dockAreaLayout;

    for (int i = 0; i < QInternal::DockCount; ++i) {
#if QT_CONFIG(tabwidget)
        QTabWidget::TabPosition pos = verticalTabsEnabled ? vertical[i] : tabPositions[i];
        QTabBar::Shape shape = _q_tb_tabBarShapeFrom(_tabShape, pos);
#else
        QTabBar::Shape shape = verticalTabsEnabled ? vertical[i] : QTabBar::RoundedSouth;
#endif
        layout.docks[i].setTabBarShape(shape);
    }
}
#endif // QT_CONFIG(tabbar)

void QMainWindowLayout::splitDockWidget(QDockWidget *after,
                                        QDockWidget *dockwidget,
                                        Qt::Orientation orientation)
{
    applyRestoredState();
    addChildWidget(dockwidget);
    layoutState.dockAreaLayout.splitDockWidget(after, dockwidget, orientation);
    emit dockwidget->dockLocationChanged(dockWidgetArea(after));
    invalidate();
}

Qt::DockWidgetArea QMainWindowLayout::dockWidgetArea(QWidget *widget) const
{
    const QList<int> pathToWidget = layoutState.dockAreaLayout.indexOf(widget);
    if (pathToWidget.isEmpty())
        return Qt::NoDockWidgetArea;
    return toDockWidgetArea(pathToWidget.first());
}

void QMainWindowLayout::keepSize(QDockWidget *w)
{
    layoutState.dockAreaLayout.keepSize(w);
}

#if QT_CONFIG(tabbar)

// Handle custom tooltip, and allow to drag tabs away.
class QMainWindowTabBar : public QTabBar
{
    Q_OBJECT
    QMainWindow *mainWindow;
    QPointer<QDockWidget> draggingDock; // Currently dragging (detached) dock widget
public:
    QMainWindowTabBar(QMainWindow *parent);
    ~QMainWindowTabBar();
    QDockWidget *dockAt(int index) const;
    QList<QDockWidget *> dockWidgets() const;
    bool contains(const QDockWidget *dockWidget) const;
protected:
    bool event(QEvent *e) override;
    void mouseReleaseEvent(QMouseEvent*) override;
    void mouseMoveEvent(QMouseEvent*) override;

};

QMainWindowTabBar *QMainWindowLayout::findTabBar(const QDockWidget *dockWidget) const
{
     for (auto *bar : usedTabBars) {
        Q_ASSERT(qobject_cast<QMainWindowTabBar *>(bar));
        auto *tabBar = static_cast<QMainWindowTabBar *>(bar);
        if (tabBar->contains(dockWidget))
            return tabBar;
    }
    return nullptr;
}

QMainWindowTabBar::QMainWindowTabBar(QMainWindow *parent)
    : QTabBar(parent), mainWindow(parent)
{
    setExpanding(false);
}

QList<QDockWidget *> QMainWindowTabBar::dockWidgets() const
{
    QList<QDockWidget *> docks;
    for (int i = 0; i < count(); ++i) {
        if (QDockWidget *dock = dockAt(i))
            docks << dock;
    }
    return docks;
}

bool QMainWindowTabBar::contains(const QDockWidget *dockWidget) const
{
    for (int i = 0; i < count(); ++i) {
        if (dockAt(i) == dockWidget)
            return true;
    }
    return false;
}

QDockWidget *QMainWindowTabBar::dockAt(int index) const
{
    QMainWindowTabBar *that = const_cast<QMainWindowTabBar *>(this);
    QMainWindowLayout* mlayout = qt_mainwindow_layout(mainWindow);
    QDockAreaLayoutInfo *info = mlayout->dockInfo(that);
    if (!info)
        return nullptr;
    const int itemIndex = info->tabIndexToListIndex(index);
    Q_ASSERT(itemIndex >= 0 && itemIndex < info->item_list.count());
    const QDockAreaLayoutItem &item = info->item_list.at(itemIndex);
    return item.widgetItem ? qobject_cast<QDockWidget *>(item.widgetItem->widget()) : nullptr;
}

void QMainWindowTabBar::mouseMoveEvent(QMouseEvent *e)
{
    // The QTabBar handles the moving (reordering) of tabs.
    // When QTabBarPrivate::dragInProgress is true, and that the mouse is outside of a region
    // around the QTabBar, we will consider the user wants to drag that QDockWidget away from this
    // tab area.

    QTabBarPrivate *d = static_cast<QTabBarPrivate*>(d_ptr.data());
    if (!draggingDock && (mainWindow->dockOptions() & QMainWindow::GroupedDragging)) {
        int offset = QApplication::startDragDistance() + 1;
        offset *= 3;
        QRect r = rect().adjusted(-offset, -offset, offset, offset);
        if (d->dragInProgress && !r.contains(e->position().toPoint()) && d->validIndex(d->pressedIndex)) {
            draggingDock = dockAt(d->pressedIndex);
            if (draggingDock) {
                // We should drag this QDockWidget away by unpluging it.
                // First cancel the QTabBar's internal move
                d->moveTabFinished(d->pressedIndex);
                d->pressedIndex = -1;
                if (d->movingTab)
                    d->movingTab->setVisible(false);
                d->dragStartPosition = QPoint();

                // Then starts the drag using QDockWidgetPrivate's API
                QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
                QDockWidgetLayout *dwlayout = static_cast<QDockWidgetLayout *>(draggingDock->layout());
                dockPriv->initDrag(dwlayout->titleArea().center(), true);
                dockPriv->startDrag(QDockWidgetPrivate::DragScope::Widget);
                if (dockPriv->state)
                    dockPriv->state->ctrlDrag = e->modifiers() & Qt::ControlModifier;
            }
        }
    }

    if (draggingDock) {
        QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
        if (dockPriv->state && dockPriv->state->dragging) {
            QPoint pos = e->globalPosition().toPoint() - dockPriv->state->pressPos;
            draggingDock->move(pos);
            // move will call QMainWindowLayout::hover
        }
    }
    QTabBar::mouseMoveEvent(e);
}

QMainWindowTabBar::~QMainWindowTabBar()
{
    if (!mainWindow || mainWindow == parentWidget())
        return;

    // tab bar is not parented to the main window
    // => can only be a dock widget group window
    // => remove itself from used and unused tab bar containers
    auto *mwLayout = qt_mainwindow_layout(mainWindow);
    if (!mwLayout)
        return;
    mwLayout->unusedTabBars.removeOne(this);
    mwLayout->usedTabBars.remove(this);
}

void QMainWindowTabBar::mouseReleaseEvent(QMouseEvent *e)
{
    if (draggingDock && e->button() == Qt::LeftButton) {
        QDockWidgetPrivate *dockPriv = static_cast<QDockWidgetPrivate *>(QObjectPrivate::get(draggingDock));
        if (dockPriv->state && dockPriv->state->dragging)
            dockPriv->endDrag(QDockWidgetPrivate::EndDragMode::LocationChange);

        draggingDock = nullptr;
    }
    QTabBar::mouseReleaseEvent(e);
}

bool QMainWindowTabBar::event(QEvent *e)
{
    // show the tooltip if tab is too small to fit label

    if (e->type() != QEvent::ToolTip)
        return QTabBar::event(e);
    QSize size = this->size();
    QSize hint = sizeHint();
    if (shape() == QTabBar::RoundedWest || shape() == QTabBar::RoundedEast) {
        size = size.transposed();
        hint = hint.transposed();
    }
    if (size.width() < hint.width())
        return QTabBar::event(e);
    e->accept();
    return true;
}

QList<QDockWidget *> QMainWindowLayout::tabifiedDockWidgets(const QDockWidget *dockWidget) const
{
    const auto *bar = findTabBar(dockWidget);
    if (!bar)
        return {};

    QList<QDockWidget *> buddies = bar->dockWidgets();
    // Return only other dock widgets associated with dockWidget in a tab bar.
    // If dockWidget is alone in a tab bar, return an empty list.
    buddies.removeOne(dockWidget);
    return buddies;
}

bool QMainWindowLayout::isDockWidgetTabbed(const QDockWidget *dockWidget) const
{
    // A single dock widget in a tab bar is not considered to be tabbed.
    // This is to make sure, we don't drag an empty QDockWidgetGroupWindow around.
    // => only consider tab bars with two or more tabs.
    const auto *bar = findTabBar(dockWidget);
    return bar && bar->count() > 1;
}

QTabBar *QMainWindowLayout::getTabBar()
{
    if (!usedTabBars.isEmpty() && !isInRestoreState) {
        /*
            If dock widgets have been removed and added while the main window was
            hidden, then the layout hasn't been activated yet, and tab bars from empty
            docking areas haven't been put in the cache yet.
        */
        activate();
    }

    QTabBar *result = nullptr;
    if (!unusedTabBars.isEmpty()) {
        result = unusedTabBars.takeLast();
    } else {
        result = new QMainWindowTabBar(static_cast<QMainWindow *>(parentWidget()));
        result->setDrawBase(true);
        result->setElideMode(Qt::ElideRight);
        result->setDocumentMode(_documentMode);
        result->setMovable(true);
        connect(result, SIGNAL(currentChanged(int)), this, SLOT(tabChanged()));
        connect(result, &QTabBar::tabMoved, this, &QMainWindowLayout::tabMoved);
    }

    usedTabBars.insert(result);
    return result;
}

// Allocates a new separator widget if needed
QWidget *QMainWindowLayout::getSeparatorWidget()
{
    QWidget *result = nullptr;
    if (!unusedSeparatorWidgets.isEmpty()) {
        result = unusedSeparatorWidgets.takeLast();
    } else {
        result = new QWidget(parentWidget());
        result->setAttribute(Qt::WA_MouseNoMask, true);
        result->setAutoFillBackground(false);
        result->setObjectName("qt_qmainwindow_extended_splitter"_L1);
    }
    usedSeparatorWidgets.insert(result);
    return result;
}

/*! \internal
    Returns a pointer QDockAreaLayoutInfo which contains this \a widget directly
    (in its internal list)
 */
QDockAreaLayoutInfo *QMainWindowLayout::dockInfo(QWidget *widget)
{
    QDockAreaLayoutInfo *info = layoutState.dockAreaLayout.info(widget);
    if (info)
        return info;
    const auto groups =
            parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
    for (QDockWidgetGroupWindow *dwgw : groups) {
        info = dwgw->layoutInfo()->info(widget);
        if (info)
            return info;
    }
    return nullptr;
}

void QMainWindowLayout::tabChanged()
{
    QTabBar *tb = qobject_cast<QTabBar*>(sender());
    if (tb == nullptr)
        return;
    QDockAreaLayoutInfo *info = dockInfo(tb);
    if (info == nullptr)
        return;

    QDockWidget *activated = info->apply(false);

    if (activated)
        emit static_cast<QMainWindow *>(parentWidget())->tabifiedDockWidgetActivated(activated);

    if (auto dwgw = qobject_cast<QDockWidgetGroupWindow*>(tb->parentWidget()))
        dwgw->adjustFlags();

    if (QWidget *w = centralWidget())
        w->raise();
}

void QMainWindowLayout::tabMoved(int from, int to)
{
    QTabBar *tb = qobject_cast<QTabBar*>(sender());
    Q_ASSERT(tb);
    QDockAreaLayoutInfo *info = dockInfo(tb);
    Q_ASSERT(info);

    info->moveTab(from, to);
}

void QMainWindowLayout::raise(QDockWidget *widget)
{
    QDockAreaLayoutInfo *info = dockInfo(widget);
    if (info == nullptr)
        return;
    if (!info->tabbed)
        return;
    info->setCurrentTab(widget);
}
#endif // QT_CONFIG(tabbar)

#endif // QT_CONFIG(dockwidget)


/******************************************************************************
** QMainWindowLayoutState - layout interface
*/

int QMainWindowLayout::count() const
{
    int result = 0;
    while (itemAt(result))
        ++result;
    return result;
}

QLayoutItem *QMainWindowLayout::itemAt(int index) const
{
    int x = 0;

    if (QLayoutItem *ret = layoutState.itemAt(index, &x))
        return ret;

    if (statusbar && x++ == index)
        return statusbar;

    return nullptr;
}

QLayoutItem *QMainWindowLayout::takeAt(int index)
{
    int x = 0;

    if (QLayoutItem *ret = layoutState.takeAt(index, &x)) {
        // the widget might in fact have been destroyed by now
        if (QWidget *w = ret->widget()) {
            widgetAnimator.abort(w);
            if (w == pluggingWidget)
                pluggingWidget = nullptr;
        }

        if (savedState.isValid() ) {
            //we need to remove the item also from the saved state to prevent crash
            savedState.remove(ret);
            //Also, the item may be contained several times as a gap item.
            layoutState.remove(ret);
        }

#if QT_CONFIG(toolbar)
        if (!currentGapPos.isEmpty() && currentGapPos.constFirst() == 0) {
            currentGapPos = layoutState.toolBarAreaLayout.currentGapIndex();
            if (!currentGapPos.isEmpty()) {
                currentGapPos.prepend(0);
                currentGapRect = layoutState.itemRect(currentGapPos);
            }
        }
#endif

        return ret;
    }

    if (statusbar && x++ == index) {
        QLayoutItem *ret = statusbar;
        statusbar = nullptr;
        return ret;
    }

    return nullptr;
}


/*!
    \internal

    restoredState stores what we earlier read from storage, but it couldn't
    be applied as the mainwindow wasn't large enough (yet) to fit the state.
    Usually, the restored state would be applied lazily in setGeometry below.
    However, if the mainwindow's layout is modified (e.g. by a call to tabify or
    splitDockWidgets), then we have to forget the restored state as it might contain
    dangling pointers (QDockWidgetLayoutItem has a copy constructor that copies the
    layout item pointer, and splitting or tabify might have to delete some of those
    layout structures).

    Functions that might result in the QMainWindowLayoutState storing dangling pointers
    have to call this function first, so that the restoredState becomes the actual state
    first, and is forgotten afterwards.
*/
void QMainWindowLayout::applyRestoredState()
{
    if (restoredState) {
        layoutState = *restoredState;
        restoredState.reset();
        discardRestoredStateTimer.stop();
    }
}

void QMainWindowLayout::setGeometry(const QRect &_r)
{
    // Check if the state is valid, and avoid replacing it again if it is currently used
    // in applyState
    if (savedState.isValid() || (restoredState && isInApplyState))
        return;

    QRect r = _r;

    QLayout::setGeometry(r);

    if (statusbar) {
        QRect sbr(QPoint(r.left(), 0),
                  QSize(r.width(), statusbar->heightForWidth(r.width()))
                  .expandedTo(statusbar->minimumSize()));
        sbr.moveBottom(r.bottom());
        QRect vr = QStyle::visualRect(parentWidget()->layoutDirection(), _r, sbr);
        statusbar->setGeometry(vr);
        r.setBottom(sbr.top() - 1);
    }

    if (restoredState) {
        /*
            The main window was hidden and was going to be maximized or full-screened when
            the state was restored. The state might have been for a larger window size than
            the current size (in _r), and the window might still be in the process of being
            shown and transitioning to the final size (there's no reliable way of knowing
            this across different platforms). Try again with the restored state.
        */
        layoutState = *restoredState;
        if (restoredState->fits()) {
            restoredState.reset();
            discardRestoredStateTimer.stop();
        } else {
            /*
                Try again in the next setGeometry call, but discard the restored state
                after 150ms without any further tries. That's a reasonably short amount of
                time during which we can expect the windowing system to either have completed
                showing the window, or resized the window once more (which then restarts the
                timer in timerEvent).
                If the windowing system is done, then the user won't have had a chance to
                change the layout interactively AND trigger another resize.
            */
            discardRestoredStateTimer.start(150, this);
        }
    }

    layoutState.rect = r;

    layoutState.fitLayout();
    applyState(layoutState, false);
}

void QMainWindowLayout::timerEvent(QTimerEvent *e)
{
    if (e->timerId() == discardRestoredStateTimer.timerId()) {
        discardRestoredStateTimer.stop();
        restoredState.reset();
    }
    QLayout::timerEvent(e);
}

void QMainWindowLayout::addItem(QLayoutItem *)
{ qWarning("QMainWindowLayout::addItem: Please use the public QMainWindow API instead"); }

QSize QMainWindowLayout::sizeHint() const
{
    if (!szHint.isValid()) {
        szHint = layoutState.sizeHint();
        const QSize sbHint = statusbar ? statusbar->sizeHint() : QSize(0, 0);
        szHint = QSize(qMax(sbHint.width(), szHint.width()),
                        sbHint.height() + szHint.height());
    }
    return szHint;
}

QSize QMainWindowLayout::minimumSize() const
{
    if (!minSize.isValid()) {
        minSize = layoutState.minimumSize();
        const QSize sbMin = statusbar ? statusbar->minimumSize() : QSize(0, 0);
        minSize = QSize(qMax(sbMin.width(), minSize.width()),
                        sbMin.height() + minSize.height());
    }
    return minSize;
}

void QMainWindowLayout::invalidate()
{
    QLayout::invalidate();
    minSize = szHint = QSize();
}

#if QT_CONFIG(dockwidget)
void QMainWindowLayout::setCurrentHoveredFloat(QDockWidgetGroupWindow *w)
{
    if (currentHoveredFloat != w) {
        if (currentHoveredFloat) {
            disconnect(currentHoveredFloat.data(), &QObject::destroyed,
                       this, &QMainWindowLayout::updateGapIndicator);
            disconnect(currentHoveredFloat.data(), &QDockWidgetGroupWindow::resized,
                       this, &QMainWindowLayout::updateGapIndicator);
            if (currentHoveredFloat)
                currentHoveredFloat->restore();
        } else if (w) {
            restore(true);
        }

        currentHoveredFloat = w;

        if (w) {
            connect(w, &QObject::destroyed,
                    this, &QMainWindowLayout::updateGapIndicator, Qt::UniqueConnection);
            connect(w, &QDockWidgetGroupWindow::resized,
                    this, &QMainWindowLayout::updateGapIndicator, Qt::UniqueConnection);
        }

        updateGapIndicator();
    }
}
#endif // QT_CONFIG(dockwidget)

/******************************************************************************
** QMainWindowLayout - remaining stuff
*/

static void fixToolBarOrientation(QLayoutItem *item, int dockPos)
{
#if QT_CONFIG(toolbar)
    QToolBar *toolBar = qobject_cast<QToolBar*>(item->widget());
    if (toolBar == nullptr)
        return;

    QRect oldGeo = toolBar->geometry();

    QInternal::DockPosition pos
        = static_cast<QInternal::DockPosition>(dockPos);
    Qt::Orientation o = pos == QInternal::TopDock || pos == QInternal::BottomDock
                        ? Qt::Horizontal : Qt::Vertical;
    if (o != toolBar->orientation())
        toolBar->setOrientation(o);

    QSize hint = toolBar->sizeHint().boundedTo(toolBar->maximumSize())
                    .expandedTo(toolBar->minimumSize());

    if (toolBar->size() != hint) {
        QRect newGeo(oldGeo.topLeft(), hint);
        if (toolBar->layoutDirection() == Qt::RightToLeft)
            newGeo.moveRight(oldGeo.right());
        toolBar->setGeometry(newGeo);
    }

#else
    Q_UNUSED(item);
    Q_UNUSED(dockPos);
#endif
}

void QMainWindowLayout::revert(QLayoutItem *widgetItem)
{
    if (!savedState.isValid())
        return;

    QWidget *widget = widgetItem->widget();
    layoutState = savedState;
    currentGapPos = layoutState.indexOf(widget);
    if (currentGapPos.isEmpty())
        return;
    fixToolBarOrientation(widgetItem, currentGapPos.at(1));
    layoutState.unplug(currentGapPos);
    layoutState.fitLayout();
    currentGapRect = layoutState.itemRect(currentGapPos);

    plug(widgetItem);
}

bool QMainWindowLayout::plug(QLayoutItem *widgetItem)
{
#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget) && QT_CONFIG(tabbar)
    if (currentHoveredFloat) {
        QWidget *widget = widgetItem->widget();
        QList<int> previousPath = layoutState.indexOf(widget);
        if (!previousPath.isEmpty())
            layoutState.remove(previousPath);
        previousPath = currentHoveredFloat->layoutInfo()->indexOf(widget);
        // Let's remove the widget from any possible group window
        const auto groups =
                parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
        for (QDockWidgetGroupWindow *dwgw : groups) {
            if (dwgw == currentHoveredFloat)
                continue;
            QList<int> path = dwgw->layoutInfo()->indexOf(widget);
            if (!path.isEmpty())
                dwgw->layoutInfo()->remove(path);
        }
        currentGapRect = QRect();
        currentHoveredFloat->apply();
        if (!previousPath.isEmpty())
            currentHoveredFloat->layoutInfo()->remove(previousPath);
        QRect globalRect = currentHoveredFloat->currentGapRect;
        globalRect.moveTopLeft(currentHoveredFloat->mapToGlobal(globalRect.topLeft()));
        pluggingWidget = widget;
        widgetAnimator.animate(widget, globalRect, dockOptions & QMainWindow::AnimatedDocks);
        return true;
    }
#endif

    if (!parentWidget()->isVisible() || parentWidget()->isMinimized() || currentGapPos.isEmpty())
        return false;

    fixToolBarOrientation(widgetItem, currentGapPos.at(1));

    QWidget *widget = widgetItem->widget();

#if QT_CONFIG(dockwidget)
    // Let's remove the widget from any possible group window
    const auto groups =
            parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
    for (QDockWidgetGroupWindow *dwgw : groups) {
        QList<int> path = dwgw->layoutInfo()->indexOf(widget);
        if (!path.isEmpty())
            dwgw->layoutInfo()->remove(path);
    }
#endif

    QList<int> previousPath = layoutState.indexOf(widget);

    const QLayoutItem *it = layoutState.plug(currentGapPos);
    if (!it)
        return false;
    Q_ASSERT(it == widgetItem);
    if (!previousPath.isEmpty())
        layoutState.remove(previousPath);

    pluggingWidget = widget;
    QRect globalRect = currentGapRect;
    globalRect.moveTopLeft(parentWidget()->mapToGlobal(globalRect.topLeft()));
#if QT_CONFIG(dockwidget)
    if (qobject_cast<QDockWidget*>(widget) != nullptr) {
        QDockWidgetLayout *layout = qobject_cast<QDockWidgetLayout*>(widget->layout());
        if (layout->nativeWindowDeco()) {
            globalRect.adjust(0, layout->titleHeight(), 0, 0);
        } else {
            int fw = widget->style()->pixelMetric(QStyle::PM_DockWidgetFrameWidth, nullptr, widget);
            globalRect.adjust(-fw, -fw, fw, fw);
        }
    }
#endif
    widgetAnimator.animate(widget, globalRect, dockOptions & QMainWindow::AnimatedDocks);

    return true;
}

void QMainWindowLayout::animationFinished(QWidget *widget)
{
    //this function is called from within the Widget Animator whenever an animation is finished
    //on a certain widget
#if QT_CONFIG(toolbar)
    if (QToolBar *tb = qobject_cast<QToolBar*>(widget)) {
        QToolBarLayout *tbl = qobject_cast<QToolBarLayout*>(tb->layout());
        if (tbl->animating) {
            tbl->animating = false;
            if (tbl->expanded)
                tbl->layoutActions(tb->size());
            tb->update();
        }
    }
#endif

    if (widget == pluggingWidget) {

#if QT_CONFIG(dockwidget)
#if QT_CONFIG(tabbar)
        if (QDockWidgetGroupWindow *dwgw = qobject_cast<QDockWidgetGroupWindow *>(widget)) {
            // When the animated widget was a QDockWidgetGroupWindow, it means each of the
            // embedded QDockWidget needs to be plugged back into the QMainWindow layout.
            savedState.clear();
            QDockAreaLayoutInfo *srcInfo = dwgw->layoutInfo();
            const QDockAreaLayoutInfo *srcTabInfo = dwgw->tabLayoutInfo();
            QDockAreaLayoutInfo *dstParentInfo;
            QList<int> dstPath;

            if (currentHoveredFloat) {
                dstPath = currentHoveredFloat->layoutInfo()->indexOf(widget);
                Q_ASSERT(dstPath.size() >= 1);
                dstParentInfo = currentHoveredFloat->layoutInfo()->info(dstPath);
            } else {
                dstPath = layoutState.dockAreaLayout.indexOf(widget);
                Q_ASSERT(dstPath.size() >= 2);
                dstParentInfo = layoutState.dockAreaLayout.info(dstPath);
            }
            Q_ASSERT(dstParentInfo);
            int idx = dstPath.constLast();
            Q_ASSERT(dstParentInfo->item_list[idx].widgetItem->widget() == dwgw);
            if (dstParentInfo->tabbed && srcTabInfo) {
                // merge the two tab widgets
                delete dstParentInfo->item_list[idx].widgetItem;
                dstParentInfo->item_list.removeAt(idx);
                std::copy(srcTabInfo->item_list.cbegin(), srcTabInfo->item_list.cend(),
                          std::inserter(dstParentInfo->item_list,
                                        dstParentInfo->item_list.begin() + idx));
                quintptr currentId = srcTabInfo->currentTabId();
                *srcInfo = QDockAreaLayoutInfo();
                dstParentInfo->reparentWidgets(currentHoveredFloat ? currentHoveredFloat.data()
                                                                   : parentWidget());
                dstParentInfo->updateTabBar();
                dstParentInfo->setCurrentTabId(currentId);
            } else {
                QDockAreaLayoutItem &item = dstParentInfo->item_list[idx];
                Q_ASSERT(item.widgetItem->widget() == dwgw);
                delete item.widgetItem;
                item.widgetItem = nullptr;
                item.subinfo = new QDockAreaLayoutInfo(std::move(*srcInfo));
                *srcInfo = QDockAreaLayoutInfo();
                item.subinfo->reparentWidgets(currentHoveredFloat ? currentHoveredFloat.data()
                                                                  : parentWidget());
                item.subinfo->setTabBarShape(dstParentInfo->tabBarShape);
            }
            dwgw->destroyOrHideIfEmpty();
        }
#endif

        if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
            dw->setParent(currentHoveredFloat ? currentHoveredFloat.data() : parentWidget());
            dw->show();
            dw->d_func()->plug(currentGapRect);
        }
#endif
#if QT_CONFIG(toolbar)
        if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
            tb->d_func()->plug(currentGapRect);
#endif

        savedState.clear();
        currentGapPos.clear();
        pluggingWidget = nullptr;
#if QT_CONFIG(dockwidget)
        setCurrentHoveredFloat(nullptr);
#endif
        //applying the state will make sure that the currentGap is updated correctly
        //and all the geometries (especially the one from the central widget) is correct
        layoutState.apply(false);

#if QT_CONFIG(dockwidget)
#if QT_CONFIG(tabbar)
        if (qobject_cast<QDockWidget*>(widget) != nullptr) {
            // info() might return null if the widget is destroyed while
            // animating but before the animationFinished signal is received.
            if (QDockAreaLayoutInfo *info = dockInfo(widget))
                info->setCurrentTab(widget);
        }
#endif
#endif
    }

    if (!widgetAnimator.animating()) {
        //all animations are finished
#if QT_CONFIG(dockwidget)
        parentWidget()->update(layoutState.dockAreaLayout.separatorRegion());
#if QT_CONFIG(tabbar)
        const auto usedTabBarsCopy = usedTabBars; // list potentially modified by animations
        for (QTabBar *tab_bar : usedTabBarsCopy)
            tab_bar->show();
#endif // QT_CONFIG(tabbar)
#endif // QT_CONFIG(dockwidget)
    }

    updateGapIndicator();
}

void QMainWindowLayout::restore(bool keepSavedState)
{
    if (!savedState.isValid())
        return;

    layoutState = savedState;
    applyState(layoutState);
    if (!keepSavedState)
        savedState.clear();
    currentGapPos.clear();
    pluggingWidget = nullptr;
    updateGapIndicator();
}

QMainWindowLayout::QMainWindowLayout(QMainWindow *mainwindow, QLayout *parentLayout)
    : QLayout(parentLayout ? static_cast<QWidget *>(nullptr) : mainwindow)
    , layoutState(mainwindow)
    , savedState(mainwindow)
    , dockOptions(QMainWindow::AnimatedDocks | QMainWindow::AllowTabbedDocks)
    , statusbar(nullptr)
#if QT_CONFIG(dockwidget)
#if QT_CONFIG(tabbar)
    , _documentMode(false)
    , verticalTabsEnabled(false)
#if QT_CONFIG(tabwidget)
    , _tabShape(QTabWidget::Rounded)
#endif
#endif
#endif // QT_CONFIG(dockwidget)
    , widgetAnimator(this)
    , pluggingWidget(nullptr)
{
    if (parentLayout)
        setParent(parentLayout);

#if QT_CONFIG(dockwidget)
#if QT_CONFIG(tabbar)
    sep = mainwindow->style()->pixelMetric(QStyle::PM_DockWidgetSeparatorExtent, nullptr, mainwindow);
#endif

#if QT_CONFIG(tabwidget)
    for (int i = 0; i < QInternal::DockCount; ++i)
        tabPositions[i] = QTabWidget::South;
#endif
#endif // QT_CONFIG(dockwidget)
    pluggingWidget = nullptr;

    setObjectName(mainwindow->objectName() + "_layout"_L1);
}

QMainWindowLayout::~QMainWindowLayout()
{
    layoutState.deleteAllLayoutItems();
    layoutState.deleteCentralWidgetItem();

    delete statusbar;
}

void QMainWindowLayout::setDockOptions(QMainWindow::DockOptions opts)
{
    if (opts == dockOptions)
        return;

    dockOptions = opts;

#if QT_CONFIG(dockwidget) && QT_CONFIG(tabbar)
    setVerticalTabsEnabled(opts & QMainWindow::VerticalTabs);
#endif

    invalidate();
}

#if QT_CONFIG(statusbar)
QStatusBar *QMainWindowLayout::statusBar() const
{ return statusbar ? qobject_cast<QStatusBar *>(statusbar->widget()) : 0; }

void QMainWindowLayout::setStatusBar(QStatusBar *sb)
{
    if (sb)
        addChildWidget(sb);
    delete statusbar;
    statusbar = sb ? new QWidgetItemV2(sb) : nullptr;
    invalidate();
}
#endif // QT_CONFIG(statusbar)

QWidget *QMainWindowLayout::centralWidget() const
{
    return layoutState.centralWidget();
}

void QMainWindowLayout::setCentralWidget(QWidget *widget)
{
    if (widget != nullptr)
        addChildWidget(widget);
    layoutState.setCentralWidget(widget);
    if (savedState.isValid()) {
#if QT_CONFIG(dockwidget)
        savedState.dockAreaLayout.centralWidgetItem = layoutState.dockAreaLayout.centralWidgetItem;
        savedState.dockAreaLayout.fallbackToSizeHints = true;
#else
        savedState.centralWidgetItem = layoutState.centralWidgetItem;
#endif
    }
    invalidate();
}

#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
/*! \internal
  This helper function is called by QMainWindowLayout::unplug if QMainWindow::GroupedDragging is
  set and we are dragging the title bar of a non-floating QDockWidget.
  If one should unplug the whole group, do so and return true, otherwise return false.
  \a item is pointing to the QLayoutItem that holds the QDockWidget, but will be updated to the
  QLayoutItem that holds the new QDockWidgetGroupWindow if the group is unplugged.
*/
static bool unplugGroup(QMainWindowLayout *layout, QLayoutItem **item,
                        QDockAreaLayoutItem &parentItem)
{
    if (!parentItem.subinfo || !parentItem.subinfo->tabbed)
        return false;

    // The QDockWidget is part of a group of tab and we need to unplug them all.
    QDockWidgetGroupWindow *floatingTabs = layout->createTabbedDockWindow();
    QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
    *info = std::move(*parentItem.subinfo);
    delete parentItem.subinfo;
    parentItem.subinfo = nullptr;
    floatingTabs->setGeometry(info->rect.translated(layout->parentWidget()->pos()));
    floatingTabs->show();
    floatingTabs->raise();
    *item = new QDockWidgetGroupWindowItem(floatingTabs);
    parentItem.widgetItem = *item;
    return true;
}
#endif

#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
static QTabBar::Shape tabwidgetPositionToTabBarShape(QWidget *w)
{
    QTabBar::Shape result = QTabBar::RoundedSouth;
    if (qobject_cast<QDockWidget *>(w)) {
        switch (static_cast<QDockWidgetPrivate *>(qt_widget_private(w))->tabPosition) {
        case QTabWidget::North:
            result = QTabBar::RoundedNorth;
            break;
        case QTabWidget::South:
            result = QTabBar::RoundedSouth;
            break;
        case QTabWidget::West:
            result = QTabBar::RoundedWest;
            break;
        case QTabWidget::East:
            result = QTabBar::RoundedEast;
            break;
        }
    }
    return result;
}
#endif // QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)

/*! \internal
    Unplug \a widget (QDockWidget or QToolBar) from it's parent container.

    If \a group is true we might actually unplug the group of tabs this
    widget is part if QMainWindow::GroupedDragging is set. When \a group
    is false, the widget itself is always unplugged alone

    Returns the QLayoutItem of the dragged element.
    The layout item is kept in the layout but set as a gap item.
 */
QLayoutItem *QMainWindowLayout::unplug(QWidget *widget, QDockWidgetPrivate::DragScope scope)
{
#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
    auto *groupWindow = qobject_cast<const QDockWidgetGroupWindow *>(widget->parentWidget());
    if (!widget->isWindow() && groupWindow) {
        if (scope == QDockWidgetPrivate::DragScope::Group && groupWindow->tabLayoutInfo()) {
            // We are just dragging a floating window as it, not need to do anything, we just have to
            // look up the corresponding QWidgetItem* if it exists
            if (QDockAreaLayoutInfo *info = dockInfo(widget->parentWidget())) {
                QList<int> groupWindowPath = info->indexOf(widget->parentWidget());
                return groupWindowPath.isEmpty() ? nullptr : info->item(groupWindowPath).widgetItem;
            }
            qCDebug(lcQpaDockWidgets) << "Drag only:" << widget << "Group:" << (scope == QDockWidgetPrivate::DragScope::Group);
            return nullptr;
        }
        QList<int> path = groupWindow->layoutInfo()->indexOf(widget);
        QDockAreaLayoutItem parentItem = groupWindow->layoutInfo()->item(path);
        QLayoutItem *item = parentItem.widgetItem;
        if (scope == QDockWidgetPrivate::DragScope::Group && path.size() > 1
            && unplugGroup(this, &item, parentItem)) {
            qCDebug(lcQpaDockWidgets) << "Unplugging:" << widget << "from" << item;
            return item;
        } else {
            // We are unplugging a single dock widget from a floating window.
            QDockWidget *dockWidget = qobject_cast<QDockWidget *>(widget);
            Q_ASSERT(dockWidget); // cannot be a QDockWidgetGroupWindow because it's not floating.
            dockWidget->d_func()->unplug(widget->geometry());

            qCDebug(lcQpaDockWidgets) << "Unplugged from floating dock:" << widget << "from" << parentItem.widgetItem;
            return item;
        }
    }
#endif
    QList<int> path = layoutState.indexOf(widget);
    if (path.isEmpty())
        return nullptr;

    QLayoutItem *item = layoutState.item(path);
    if (widget->isWindow())
        return item;

    QRect r = layoutState.itemRect(path);
    savedState = layoutState;

#if QT_CONFIG(dockwidget)
    if (QDockWidget *dw = qobject_cast<QDockWidget*>(widget)) {
        Q_ASSERT(path.constFirst() == 1);
#if QT_CONFIG(tabwidget)
        if (scope == QDockWidgetPrivate::DragScope::Group && (dockOptions & QMainWindow::GroupedDragging) && path.size() > 3
            && unplugGroup(this, &item,
                           layoutState.dockAreaLayout.item(path.mid(1, path.size() - 2)))) {
            path.removeLast();
            savedState = layoutState;
        } else
#endif // QT_CONFIG(tabwidget)
        {
            // Dock widget is unplugged from a main window dock
            // => height or width need to be decreased by separator size
            switch (dockWidgetArea(dw)) {
            case Qt::LeftDockWidgetArea:
            case Qt::RightDockWidgetArea:
                r.setHeight(r.height() - sep);
                break;
            case Qt::TopDockWidgetArea:
            case Qt::BottomDockWidgetArea:
                r.setWidth(r.width() - sep);
                break;
            case Qt::NoDockWidgetArea:
            case Qt::DockWidgetArea_Mask:
                break;
            }

            // Depending on the title bar layout (vertical / horizontal),
            // width and height have to provide minimum space for window handles
            // and mouse dragging.
            // Assuming horizontal title bar, if the dock widget does not have a layout.
            const auto *layout = qobject_cast<QDockWidgetLayout *>(dw->layout());
            const bool verticalTitleBar = layout ? layout->verticalTitleBar : false;
            const int tbHeight = QApplication::style()
                      ? QApplication::style()->pixelMetric(QStyle::PixelMetric::PM_TitleBarHeight, nullptr, dw)
                      : 20;
            const int minHeight = verticalTitleBar ? 2 * tbHeight : tbHeight;
            const int minWidth = verticalTitleBar ? tbHeight : 2 * tbHeight;
            r.setSize(r.size().expandedTo(QSize(minWidth, minHeight)));
            qCDebug(lcQpaDockWidgets) << dw << "will be unplugged with size" << r.size();

            dw->d_func()->unplug(r);
        }
    }
#endif // QT_CONFIG(dockwidget)
#if QT_CONFIG(toolbar)
    if (QToolBar *tb = qobject_cast<QToolBar*>(widget)) {
        tb->d_func()->unplug(r);
    }
#endif

#if !QT_CONFIG(dockwidget) || !QT_CONFIG(tabbar)
    Q_UNUSED(scope);
#endif

    layoutState.unplug(path ,&savedState);
    savedState.fitLayout();
    currentGapPos = path;
    currentGapRect = r;
    updateGapIndicator();

    fixToolBarOrientation(item, currentGapPos.at(1));

    return item;
}

void QMainWindowLayout::updateGapIndicator()
{
#if QT_CONFIG(rubberband)
    if (!widgetAnimator.animating() && (!currentGapPos.isEmpty()
#if QT_CONFIG(dockwidget)
                                        || currentHoveredFloat
#endif
                                        )) {
        QWidget *expectedParent =
#if QT_CONFIG(dockwidget)
            currentHoveredFloat ? currentHoveredFloat.data() :
#endif
            parentWidget();
        if (!gapIndicator) {
            gapIndicator = new QRubberBand(QRubberBand::Rectangle, expectedParent);
            // For accessibility to identify this special widget.
            gapIndicator->setObjectName("qt_rubberband"_L1);
        } else if (gapIndicator->parent() != expectedParent) {
            gapIndicator->setParent(expectedParent);
        }

        // Prevent re-entry in case of size change
        const bool sigBlockState = gapIndicator->signalsBlocked();
        auto resetSignals = qScopeGuard([this, sigBlockState](){ gapIndicator->blockSignals(sigBlockState); });
        gapIndicator->blockSignals(true);

#if QT_CONFIG(dockwidget)
        if (currentHoveredFloat)
            gapIndicator->setGeometry(currentHoveredFloat->currentGapRect);
        else
#endif
            gapIndicator->setGeometry(currentGapRect);

        gapIndicator->show();
        gapIndicator->raise();

        // Reset signal state

    } else if (gapIndicator) {
        gapIndicator->hide();
    }

#endif // QT_CONFIG(rubberband)
}

void QMainWindowLayout::hover(QLayoutItem *hoverTarget,
                              const QPoint &mousePos) {
  if (!parentWidget()->isVisible() || parentWidget()->isMinimized() ||
      pluggingWidget != nullptr || hoverTarget == nullptr)
    return;

  QWidget *widget = hoverTarget->widget();

#if QT_CONFIG(dockwidget)
    widget->raise();
    if ((dockOptions & QMainWindow::GroupedDragging) && (qobject_cast<QDockWidget*>(widget)
            || qobject_cast<QDockWidgetGroupWindow *>(widget))) {

        // Check if we are over another floating dock widget
        QVarLengthArray<QWidget *, 10> candidates;
        const auto siblings = parentWidget()->children();
        for (QObject *c : siblings) {
            QWidget *w = qobject_cast<QWidget*>(c);
            if (!w)
                continue;

            // Handle only dock widgets and group windows
            if (!qobject_cast<QDockWidget*>(w) && !qobject_cast<QDockWidgetGroupWindow *>(w))
                continue;

            // Check permission to dock on another dock widget or floating dock
            // FIXME in Qt 7

            if (w != widget && w->isWindow() && w->isVisible() && !w->isMinimized())
                candidates << w;

            if (QDockWidgetGroupWindow *group = qobject_cast<QDockWidgetGroupWindow *>(w)) {
                // floating QDockWidgets have a QDockWidgetGroupWindow as a parent,
                // if they have been hovered over
                const auto groupChildren = group->children();
                for (QObject *c : groupChildren) {
                    if (QDockWidget *dw = qobject_cast<QDockWidget*>(c)) {
                        if (dw != widget && dw->isFloating() && dw->isVisible() && !dw->isMinimized())
                            candidates << dw;
                    }
                }
            }
        }

        for (QWidget *w : candidates) {
            const QScreen *screen1 = qt_widget_private(widget)->associatedScreen();
            const QScreen *screen2 = qt_widget_private(w)->associatedScreen();
            if (screen1 && screen2 && screen1 != screen2)
                continue;
            if (!w->geometry().contains(mousePos))
                continue;

#if QT_CONFIG(tabwidget)
            if (auto dropTo = qobject_cast<QDockWidget *>(w)) {

                // w is the drop target's widget
                w = dropTo->widget();

                // Create a floating tab, unless already existing
                if (!qobject_cast<QDockWidgetGroupWindow *>(w)) {
                    QDockWidgetGroupWindow *floatingTabs = createTabbedDockWindow();
                    floatingTabs->setGeometry(dropTo->geometry());
                    QDockAreaLayoutInfo *info = floatingTabs->layoutInfo();
                    const QTabBar::Shape shape = tabwidgetPositionToTabBarShape(dropTo);

                    // dropTo and widget may be in a state where they transition
                    // from being a group window child to a single floating dock widget.
                    // In that case, their path to a main window dock may not have been
                    // updated yet.
                    // => ask both and fall back to dock 1 (right dock)
                    QInternal::DockPosition dockPosition = toDockPos(dockWidgetArea(dropTo));
                    if (dockPosition == QInternal::DockPosition::DockCount)
                        dockPosition = toDockPos(dockWidgetArea(widget));
                    if (dockPosition == QInternal::DockPosition::DockCount)
                        dockPosition = QInternal::DockPosition::RightDock;

                    *info = QDockAreaLayoutInfo(&layoutState.dockAreaLayout.sep, dockPosition,
                                                Qt::Horizontal, shape,
                                                static_cast<QMainWindow *>(parentWidget()));
                    info->tabBar = getTabBar();
                    info->tabbed = true;
                    info->add(dropTo);
                    QDockAreaLayoutInfo &parentInfo = layoutState.dockAreaLayout.docks[dockPosition];
                    parentInfo.add(floatingTabs);
                    dropTo->setParent(floatingTabs);
                    qCDebug(lcQpaDockWidgets) << "Wrapping" << widget << "into floating tabs" << floatingTabs;
                    w = floatingTabs;
                }

                // Show the drop target and raise widget to foreground
                dropTo->show();
                qCDebug(lcQpaDockWidgets) << "Showing" << dropTo;
                widget->raise();
                qCDebug(lcQpaDockWidgets) << "Raising" << widget;
            }
#endif
            auto *groupWindow = qobject_cast<QDockWidgetGroupWindow *>(w);
            Q_ASSERT(groupWindow);
            if (groupWindow->hover(hoverTarget, groupWindow->mapFromGlobal(mousePos))) {
                setCurrentHoveredFloat(groupWindow);
                applyState(layoutState); // update the tabbars
            }
            return;
        }
    }

    // If a temporary group window has been created during a hover,
    // remove it, if it has only one dockwidget child
    if (currentHoveredFloat)
        currentHoveredFloat->destroyIfSingleItemLeft();

    setCurrentHoveredFloat(nullptr);
    layoutState.dockAreaLayout.fallbackToSizeHints = false;
#endif // QT_CONFIG(dockwidget)

    QPoint pos = parentWidget()->mapFromGlobal(mousePos);

    if (!savedState.isValid())
        savedState = layoutState;

    QList<int> path = savedState.gapIndex(widget, pos);

    if (!path.isEmpty()) {
        bool allowed = false;

#if QT_CONFIG(dockwidget)
        allowed = isAreaAllowed(widget, path);
#endif
#if QT_CONFIG(toolbar)
        if (QToolBar *tb = qobject_cast<QToolBar*>(widget))
            allowed = tb->isAreaAllowed(toToolBarArea(path.at(1)));
#endif

        if (!allowed)
            path.clear();
    }

    if (path == currentGapPos)
        return; // the gap is already there

    currentGapPos = path;
    if (path.isEmpty()) {
        fixToolBarOrientation(hoverTarget, 2); // 2 = top dock, ie. horizontal
        restore(true);
        return;
    }

    fixToolBarOrientation(hoverTarget, currentGapPos.at(1));

    QMainWindowLayoutState newState = savedState;

    if (!newState.insertGap(path, hoverTarget)) {
        restore(true); // not enough space
        return;
    }

    QSize min = newState.minimumSize();
    QSize size = newState.rect.size();

    if (min.width() > size.width() || min.height() > size.height()) {
        restore(true);
        return;
    }

    newState.fitLayout();

    currentGapRect = newState.gapRect(currentGapPos);

#if QT_CONFIG(dockwidget)
    parentWidget()->update(layoutState.dockAreaLayout.separatorRegion());
#endif
    layoutState = std::move(newState);
    applyState(layoutState);

    updateGapIndicator();
}

#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
QDockWidgetGroupWindow *QMainWindowLayout::createTabbedDockWindow()
{
    QDockWidgetGroupWindow* f = new QDockWidgetGroupWindow(parentWidget(), Qt::Tool);
    new QDockWidgetGroupLayout(f);
    return f;
}
#endif

void QMainWindowLayout::applyState(QMainWindowLayoutState &newState, bool animate)
{
    // applying the state can lead to showing separator widgets, which would lead to a re-layout
    // (even though the separator widgets are not really part of the layout)
    // break the loop
    if (isInApplyState)
        return;
    isInApplyState = true;
#if QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
    QSet<QTabBar*> used = newState.dockAreaLayout.usedTabBars();
    const auto groups =
            parent()->findChildren<QDockWidgetGroupWindow*>(Qt::FindDirectChildrenOnly);
    for (QDockWidgetGroupWindow *dwgw : groups)
        used += dwgw->layoutInfo()->usedTabBars();

    const QSet<QTabBar*> retired = usedTabBars - used;
    usedTabBars = used;
    for (QTabBar *tab_bar : retired) {
        tab_bar->hide();
        while (tab_bar->count() > 0)
            tab_bar->removeTab(0);
        unusedTabBars.append(tab_bar);
    }

    if (sep == 1) {
        const QSet<QWidget*> usedSeps = newState.dockAreaLayout.usedSeparatorWidgets();
        const QSet<QWidget*> retiredSeps = usedSeparatorWidgets - usedSeps;
        usedSeparatorWidgets = usedSeps;
        for (QWidget *sepWidget : retiredSeps) {
            unusedSeparatorWidgets.append(sepWidget);
            sepWidget->hide();
        }
    }

    for (int i = 0; i < QInternal::DockCount; ++i)
        newState.dockAreaLayout.docks[i].reparentWidgets(parentWidget());

#endif // QT_CONFIG(dockwidget) && QT_CONFIG(tabwidget)
    newState.apply(dockOptions & QMainWindow::AnimatedDocks && animate);
    isInApplyState = false;
}

void QMainWindowLayout::saveState(QDataStream &stream) const
{
    layoutState.saveState(stream);
}

bool QMainWindowLayout::restoreState(QDataStream &stream)
{
    QScopedValueRollback<bool> guard(isInRestoreState, true);
    savedState = layoutState;
    layoutState.clear();
    layoutState.rect = savedState.rect;

    if (!layoutState.restoreState(stream, savedState)) {
        layoutState.deleteAllLayoutItems();
        layoutState = savedState;
        if (parentWidget()->isVisible())
            applyState(layoutState, false); // hides tabBars allocated by newState
        return false;
    }

    if (parentWidget()->isVisible()) {
        layoutState.fitLayout();
        applyState(layoutState, false);
    } else {
        /*
            The state might not fit into the size of the widget as it gets shown, but
            if the window is expected to be maximized or full screened, then we might
            get several resizes as part of that transition, at the end of which the
            state might fit. So keep the restored state around for now and try again
            later in setGeometry.
        */
        if ((parentWidget()->windowState() & (Qt::WindowFullScreen | Qt::WindowMaximized))
            && !layoutState.fits()) {
            restoredState.reset(new QMainWindowLayoutState(layoutState));
        }
    }

    savedState.deleteAllLayoutItems();
    savedState.clear();

#if QT_CONFIG(dockwidget)
    if (parentWidget()->isVisible()) {
#if QT_CONFIG(tabbar)
        for (QTabBar *tab_bar : std::as_const(usedTabBars))
            tab_bar->show();

#endif
    }
#endif // QT_CONFIG(dockwidget)

    return true;
}

#if QT_CONFIG(draganddrop)
bool QMainWindowLayout::needsPlatformDrag()
{
    static const bool wayland =
            QGuiApplication::platformName().startsWith("wayland"_L1, Qt::CaseInsensitive);
    return wayland;
}

Qt::DropAction QMainWindowLayout::performPlatformWidgetDrag(QLayoutItem *widgetItem,
                                                            const QPoint &pressPosition)
{
    draggingWidget = widgetItem;
    QWidget *widget = widgetItem->widget();
    auto drag = QDrag(widget);
    auto mimeData = new QMimeData();
    auto window = widgetItem->widget()->windowHandle();

    auto serialize = [](const auto &object) {
        QByteArray data;
        QDataStream dataStream(&data, QIODevice::WriteOnly);
        dataStream << object;
        return data;
    };
    mimeData->setData("application/x-qt-mainwindowdrag-window"_L1,
                      serialize(reinterpret_cast<qintptr>(window)));
    mimeData->setData("application/x-qt-mainwindowdrag-position"_L1, serialize(pressPosition));
    drag.setMimeData(mimeData);

    auto result = drag.exec();

    draggingWidget = nullptr;
    return result;
}
#endif

QT_END_NAMESPACE

#include "qmainwindowlayout.moc"
#include "moc_qmainwindowlayout_p.cpp"