This file is indexed.

/usr/lib/lazarus/0.9.30.4/lcl/ldocktree.pas is in lazarus-src-0.9.30.4 0.9.30.4-6.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
{
 /***************************************************************************
                               LDockTree.pas
                             -----------------

 ***************************************************************************/

 *****************************************************************************
 *                                                                           *
 *  This file is part of the Lazarus Component Library (LCL)                 *
 *                                                                           *
 *  See the file COPYING.modifiedLGPL.txt, included in this distribution,    *
 *  for details about the copyright.                                         *
 *                                                                           *
 *  This program is distributed in the hope that it will be useful,          *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.                     *
 *                                                                           *
 *****************************************************************************

  Author: Mattias Gaertner

  Abstract:
    This unit contains TLazDockTree, the default TDockTree for the LCL.
}
unit LDockTree;

{$mode objfpc}{$H+}

interface

uses
  Math, Types, Classes, SysUtils, LCLProc, LCLType, LCLStrConsts,
  Graphics, Controls, ExtCtrls, Forms, Menus, Themes, LCLIntf,
  LMessages, LResources, typinfo;

type
  TLazDockPages = class;
  TLazDockPage = class;
  TLazDockSplitter = class;


  { TLazDockZone }

  TLazDockZone = class(TDockZone)
  private
    FPage: TLazDockPage;
    FPages: TLazDockPages;
    FSplitter: TLazDockSplitter;
  public
    destructor Destroy; override;
    procedure FreeSubComponents;
    function GetCaption: string;
    function GetParentControl: TWinControl;
    property Splitter: TLazDockSplitter read FSplitter write FSplitter;
    property Pages: TLazDockPages read FPages write FPages;
    property Page: TLazDockPage read FPage write FPage;
  end;

  TDockHeaderMouseState = record
    Rect: TRect;
    IsMouseDown: Boolean;
  end;

  TDockHeaderImageKind =
  (
    dhiRestore,
    dhiClose
  );

  TDockHeaderImages = array[TDockHeaderImageKind] of TCustomBitmap;

  { TLazDockTree }

  TLazDockTree = class(TDockTree)
  private
    FAutoFreeDockSite: boolean;
    FMouseState: TDockHeaderMouseState;
    FDockHeaderImages: TDockHeaderImages;
  protected
    procedure AnchorDockLayout(Zone: TLazDockZone);
    procedure CreateDockLayoutHelperControls(Zone: TLazDockZone);
    procedure ResetSizes(Zone: TLazDockZone);
    procedure BreakAnchors(Zone: TDockZone);
    procedure PaintDockFrame(ACanvas: TCanvas; AControl: TControl;
                             const ARect: TRect); override;
    procedure UndockControlForDocking(AControl: TControl);
    function DefaultDockGrabberSize: Integer;
  public
    constructor Create(TheDockSite: TWinControl); override;
    destructor Destroy; override;
    procedure AdjustDockRect(AControl: TControl; var ARect: TRect); override;
    procedure InsertControl(AControl: TControl; InsertAt: TAlign;
                            DropControl: TControl); override;
    procedure RemoveControl(AControl: TControl); override;
    procedure BuildDockLayout(Zone: TLazDockZone);
    procedure FindBorderControls(Zone: TLazDockZone; Side: TAnchorKind;
                                 var List: TFPList);
    function FindBorderControl(Zone: TLazDockZone; Side: TAnchorKind): TControl;
    function GetAnchorControl(Zone: TLazDockZone; Side: TAnchorKind;
                              OutSide: boolean): TControl;
    procedure PaintSite(DC: HDC); override;
    procedure MessageHandler(Sender: TControl; var Message: TLMessage); override;
    procedure DumpLayout(FileName: String); override;
  public
    property AutoFreeDockSite: boolean read FAutoFreeDockSite write FAutoFreeDockSite;
  end;

  TLazDockHeaderPart =
  (
    ldhpAll,           // total header rect
    ldhpCaption,       // header caption
    ldhpRestoreButton, // header restore button
    ldhpCloseButton    // header close button
  );

  { TLazDockForm
    The default DockSite for a TLazDockTree and for TCustomAnchoredDockManager.

    Note: There are two docking managers:
      TLazDockTree uses TLazDockZone to allow docking in rows and columns.
      TCustomAnchoredDockManager does not use TLazDockZone and allows arbitrary
        layouts.
 }

  TLazDockForm = class(TCustomForm)
  private
    FMainControl: TControl;
    FMouseState: TDockHeaderMouseState;
    FDockHeaderImages: TDockHeaderImages;
    procedure SetMainControl(const AValue: TControl);
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure UpdateMainControl;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X,Y: Integer); override;
    procedure MouseLeave; override;
    procedure PaintWindow(DC: HDC); override;
    procedure TrackMouse(X, Y: Integer);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    function CloseQuery: boolean; override;
    procedure UpdateCaption; virtual;
    class procedure UpdateMainControlInParents(StartControl: TControl);
    function FindMainControlCandidate: TControl;
    function FindHeader(x, y: integer; out Part: TLazDockHeaderPart): TControl;
    procedure InsertControl(AControl: TControl; Index: integer); override;
    function IsDockedControl(Control: TControl): boolean;
    function ControlHasTitle(Control: TControl): boolean;
    function GetTitleRect(Control: TControl): TRect;
    function GetTitleOrientation(Control: TControl): TDockOrientation;
    property MainControl: TControl read FMainControl write SetMainControl;// used for the default caption
  end;


  { TLazDockPage
    Pretty the same as a TLazDockForm but as page of a TLazDockPages }

  TLazDockPage = class(TCustomPage)
  private
    FDockZone: TDockZone;
    function GetPageControl: TLazDockPages;
  public
    procedure InsertControl(AControl: TControl; Index: integer); override;
    property DockZone: TDockZone read FDockZone;
    property PageControl: TLazDockPages read GetPageControl;
  end;


  { TLazDockPages }

  TLazDockPages = class(TCustomNotebook)
  private
    function GetActiveNotebookPageComponent: TLazDockPage;
    function GetNoteBookPage(Index: Integer): TLazDockPage;
    procedure SetActiveNotebookPageComponent(const AValue: TLazDockPage);
  protected
    function GetFloatingDockSiteClass: TWinControlClass; override;
    procedure Change; override;
  public
    constructor Create(TheOwner: TComponent); override;
    property Page[Index: Integer]: TLazDockPage read GetNoteBookPage;
    property ActivePageComponent: TLazDockPage read GetActiveNotebookPageComponent
                                           write SetActiveNotebookPageComponent;
    property Pages;
  end;


  { TLazDockSplitter }

  TLazDockSplitter = class(TCustomSplitter)
  public
    constructor Create(AOwner: TComponent); override;
  end;


  TCustomAnchoredDockManager = class;

  { TLazDockOwnerComponent
    A TComponent owning all automatically created controls of a
    TCustomAnchoredDockManager, like TLazDockForm }

  TLazDockOwnerComponent = class(TComponent)
  public
    Manager: TCustomAnchoredDockManager;
  end;

  //----------------------------------------------------------------------------

  { TCustomAnchoredDockManager
    This class implements an LCL TDockManager via anchoring.
    It implements the docking, undocking, enlarging, shrinking.

    The TCustomLazDockingManager component in LDockCtrl uses this
    docking manager and extends it by layouts that can be stored/restored. }

  TCustomAnchoredDockManager = class(TDockManager)
  private
    FSplitterSize: integer;
    FTitleHeight: integer;
    FTitleWidth: integer;
    FUpdateCount: integer;
  protected
    FOwnerComponent: TLazDockOwnerComponent;
    procedure DeleteSideSplitter(Splitter: TLazDockSplitter; Side: TAnchorKind;
                                 NewAnchorControl: TControl);
    procedure CombineSpiralSplitterPair(Splitter1, Splitter2: TLazDockSplitter);
    procedure DeletePage(Page: TLazDockPage);
    procedure DeletePages(Pages: TLazDockPages);
    procedure DeleteDockForm(ADockForm: TLazDockForm);
    function GetAnchorDepth(AControl: TControl; Side: TAnchorKind): Integer;
    function GetPreferredTitlePosition(AWidth, AHeight: integer): TAnchorKind;
  public
    constructor Create(ADockSite: TWinControl); override;
    destructor Destroy; override;
    procedure BeginUpdate; override;
    procedure EndUpdate; override;
    procedure GetControlBounds(Control: TControl;
                               out AControlBounds: TRect); override;
    procedure DisableLayout(Control: TControl); virtual;
    procedure EnableLayout(Control: TControl); virtual;
    procedure DockControl(Control: TControl; InsertAt: TAlign;
                          DropCtl: TControl);
    procedure UndockControl(Control: TControl; Float: boolean);
    procedure InsertControl(Control: TControl; InsertAt: TAlign;
                            DropCtl: TControl); override;
    function EnlargeControl(Control: TControl; Side: TAnchorKind;
                            Simulate: boolean = false): boolean;
    procedure RemoveControl(Control: TControl); override;
    procedure ReplaceAnchoredControl(OldControl, NewControl: TControl);
    function GetSplitterWidth(Splitter: TControl): integer;
    function GetSplitterHeight(Splitter: TControl): integer;
    property SplitterSize: integer read FSplitterSize write FSplitterSize default 5;
    property TitleWidth: integer read FTitleWidth write FTitleWidth default 20;
    property TitleHeight: integer read FTitleHeight write FTitleHeight default 20;
    procedure UpdateTitlePosition(Control: TControl);

    procedure PaintSite(DC: HDC); override;
    procedure MessageHandler(Sender: TControl; var Message: TLMessage); override;// not implemented
    procedure PositionDockRect(Client, DropCtl: TControl; DropAlign: TAlign;
                               var DockRect: TRect); override;// not implemented
    procedure ResetBounds(Force: Boolean); override;// not implemented
    procedure SetReplacingControl(Control: TControl); override;// not implemented
    procedure LoadFromStream(Stream: TStream); override;// not implemented
    procedure SaveToStream(Stream: TStream); override;// not implemented
    function AutoFreeByControl: Boolean; override;

    // ToDo: move this to protected, after dockig code from LDockCtrl was moved
    // here.
    function CreateForm: TLazDockForm;
  end;


const
  DockAlignOrientations: array[TAlign] of TDockOrientation =
  (
 { alNone   } doPages,
 { alTop    } doHorizontal,
 { alBottom } doHorizontal,
 { alLeft   } doVertical,
 { alRight  } doVertical,
 { alClient } doPages,
 { alCustom } doPages
  );

type
  TAnchorControlsRect = array[TAnchorKind] of TControl;

function GetLazDockSplitter(Control: TControl; Side: TAnchorKind;
                            out Splitter: TLazDockSplitter): boolean;
function GetLazDockSplitterOrParent(Control: TControl; Side: TAnchorKind;
                                    out AnchorControl: TControl): boolean;
function CountAnchoredControls(Control: TControl; Side: TAnchorKind
                               ): Integer;
function NeighbourCanBeShrinked(EnlargeControl, Neighbour: TControl;
                                Side: TAnchorKind): boolean;
function ControlIsAnchoredIndirectly(StartControl: TControl; Side: TAnchorKind;
                                     DestControl: TControl): boolean;
procedure GetAnchorControlsRect(Control: TControl;
                                out ARect: TAnchorControlsRect);
function GetEnclosingControlRect(ControlList: TFPlist;
                                 out ARect: TAnchorControlsRect): boolean;
function GetEnclosedControls(const ARect: TAnchorControlsRect): TFPList;


implementation

const
  DockHeaderImageNames: array[TDockHeaderImageKind] of String =
  (
{ dhiRestore } 'lcl_dock_restore',
{ dhiClose   } 'lcl_dock_close'
  );

type

  { TDockHeader }

  // maybe once it will be control, so now better to move all related to header things to class
  TDockHeader = class
    class procedure CreateDockHeaderImages(out Images: TDockHeaderImages);
    class procedure DestroyDockHeaderImages(var Images: TDockHeaderImages);

    class function GetRectOfPart(AHeaderRect: TRect; AOrientation: TDockOrientation; APart: TLazDockHeaderPart): TRect;
    class function FindPart(AHeaderRect: TRect; APoint: TPoint; AOrientation: TDockOrientation): TLazDockHeaderPart;
    class procedure Draw(ACanvas: TCanvas; ACaption: String; DockBtnImages: TDockHeaderImages; AOrientation: TDockOrientation; const ARect: TRect; const MousePos: TPoint);
    class procedure PerformMouseUp(AControl: TControl; APart: TLazDockHeaderPart);
    class procedure PerformMouseDown(AControl: TControl; APart: TLazDockHeaderPart);
  end;

class procedure TDockHeader.CreateDockHeaderImages(out Images: TDockHeaderImages);
var
  ImageKind: TDockHeaderImageKind;
begin
  for ImageKind := Low(TDockHeaderImageKind) to High(TDockHeaderImageKind) do
    Images[ImageKind] := CreateBitmapFromLazarusResource(DockHeaderImageNames[ImageKind]);
end;

class procedure TDockHeader.DestroyDockHeaderImages(
  var Images: TDockHeaderImages);
var
  ImageKind: TDockHeaderImageKind;
begin
  for ImageKind := Low(TDockHeaderImageKind) to High(TDockHeaderImageKind) do
    FreeAndNil(Images[ImageKind]);
end;

class function TDockHeader.GetRectOfPart(AHeaderRect: TRect; AOrientation: TDockOrientation;
  APart: TLazDockHeaderPart): TRect;
var
  d: Integer;
begin
  Result := AHeaderRect;
  if APart = ldhpAll then
    Exit;
  InflateRect(Result, -2, -2);
  case AOrientation of
    doHorizontal:
    begin
      d := Result.Bottom - Result.Top;
      if APart = ldhpCloseButton then
      begin
        Result.Left := Max(Result.Left, Result.Right - d);
        Exit;
      end;
      Result.Right := Max(Result.Left, Result.Right - d - 1);
      if APart = ldhpRestoreButton then
      begin
        Result.Left := Max(Result.Left, Result.Right - d);
        Exit;
      end;
      Result.Right := Max(Result.Left, Result.Right - d - 1);
      InflateRect(Result, -4, 0);
    end;
    doVertical:
    begin
      d := Result.Right - Result.Left;
      if APart = ldhpCloseButton then
      begin
        Result.Bottom := Min(Result.Bottom, Result.Top + d);
        Exit;
      end;
      Result.Top := Min(Result.Bottom, Result.Top + d + 1);
      if APart = ldhpRestoreButton then
      begin
        Result.Bottom := Min(Result.Bottom, Result.Top + d);
        Exit;
      end;
      Result.Top := Min(Result.Bottom, Result.Top + d + 1);
      InflateRect(Result, 0, -4);
    end;
  end;
end;

class function TDockHeader.FindPart(AHeaderRect: TRect; APoint: TPoint; AOrientation: TDockOrientation): TLazDockHeaderPart;
var
  SubRect: TRect;
begin
  for Result := Low(TLazDockHeaderPart) to High(TLazDockHeaderPart) do
  begin
    if Result = ldhpAll then
      Continue;
    SubRect := GetRectOfPart(AHeaderRect, AOrientation, Result);
    if PtInRect(SubRect, APoint) then
      Exit;
  end;
  Result := ldhpAll;
end;

class procedure TDockHeader.Draw(ACanvas: TCanvas; ACaption: String; DockBtnImages: TDockHeaderImages; AOrientation: TDockOrientation; const ARect: TRect; const MousePos: TPoint);

  procedure DrawButton(ARect: TRect; IsMouseDown, IsMouseOver: Boolean; ABitmap: TCustomBitmap); inline;
  const
    // ------------- Pressed, Hot -----------------------
    BtnDetail: array[Boolean, Boolean] of TThemedToolBar =
    (
     (ttbButtonNormal, ttbButtonHot),
     (ttbButtonNormal, ttbButtonPressed)
    );
  var
    Details: TThemedElementDetails;
    dx, dy: integer;
  begin
    Details := ThemeServices.GetElementDetails(BtnDetail[IsMouseDown, IsMouseOver]);
    ThemeServices.DrawElement(ACanvas.Handle, Details, ARect);
    ARect := ThemeServices.ContentRect(ACanvas.Handle, Details, ARect);
    dx := (ARect.Right - ARect.Left - ABitmap.Width) div 2;
    dy := (ARect.Bottom - ARect.Top - ABitmap.Height) div 2;
    ACanvas.Draw(ARect.Left + dx, ARect.Top + dy, ABitmap);
  end;

  procedure DrawTitle(ARect: TRect); inline;
  begin
    ACanvas.Pen.Color := clBtnShadow;
    ACanvas.Brush.Color := clBtnFace;
    ACanvas.Rectangle(ARect);
  end;

var
  BtnRect: TRect;
  DrawRect: TRect;
  // LCL do not handle orientation in TFont
  OldFont, RotatedFont: HFONT;
  OldMode: Integer;
  ALogFont: TLogFont;
  IsMouseDown: Boolean;
begin
  DrawRect := ARect;
  InflateRect(DrawRect, -1, -1);
  DrawTitle(DrawRect);
  InflateRect(DrawRect, -1, -1);

  IsMouseDown := (GetKeyState(VK_LBUTTON) and $80) <> 0;

  // draw close button
  BtnRect := GetRectOfPart(ARect, AOrientation, ldhpCloseButton);

  DrawButton(BtnRect, IsMouseDown, PtInRect(BtnRect, MousePos), DockBtnImages[dhiClose]);

  // draw restore button
  BtnRect := GetRectOfPart(ARect, AOrientation, ldhpRestoreButton);
  DrawButton(BtnRect, IsMouseDown, PtInRect(BtnRect, MousePos), DockBtnImages[dhiRestore]);

  // draw caption
  DrawRect := GetRectOfPart(ARect, AOrientation, ldhpCaption);

  OldMode := SetBkMode(ACanvas.Handle, TRANSPARENT);

  case AOrientation of
    doHorizontal:
      begin
        DrawText(ACanvas.Handle, PChar(ACaption), -1, DrawRect, DT_LEFT or DT_SINGLELINE or DT_VCENTER);
      end;
    doVertical:
      begin
        OldFont := 0;
        if GetObject(ACanvas.Font.Reference.Handle, SizeOf(ALogFont), @ALogFont) <> 0 then
        begin
          ALogFont.lfEscapement := 900;
          RotatedFont := CreateFontIndirect(ALogFont);
          if RotatedFont <> 0 then
            OldFont := SelectObject(ACanvas.Handle, RotatedFont);
        end;
        // from msdn: DrawText doesnot support font with orientation and escapement <> 0
        TextOut(ACanvas.Handle, DrawRect.Left, DrawRect.Bottom, PChar(ACaption), Length(ACaption));
        if OldFont <> 0 then
          DeleteObject(SelectObject(ACanvas.Handle, OldFont));
      end;
  end;
  SetBkMode(ACanvas.Handle, OldMode);
end;

class procedure TDockHeader.PerformMouseUp(AControl: TControl;
  APart: TLazDockHeaderPart);
begin
  case APart of
    ldhpRestoreButton:
      AControl.ManualDock(nil, nil, alNone);
    ldhpCloseButton:
      if AControl is TCustomForm then
        TCustomForm(AControl).Close
      else
        // not a form => doesnot have close => just hide
        AControl.Visible := False;
  end;
end;

class procedure TDockHeader.PerformMouseDown(AControl: TControl;
  APart: TLazDockHeaderPart);
begin
  case APart of
    ldhpAll, ldhpCaption:
      // mouse down on not buttons => start drag
      AControl.BeginDrag(False);
  end;
end;


function GetLazDockSplitter(Control: TControl; Side: TAnchorKind; out
  Splitter: TLazDockSplitter): boolean;
begin
  Result:=false;
  Splitter:=nil;
  if not (Side in Control.Anchors) then exit;
  Splitter:=TLazDockSplitter(Control.AnchorSide[Side].Control);
  if not (Splitter is TLazDockSplitter) then begin
    Splitter:=nil;
    exit;
  end;
  if Splitter.Parent<>Control.Parent then exit;
  Result:=true;
end;

function GetLazDockSplitterOrParent(Control: TControl; Side: TAnchorKind; out
  AnchorControl: TControl): boolean;
begin
  Result:=false;
  AnchorControl:=nil;
  if not (Side in Control.Anchors) then exit;
  AnchorControl:=Control.AnchorSide[Side].Control;
  if (AnchorControl is TLazDockSplitter)
  and (AnchorControl.Parent=Control.Parent)
  then
    Result:=true
  else if AnchorControl=Control.Parent then
    Result:=true;
end;

function CountAnchoredControls(Control: TControl; Side: TAnchorKind): Integer;
{ return the number of siblings, that are anchored on Side of Control
  For example: if Side=akLeft it will return the number of controls, which
  right side is anchored to the left of Control }
var
  i: Integer;
  Neighbour: TControl;
begin
  Result:=0;
  for i:=0 to Control.Parent.ControlCount-1 do begin
    Neighbour:=Control.Parent.Controls[i];
    if Neighbour=Control then continue;
    if (OppositeAnchor[Side] in Neighbour.Anchors)
    and (Neighbour.AnchorSide[OppositeAnchor[Side]].Control=Control) then
      inc(Result);
  end;
end;

function NeighbourCanBeShrinked(EnlargeControl, Neighbour: TControl;
  Side: TAnchorKind): boolean;
const
  MinControlSize = 20;
var
  Splitter: TLazDockSplitter;
begin
  Result:=false;
  if not GetLazDockSplitter(EnlargeControl,OppositeAnchor[Side],Splitter) then
    exit;
  case Side of
  akLeft: // check if left side of Neighbour can be moved
    Result:=Neighbour.Left+Neighbour.Width
        >EnlargeControl.Left+EnlargeControl.Width+Splitter.Width+MinControlSize;
  akRight: // check if right side of Neighbour can be moved
    Result:=Neighbour.Left+MinControlSize+Splitter.Width<EnlargeControl.Left;
  akTop: // check if top side of Neighbour can be moved
    Result:=Neighbour.Top+Neighbour.Height
       >EnlargeControl.Top+EnlargeControl.Height+Splitter.Height+MinControlSize;
  akBottom: // check if bottom side of Neighbour can be moved
    Result:=Neighbour.Top+MinControlSize+Splitter.Height<EnlargeControl.Top;
  end;
end;

function ControlIsAnchoredIndirectly(StartControl: TControl; Side: TAnchorKind;
  DestControl: TControl): boolean;
{ true if there is an Anchor way from StartControl to DestControl over Side.
  For example:

    +-+|+-+
    |A|||B|
    +-+|+-+

  A is akLeft to B.
  B is akRight to A.
  The splitter is akLeft to B.
  The splitter is akRight to A.
  All other are false.
}
var
  Checked: array of Boolean;
  Parent: TWinControl;

  function Check(ControlIndex: integer): boolean;
  var
    AControl: TControl;
    SideControl: TControl;
    i: Integer;
  begin
    if Checked[ControlIndex] then
      exit(false);
    Checked[ControlIndex]:=true;
    AControl:=Parent.Controls[ControlIndex];
    if AControl=DestControl then exit(true);

    if (Side in AControl.Anchors) then begin
      SideControl:=AControl.AnchorSide[Side].Control;
      if (SideControl<>nil) and Check(Parent.GetControlIndex(SideControl)) then
        exit(true);
    end;
    for i:=0 to Parent.ControlCount-1 do begin
      if Checked[i] then continue;
      SideControl:=Parent.Controls[i];
      if OppositeAnchor[Side] in SideControl.Anchors then begin
        if (SideControl.AnchorSide[OppositeAnchor[Side]].Control=AControl)
        and Check(i) then
          exit(true);
      end;
    end;
    Result:=false;
  end;

var
  i: Integer;
begin
  if (StartControl=nil) or (DestControl=nil)
  or (StartControl.Parent=nil)
  or (StartControl.Parent<>DestControl.Parent)
  or (StartControl=DestControl) then
    exit(false);
  Parent:=StartControl.Parent;
  SetLength(Checked,Parent.ControlCount);
  for i:=0 to length(Checked)-1 do Checked[i]:=false;
  Result:=Check(Parent.GetControlIndex(StartControl));
end;

procedure GetAnchorControlsRect(Control: TControl;
  out ARect: TAnchorControlsRect);
var
  a: TAnchorKind;
begin
  for a:=Low(TAnchorKind) to High(TAnchorKind) do
    ARect[a]:=Control.AnchorSide[a].Control;
end;

function GetEnclosingControlRect(ControlList: TFPlist; out
  ARect: TAnchorControlsRect): boolean;
{ ARect will be the minimum TAnchorControlsRect around the controls in the list
  returns true, if there is such a TAnchorControlsRect.

  The controls in ARect will either be the Parent or a TLazDockSplitter
}
var
  Parent: TWinControl;

  function ControlIsValidAnchor(Control: TControl; Side: TAnchorKind): boolean;
  var
    i: Integer;
  begin
    Result:=false;
    if (Control=ARect[Side]) then exit(true);// this allows Parent at the beginning

    if not (Control is TLazDockSplitter) then
      exit;// not a splitter
    if (TLazDockSplitter(Control).ResizeAnchor in [akLeft,akRight])
      <>(Side in [akLeft,akRight]) then
        exit;// wrong alignment
    if ControlList.IndexOf(Control)>=0 then
      exit;// is an inner control
    if ControlIsAnchoredIndirectly(Control,Side,ARect[Side]) then
      exit; // this anchor would be worse than the current maximum
    for i:=0 to ControlList.Count-1 do begin
      if not ControlIsAnchoredIndirectly(Control,Side,TControl(ControlList[i]))
      then begin
        // this anchor is not above (below, ...) the inner controls
        exit;
      end;
    end;
    Result:=true;
  end;

var
  TopIndex: Integer;
  TopControl: TControl;
  RightIndex: Integer;
  RightControl: TControl;
  BottomIndex: Integer;
  BottomControl: TControl;
  LeftIndex: Integer;
  LeftControl: TControl;
  Candidates: TFPList;
  i: Integer;
  a: TAnchorKind;
begin
  Result:=false;
  if (ControlList=nil) or (ControlList.Count=0) then exit;

  // get Parent
  Parent:=TControl(ControlList[0]).Parent;
  if Parent=nil then exit;
  for i:=0 to ControlList.Count-1 do
    if TControl(ControlList[i]).Parent<>Parent then exit;

  // set the default rect: the Parent
  Result:=true;
  for a:=Low(TAnchorKind) to High(TAnchorKind) do
    ARect[a]:=Parent;

  // find all possible Candidates
  Candidates:=TFPList.Create;
  Candidates.Add(Parent);
  for i:=0 to Parent.ControlCount-1 do
    if Parent.Controls[i] is TLazDockSplitter then
      Candidates.Add(Parent.Controls[i]);

  // now check every possible rectangle
  // Note: four loops seems to be dog slow, but the checks
  //       avoid most possibilities early
  for TopIndex:=0 to Candidates.Count-1 do begin
    TopControl:=TControl(Candidates[TopIndex]);
    if not ControlIsValidAnchor(TopControl,akTop) then continue;

    for RightIndex:=0 to Candidates.Count-1 do begin
      RightControl:=TControl(Candidates[RightIndex]);
      if (TopControl.AnchorSide[akRight].Control<>RightControl)
      and (RightControl.AnchorSide[akTop].Control<>TopControl) then
        continue; // not touching / not a corner
      if not ControlIsValidAnchor(RightControl,akRight) then continue;

      for BottomIndex:=0 to Candidates.Count-1 do begin
        BottomControl:=TControl(Candidates[BottomIndex]);
        if (RightControl.AnchorSide[akBottom].Control<>BottomControl)
        and (BottomControl.AnchorSide[akRight].Control<>RightControl) then
          continue; // not touching / not a corner
        if not ControlIsValidAnchor(BottomControl,akBottom) then continue;

        for LeftIndex:=0 to Candidates.Count-1 do begin
          LeftControl:=TControl(Candidates[LeftIndex]);
          if (BottomControl.AnchorSide[akLeft].Control<>LeftControl)
          and (LeftControl.AnchorSide[akBottom].Control<>BottomControl) then
            continue; // not touching / not a corner
          if (TopControl.AnchorSide[akLeft].Control<>LeftControl)
          and (LeftControl.AnchorSide[akTop].Control<>LeftControl) then
            continue; // not touching / not a corner
          if not ControlIsValidAnchor(LeftControl,akLeft) then continue;

          // found a better rectangle
          ARect[akLeft]  :=LeftControl;
          ARect[akRight] :=RightControl;
          ARect[akTop]   :=TopControl;
          ARect[akBottom]:=BottomControl;
        end;
      end;
    end;
  end;

  Candidates.Free;
end;

function GetEnclosedControls(const ARect: TAnchorControlsRect): TFPList;
{ return a list of all controls bounded by the anchors in ARect }
var
  Parent: TWinControl;

  procedure Fill(AControl: TControl);
  var
    a: TAnchorKind;
    SideControl: TControl;
    i: Integer;
  begin
    if AControl=nil then exit;
    if AControl=Parent then exit;// do not add Parent
    for a:=Low(TAnchorKind) to High(TAnchorKind) do
      if ARect[a]=AControl then exit;// do not add boundary

    if Result.IndexOf(AControl)>=0 then exit;// already added
    Result.Add(AControl);

    for a:=Low(TAnchorKind) to High(TAnchorKind) do
      Fill(AControl.AnchorSide[a].Control);
    for i:=0 to Parent.ControlCount-1 do begin
      SideControl:=Parent.Controls[i];
      for a:=Low(TAnchorKind) to High(TAnchorKind) do
        if SideControl.AnchorSide[a].Control=AControl then
          Fill(SideControl);
    end;
  end;

var
  i: Integer;
  AControl: TControl;
  LeftTopControl: TControl;
begin
  Result:=TFPList.Create;

  // find the Parent
  if (ARect[akLeft]=ARect[akRight]) and (ARect[akLeft] is TWinControl) then
    Parent:=TWinControl(ARect[akLeft])
  else
    Parent:=ARect[akLeft].Parent;

  // find the left, top most control
  for i:=0 to Parent.ControlCount-1 do begin
    AControl:=Parent.Controls[i];
    if (AControl.AnchorSide[akLeft].Control=ARect[akLeft])
    and (AControl.AnchorSide[akTop].Control=ARect[akTop]) then begin
      LeftTopControl:=AControl;
      break;
    end;
  end;
  if Result.Count=0 then exit;

  // use flood fill to find the rest
  Fill(LeftTopControl);
end;

{ TLazDockPages }

function TLazDockPages.GetActiveNotebookPageComponent: TLazDockPage;
begin
  Result:=TLazDockPage(inherited ActivePageComponent);
end;

function TLazDockPages.GetNoteBookPage(Index: Integer): TLazDockPage;
begin
  Result:=TLazDockPage(inherited Page[Index]);
end;

procedure TLazDockPages.SetActiveNotebookPageComponent(
  const AValue: TLazDockPage);
begin
  ActivePageComponent:=AValue;
end;

function TLazDockPages.GetFloatingDockSiteClass: TWinControlClass;
begin
  Result:=TLazDockForm;
end;

procedure TLazDockPages.Change;
begin
  inherited Change;
  TLazDockForm.UpdateMainControlInParents(Self);
end;

constructor TLazDockPages.Create(TheOwner: TComponent);
begin
  PageClass := TLazDockPage;
  inherited Create(TheOwner);
end;

{ TLazDockTree }

procedure TLazDockTree.UndockControlForDocking(AControl: TControl);
var
  AWinControl: TWinControl;
  Sibling: TControl;
  a: TAnchorKind;
  i: Integer;
begin
  DebugLn(['TLazDockTree.UndockControlForDocking AControl=',DbgSName(AControl),' AControl.Parent=',DbgSName(AControl.Parent)]);
  // undock AControl
  if AControl is TWinControl then
  begin
    AWinControl := TWinControl(AControl);
    if (AWinControl.DockManager<>nil) and (AWinControl.DockManager<>Self) then
    begin
      raise Exception.Create('TLazDockTree.UndockControlForDocking mixing docking managers is not supported');
    end;
  end;
  if AControl.Parent <> nil then
  begin
    AControl.Parent := nil;
  end;
  for i:=AControl.AnchoredControlCount - 1 downto 0 do
  begin
    Sibling := AControl.AnchoredControls[i];
    if (Sibling <> AControl.Parent) and (Sibling.Parent <> AControl) then
    begin
      for a := Low(TAnchorKind) to High(TAnchorKind) do
        if Sibling.AnchorSide[a].Control = AControl then
          Sibling.AnchorSide[a].Control := nil;
    end;
  end;
end;

function TLazDockTree.DefaultDockGrabberSize: Integer;
begin
  Result := {Abs(DockSite.Font.Height) + 4} 20;
end;

procedure TLazDockTree.BreakAnchors(Zone: TDockZone);
begin
  if Zone = nil then Exit;
  if (Zone.ChildControl <> nil) and (Zone.ChildControl <> DockSite) then
  begin
    Zone.ChildControl.AnchorSide[akLeft].Control := nil;
    Zone.ChildControl.AnchorSide[akTop].Control := nil;
    Zone.ChildControl.Anchors := [akLeft, akTop];
    Zone.ChildControl.BorderSpacing.Left := 0;
    Zone.ChildControl.BorderSpacing.Top := 0;
  end;
  BreakAnchors(Zone.FirstChild);
  BreakAnchors(Zone.NextSibling);
end;

procedure TLazDockTree.PaintDockFrame(ACanvas: TCanvas; AControl: TControl; const ARect: TRect);
var
  Pt: TPoint;
begin
  GetCursorPos(Pt);
  Pt := DockSite.ScreenToClient(Pt);
  TDockHeader.Draw(ACanvas, DockSite.GetDockCaption(AControl), FDockHeaderImages,
    AControl.DockOrientation, ARect, Pt);
end;

procedure TLazDockTree.CreateDockLayoutHelperControls(Zone: TLazDockZone);
var
  ParentPages: TLazDockPages;
  ZoneIndex: LongInt;
begin
  if Zone = nil then
    Exit;

  // create needed TLazDockSplitter
  if (Zone.Parent <> nil) and
     (Zone.Parent.Orientation in [doVertical,doHorizontal]) and
     (Zone.PrevSibling <> nil) then
  begin
    // a zone with a side sibling -> needs a TLazDockSplitter
    if Zone.Splitter = nil then
    begin
      Zone.Splitter := TLazDockSplitter.Create(nil);
      Zone.Splitter.Align := alNone;
    end;
  end
  else
  if Zone.Splitter <> nil then
  begin
    // zone no longer needs the splitter
    Zone.Splitter.Free;
    Zone.Splitter := nil;
  end;

  // create needed TLazDockPages
  if (Zone.Orientation = doPages) then
  begin
    // a zone of pages -> needs a TLazDockPages
    if Zone.FirstChild = nil then
      RaiseGDBException('TLazDockTree.CreateDockLayoutHelperControls Inconsistency: doPages without children');
    if (Zone.Pages = nil) then
      Zone.Pages:=TLazDockPages.Create(nil);
  end
  else
  if Zone.Pages<>nil then
  begin
    // zone no longer needs the pages
    Zone.Pages.Free;
    Zone.Pages := nil;
  end;

  // create needed TLazDockPage
  if (Zone.Parent<>nil) and
     (Zone.Parent.Orientation = doPages) then
  begin
    // a zone as page -> needs a TLazDockPage
    if (Zone.Page = nil) then
    begin
      ParentPages := TLazDockZone(Zone.Parent).Pages;
      ZoneIndex := Zone.GetIndex;
      ParentPages.Pages.Insert(ZoneIndex,Zone.GetCaption);
      Zone.Page := ParentPages.Page[ZoneIndex];
    end;
  end
  else
  if Zone.Page <> nil then
  begin
    // zone no longer needs the page
    Zone.Page.Free;
    Zone.Page := nil;
  end;

  // create controls for children and siblings
  CreateDockLayoutHelperControls(Zone.FirstChild as TLazDockZone);
  CreateDockLayoutHelperControls(Zone.NextSibling as TLazDockZone);
end;

procedure TLazDockTree.ResetSizes(Zone: TLazDockZone);
var
  NewSize, NewPos: Integer;
  Child: TLazDockZone;
begin
  if Zone = nil then
    Exit;

  // split available size between children
  if (Zone.Orientation in [doHorizontal, doVertical]) and
     (Zone.VisibleChildCount > 0) then
  begin
    NewSize := Zone.LimitSize div Zone.VisibleChildCount;
    NewPos := Zone.LimitBegin;
    Child := Zone.FirstChild as TLazDockZone;
    while Child <> nil do
    begin
      if Child.Visible then
      begin
        case Zone.Orientation of
          doHorizontal:
            begin
              Child.Top := NewPos;
              Child.Height := NewSize;
            end;
          doVertical:
            begin
              Child.Left := NewPos;
              Child.Width := NewSize;
            end;
        end;
        ResetSizes(Child);
        inc(NewPos, NewSize);
      end;
      Child := Child.NextSibling as TLazDockZone;
    end;
  end;
end;

procedure TLazDockTree.AdjustDockRect(AControl: TControl; var ARect: TRect);
begin
  // offset one of the borders of control rect in order to get space for frame
  case AControl.DockOrientation of
    doHorizontal:
      Inc(ARect.Top, DefaultDockGrabberSize);
    doVertical:
      Inc(ARect.Left, DefaultDockGrabberSize);
  end;
end;

procedure TLazDockTree.AnchorDockLayout(Zone: TLazDockZone);
// setup all anchors between all docked controls and helper controls
const
  SplitterWidth = 5;
  SplitterHeight = 5;
var
  AnchorControls: array[TAnchorKind] of TControl;
  a: TAnchorKind;
  SplitterSide: TAnchorKind;
  CurControl: TControl;
  NewSplitterAnchors: TAnchors;
  NewAnchors: TAnchors;
begin
  if Zone = nil then
    Exit;

  if Zone.Pages <> nil then
    CurControl := Zone.Pages
  else
    CurControl := Zone.ChildControl;
  //DebugLn(['TLazDockTree.AnchorDockLayout CurControl=',DbgSName(CurControl),' DockSite=',DbgSName(DockSite)]);
  if ((CurControl <> nil) and (CurControl <> DockSite)) or (Zone.Splitter <> nil) then
  begin
    // get outside anchor controls
    NewAnchors := [akLeft, akRight, akTop, akBottom];
    for a := Low(TAnchorKind) to High(TAnchorKind) do
      AnchorControls[a] := GetAnchorControl(Zone, a, true);

    // anchor splitter
    if (Zone.Splitter <> nil) then
    begin
      if Zone.Parent.Orientation = doHorizontal then
      begin
        SplitterSide := akTop;
        NewSplitterAnchors := [akLeft, akRight];
        Zone.Splitter.AnchorSide[akLeft].Side := asrTop;
        Zone.Splitter.AnchorSide[akRight].Side := asrBottom;
        Zone.Splitter.Height := SplitterHeight;
        if Zone.PrevSibling <> nil then
          Zone.Splitter.Top := (Zone.PrevSibling.Top + Zone.PrevSibling.Height) - DefaultDockGrabberSize;
        Zone.Splitter.ResizeAnchor := akBottom;
      end
      else
      begin
        SplitterSide := akLeft;
        NewSplitterAnchors := [akTop, akBottom];
        Zone.Splitter.AnchorSide[akTop].Side := asrTop;
        Zone.Splitter.AnchorSide[akBottom].Side := asrBottom;
        Zone.Splitter.Width := SplitterWidth;
        if Zone.PrevSibling <> nil then
          Zone.Splitter.Left := (Zone.PrevSibling.Left + Zone.PrevSibling.Width) - DefaultDockGrabberSize;
        Zone.Splitter.ResizeAnchor := akRight;
      end;
      // IMPORTANT: first set the AnchorSide, then set the Anchors
      for a := Low(TAnchorKind) to High(TAnchorKind) do
      begin
        if a in NewSplitterAnchors then
          Zone.Splitter.AnchorSide[a].Control := AnchorControls[a]
        else
          Zone.Splitter.AnchorSide[a].Control := nil;
      end;
      Zone.Splitter.Anchors := NewSplitterAnchors;
      Zone.Splitter.Parent := Zone.GetParentControl;
      AnchorControls[SplitterSide] := Zone.Splitter;
    end;

    if (CurControl <> nil) then
    begin
      // anchor pages
      // IMPORTANT: first set the AnchorSide, then set the Anchors
      //DebugLn(['TLazDockTree.AnchorDockLayout CurControl.Parent=',DbgSName(CurControl.Parent),' ',CurControl.Visible]);
      for a := Low(TAnchorKind) to High(TAnchorKind) do
      begin
        if AnchorControls[a] <> CurControl then
          CurControl.AnchorSide[a].Control := AnchorControls[a];
        if (AnchorControls[a] <> nil) and (AnchorControls[a].Parent = CurControl.Parent) then
          CurControl.AnchorSide[a].Side := DefaultSideForAnchorKind[a]
        else
          CurControl.AnchorSide[a].Side := DefaultSideForAnchorKind[OppositeAnchor[a]];
      end;
      CurControl.Anchors := NewAnchors;
      // set space for header
      case CurControl.DockOrientation of
        doHorizontal: CurControl.BorderSpacing.Top := DefaultDockGrabberSize;
        doVertical: CurControl.BorderSpacing.Left := DefaultDockGrabberSize;
      end;
    end;
  end;

  // anchor controls for children and siblings
  AnchorDockLayout(Zone.FirstChild as TLazDockZone);
  AnchorDockLayout(Zone.NextSibling as TLazDockZone);
end;

constructor TLazDockTree.Create(TheDockSite: TWinControl);
begin
  FillChar(FMouseState, SizeOf(FMouseState), 0);
  TDockHeader.CreateDockHeaderImages(FDockHeaderImages);
  SetDockZoneClass(TLazDockZone);
  if TheDockSite = nil then
  begin
    TheDockSite := TLazDockForm.Create(nil);
    TheDockSite.DockManager := Self;
    FAutoFreeDockSite := True;
  end;
  inherited Create(TheDockSite);
end;

destructor TLazDockTree.Destroy;
begin
  if FAutoFreeDockSite then
  begin
    if DockSite.DockManager = Self then
      DockSite.DockManager := nil;
    DockSite.Free;
    DockSite := nil;
  end;
  TDockHeader.DestroyDockHeaderImages(FDockHeaderImages);
  inherited Destroy;
end;

procedure TLazDockTree.InsertControl(AControl: TControl; InsertAt: TAlign;
  DropControl: TControl);
{ undocks AControl and docks it into the tree
  It creates a new TDockZone for AControl and inserts it as a new leaf.
  It automatically changes the tree, so that the parent of the new TDockZone
  will have the Orientation for InsertAt.

  Example 1:

    A newly created TLazDockTree has only a DockSite (TLazDockForm) and a single
    TDockZone - the RootZone, which has as ChildControl the DockSite.

    Visual:
      +-DockSite--+
      |           |
      +-----------+
    Tree of TDockZone:
      RootZone (DockSite,doNoOrient)


  Inserting the first control:  InsertControl(Form1,alLeft,nil);
    Visual:
      +-DockSite---+
      |+--Form1---+|
      ||          ||
      |+----------+|
      +------------+
    Tree of TDockZone:
      RootZone (DockSite,doHorizontal)
       +-Zone2 (Form1,doNoOrient)


  Dock Form2 right of Form1:  InsertControl(Form2,alLeft,Form1);
    Visual:
      +-DockSite----------+
      |+-Form1-+|+-Form2-+|
      ||        ||       ||
      |+-------+|+-------+|
      +-------------------+
    Tree of TDockZone:
      RootZone (DockSite,doHorizontal)
       +-Zone2 (Form1,doNoOrient)
       +-Zone3 (Form2,doNoOrient)
}

  procedure PrepareControlForResize(AControl: TControl); inline;
  var
    a: TAnchorKind;
  begin
    AControl.Align := alNone;
    AControl.Anchors := [akLeft, akTop];
    for a := Low(TAnchorKind) to High(TAnchorKind) do
      AControl.AnchorSide[a].Control := nil;
    AControl.AutoSize := False;
  end;

var
  CtlZone, DropZone, OldParentZone, NewParentZone: TDockZone;
  NewZone: TLazDockZone;
  NewOrientation: TDockOrientation;
  NeedNewParentZone: Boolean;
  NewBounds: TRect;
begin
  CtlZone := RootZone.FindZone(AControl);
  if CtlZone <> nil then
    RemoveControl(AControl);

  if (DropControl = nil) or (DropControl = AControl) then
    DropControl := DockSite;

  DropZone := RootZone.FindZone(DropControl);
  if DropZone = nil then
    raise Exception.Create('TLazDockTree.InsertControl DropControl is not part of this TDockTree');

  NewOrientation := DockAlignOrientations[InsertAt];

  // undock
  UndockControlForDocking(AControl);

  // dock
  // create a new zone for AControl
  NewZone := DockZoneClass.Create(Self,AControl) as TLazDockZone;

  // insert new zone into tree
  if (DropZone = RootZone) and (RootZone.FirstChild = nil) then
  begin
    // this is the first child
    debugln('TLazDockTree.InsertControl First Child');
    //RootZone.Orientation := NewOrientation;
    RootZone.AddAsFirstChild(NewZone);
    AControl.DockOrientation := NewOrientation;
    if not AControl.Visible then
      DockSite.Visible := False;

    NewBounds := DockSite.ClientRect;
    AdjustDockRect(AControl, NewBounds);
    PrepareControlForResize(AControl);

    AControl.BoundsRect := NewBounds;
    AControl.Parent := DockSite;

    if AControl.Visible then
      DockSite.Visible := True;
  end else
  begin
    // there are already other children

    // optimize DropZone
    if (DropZone.ChildCount>0) and
       (NewOrientation in [doHorizontal,doVertical]) and
       (DropZone.Orientation in [NewOrientation, doNoOrient]) then
    begin
      // docking on a side of an inner node is the same as docking to a side of
      // a child
      if InsertAt in [alLeft,alTop] then
        DropZone := DropZone.FirstChild
      else
        DropZone := DropZone.GetLastChild;
    end;

    // insert a new Parent Zone if needed
    NeedNewParentZone := True;
    if (DropZone.Parent <> nil) then
    begin
      if (DropZone.Parent.Orientation = doNoOrient) then
        NeedNewParentZone := False;
      if (DropZone.Parent.Orientation = NewOrientation) then
        NeedNewParentZone := False;
    end;
    if NeedNewParentZone then
    begin
      // insert a new zone between current DropZone.Parent and DropZone
      // this new zone will become the new DropZone.Parent
      OldParentZone := DropZone.Parent;
      NewParentZone := DockZoneClass.Create(Self, nil);
      if OldParentZone <> nil then
        OldParentZone.ReplaceChild(DropZone, NewParentZone);
      NewParentZone.AddAsFirstChild(DropZone);
      if RootZone = DropZone then
        FRootZone := NewParentZone;
    end;

    if DropZone.Parent = nil then
      RaiseGDBException('TLazDockTree.InsertControl Inconsistency DropZone.Parent=nil');
    // adjust Orientation in tree
    if DropZone.Parent.Orientation = doNoOrient then
    begin
      // child control already had orientation but now we moved it to parent
      // which can take another orientation => change child control orientation
      DropZone.Parent.Orientation := NewOrientation;
      if (DropZone.Parent.ChildCount = 1) and (DropZone.Parent.FirstChild.ChildControl <> nil) then
        DropZone.Parent.FirstChild.ChildControl.DockOrientation := NewOrientation;
    end;
    if DropZone.Parent.Orientation <> NewOrientation then
      RaiseGDBException('TLazDockTree.InsertControl Inconsistency DropZone.Orientation<>NewOrientation');

    // insert new node
    //DoDi: should insert relative to dropzone, not at begin/end of the parent zone
    DropZone.AddSibling(NewZone, InsertAt);

    // add AControl to DockSite
    PrepareControlForResize(AControl);
    AControl.DockOrientation := NewOrientation;
    AControl.Parent := NewZone.GetParentControl;
  end;

  // Build dock layout (anchors, splitters, pages)
  if NewZone.Parent <> nil then
    BuildDockLayout(NewZone.Parent as TLazDockZone)
  else
    BuildDockLayout(RootZone as TLazDockZone);
end;

procedure TLazDockTree.RemoveControl(AControl: TControl);
var
  RemoveZone, ParentZone: TLazDockZone;
begin
  RemoveZone := RootZone.FindZone(AControl) as TLazDockZone;

  // no such control => exit
  if RemoveZone = nil then
    Exit;

  // has children
  if (RemoveZone.ChildCount > 0) then
    raise Exception.Create('TLazDockTree.RemoveControl RemoveZone.ChildCount > 0');

  // destroy child zone and all parents if they does not contain anything else
  while (RemoveZone <> RootZone) and
        (RemoveZone.ChildCount = 0) do
  begin
    ParentZone := RemoveZone.Parent as TLazDockZone;
    RemoveZone.FreeSubComponents;
    BreakAnchors(RemoveZone);
    if ParentZone <> nil then
      ParentZone.Remove(RemoveZone);
    RemoveZone.Free;
    // try with ParentZone now
    RemoveZone := ParentZone;
  end;

  // reset orientation
  if (RemoveZone.ChildCount = 1) and (RemoveZone.Orientation in [doHorizontal, doVertical]) then
    RemoveZone.Orientation := doNoOrient;

  // Build dock layout (anchors, splitters, pages)
  if (RemoveZone.Parent <> nil) then
    BuildDockLayout(RemoveZone.Parent as TLazDockZone)
  else
    BuildDockLayout(RootZone as TLazDockZone);
end;

procedure TLazDockTree.BuildDockLayout(Zone: TLazDockZone);
begin
  if DockSite <> nil then
    DockSite.DisableAlign;
  try
    BreakAnchors(Zone);
    CreateDockLayoutHelperControls(Zone);
    ResetSizes(Zone);
    AnchorDockLayout(Zone);
  finally
    if DockSite <> nil then
    begin
      DockSite.EnableAlign;
      DockSite.Invalidate;
    end;
  end;
end;

procedure TLazDockTree.FindBorderControls(Zone: TLazDockZone; Side: TAnchorKind;
  var List: TFPList);
begin
  if List=nil then List:=TFPList.Create;
  if Zone=nil then exit;

  if (Zone.Splitter<>nil) and (Zone.Parent<>nil)
  and (Zone.Orientation=doVertical) then begin
    // this splitter is leftmost, topmost, bottommost
    if Side in [akLeft,akTop,akBottom] then
      List.Add(Zone.Splitter);
    if Side=akLeft then begin
      // the splitter fills the whole left side => no more controls
      exit;
    end;
  end;
  if (Zone.Splitter<>nil) and (Zone.Parent<>nil)
  and (Zone.Orientation=doHorizontal) then begin
    // this splitter is topmost, leftmost, rightmost
    if Side in [akTop,akLeft,akRight] then
      List.Add(Zone.Splitter);
    if Side=akTop then begin
      // the splitter fills the whole top side => no more controls
      exit;
    end;
  end;
  if Zone.ChildControl<>nil then begin
    // the ChildControl fills the whole zone (except for the splitter)
    List.Add(Zone.ChildControl);
    exit;
  end;
  if Zone.Pages<>nil then begin
    // the pages fills the whole zone (except for the splitter)
    List.Add(Zone.Pages);
    exit;
  end;

  // go recursively through all child zones
  if (Zone.Parent<>nil) and (Zone.Orientation in [doVertical,doHorizontal])
  and (Zone.FirstChild<>nil) then
  begin
    if Side in [akLeft,akTop] then
      FindBorderControls(Zone.FirstChild as TLazDockZone,Side,List)
    else
      FindBorderControls(Zone.GetLastChild as TLazDockZone,Side,List);
  end;
end;

function TLazDockTree.FindBorderControl(Zone: TLazDockZone; Side: TAnchorKind
  ): TControl;
var
  List: TFPList;
begin
  Result:=nil;
  if Zone=nil then exit;
  List:=nil;
  FindBorderControls(Zone,Side,List);
  if (List=nil) or (List.Count=0) then
    Result:=DockSite
  else
    Result:=TControl(List[0]);
  List.Free;
end;

function TLazDockTree.GetAnchorControl(Zone: TLazDockZone; Side: TAnchorKind;
  OutSide: boolean): TControl;
// find a control to anchor the Zone's Side
begin
  if Zone = nil then
  begin
    Result := DockSite;
    exit;
  end;

  if not OutSide then
  begin
    // also check the Splitter and the Page
    if (Side = akLeft) and (Zone.Parent <> nil) and
       (Zone.Parent.Orientation = doVertical) and (Zone.Splitter<>nil) then
    begin
      Result := Zone.Splitter;
      exit;
    end;
    if (Side = akTop) and (Zone.Parent<>nil) and
       (Zone.Parent.Orientation=doHorizontal) and (Zone.Splitter<>nil) then
    begin
      Result := Zone.Splitter;
      exit;
    end;
    if (Zone.Page <> nil) then
    begin
      Result := Zone.Page;
      exit;
    end;
  end;

  // search the neighbour zones:
  Result := DockSite;
  if (Zone.Parent = nil) then
    Exit;

  case Zone.Parent.Orientation of
    doHorizontal:
      if (Side=akTop) and (Zone.PrevSibling<>nil) then
        Result:=FindBorderControl(Zone.PrevSibling as TLazDockZone,akBottom)
      else if (Side=akBottom) and (Zone.NextSibling<>nil) then
        Result:=FindBorderControl(Zone.NextSibling as TLazDockZone,akTop)
      else
        Result:=GetAnchorControl(Zone.Parent as TLazDockZone,Side,false);
    doVertical:
      if (Side=akLeft) and (Zone.PrevSibling<>nil) then
        Result:=FindBorderControl(Zone.PrevSibling as TLazDockZone,akRight)
      else if (Side=akRight) and (Zone.NextSibling<>nil) then
        Result:=FindBorderControl(Zone.NextSibling as TLazDockZone,akLeft)
      else
        Result:=GetAnchorControl(Zone.Parent as TLazDockZone,Side,false);
    doPages:
      Result:=GetAnchorControl(Zone.Parent as TLazDockZone,Side,false);
  end;
end;

procedure TLazDockTree.PaintSite(DC: HDC);
var
  ACanvas: TCanvas;
  ARect: TRect;
  i: integer;
begin
  // paint bounds for each control and close button
  if DockSite.ControlCount > 0 then
  begin
    ACanvas := TCanvas.Create;
    ACanvas.Handle := DC;
    try
      for i := 0 to DockSite.ControlCount - 1 do
      begin
        if (DockSite.Controls[i].HostDockSite = DockSite) and
           (DockSite.Controls[i].Visible) then
        begin
          ARect := DockSite.Controls[i].BoundsRect;
          case DockSite.Controls[i].DockOrientation of
            doHorizontal:
              begin
                ARect.Bottom := ARect.Top;
                Dec(ARect.Top, DefaultDockGrabberSize);
              end;
            doVertical:
              begin
                ARect.Right := ARect.Left;
                Dec(ARect.Left, DefaultDockGrabberSize);
              end;
          end;
          PaintDockFrame(ACanvas, DockSite.Controls[i], ARect);
        end;
      end;
    finally
      ACanvas.Free;
    end;
  end;
end;

procedure TLazDockTree.MessageHandler(Sender: TControl; var Message: TLMessage);

  procedure CheckNeedRedraw(AControl: TControl; ARect: TRect; APart: TLazDockHeaderPart);
  var
    NewMouseState: TDockHeaderMouseState;
  begin
    if AControl = nil then
      FillChar(ARect, SizeOf(ARect), 0)
    else
      ARect := TDockHeader.GetRectOfPart(ARect, AControl.DockOrientation, APart);
    // we cannot directly redraw this part since we should paint only in paint events
    FillChar(NewMouseState, SizeOf(NewMouseState), 0);
    NewMouseState.Rect := ARect;
    NewMouseState.IsMouseDown := (GetKeyState(VK_LBUTTON) and $80) <> 0;
    if not CompareMem(@FMouseState, @NewMouseState, SizeOf(NewMouseState)) then
    begin
      if not CompareRect(@FMouseState.Rect, @NewMouseState.Rect) then
        InvalidateRect(DockSite.Handle, @FMouseState.Rect, False);
      FMouseState := NewMouseState;
      InvalidateRect(DockSite.Handle, @NewMouseState.Rect, False);
    end;
  end;

  function GetControlHeaderRect(AControl: TControl; out ARect: TRect): Boolean;
  begin
    Result := True;
    ARect := AControl.BoundsRect;
    case AControl.DockOrientation of
      doHorizontal:
        begin
          ARect.Bottom := ARect.Top;
          Dec(ARect.Top, DefaultDockGrabberSize);
        end;
      doVertical:
        begin
          ARect.Right := ARect.Left;
          Dec(ARect.Left, DefaultDockGrabberSize);
        end;
      else
        Result := False;
    end;
  end;

  function FindControlAndPart(MouseMsg: TLMMouse; out ARect: TRect; out APart: TLazDockHeaderPart): TControl;
  var
    i: integer;
    Pt: TPoint;
  begin
    Pt := SmallPointToPoint(MouseMsg.Pos);
    for i := 0 to DockSite.ControlCount - 1 do
    begin
      if DockSite.Controls[i].HostDockSite = DockSite then
      begin
        if not GetControlHeaderRect(DockSite.Controls[i], ARect) then
          Continue;
        if not PtInRect(ARect, Pt) then
          Continue;
        // we have control here
        Result := DockSite.Controls[i];
        APart := TDockHeader.FindPart(ARect, Pt, DockSite.Controls[i].DockOrientation);
        Exit;
      end;
    end;
    Result := nil;
  end;

var
  ARect: TRect;
  Part: TLazDockHeaderPart;
  Control: TControl;
  AZone: TLazDockZone;
begin
  case Message.msg of
    LM_LBUTTONUP:
      begin
        Control := FindControlAndPart(TLMMouse(Message), ARect, Part);
        CheckNeedRedraw(Control, ARect, Part);
        TDockHeader.PerformMouseUp(Control, Part);
      end;
    LM_LBUTTONDOWN:
      begin
        Control := FindControlAndPart(TLMMouse(Message), ARect, Part);
        CheckNeedRedraw(Control, ARect, Part);
        TDockHeader.PerformMouseDown(Control, Part);
      end;
    LM_MOUSEMOVE:
      begin
        Control := FindControlAndPart(TLMMouse(Message), ARect, Part);
        CheckNeedRedraw(Control, ARect, Part);
      end;
    CM_MOUSELEAVE:
      CheckNeedRedraw(nil, Rect(0,0,0,0), ldhpAll);
    CM_TEXTCHANGED:
      begin
        if GetControlHeaderRect(Sender, ARect) then
        begin
          ARect := TDockHeader.GetRectOfPart(ARect, Sender.DockOrientation, ldhpCaption);
          InvalidateRect(DockSite.Handle, @ARect, False);
        end;
      end;
    CM_VISIBLECHANGED:
      begin
        if not (csDestroying in Sender.ComponentState) then
        begin
          AZone := RootZone.FindZone(Sender) as TLazDockZone;
          if AZone <> nil then
            BuildDockLayout(TLazDockZone(AZone.Parent));
        end;
      end;
    LM_SIZE, LM_MOVE:
      begin
        if GetControlHeaderRect(Sender, ARect) then
          InvalidateRect(DockSite.Handle, @ARect, False);
      end;
  end
end;

procedure TLazDockTree.DumpLayout(FileName: String);
var
  Stream: TStream;

  procedure WriteLn(S: String);
  begin
    S := S + #$D#$A;
    Stream.Write(S[1], Length(S));
  end;

  procedure WriteHeader;
  begin
    WriteLn('<HTML>');
    WriteLn('<HEAD>');
    WriteLn('<TITLE>Dock Layout</TITLE>');
    WriteLn('<META content="text/html; charset=utf-8" http-equiv=Content-Type>');
    WriteLn('</HEAD>');
    WriteLn('<BODY>');
  end;

  procedure WriteFooter;
  begin
    WriteLn('</BODY>');
    WriteLn('</HTML>');
  end;

  procedure DumpAnchors(Title: String; AControl: TControl);
  var
    a: TAnchorKind;
    S, Name: String;
  begin
    S := Title;
    if AControl.Anchors <> [] then
    begin
      S := S + '<UL>';
      for a := Low(TAnchorKind) to High(TAnchorKind) do
        if a in AControl.Anchors then
        begin
          Name := DbgsName(AControl.AnchorSide[a].Control);
          if (AControl.AnchorSide[a].Control <> nil) and (AControl.AnchorSide[a].Control.Name = '') then
            Name := dbgs(AControl.AnchorSide[a].Control) + Name;
          S := S + '<LI><b>' + GetEnumName(TypeInfo(TAnchorKind), Ord(a)) + '</b> = ' +
             Name + ' (' +
             GetEnumName(TypeInfo(TAnchorSideReference), Ord(AControl.AnchorSide[a].Side)) +
             ')' + '</LI>';
        end;
      S := S + '</UL>';
    end
    else
      S := S + '[]';
    WriteLn(S);
  end;

  procedure DumpZone(Zone: TDockZone);
  const
    DumpStr = 'Zone: Orientation = <b>%s</b>, ChildCount = <b>%d</b>, ChildControl = <b>%s</b>, %s, Splitter = <b>%s</b>';
    StrOrientation: array[TDockOrientation] of String =
    (
      'doNoOrient',
      'doHorizontal',
      'doVertical',
      'doPages'
    );
  begin
    WriteLn(Format(DumpStr, [StrOrientation[Zone.Orientation], Zone.ChildCount,
      DbgSName(Zone.ChildControl), DbgS(Bounds(Zone.Left, Zone.Top, Zone.Width, Zone.Height)),
      dbgs(TLazDockZone(Zone).Splitter)]));
    if TLazDockZone(Zone).Splitter <> nil then
      DumpAnchors('<br>Splitter anchors: ', TLazDockZone(Zone).Splitter);
    if Zone.ChildControl <> nil then
      DumpAnchors('<br>ChildControl anchors: ', Zone.ChildControl);
  end;

  procedure WriteZone(Zone: TDockZone);
  begin
    if Zone <> nil then
    begin
      WriteLn('<LI>');
      DumpZone(Zone);
      if Zone.ChildCount > 0 then
      begin
        WriteLn('<OL>');
        WriteZone(Zone.FirstChild);
        WriteLn('</OL>');
      end;
      WriteLn('</LI>');
      WriteZone(Zone.NextSibling);
    end;
  end;

  procedure WriteLayout;
  begin
    WriteLn('<OL>');
    WriteZone(RootZone);
    WriteLn('</OL>');
  end;

begin
  Stream := TFileStream.Create(FileName, fmCreate);
  try
    WriteHeader;
    WriteLayout;
    WriteFooter;
  finally
    Stream.Free;
  end;
end;

{ TLazDockZone }

destructor TLazDockZone.Destroy;
begin
  FreeSubComponents;
  inherited Destroy;
end;

procedure TLazDockZone.FreeSubComponents;
begin
  FreeAndNil(FSplitter);
  FreeAndNil(FPage);
  FreeAndNil(FPages);
end;

function TLazDockZone.GetCaption: string;
begin
  if ChildControl<>nil then
    Result:=ChildControl.Caption
  else
    Result:=IntToStr(GetIndex);
end;

function TLazDockZone.GetParentControl: TWinControl;
var
  Zone: TDockZone;
begin
  Result := nil;
  Zone := Parent;
  while Zone <> nil do
  begin
    if Zone.Orientation = doPages then
      Exit((Zone as TLazDockZone).Pages);

    if (Zone.Parent = nil) then
    begin
      if Zone.ChildControl is TWinControl then
        Result := TWinControl(Zone.ChildControl)
      else
      if Zone = Tree.RootZone then
        Result := Tree.DockSite;
      Exit;
    end;
    Zone := Zone.Parent;
  end;
end;

{ TCustomAnchoredDockManager }

procedure TCustomAnchoredDockManager.DeleteSideSplitter(Splitter: TLazDockSplitter;
  Side: TAnchorKind; NewAnchorControl: TControl);
var
  SplitterParent: TWinControl;
  i: Integer;
  CurControl: TControl;
  NewSideRef: TAnchorSideReference;
begin
  //DebugLn('TCustomAnchoredDockManager.DeleteSideSplitter Splitter=',DbgSName(Splitter),' Side=',dbgs(Side),' NewAnchorControl=',DbgSName(NewAnchorControl));
  SplitterParent:=Splitter.Parent;
  SplitterParent.DisableAlign;
  try
    for i:=0 to SplitterParent.ControlCount-1 do begin
      CurControl:=SplitterParent.Controls[i];
      if CurControl.AnchorSide[Side].Control=Splitter then begin
        CurControl.AnchorSide[Side].Control:=NewAnchorControl;
        if NewAnchorControl=CurControl.Parent then
          NewSideRef:=DefaultSideForAnchorKind[OppositeAnchor[Side]]
        else
          NewSideRef:=DefaultSideForAnchorKind[Side];
        CurControl.AnchorSide[Side].Side:=NewSideRef;
        //DebugLn('TCustomAnchoredDockManager.DeleteSideSplitter Anchor ',DbgSName(CurControl),'(',dbgs(Side),') to ',DbgSName(NewAnchorControl));
      end;
    end;
    Splitter.Free;
  finally
    SplitterParent.EnableAlign;
  end;
end;

procedure TCustomAnchoredDockManager.CombineSpiralSplitterPair(Splitter1,
  Splitter2: TLazDockSplitter);
{  - Anchor all controls anchored to Splitter2 to Splitter1
   - extend Splitter1
   - delete Splitter2

   Example:

   Four spiral splitters:

     Before:
              |
           A  |
     ---------|
       | +--+ |  C
     B | |  | |
       | +--+ |
       | ----------
       |   D

     The left and right splitter will be combined to one.

     After:
              |
           A  |
       -------|
              |  C
            B |
              |
              |------
              |   D
  }

  procedure MoveAnchorSide(AControl: TControl; Side: TAnchorKind);
  begin
    if AControl.AnchorSide[Side].Control=Splitter2 then
      AControl.AnchorSide[Side].Control:=Splitter1;
  end;

  procedure EnlargeSplitter(Side: TAnchorKind);
  begin
    if GetAnchorDepth(Splitter1,Side)>GetAnchorDepth(Splitter2,Side) then
      Splitter1.AnchorSide[Side].Assign(Splitter2.AnchorSide[Side]);
  end;

var
  LeftRightSplitter: boolean;
  ParentControl: TWinControl;
  i: Integer;
  CurControl: TControl;
begin
  DebugLn('TCustomAnchoredDockManager.CombineSpiralSplitterPair Splitter1=',DbgSName(Splitter1),dbgs(Splitter1.BoundsRect),' Splitter2=',DbgSName(Splitter2),dbgs(Splitter2.BoundsRect));
  // check splitters have the same Parent
  ParentControl:=Splitter1.Parent;
  if (ParentControl=nil) then
    RaiseGDBException('TCustomAnchoredDockManager.CombineSpiralSplitterPair Inconsistency: Parent=nil');
  if (ParentControl<>Splitter2.Parent) then
    RaiseGDBException('TCustomAnchoredDockManager.CombineSpiralSplitterPair Inconsistency: Splitters not siblings');
  // check splitters have same orientation
  LeftRightSplitter:=(Splitter1.ResizeAnchor in [akLeft,akRight]);
  if LeftRightSplitter<>(Splitter2.ResizeAnchor in [akLeft,akRight]) then
    RaiseGDBException('TCustomAnchoredDockManager.CombineSpiralSplitterPair Inconsistency: different orientation');

  ParentControl.DisableAlign;
  try
    // move incident anchors from Splitter2 to Splitter1
    for i:=0 to ParentControl.ControlCount-1 do begin
      CurControl:=ParentControl.Controls[i];
      if CurControl=Splitter1 then continue;
      if CurControl=Splitter2 then continue;
      if LeftRightSplitter then begin
        MoveAnchorSide(CurControl,akLeft);
        MoveAnchorSide(CurControl,akRight);
      end else begin
        MoveAnchorSide(CurControl,akTop);
        MoveAnchorSide(CurControl,akBottom);
      end;
    end;

    // enlarge Splitter1
    if LeftRightSplitter then begin
      // enlarge Splitter1 to top and bottom
      EnlargeSplitter(akTop);
      EnlargeSplitter(akBottom);
    end else begin
      // enlarge Splitter1 to left and right
      EnlargeSplitter(akLeft);
      EnlargeSplitter(akRight);
    end;

    // delete Splitter2
    Splitter2.Free;
  finally
    ParentControl.EnableAlign;
  end;
end;

procedure TCustomAnchoredDockManager.DeletePage(Page: TLazDockPage);
var
  Pages: TLazDockPages;
begin
  DebugLn('TCustomAnchoredDockManager.DeletePage Page=',DbgSName(Page));
  Pages:=Page.PageControl;
  Page.Free;
  if Pages.PageCount=0 then
    DeletePages(Pages);
end;

procedure TCustomAnchoredDockManager.DeletePages(Pages: TLazDockPages);
begin
  DebugLn('TCustomAnchoredDockManager.DeletePages Pages=',DbgSName(Pages));
  if Pages.Parent<>nil then
    UndockControl(Pages,false);
  Pages.Free;
end;

procedure TCustomAnchoredDockManager.DeleteDockForm(ADockForm: TLazDockForm);
begin
  DebugLn('TCustomAnchoredDockManager.DeleteDockForm ADockForm=',DbgSName(ADockForm));
  if ADockForm.Parent<>nil then
    UndockControl(ADockForm,false);
  ADockForm.DockManager:=nil;
  ADockForm.UseDockManager:=false;
  Application.ReleaseComponent(ADockForm);
end;

function TCustomAnchoredDockManager.GetAnchorDepth(AControl: TControl;
  Side: TAnchorKind): Integer;
var
  NewControl: TControl;
begin
  Result:=0;
  while (AControl<>nil) do begin
    inc(Result);
    if not (Side in AControl.Anchors) then break; // loose end
    NewControl:=AControl.AnchorSide[Side].Control;
    if NewControl=nil then break; // loose end
    if NewControl.Parent<>AControl.Parent then break; // parent end
    if Result>AControl.Parent.ControlCount then break; // circle
    AControl:=NewControl;
  end;
end;

function TCustomAnchoredDockManager.GetPreferredTitlePosition(AWidth,
  AHeight: integer): TAnchorKind;
begin
  if AWidth>((AHeight*3) div 2) then
    Result:=akLeft
  else
    Result:=akTop;
end;

procedure TCustomAnchoredDockManager.UpdateTitlePosition(Control: TControl);
var
  TitlePos: TAnchorKind;
begin
  if Control.Parent is TLazDockForm then begin
    TitlePos:=GetPreferredTitlePosition(Control.Width,Control.Height);
    if TitlePos=akLeft then begin
      Control.BorderSpacing.Left:=TitleWidth;
      Control.BorderSpacing.Top:=0;
    end else begin
      Control.BorderSpacing.Left:=0;
      Control.BorderSpacing.Top:=TitleHeight;
    end;
  end else begin
    Control.BorderSpacing.Left:=0;
    Control.BorderSpacing.Top:=0;
  end;
end;

constructor TCustomAnchoredDockManager.Create(ADockSite: TWinControl);
begin
  inherited Create(ADockSite);
  FOwnerComponent:=TLazDockOwnerComponent.Create(nil);
  FSplitterSize:=5;
  FTitleWidth:=20;
  FTitleHeight:=20;
end;

destructor TCustomAnchoredDockManager.Destroy;
begin
  FreeAndNil(FOwnerComponent);
  inherited Destroy;
end;

procedure TCustomAnchoredDockManager.BeginUpdate;
begin
  inc(FUpdateCount);
end;

procedure TCustomAnchoredDockManager.EndUpdate;
begin
  if FUpdateCount<=0 then
    RaiseGDBException('TCustomAnchoredDockManager.EndUpdate');
  dec(FUpdateCount);
  if FUpdateCount=0 then begin

  end;
end;

procedure TCustomAnchoredDockManager.GetControlBounds(Control: TControl;
  out AControlBounds: TRect);
begin
  AControlBounds:=Control.BoundsRect;
end;

procedure TCustomAnchoredDockManager.DisableLayout(Control: TControl);
begin

end;

procedure TCustomAnchoredDockManager.EnableLayout(Control: TControl);
begin

end;

{-------------------------------------------------------------------------------
  procedure TCustomAnchoredDockManager.DockControl(Control: TControl;
    InsertAt: TAlign; DropCtl: TControl);

  Docks Control to or into DropCtl.
  Control.Parent must be nil.

  If InsertAt in [alLeft,alTop,alRight,alBottom] then Control will be docked to
  the side of DropCtl.
  Otherwise it is docked as Page to a TLazDockPages.

  Docking to a side:
    If DockCtl.Parent=nil then a parent will be created via
    DropCtl.ManualFloat.
    Then Control is added as child to DockCtl.Parent.
    Then a Splitter is added.
    Then all three are anchored.

  Docking as page:
    if DropCtl.Parent is not a TLazDockPage then a new TLazDockPages is created
    and replaces DropCtl and DropCtl is added as page.
    Then Control is added as page.
-------------------------------------------------------------------------------}
procedure TCustomAnchoredDockManager.DockControl(Control: TControl;
  InsertAt: TAlign; DropCtl: TControl);
var
  Splitter: TLazDockSplitter;
  NewDropCtlBounds: TRect;
  NewControlBounds: TRect;
  NewDropCtlWidth: Integer;
  SplitterBounds: TRect;
  a: TAnchorKind;
  ControlAnchor: TAnchorKind;
  DropCtlAnchor: TAnchorKind;
  NewDropCtlHeight: Integer;
  SplitterWidth: LongInt;
  SplitterHeight: LongInt;
  DockPages: TLazDockPages;
  DropCtlPage: TLazDockPage;
  NewPageIndex: Integer;
  NewPage: TLazDockPage;
  NewParent: TLazDockForm;
  ParentDisabledAlign: Boolean;
  DropCtlTitlePos: TAnchorKind;
begin
  if Control.Parent<>nil then
    RaiseGDBException('TCustomAnchoredDockManager.InsertControl Control.Parent<>nil');
  if Control=DropCtl then
    RaiseGDBException('TCustomAnchoredDockManager.InsertControl Control=DropCtl');
  DisableLayout(Control);
  DisableLayout(DropCtl);
  try

    // dock Control to DropCtl
    case InsertAt of
    alLeft,alTop,alRight,alBottom:
      begin
        // dock Control to a side of DropCtl
        // e.g. alLeft: insert Control to the left of DropCtl

        DropCtlAnchor:=MainAlignAnchor[InsertAt];
        ControlAnchor:=OppositeAnchor[DropCtlAnchor];

        DropCtlTitlePos:=GetPreferredTitlePosition(DropCtl.ClientWidth,
                                                   DropCtl.ClientHeight);

        ParentDisabledAlign := False;
        try
          NewDropCtlBounds:=DropCtl.BoundsRect;
          if DropCtlTitlePos=akLeft then
            inc(NewDropCtlBounds.Right,TitleWidth)
          else
            inc(NewDropCtlBounds.Bottom,TitleHeight);

          // make sure, there is a parent HostSite
          if DropCtl.Parent=nil then begin
            // remember bounds
            NewDropCtlBounds:=Rect(0,0,DropCtl.ClientWidth,DropCtl.ClientHeight);
            // create a TLazDockForm as new parent with the size of DropCtl
            NewParent := CreateForm;// starts with Visible=false
            NewParent.DisableAlign;
            ParentDisabledAlign := True;
            NewParent.BoundsRect:=DropCtl.BoundsRect;
            // move the WindowState to the new parent
            if DropCtl is TCustomForm then
            begin
              NewParent.WindowState:=TCustomForm(DropCtl).WindowState;
              TCustomForm(DropCtl).WindowState:=wsNormal;
            end;
            // first move DropCtl to the invsible parent, so changes do not cause flicker
            DropCtl.Dock(NewParent, Rect(0, 0, 0, 0));
            // init anchors of DropCtl
            DropCtl.Align:=alNone;
            DropCtl.AnchorClient(0);
            DropCtl.Anchors:=[akLeft,akTop,akRight,akBottom];
            DropCtl.Visible:=true;
            NewParent.Visible:=true;
            //DebugLn('TCustomAnchoredDockManager.DockControl DropCtl=',DbgSName(DropCtl),' NewParent.BoundsRect=',dbgs(NewParent.BoundsRect));
          end else begin
            if (DropCtl.Parent is TLazDockForm) then begin
              // ok
            end else if (DropCtl.Parent is TLazDockPage) then begin
              // ok
            end else begin
              RaiseGDBException('TCustomAnchoredDockManager.InsertControl DropCtl has invalid parent');
            end;
          end;

          if not ParentDisabledAlign then
          begin
            DropCtl.Parent.DisableAlign;
            ParentDisabledAlign := True;
          end;
          // create a splitter
          Splitter := TLazDockSplitter.Create(Control);
          Splitter.Align:=alNone;
          Splitter.Beveled:=true;
          Splitter.ResizeAnchor:=ControlAnchor;
          //debugln('TCustomAnchoredDockManager.InsertControl A Control.Bounds=',DbgSName(Control),dbgs(Control.BoundsRect),' DropCtl.Bounds=',DbgSName(DropCtl),dbgs(DropCtl.BoundsRect),' Splitter.Bounds=',DbgSName(Splitter),dbgs(Splitter.BoundsRect));

          // calculate new bounds
          NewControlBounds := NewDropCtlBounds;
          if InsertAt in [alLeft,alRight] then begin
            SplitterWidth:=Splitter.Constraints.MinMaxWidth(SplitterSize);
            NewDropCtlWidth:=NewDropCtlBounds.Right-NewDropCtlBounds.Left;
            dec(NewDropCtlWidth,Control.Width+SplitterWidth);
            NewDropCtlWidth:=DropCtl.Constraints.MinMaxWidth(NewDropCtlWidth);
            if InsertAt=alLeft then begin
              // alLeft: insert Control to the left of DropCtl
              NewDropCtlBounds.Left:=NewDropCtlBounds.Right-NewDropCtlWidth;
              NewControlBounds.Right:=NewDropCtlBounds.Left-SplitterWidth;
              SplitterBounds:=Rect(NewControlBounds.Right,NewDropCtlBounds.Top,
                                   NewDropCtlBounds.Left,NewDropCtlBounds.Bottom);
            end else begin
              // alRight: insert Control to the right of DropCtl
              NewDropCtlBounds.Right:=NewDropCtlBounds.Left+NewDropCtlWidth;
              NewControlBounds.Left:=NewDropCtlBounds.Right+SplitterWidth;
              SplitterBounds:=Rect(NewDropCtlBounds.Right,NewDropCtlBounds.Top,
                                   NewControlBounds.Left,NewDropCtlBounds.Bottom);
              //debugln('TCustomAnchoredDockManager.InsertControl A NewDropCtlBounds=',dbgs(NewDropCtlBounds),' NewControlBounds=',dbgs(NewControlBounds),' SplitterBounds=',dbgs(SplitterBounds));
            end;
          end else begin
            SplitterHeight:=Splitter.Constraints.MinMaxHeight(SplitterSize);
            NewDropCtlHeight:=NewDropCtlBounds.Bottom-NewDropCtlBounds.Top;
            dec(NewDropCtlHeight,Control.Height+SplitterHeight);
            NewDropCtlHeight:=DropCtl.Constraints.MinMaxHeight(NewDropCtlHeight);
            if InsertAt=alTop then begin
              // alTop: insert Control to the top of DropCtl
              NewDropCtlBounds.Top:=NewDropCtlBounds.Bottom-NewDropCtlHeight;
              NewControlBounds.Bottom:=NewDropCtlBounds.Top-SplitterHeight;
              SplitterBounds:=Rect(NewDropCtlBounds.Left,NewControlBounds.Bottom,
                                   NewDropCtlBounds.Right,NewDropCtlBounds.Top);
            end else begin
              // alBottom: insert Control to the bottom of DropCtl
              NewDropCtlBounds.Bottom:=NewDropCtlBounds.Top+NewDropCtlHeight;
              NewControlBounds.Top:=NewDropCtlBounds.Bottom+SplitterHeight;
              SplitterBounds:=Rect(NewDropCtlBounds.Left,NewDropCtlBounds.Bottom,
                                   NewDropCtlBounds.Right,NewControlBounds.Top);
            end;
            //debugln('TCustomAnchoredDockManager.InsertControl A NewDropCtlBounds=',dbgs(NewDropCtlBounds),' NewControlBounds=',dbgs(NewControlBounds),' SplitterBounds=',dbgs(SplitterBounds));
          end;

          // position splitter
          Splitter.BoundsRect:=SplitterBounds;
          if InsertAt in [alLeft,alRight] then begin
            Splitter.AnchorSide[akTop].Assign(DropCtl.AnchorSide[akTop]);
            Splitter.AnchorSide[akBottom].Assign(DropCtl.AnchorSide[akBottom]);
            Splitter.Anchors:=[akLeft,akTop,akBottom];
          end else begin
            Splitter.AnchorSide[akLeft].Assign(DropCtl.AnchorSide[akLeft]);
            Splitter.AnchorSide[akRight].Assign(DropCtl.AnchorSide[akRight]);
            Splitter.Anchors:=[akLeft,akTop,akRight];
          end;
          Splitter.Parent := DropCtl.Parent;

          // position Control
          Control.Align := alNone;
          for a:=Low(TAnchorKind) to High(TAnchorKind) do begin
            Control.AnchorSide[a].Control:=nil;
            Control.BorderSpacing.Space[a]:=0;
          end;
          Control.AnchorSide[DropCtlAnchor].Assign(DropCtl.AnchorSide[DropCtlAnchor]);
          Control.AnchorToNeighbour(ControlAnchor,0,Splitter);
          if InsertAt in [alLeft,alRight] then begin
            Control.AnchorSide[akTop].Assign(DropCtl.AnchorSide[akTop]);
            Control.AnchorSide[akBottom].Assign(DropCtl.AnchorSide[akBottom]);
          end else begin
            Control.AnchorSide[akLeft].Assign(DropCtl.AnchorSide[akLeft]);
            Control.AnchorSide[akRight].Assign(DropCtl.AnchorSide[akRight]);
          end;
          Control.Anchors := [akLeft,akTop,akRight,akBottom];
          Control.Dock(DropCtl.Parent, Rect(0, 0, 0, 0));
          Control.Visible := true;

          // position DropCtl
          DropCtl.AnchorToNeighbour(DropCtlAnchor,0,Splitter);

          // set titles
          UpdateTitlePosition(DropCtl);
          UpdateTitlePosition(Control);

          //debugln('TCustomAnchoredDockManager.InsertControl BEFORE ALIGNING Control.Bounds=',DbgSName(Control),dbgs(Control.BoundsRect),' DropCtl.Bounds=',DbgSName(DropCtl),dbgs(DropCtl.BoundsRect),' Splitter.Bounds=',DbgSName(Splitter),dbgs(Splitter.BoundsRect));
        finally
          // in case of Exception inside try-finally Parent can be nil
          if ParentDisabledAlign and (DropCtl.Parent <> nil) then
            DropCtl.Parent.EnableAlign;
        end;
        //debugln('TCustomAnchoredDockManager.InsertControl END Control.Bounds=',DbgSName(Control),dbgs(Control.BoundsRect),' DropCtl.Bounds=',DbgSName(DropCtl),dbgs(DropCtl.BoundsRect),' Splitter.Bounds=',DbgSName(Splitter),dbgs(Splitter.BoundsRect));
      end;

    alClient:
      begin
        // docking as page
        DebugLn('TCustomAnchoredDockManager.InsertControl alClient DropCtl=',DbgSName(DropCtl),' Control=',DbgSName(Control));

        if not (DropCtl.Parent is TLazDockPage) then begin
          // create a new TLazDockPages
          //DebugLn('TCustomAnchoredDockManager.InsertControl Create TLazDockPages');
          DockPages:=TLazDockPages.Create(nil);
          if DropCtl.Parent<>nil then begin
            // DockCtl is a child control
            // => replace the anchors to and from DockCtl with the new DockPages
            ReplaceAnchoredControl(DropCtl,DockPages);
          end else begin
            // DockCtl has no parent
            // => float DockPages
            DockPages.ManualFloat(DropCtl.BoundsRect);
            DockPages.AnchorClient(0);
          end;
          // add DockCtl as page to DockPages
          DockPages.Pages.Add(DropCtl.Caption);
          DropCtlPage:=DockPages.Page[0];
          DropCtlPage.DisableAlign;
          try
            DropCtl.Dock(DropCtlPage, Rect(0,0,0,0));
            DropCtl.AnchorClient(0);
          finally
            DropCtlPage.EnableAlign;
          end;
        end;
        // add Control as new page behind the page of DockCtl
        DropCtlPage:=DropCtl.Parent as TLazDockPage;
        DockPages:=DropCtlPage.PageControl as TLazDockPages;
        NewPageIndex:=DropCtlPage.PageIndex+1;
        DockPages.Pages.Insert(NewPageIndex,Control.Caption);
        NewPage:=DockPages.Page[NewPageIndex];
        DebugLn(['TCustomAnchoredDockManager.DockControl NewPage=',NewPage.Caption,' Control=',Control.Caption,',',DbgSName(Control)]);
        NewPage.DisableAlign;
        try
          if DropCtl is TCustomForm then
            TCustomForm(DropCtl).WindowState:=wsNormal;
          Control.Dock(NewPage, Rect(0, 0, 0, 0));
          Control.AnchorClient(0);
        finally
          NewPage.EnableAlign;
        end;
      end;
    else
      RaiseGDBException('TCustomAnchoredDockManager.InsertControl TODO');
    end;
  finally
    EnableLayout(Control);
    EnableLayout(DropCtl);
  end;
end;

{-------------------------------------------------------------------------------
  procedure TCustomAnchoredDockManager.UndockControl(Control: TControl);

  Removes a control from a docking form.
  It breaks all anchors and cleans up.

  The created gap will be tried to fill up.
  It removes TLazDockSplitter, TLazDockPage and TLazDockPages if they are no
  longer needed.
-------------------------------------------------------------------------------}
procedure TCustomAnchoredDockManager.UndockControl(Control: TControl; Float: boolean);
{

  Examples:

  Search Order:

  1. A TLazDockSplitter dividing only two controls:

     Before:
     |-------------
     | +--+ | +---
     | |  | | | B
     | +--+ | +---
     |-------------

     The splitter will be deleted and the right control will be anchored to the
     left.

     After:
     |-------------
     | +---
     | | B
     | +---
     |-------------


  2. Four spiral splitters:

     Before:
              |
           A  |
     ---------|
       | +--+ |  C
     B | |  | |
       | +--+ |
       | ----------
       |   D

     The left and right splitter will be combined to one.

     After:
              |
           A  |
       -------|
              |  C
            B |
              |
              |------
              |   D


  3. No TLazDockSplitter. Control is the only child of a TLazDockPage
     In this case the page will be deleted.
     If the TLazDockPages has no children left, it is recursively undocked.

  4. No TLazDockSplitter, Control is the only child of a TLazDockForm.
     The TLazDockForm is deleted and the Control is floated.
     This normally means: A form will simply be placed on the desktop, other
     controls will be docked into their DockSite.

  5. Otherwise: this control was not docked.
}
var
  AnchorControl: TControl;
  AnchorSplitter: TLazDockSplitter;
  i: Integer;
  Sibling: TControl;
  OldAnchorControls: array[TAnchorKind] of TControl;
  IsSpiralSplitter: Boolean;
  ParentControl: TWinControl;
  Done: Boolean;

  procedure DoFinallyForParent;
  var
    OldParentControl: TWinControl;
    NewBounds: TRect;
    NewOrigin: TPoint;
    OtherControl: TControl;
    a: TAnchorKind;
  begin
    try
      NewBounds:=Control.BoundsRect;
      NewOrigin:=Control.ControlOrigin;
      OffsetRect(NewBounds,NewOrigin.X,NewOrigin.Y);
      if Float then begin
        Control.ManualFloat(NewBounds);
        if Control.Parent<>nil then
          Control.AnchorClient(0);
      end else if Control.Parent<>nil then begin
        Control.Anchors:=[akLeft,akTop];
        for a:=Low(TAnchorKind) to High(TAnchorKind) do
          Control.AnchorSide[a].Control:=nil;
        Control.BoundsRect:=NewBounds;
        Control.Parent:=nil;
      end;
    finally
      if (ParentControl<>nil) then begin
        OldParentControl:=ParentControl;
        ParentControl:=nil;
        DebugLn(['DoFinallyForParent EnableAlign for ',DbgSName(OldParentControl),' Control=',DbgSName(Control),' OldParentControl.ControlCount=',OldParentControl.ControlCount]);
        OldParentControl.EnableAlign;

        // check if the remaining is a TLazDockForm with only one child
        if (OldParentControl is TLazDockForm)
        and (OldParentControl.ControlCount=1) then
        begin
          OtherControl:=OldParentControl.Controls[0];
          DebugLn(['DoFinallyForParent OtherControl=',DbgSName(OtherControl)]);
          if (OtherControl is TWinControl)
          and (TWinControl(OtherControl).UseDockManager)
          and (TWinControl(OtherControl).DockManager=Self)
          then begin
            UndockControl(OtherControl,true);
          end;
        end;

        //OldParentControl.WriteLayoutDebugReport('X  ');
      end;
    end;
  end;

var
  OldParentPage: TLazDockPage;
  OldParentForm: TLazDockForm;
  a: TAnchorKind;
begin
  if Control.Parent=nil then begin
    // already undocked
    RaiseGDBException('TCustomAnchoredDockManager.UndockControl Control.Parent=nil');
  end;

  ParentControl:=Control.Parent;
  ParentControl.DisableAlign;
  try
    // break anchors
    Control.Align:=alNone;
    for a:=Low(TAnchorKind) to High(TAnchorKind) do begin
      OldAnchorControls[a]:=Control.AnchorSide[a].Control;
      Control.AnchorSide[a].Control:=nil;
    end;
    Control.Anchors:=[akLeft,akTop];

    Done:=false;

    if not Done then begin
      // check if there is a splitter, that has a side with only 'Control'
      // anchored to it.
      for a:=Low(TAnchorKind) to High(TAnchorKind) do begin
        AnchorControl:=OldAnchorControls[a];
        if AnchorControl is TLazDockSplitter then begin
          AnchorSplitter:=TLazDockSplitter(AnchorControl);
          i:=ParentControl.ControlCount-1;
          while i>=0 do begin
            Sibling:=ParentControl.Controls[i];
            if (Sibling.AnchorSide[a].Control=AnchorSplitter) then begin
              // Sibling is anchored with the same side to the splitter
              // => this splitter is needed, can not be deleted.
              //DebugLn('TCustomAnchoredDockManager.UndockControl Splitter still needed: ',DbgSName(AnchorSplitter),'(',dbgs(AnchorSplitter.BoundsRect),') by ',DbgSName(Sibling));
              break;
            end;
            dec(i);
          end;
          if i<0 then begin
            // this splitter is not needed anymore
            //DebugLn('TCustomAnchoredDockManager.UndockControl Splitter not needed: ',DbgSName(AnchorSplitter),'(',dbgs(AnchorSplitter.BoundsRect),')');
            DeleteSideSplitter(AnchorSplitter,OppositeAnchor[a],
                               OldAnchorControls[OppositeAnchor[a]]);
            //update caption
            if (ParentControl is TLazDockPage) and (TLazDockPage(ParentControl).ControlCount > 1) and
               (TLazDockPage(ParentControl).Controls[0] = Control) then
               TLazDockPage(ParentControl).Caption := TLazDockPage(ParentControl).Controls[1].Caption;
            Done:=true;
          end;
        end;
      end;
    end;

    if not Done then begin
      // check if there are four spiral splitters around Control
      IsSpiralSplitter:=true;
      for a:=Low(TAnchorKind) to High(TAnchorKind) do begin
        AnchorControl:=OldAnchorControls[a];
        if (AnchorControl=nil)
        or (not (AnchorControl is TLazDockSplitter)) then begin
          IsSpiralSplitter:=false;
        end;
      end;
      if IsSpiralSplitter then begin
        CombineSpiralSplitterPair(OldAnchorControls[akLeft] as TLazDockSplitter,
                                OldAnchorControls[akRight] as TLazDockSplitter);
        Done:=true;
      end;
    end;

    if not Done then begin
      // check if Control is the only child of a TLazDockPage
      if (ParentControl.ControlCount=1)
      and (ParentControl is TLazDockPage) then begin
        OldParentPage:=TLazDockPage(ParentControl);
        DoFinallyForParent;
        DeletePage(OldParentPage);
        Done:=true;
      end;
    end;

    if not Done then begin
      // check if Control is the only child of a TLazDockForm
      if (ParentControl.ControlCount=1)
      and (ParentControl is TLazDockForm) then begin
        OldParentForm:=TLazDockForm(ParentControl);
        DoFinallyForParent;
        DeleteDockForm(OldParentForm);
        Done:=true;
      end;
    end;

    if not Done then begin
      // otherwise: keep
    end;

  finally
    DoFinallyForParent;
  end;
end;

procedure TCustomAnchoredDockManager.InsertControl(Control: TControl;
  InsertAt: TAlign; DropCtl: TControl);
begin
  DockControl(Control, InsertAt, DropCtl);
end;

function TCustomAnchoredDockManager.EnlargeControl(Control: TControl;
  Side: TAnchorKind; Simulate: boolean): boolean;
{ If Simulate=true then it will only test if control can be enlarged.

  Case A:
  Shrink one neighbour control, enlarge Control. Two splitters are resized.

      |#|         |#         |#|         |#
      |#| Control |#         |#|         |#
    --+#+---------+#   --> --+#| Control |#
    ===============#       ===#|         |#
    --------------+#       --+#|         |#
        A         |#        A|#|         |#
    --------------+#       --+#+---------+#
    ==================     ===================


  Case B:
  Move one neighbour splitter, enlarge Control, resize one splitter,
  rotate the other splitter.

      |#|         |#|          |#|         |#|
      |#| Control |#|          |#|         |#|
    --+#+---------+#+--  --> --+#| Control |#+--
    ===================      ===#|         |#===
    --------+#+--------      --+#|         |#+--
            |#|   B            |#|         |#|B
            |#+--------        |#|         |#+--
        A   |#=========       A|#|         |#===
            |#+--------        |#|         |#+--
            |#|   C            |#|         |#|C
    --------+#+--------      --+#+---------+#+--
    ===================      ===================
}
const
  MinControlSize = 20;
var
  MainSplitter: TLazDockSplitter;
  Side2: TAnchorKind;
  Side3: TAnchorKind;
  Side2Anchor: TControl;
  Side3Anchor: TControl;
  Parent: TWinControl;
  i: Integer;
  Sibling: TControl;
  CurSplitter: TLazDockSplitter;
  Neighbour: TControl;
  ShrinkSide: TAnchorKind;
  ParentDisabledAlign: Boolean;
  EnlargeSplitter: TLazDockSplitter;
  RotateSplitter: TLazDockSplitter;

  procedure ParentDisableAlign;
  begin
    if ParentDisabledAlign then exit;
    ParentDisabledAlign:=true;
    Parent.DisableAlign;
  end;

begin
  Result:=false;
  if Control=nil then exit;
  DebugLn(['TCustomAnchoredDockManager.EnlargeControl Control=',DbgSName(Control),' Side=',AnchorNames[Side]]);
  if Side in [akLeft,akRight] then
    Side2:=akTop
  else
    Side2:=akLeft;
  Side3:=OppositeAnchor[Side2];
  if not GetLazDockSplitter(Control,Side,MainSplitter) then exit;
  if not GetLazDockSplitterOrParent(Control,Side2,Side2Anchor) then exit;
  if not GetLazDockSplitterOrParent(Control,Side3,Side3Anchor) then exit;
  Parent:=Control.Parent;
  if (Side2Anchor=Parent) and (Side3Anchor=Parent) then exit;

  // search controls anchored to the MainSplitter on the other side
  Neighbour:=nil;
  for i:=0 to Parent.ControlCount-1 do begin
    Sibling:=Parent.Controls[i];
    if (not GetLazDockSplitter(Sibling,OppositeAnchor[Side],CurSplitter))
    or (CurSplitter<>MainSplitter) then continue;
    DebugLn(['TCustomAnchoredDockManager.EnlargeControl neighbour Sibling=',DbgSName(Sibling)]);
    // Sibling is anchored to MainSplitter on the other side
    // check if it is at the same height as Control
    if Side in [akTop,akBottom] then begin
      if (Side2Anchor is TLazDockSplitter) then begin
        if (Sibling.Left+Sibling.Width<Side2Anchor.Left) then continue;
      end else begin
        // Side2Anchor is Parent
        if Sibling.Left+Sibling.Width<Control.Left then continue;
      end;
      if (Side3Anchor is TLazDockSplitter) then begin
        if (Sibling.Left>Side3Anchor.Left+Side3Anchor.Width) then continue;
      end else begin
        // Side3Anchor is Parent
        if Sibling.Left>Control.Left+Control.Width then continue;
      end;
    end else begin
      if (Side2Anchor is TLazDockSplitter) then begin
        if (Sibling.Top+Sibling.Height<Side2Anchor.Top) then continue;
      end else begin
        // Side2Anchor is Parent
        if Sibling.Top+Sibling.Height<Control.Top then continue;
      end;
      if (Side3Anchor is TLazDockSplitter) then begin
        if (Sibling.Top>Side3Anchor.Top+Side3Anchor.Height) then continue;
      end else begin
        // Side3Anchor is Parent
        if Sibling.Top>Control.Top+Control.Height then continue;
      end;
    end;

    if Neighbour=nil then
      Neighbour:=Sibling
    else if Sibling is TLazDockSplitter then begin
      if Neighbour is TLazDockSplitter then begin
        // two splitters means, there is at least one Neighbour which can not
        // be shrinked
        exit;
      end;
      Neighbour:=Sibling;
    end;
  end;

  if Neighbour=nil then exit; // no neighbour found
  DebugLn(['TCustomAnchoredDockManager.EnlargeControl Neighbour=',DbgSName(Neighbour)]);

  ParentDisabledAlign:=false;
  try
    if Neighbour is TLazDockSplitter then begin
      // one splitter as Neighbour
      RotateSplitter:=TLazDockSplitter(Neighbour);
      DebugLn(['TCustomAnchoredDockManager.EnlargeControl rotate splitter RotateSplitter=',DbgSName(RotateSplitter)]);
      // check that all anchored controls of this splitter can be shrinked
      for i:=0 to Parent.ControlCount-1 do begin
        Sibling:=Parent.Controls[i];
        if Sibling=RotateSplitter then continue;
        if GetLazDockSplitter(Sibling,Side2,CurSplitter)
        and (CurSplitter=RotateSplitter)
        and (not NeighbourCanBeShrinked(Control,Sibling,Side2))
        then begin
          // this Sibling is anchored with Side2 at RotateSplitter
          // but can not be shrinked
          exit;
        end;
        if GetLazDockSplitter(Sibling,Side3,CurSplitter)
        and (CurSplitter=RotateSplitter)
        and (not NeighbourCanBeShrinked(Control,Sibling,Side3))
        then begin
          // this Sibling is anchored with Side3 at RotateSplitter
          // but can not be shrinked
          exit;
        end;
      end;

      {   |#|         |#|          |#|         |#|
          |#| Control |#|          |#|         |#|
        --+#+---------+#+--  --> --+#| Control |#+--
        ===================      ===#|         |#===
        --------+#+--------      --+#|         |#+--
                |#|   B            |#|         |#|B
                |#+--------        |#|         |#+--
            A   |#=========       A|#|         |#===
                |#+--------        |#|         |#+--
                |#|   C            |#|         |#|C
        --------+#+--------      --+#+---------+#+--
        ===================      =================== }

      Result:=true;
      if not Simulate then begin
        ParentDisableAlign;
        GetLazDockSplitter(Control,OppositeAnchor[Side2],EnlargeSplitter);
        // enlarge Control and its two side splitters
        Control.AnchorSame(Side,RotateSplitter);
        Side2Anchor.AnchorSame(Side,RotateSplitter);
        Side3Anchor.AnchorSame(Side,RotateSplitter);
        // shrink controls anchored to RotateSplitter
        for i:=0 to Parent.ControlCount-1 do begin
          Sibling:=Parent.Controls[i];
          if Sibling=RotateSplitter then continue;
          if GetLazDockSplitter(Sibling,Side2,CurSplitter)
          and (CurSplitter=RotateSplitter) then begin
            // this Sibling is anchored with Side2 at RotateSplitter
            Sibling.AnchorToNeighbour(Side2,0,Side3Anchor);
          end;
          if GetLazDockSplitter(Sibling,Side3,CurSplitter)
          and (CurSplitter=RotateSplitter) then begin
            // this Sibling is anchored with Side3 at RotateSplitter
            Sibling.AnchorToNeighbour(Side3,0,Side2Anchor);
          end;
        end;
        // rotate RotateSplitter
        RotateSplitter.AnchorSide[Side].Control:=nil;
        RotateSplitter.AnchorSide[OppositeAnchor[Side]].Control:=nil;
        RotateSplitter.ResizeAnchor:=Side;
        RotateSplitter.AnchorToNeighbour(Side2,0,Side3Anchor);
        RotateSplitter.AnchorSame(Side3,MainSplitter);
        if Side in [akLeft,akRight] then
          RotateSplitter.Anchors:=RotateSplitter.Anchors-[akRight]+[akLeft]
        else
          RotateSplitter.Anchors:=RotateSplitter.Anchors-[akBottom]+[akTop];
        // shrink MainSplitter
        MainSplitter.AnchorToNeighbour(Side2,0,Side2Anchor);
        // reanchor controls from MainSplitter to RotateSplitter
        for i:=0 to Parent.ControlCount-1 do begin
          Sibling:=Parent.Controls[i];
          if GetLazDockSplitter(Sibling,Side,CurSplitter)
          and (CurSplitter=MainSplitter) then begin
            if Side in [akLeft,akRight] then begin
              if Sibling.Top>Control.Top then
                Sibling.AnchorSide[Side].Control:=RotateSplitter;
            end else begin
              if Sibling.Left>Control.Left then
                Sibling.AnchorSide[Side].Control:=RotateSplitter;
            end;
          end;
        end;
        UpdateTitlePosition(Control);
      end;

    end else begin
      // shrink a neighbour control
      DebugLn(['TCustomAnchoredDockManager.EnlargeControl Shrink one control: Neighbour=',DbgSName(Neighbour)]);
      // check if Neighbour already shares a side with Control
      if (Neighbour.AnchorSide[Side2].Control<>Side2Anchor)
      and (Neighbour.AnchorSide[Side3].Control<>Side3Anchor) then begin
        { Neighbour is too broad.
            |#|         |#|
            |#| Control |#|
          --+#+---------+#+--
          ===================
          -------------------
               Neighbour
          ------------------- }
        exit;
      end;

      // check if the Neighbour can be shrinked
      if NeighbourCanBeShrinked(Control,Neighbour,Side2) then begin
        ShrinkSide:=Side2;
      end else if NeighbourCanBeShrinked(Control,Neighbour,Side3) then begin
        ShrinkSide:=Side3;
      end else begin
        // Neighbour can not be shrinked
        exit;
      end;


      {              EnlargeSplitter
                           ^
                          |#|         |#         |#|         |#
                          |#| Control |#         |#|         |#
                        --+#+---------+#   --> --+#| Control |#
       MainSplitter <-- ===============#       ===#|         |#
                        --------------+#       --+#|         |#
                             Neighbour|#        N|#|         |#
                        --------------+#       --+#+---------+#
                        ==================     =================== }
      Result:=true;
      if not Simulate then begin
        ParentDisableAlign;
        GetLazDockSplitter(Control,OppositeAnchor[ShrinkSide],EnlargeSplitter);
        Neighbour.AnchorToNeighbour(ShrinkSide,0,EnlargeSplitter);
        MainSplitter.AnchorToNeighbour(ShrinkSide,0,EnlargeSplitter);
        EnlargeSplitter.AnchorSame(Side,Neighbour);
        Control.AnchorSame(Side,Neighbour);
        UpdateTitlePosition(Control);
        UpdateTitlePosition(Neighbour);
      end;
    end;
  finally
    if ParentDisabledAlign then
      Parent.EnableAlign;
  end;
end;

procedure TCustomAnchoredDockManager.LoadFromStream(Stream: TStream);
begin
  RaiseGDBException('TCustomAnchoredDockManager.LoadFromStream TODO');
end;

procedure TCustomAnchoredDockManager.PaintSite(DC: HDC);
begin
  // drawing of titles is done by TLazDockForm
end;

procedure TCustomAnchoredDockManager.PositionDockRect(Client, DropCtl: TControl;
  DropAlign: TAlign; var DockRect: TRect);
begin
  RaiseGDBException('TCustomAnchoredDockManager.PositionDockRect TODO');
end;

procedure TCustomAnchoredDockManager.RemoveControl(Control: TControl);
begin
  UndockControl(Control,false);
end;

procedure TCustomAnchoredDockManager.ResetBounds(Force: Boolean);
begin
  // TODO: 'TCustomAnchoredDockManager.ResetBounds'
end;

procedure TCustomAnchoredDockManager.SaveToStream(Stream: TStream);
begin
  RaiseGDBException('TCustomAnchoredDockManager.SaveToStream TODO');
end;

function TCustomAnchoredDockManager.AutoFreeByControl: Boolean;
begin
  Result:=false;
end;

procedure TCustomAnchoredDockManager.SetReplacingControl(Control: TControl);
begin
  RaiseGDBException('TCustomAnchoredDockManager.SetReplacingControl TODO');
end;

procedure TCustomAnchoredDockManager.MessageHandler(Sender: TControl; var Message: TLMessage);
begin

end;

function TCustomAnchoredDockManager.CreateForm: TLazDockForm;
begin
  Result:=TLazDockForm.Create(FOwnerComponent);
  Result.DockManager:=Self;
  Result.UseDockManager:=true;
end;

procedure TCustomAnchoredDockManager.ReplaceAnchoredControl(OldControl,
  NewControl: TControl);
var
  a: TAnchorKind;
  Side: TAnchorSide;
  i: Integer;
  Sibling: TControl;
  CurParent: TWinControl;
begin
  if OldControl.Parent<>nil then begin
    CurParent:=OldControl.Parent;
    CurParent.DisableAlign;
    try
      // put NewControl on the same Parent with the same bounds
      NewControl.Parent:=nil;
      NewControl.Align:=alNone;
      NewControl.BoundsRect:=OldControl.BoundsRect;
      NewControl.Parent:=CurParent;
      // copy all four AnchorSide
      for a:=Low(TAnchorKind) to High(TAnchorKind) do
        NewControl.AnchorSide[a].Assign(OldControl.AnchorSide[a]);
      // bend all Anchors from OldControl to NewControl
      for i:=0 to CurParent.ControlCount-1 do begin
        Sibling:=CurParent.Controls[i];
        if (Sibling=NewControl) or (Sibling=OldControl) then continue;
        for a:=Low(TAnchorKind) to High(TAnchorKind) do begin
          Side:=Sibling.AnchorSide[a];
          if Side.Control=OldControl then begin
            Side.Control:=NewControl;
          end;
        end;
      end;
      // remove OldControl from its Parent
      OldControl.Parent:=nil;
    finally
      CurParent.EnableAlign;
    end;
  end else begin
    NewControl.Parent:=nil;
    NewControl.Align:=alNone;
    NewControl.BoundsRect:=OldControl.BoundsRect;
  end;
end;

function TCustomAnchoredDockManager.GetSplitterWidth(Splitter: TControl): integer;
begin
  Result:=Splitter.Constraints.MinMaxWidth(SplitterSize);
end;

function TCustomAnchoredDockManager.GetSplitterHeight(Splitter: TControl): integer;
begin
  Result:=Splitter.Constraints.MinMaxHeight(SplitterSize);
end;

{ TLazDockPage }

function TLazDockPage.GetPageControl: TLazDockPages;
begin
  Result:=Parent as TLazDockPages;
end;

procedure TLazDockPage.InsertControl(AControl: TControl; Index: integer);
begin
  inherited InsertControl(AControl, Index);
  TLazDockForm.UpdateMainControlInParents(Self);
end;

{ TLazDockForm }

procedure TLazDockForm.SetMainControl(const AValue: TControl);
var
  NewValue: TControl;
begin
  if (AValue<>nil) and (not IsParentOf(AValue)) then
    raise Exception.Create('invalid main control');
  NewValue:=AValue;
  if NewValue=nil then
    NewValue:=FindMainControlCandidate;
  if FMainControl=NewValue then exit;
  FMainControl:=NewValue;
  if FMainControl<>nil then
    FMainControl.FreeNotification(Self);
  UpdateCaption;
end;

procedure TLazDockForm.PaintWindow(DC: HDC);
var
  i: Integer;
  Control: TControl;
  ACanvas: TCanvas;
  Pt: TPoint;
begin
  inherited PaintWindow(DC);
  ACanvas:=nil;
  try
    for i := 0 to ControlCount-1 do
    begin
      Control := Controls[i];
      if not ControlHasTitle(Control) then
        continue;

      if ACanvas = nil then
      begin
        ACanvas := TCanvas.Create;
        ACanvas.Handle := DC;
      end;
      GetCursorPos(Pt);
      Pt := ScreenToClient(Pt);
      TDockHeader.Draw(ACanvas, Control.Caption, FDockHeaderImages,
        GetTitleOrientation(Control), GetTitleRect(Control), Pt);
    end;
  finally
    ACanvas.Free;
  end;
end;

procedure TLazDockForm.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  if (Operation=opRemove) then begin
    if AComponent=FMainControl then
      MainControl:=nil;
  end;
  inherited Notification(AComponent, Operation);
end;

procedure TLazDockForm.InsertControl(AControl: TControl; Index: integer);
begin
  inherited InsertControl(AControl, Index);
  UpdateMainControl;
end;

procedure TLazDockForm.UpdateMainControl;
var
  NewMainControl: TControl;
begin
  if (FMainControl=nil) or (not FMainControl.IsVisible) then begin
    NewMainControl:=FindMainControlCandidate;
    if NewMainControl<>nil then
      MainControl:=NewMainControl;
  end;
end;

function TLazDockForm.CloseQuery: boolean;
// query all top level forms, if form can close

  function QueryForms(ParentControl: TWinControl): boolean;
  var
    i: Integer;
    AControl: TControl;
  begin
    for i:=0 to ParentControl.ControlCount-1 do begin
      AControl:=ParentControl.Controls[i];
      if (AControl is TWinControl) then begin
        if (AControl is TCustomForm) then begin
          // a top level form: query and do not ask children
          if (not TCustomForm(AControl).CloseQuery) then
            exit(false);
        end
        else if not QueryForms(TWinControl(AControl)) then
          // search children for forms
          exit(false);
      end;
    end;
    Result:=true;
  end;

begin
  Result:=inherited CloseQuery;
  if Result then
    Result:=QueryForms(Self);
end;

procedure TLazDockForm.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  Part: TLazDockHeaderPart;
  Control: TControl;
begin
  inherited MouseUp(Button, Shift, X, Y);
  TrackMouse(X, Y);
  if Button = mbLeft then
  begin
    Control := FindHeader(X, Y, Part);
    if (Control <> nil) then
      TDockHeader.PerformMouseUp(Control, Part);
  end;
end;

procedure TLazDockForm.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
  Y: Integer);
var
  Part: TLazDockHeaderPart;
  Control: TControl;
begin
  inherited MouseDown(Button, Shift, X, Y);
  TrackMouse(X, Y);
  if Button = mbLeft then
  begin
    Control := FindHeader(X, Y, Part);
    if (Control <> nil) then
      TDockHeader.PerformMouseDown(Control, Part);
  end;
end;

procedure TLazDockForm.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited MouseMove(Shift, X, Y);
  TrackMouse(X, Y);
end;

procedure TLazDockForm.MouseLeave;
begin
  inherited MouseLeave;
  TrackMouse(-1, -1);
end;

procedure TLazDockForm.TrackMouse(X, Y: Integer);
var
  Control: TControl;
  Part: TLazDockHeaderPart;
  ARect: TRect;
  NewMouseState: TDockHeaderMouseState;
begin
  Control := FindHeader(X, Y, Part);
  FillChar(NewMouseState,SizeOf(NewMouseState),0);
  if (Control <> nil) then
  begin
    ARect := GetTitleRect(Control);
    ARect := TDockHeader.GetRectOfPart(ARect, GetTitleOrientation(Control), Part);
    NewMouseState.Rect := ARect;
    NewMouseState.IsMouseDown := (GetKeyState(VK_LBUTTON) and $80) <> 0;
  end;
  if not CompareMem(@FMouseState, @NewMouseState, SizeOf(NewMouseState)) then
  begin
    if not CompareRect(@FMouseState.Rect, @NewMouseState.Rect) then
      InvalidateRect(Handle, @FMouseState.Rect, False);
    FMouseState := NewMouseState;
    InvalidateRect(Handle, @NewMouseState.Rect, False);
  end;
end;

constructor TLazDockForm.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FillChar(FMouseState, SizeOf(FMouseState), 0);
  TDockHeader.CreateDockHeaderImages(FDockHeaderImages);
end;

destructor TLazDockForm.Destroy;
begin
  TDockHeader.DestroyDockHeaderImages(FDockHeaderImages);
  inherited Destroy;
end;

procedure TLazDockForm.UpdateCaption;
begin
  if FMainControl<>nil then
    Caption:=FMainControl.Caption
  else
    Caption:='';
end;

class procedure TLazDockForm.UpdateMainControlInParents(StartControl: TControl
  );
var
  Form: TLazDockForm;
begin
  while StartControl<>nil do begin
    if (StartControl is TLazDockForm) then
    begin
      Form:=TLazDockForm(StartControl);
      if (Form.MainControl=nil)
      or (not Form.MainControl.IsVisible) then
        Form.UpdateMainControl;
    end;
    StartControl:=StartControl.Parent;
  end;
end;

function TLazDockForm.FindMainControlCandidate: TControl;
var
  BestLevel: integer;

  procedure FindCandidate(ParentControl: TWinControl; Level: integer);
  var
    i: Integer;
    AControl: TControl;
    ResultIsForm, ControlIsForm: boolean;
  begin
    for i:=0 to ParentControl.ControlCount-1 do begin
      AControl:=ParentControl.Controls[i];
      //DebugLn(['FindCandidate ParentControl=',DbgSName(ParentControl),' AControl=',DbgSName(AControl)]);
      if (not AControl.IsControlVisible) then continue;
      if ((AControl.Name<>'') or (AControl.Caption<>''))
      and (not (AControl is TLazDockForm))
      and (not (AControl is TLazDockSplitter))
      and (not (AControl is TLazDockPages))
      and (not (AControl is TLazDockPage))
      then begin
        // this is a candidate
        // prefer forms and top level controls
        if (Application<>nil) and (Application.MainForm=AControl) then begin
          // the MainForm is the best control
          Result:=Application.MainForm;
          BestLevel:=-1;
          exit;
        end;
        ResultIsForm:=Result is TCustomForm;
        ControlIsForm:=AControl is TCustomForm;
        if (Result=nil)
        or ((not ResultIsForm) and ControlIsForm)
        or ((ResultIsForm=ControlIsForm) and (Level<BestLevel))
        then begin
          BestLevel:=Level;
          Result:=AControl;
        end;
      end;
      if AControl is TWinControl then
        FindCandidate(TWinControl(AControl),Level+1);
    end;
  end;

begin
  Result:=nil;
  BestLevel:=High(Integer);
  FindCandidate(Self,0);
end;

function TLazDockForm.FindHeader(x, y: integer; out Part: TLazDockHeaderPart): TControl;
var
  i: Integer;
  Control: TControl;
  TitleRect: TRect;
  p: TPoint;
  Orientation: TDockOrientation;
begin
  for i := 0 to ControlCount-1 do
  begin
    Control := Controls[i];
    if not ControlHasTitle(Control) then
      Continue;
    TitleRect := GetTitleRect(Control);
    p := Point(X,Y);
    if not PtInRect(TitleRect, p) then
      Continue;
    // on header
    // => check sub parts
    Result := Control;
    Orientation := GetTitleOrientation(Control);
    Part := TDockHeader.FindPart(TitleRect, p, Orientation);
    Exit;
  end;
  Result := nil;
end;

function TLazDockForm.IsDockedControl(Control: TControl): boolean;
// checks if control is a child, not a TLazDockSplitter and properly anchor docked
var
  a: TAnchorKind;
  AnchorControl: TControl;
begin
  Result:=false;
  if (Control.Anchors<>[akLeft,akRight,akBottom,akTop])
  or (Control.Parent<>Self) then
    exit;
  for a:=low(TAnchorKind) to high(TAnchorKind) do begin
    AnchorControl:=Control.AnchorSide[a].Control;
    if (AnchorControl=nil) then exit;
    if (AnchorControl<>Self) and (not (AnchorControl is TLazDockSplitter)) then
      exit;
  end;
  Result:=true;
end;

function TLazDockForm.ControlHasTitle(Control: TControl): boolean;
begin
  Result:=Control.Visible
           and IsDockedControl(Control)
           and ((Control.BorderSpacing.Left>0) or (Control.BorderSpacing.Top>0));
end;

function TLazDockForm.GetTitleRect(Control: TControl): TRect;
begin
  Result := Control.BoundsRect;
  if Control.BorderSpacing.Top > 0 then
  begin
    Result.Top := Control.Top - Control.BorderSpacing.Top;
    Result.Bottom := Control.Top;
  end else
  begin
    Result.Left := Control.Left - Control.BorderSpacing.Left;
    Result.Right := Control.Left;
  end;
end;

function TLazDockForm.GetTitleOrientation(Control: TControl): TDockOrientation;
begin
  if Control.BorderSpacing.Top > 0 then
    Result := doHorizontal
  else
  if Control.BorderSpacing.Left > 0 then
    Result := doVertical
  else
    Result := doNoOrient;
end;

{ TLazDockSplitter }

constructor TLazDockSplitter.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  MinSize := 1;
end;

initialization
  DefaultDockManagerClass := TLazDockTree;
{$I lcl_dock_images.lrs}

end.