File: easydocksite.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (2420 lines) | stat: -rw-r--r-- 71,805 bytes parent folder | download | duplicates (5)
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
unit EasyDockSite;
(* A tree docking manager by DoDi <DrDiettrich1@aol.com>.

This project can be used instead of the LDockTree manager.

AppLoadStore is a global link to an application handler for saving and reloading
sites and docked controls.

CustomDockSites have their own handler for saving and loading site and clients.


To be added or ported:
  - field and method argument names

Possible extensions:
  - separate docking management and dock site layout
  + various dock headers
  - multiple splitters (on zones without controls)
  + persistence (requires application-wide management of dock sources!)
  - purpose of Restore button?
  - purpose of Close button? (currently: undock)

More issues, concerning the rest of the LCL (mainly unit Controls):

LCL TODO:
=========
  LCL does not handle existing (or added) controls in a dock site. This results
  in interference of docked and "resident" controls, handled by different
  layout/docking managers.
  Delphi moves all controls into the docked clients list, as soon as a TWinControl
  becomes a DockSite.

  LCL does not handle docking managers as interfaces.
  (this will most probably never come)

  LCL undocks a control when it just is clicked. (Delphi flaw)

  LCL controls don't notify the dock manager about visibility changes.

  LCL doesn't handle properly the possible start of a drag operation (WM_LBUTTONDOWN).
  In DragMode=dmAutomatic the drag manager should capture mouse input.
  When an LB_UP occurs while waiting for the threshold, a normal Click should
  occur (perform LB_DOWN and LB_UP).
  Otherwise dragging starts, and the control has to be reset into "no button down"
  state.

  The default floating site doesn't work properly.
  When multiple clients are docked, and one of them should become floating,
  the client is undocked BUT stays in the site.
*)

{$mode objfpc}{$H+}

{$DEFINE ctlType} //save <name>:<classname>=<caption>
{$DEFINE RootDock} //allow docking into the root zone?
{$DEFINE KeepSize}  //preserve relative sizes on dock?
{.$DEFINE freeImages} //free dockheader images on finalization? (can cause exception)
//{$DEFINE newSplitter} //exclude splitter from remaining zone
{.$DEFINE handle_existing} //dock controls existing in the dock site?
{.$DEFINE splitter_color} //use colored splitter, for debugging?
{.$DEFINE visibility} //handling of invisible clients deserves dock manager notification!
{.$DEFINE restore} //restore button?
  //looks useless: how to restore a hidden zone?
{$DEFINE singleTab} //allow to create notebooks with 1 tab (in the topzone)?
  //doesn't look nice, with both a header AND a button list

//depending on widgetset or patched LCL
{.$DEFINE NoDrop} //applied DoDiPatch1?
{.$DEFINE replace} //using ReplaceDockedControl?

interface

uses
  LCLIntf, //TRect
  LCLType, //HDC
  LMessages, //TLMessage
  Classes, //TStream
  Graphics, //TCanvas
  Forms,
  ExtCtrls, //splitter
  Controls,
  ComCtrls; //TPageControl

type
  TEasyTree = class; //forward declaration
  TEasyZone = class; //forward declaration
  TEasySplitter = TCustomSplitter;

  TEasyZonePart =
  (
    zpNowhere,        // not in any zone
    zpClient,         // on client control
    zpAll,            // total header rect
    zpCaption,        // header caption
    zpSizer,          // splitter/sizer
  {$IFDEF restore}
    zpRestoreButton,  // header restore button
  {$ENDIF}
    zpCloseButton     // header close button
  );

  TEasyHeaderStyle = (
    hsMinimal,  //Delphi style
    hsForm,     //form style
    hsNone      //no header (special notebook etc. style)
  );

  TEasyDockHeader = class
  public
  //state last drawn
    MouseZone: TEasyZone;
    MouseDown: boolean;
    MousePart: TEasyZonePart;
    PartRect: TRect;
  public
    constructor Create;
    function  GetRectOfPart(ARect: TRect; AOrientation: TDockOrientation; APart: TEasyZonePart; HasSplitter: boolean; AStyle: TEasyHeaderStyle): TRect; virtual;
    function  FindPart(AZone: TEasyZone; MousePos: TPoint; fButtonDown: boolean): TEasyZonePart;
    procedure Draw(AZone: TEasyZone; ACanvas: TCanvas; ACaption: string; const MousePos: TPoint);
  end;

  TEasyZone = class
  private
    FChildControl: TControl;
    FTree: TEasyTree;
    FFirstChild,
    FNextSibling, FPrevSibling, FParent: TEasyZone;
    FZoneOrientation, //true orientation
    FOrientation: TDockOrientation; //Delphi compatible (doNone when containing a control)
    procedure SetControl(Control: TControl);
    procedure SetOrientation(NewOrientation: TDockOrientation);
    function GetLeft: Integer;
    function GetTop: Integer;
    function GetTopOrLeft(fTop: boolean): Integer;
  private //very basic liniking
    procedure InsertAfter(LinkAfter, NewZone: TEasyZone);
      //do not handle orientation!
    procedure SetParent(zone: TEasyZone);
      //unlink
  protected
    BR: TPoint;
    procedure SetBounds(TLBR: TRect);

    function  GetHandle: HWND;
  {$IFDEF visibility}  //to be redesigned
    function  GetVisible: boolean;
    function  GetVisibleControl: TControl;
  {$ENDIF}
    function  GetPartRect(APart: TEasyZonePart): TRect;
    function  GetStyle: TEasyHeaderStyle;
  public
    constructor Create(ATree: TEasyTree);
    destructor Destroy; override;
    procedure Clear;
    function  DockSite: TWinControl;
    function  HasSizer: boolean;
    function  GetBounds: TRect;

    procedure AddSibling(NewZone: TEasyZone; where: TAlign);
    procedure ReplaceChild(OldChild, NewChild: TEasyZone);
    procedure ScaleTo(ptOld, ptNew, ptOuter: TPoint);
    procedure PositionControl;
  public //properties
    property ChildControl: TControl read FChildControl write SetControl;
    property FirstChild: TEasyZone read FFirstChild;
    property NextSibling: TEasyZone read FNextSibling;
    property PrevSibling: TEasyZone read FPrevSibling;
    property Parent: TEasyZone read FParent write SetParent;
    property Orientation: TDockOrientation read FOrientation write SetOrientation;
    property Style: TEasyHeaderStyle read GetStyle;
    //property Visible: boolean read GetVisible;

    property Bottom: integer read BR.Y;
    property Left: integer read GetLeft;
    property Right: integer read BR.X;
    property Top: integer read GetTop;
  end;

(* TEasyDockManager implements some of the abstract methods of TDockManager.
*)
  TEasyDockManager = class(TDockManager)
  protected
    FDockSite: TWinControl;
    FReplacingControl: TControl;
    FUpdateCount: integer;
    procedure Update; virtual;
    property  DockSite: TWinControl read FDockSite;
  public
    constructor Create(ADockSite: TWinControl); override;
    class function  DetectAlign(ZoneRect: TRect; MousePos: TPoint): TAlign;
    function GetDockEdge(ADockObject: TDragDockObject): boolean; override;
    procedure PositionDockRect(ADockObject: TDragDockObject); override;
    procedure PositionDockRect(Client, DropCtl: TControl; DropAlign: TAlign;
      var DockRect: TRect);  override;
    procedure SetReplacingControl(Control: TControl); override; //unused
    procedure BeginUpdate; override;
    procedure EndUpdate; override;
  end;

  { TEasyTree }

  TEasyTree = class(TEasyDockManager)
  private
  {$IFDEF replace}
    FReplaceZone: TEasyZone;
  {$ELSE}
  {$ENDIF}
    FTopZone: TEasyZone;
    FSiteRect: TRect; //to detect changed site extent
    procedure UpdateTree;
  protected
  //extended interface
    //procedure ControlVisibilityChanged(Control: TControl; Visible: Boolean);  override;
    function  ZoneFromPoint(SitePos: TPoint): TEasyZone;
    function  ReloadDockedControl(const AName: string): TControl; virtual;
    function  SaveDockedControl(Control: TControl): string; virtual;
  protected //added
    function  FindControlZone(zone: TEasyZone; Control: TControl): TEasyZone;
    procedure RemoveZone(Zone: TEasyZone);
    procedure MakeVisible(ctl: TControl);
  //Lazarus extension
  private
    FHeader: TEasyDockHeader;
    FHideSingleCaption: boolean;
    FStyle: TEasyHeaderStyle;
    FSplitter: TEasySplitter;
    FSizeZone: TEasyZone; //zone to be resized, also PrevSibling
    procedure SplitterMoved(Sender: TObject); //hide and reposition zone
    procedure SetSingleCaption(Value: boolean);
  public
    procedure MessageHandler(Sender: TControl; var Message: TLMessage); override;
    procedure GetControlBounds(Control: TControl; out CtlBounds: TRect);  override;
    procedure InsertControl(Control: TControl; InsertAt: TAlign;
      DropCtl: TControl);  override;
    procedure RemoveControl(Control: TControl);  override;
    procedure ResetBounds(Force: Boolean);  override; //site resized
    procedure LoadFromStream(Stream: TStream);  override;
    procedure SaveToStream(Stream: TStream);  override;
    procedure SetReplacingControl(Control: TControl); override;
  public
  {$IFDEF singleTab}
    SingleTab: boolean; //always create notebook for alCustom?
  {$ENDIF}
    constructor Create(ADockSite: TWinControl); override;
    destructor Destroy; override;
    procedure DumpToStream(Stream: TStream);
    procedure PaintSite(DC: HDC); override;
    procedure SetStyle(NewStyle: TEasyHeaderStyle);
    function  GetEffectiveStyle: TEasyHeaderStyle;
    procedure PositionDockRect(ADockObject: TDragDockObject); override;
    property HideSingleCaption: boolean read FHideSingleCaption write SetSingleCaption;
  end;

(* General DockSite, also Notebook dock site.

  All restorable application forms should inherit from this class,
  regardless of docking capabilities.

  Add Save/Reload of docked controls?
*)
  TCustomDockSite = class(TForm)
  public
    StayDocked: boolean; //here???
    class function ReloadSite(AName: string; AOwner: TComponent): TCustomDockSite;
    procedure ShowForm(AForm: TControl); virtual;
    function  SaveSite: string; virtual;
    procedure LoadFromStream(strm: TStream); virtual;
    procedure SaveToStream(strm: TStream); virtual;
  end;

  TDockSiteClass = class of TCustomDockSite;


//events triggered from load/save docked controls
  TOnReloadControl = function(const CtrlName: string; ASite: TWinControl): TControl of object;
  TOnSaveControl = function(ACtrl: TControl): string of object;

(* TDockMaster base class, contains functions for layout save/load controls.
  The default implementation is for use by both a DockManager and a (unmanaged) DockSite.
  Unless overridden, it handles in this sequence:
  1) TCustomDockSite (notebooks...)
  2) AppLoadStore
  3) OnSave/Reload
  4) Owner of DockMaster (Application)
  5) default (Delphi) compatible handling.

  Customization is provided by OnSave/Restore handlers.
  Further customization is feasable using the AppLoadStore variable (below).
  At the time of an call, ControlDescriptor holds the full control description.

  The DockLoader variable is initialized to a default TCustomDockMaster instance,
  owned by Application. It can be overridden by the application.
  uMakeSite.DockMaster represents the full interface.
*)
  RControlDescriptor = record
    Ctrl: TControl;
    Name, ClassName, Caption: string;
  end;

  TCustomDockMaster = class(TComponent)
  protected
    rc: RControlDescriptor;
    FOnSave: TOnSaveControl;
    FOnRestore: TOnReloadControl;
    procedure CtlToRec(ctl: TControl);
    procedure IdToRec(const ID: string);
    function  RecToId: string;
  public //become class functions?
    TryCreateControls: boolean;
    function  MakeDockable(AForm: TWinControl; fWrap: boolean = True; fVisible: boolean = False): TForm; virtual;
    function  SaveControl(Control: TControl; Site: TWinControl): string; virtual;
    function  ReloadControl(const AName: string; Site: TWinControl): TControl; virtual;
    property OnSave: TOnSaveControl read FOnSave write FOnSave;
    property OnRestore: TOnReloadControl read FOnRestore write FOnRestore;
    property ControlDescriptor: RControlDescriptor read rc;
  end;
var
  DockLoader: TCustomDockMaster;

(* Application loader - a single method for consistency.
  The method has several tasks, see eAppLoadStore.
  When the application handles the request, it returns True.
  If False is returned, default actions are used (load/store controls by name).

The DockManager only deals with docked clients, whereas
the DockLoader manages sites.

When a site is to be created, notebook sites can have a different docksite
control. Here Ctrl is the outer control, containing Site.
*)
//application loader link
type
  eAppLoadStore = (
    alsSaveControl,   //save docked Control as string
    alsReloadControl, //load docked Control from string
    alsSaveSite,  //save entire Site as string
    alsReloadSite //load entire Site from string
  );

  //TAppLoadStore = function(fLoad, fSite: boolean;
  TAppLoadStore = function(mode: eAppLoadStore;
    var Site: TWinControl; var Control: TControl; var AName: string): boolean of object;
var
  AppLoadStore: TAppLoadStore;

//handy function for DockRect initialization
function  ScreenRect(ACtrl: TControl): TRect;

//primarily for DockManager internal use
function  NoteBookCreate: TCustomDockSite;
procedure NoteBookAdd(ABook: TCustomDockSite; AItem: TControl); //to be removed
function  TryRename(AComp: TComponent; const NewName: string): boolean;
function  CreateUniqueComponentName(const AClassName: string; OwnerComponent: TComponent): string;
function  FindOwnedComponent(const AName: string; AOwner: TComponent): TComponent;

const
  CustomDockSiteID = 1;
//var  AppDockBookClass: TDockBookClass;
  AlignNames: array[TAlign] of string = (
    'alNone', 'alTop', 'alBottom', 'alLeft', 'alRight', 'alClient', 'alCustom'
  );

var //debug only, these are valid only until drop
  DropOn: TControl;
  DockObj: TDragDockObject;

implementation

{$R easy_dock_images.res}

uses
  SysUtils, Types,
  math,
  Themes, LResources,
  fDockBook,
  Dialogs,
  LCLproc; //DebugLn

type
  TWinControlAccess = class(TWinControl)
  end;

const
{$IFDEF restore}
  HeaderButtons = [zpCloseButton, zpRestoreButton];
{$ELSE}
  HeaderButtons = [zpCloseButton];
{$ENDIF}

function  NoteBookCreate: TCustomDockSite;
begin
(* Create default dockbook type.
  Dockable notebooks must not have an specific owner.
*)
{
  if assigned(AppDockBookClass) then
    Result := AppDockBookClass.Create(AOwner)
  else
}
  //Result := TEasyDockBook.Create(AOwner);
  Result := TEasyDockBook.Create(Application);
  DockLoader.MakeDockable(Result, False, False); //do not make visible here!
  { TODO : form style should become bsNone when docked - workaround here }
  //Result.BorderStyle := bsNone;
end;

procedure NoteBookAdd(ABook: TCustomDockSite; AItem: TControl);
begin
  AItem.ManualDock(ABook);
  AItem.Visible := True;
end;

function  TryRename(AComp: TComponent; const NewName: string): boolean;
begin
(* catch errors in renaming a component
*)
  try
    AComp.Name := NewName;
    Result := True;
  except
    Result := False;
  end;
end;

function  ScreenRect(ACtrl: TControl): TRect;
begin
  Result.TopLeft := ACtrl.ControlOrigin; //screen coords
  Result.Right := Result.Left + ACtrl.Width;
  Result.Bottom := Result.Top + ACtrl.Height;
end;

function  FindOwnedComponent(const AName: string; AOwner: TComponent): TComponent;
var
  i: integer;
begin
  if assigned(AOwner) then begin
    for i := 0 to AOwner.ComponentCount - 1 do begin
      Result := AOwner.Components[i];
      if CompareText(Result.Name, AName) = 0 then
        exit; //found
    end;
  end;
//not found
  Result := nil;
end;

//from CustomFormEditor.pp
function {TCustomFormEditor.}CreateUniqueComponentName(const AClassName: string;
  OwnerComponent: TComponent): string;
var
  inst: integer;
  basename: string;
begin
(* Add instance number until unique.
  <T><basename> ==> <basename><_><number>
  The classname can be reconstructed by prefixing 'T' (typically)
  and stripping trailing digits and (optionally) '_'.
*)
  Result:=AClassName;
//strip leading 'T'
  if (length(Result)>1) and (Result[1]='T') then
    Result:=RightStr(Result,length(Result)-1);
  if (OwnerComponent=nil) or (Result='') then
    exit;
//if trailing digit, append '_'
  if Result[length(Result)] in ['0'..'9'] then
    Result:=Result+'_';
  basename := Result;
  inst := 1;
  while true do begin
  //append instance number
    Result := basename + IntToStr(inst);
    if FindOwnedComponent(Result, OwnerComponent) = nil then
      break;
    inc(inst);
  end;
end;


//implement various headers
{$I zoneheader.inc}

{ TEasyTree }

constructor TEasyTree.Create(ADockSite: TWinControl);

  procedure DockExisting;
  var
    i: integer;
    ctl: TControl;
  begin
    for i := DockSite.ControlCount - 1 downto 0 do begin
      ctl := DockSite.Controls[i];
      //InsertControl(ctl, ctl.Align, nil); //this is what Delphi does
      ctl.ManualDock(FDockSite, nil, ctl.Align); //this is what should be done
    end;
  end;

begin
  inherited Create(ADockSite);
{$IFDEF singleTab}
//test: notebook with 1 tab in root zone
  SingleTab := True;
{$ENDIF}
//init top zone
  FSiteRect := DockSite.ClientRect;
  FTopZone := TEasyZone.Create(self);
  FTopZone.SetBounds(FSiteRect);
//init helpers
  FHeader := TEasyDockHeader.Create;

  FSplitter := TEasySplitter.Create(nil);
  FSplitter.Beveled := True;
  //FSplitter.BorderStyle := bsSingle; //border does NOT react!
  //FSplitter.BorderWidth := 1;
  FSplitter.Parent := ADockSite;
  FSplitter.OnMoved := @SplitterMoved;
  FSplitter.Align := alNone;
  FSplitter.ResizeStyle := rsLine;
{$IFDEF splitter_color}
  FSplitter.Color := clPurple; //test!!!
{$ENDIF}
{$IFDEF handle_existing}
//handle controls, already residing in the site
  DockExisting; //doesn't work in the current LCL :-(
{$ENDIF}
end;

destructor TEasyTree.Destroy;
begin
  FreeAndNil(FTopZone);
  FreeAndNil(FSplitter);
  FreeAndNil(FHeader);
  inherited;
end;

function TEasyTree.ZoneFromPoint(SitePos: TPoint): TEasyZone;
var
  zone: TEasyZone;
begin
(* Return zone from site client coordinates.
*)
  zone := FTopZone; //bad coordinates???
  while zone <> nil do begin
    if (SitePos.X > zone.Right) or (SitePos.Y > zone.Bottom) then
      zone := zone.NextSibling
    else if zone.HasSizer and PtInRect(zone.GetPartRect(zpSizer), SitePos) then
      break
    else if zone.FirstChild <> nil then
      zone := zone.FirstChild
    else begin
      break; //found it
    end;
  end;
  Result := zone;
end;

function TEasyTree.FindControlZone(zone: TEasyZone; Control: TControl): TEasyZone;
begin
//return the zone containing the given control
  Result := zone;
  if Result = nil then
    exit;
  if Result.ChildControl = Control then
    exit;
  zone := zone.FirstChild;
  Result := nil;
  while (zone <> nil) and (Result = nil) do begin
    Result := FindControlZone(zone, Control);
    zone := zone.NextSibling;
  end;
end;

procedure TEasyTree.GetControlBounds(Control: TControl;
  out CtlBounds: TRect);
var
  zone: TEasyZone;
begin
//zone in client TLBR
  zone := FindControlZone(FTopZone, Control);
  if zone = nil then
    CtlBounds := Rect(0,0,0,0)
  else begin
    CtlBounds := zone.GetPartRect(zpClient);
  end;
end;

function TEasyTree.GetEffectiveStyle: TEasyHeaderStyle;
begin
(* Handle suppression of single-client header.
  DockSite.DockClientCount is not reliable at the time a control is being un/docked.
  We could count our client controls, or take some more direct approach.
*)
  //if FHideSingleCaption and (DockSite.DockClientCount <= 1) then begin
  if FHideSingleCaption //and (ChildControlCount <= 1)
  and ((FTopZone.FFirstChild = nil)
      or ((FTopZone.FFirstChild.ChildControl <> nil)
        and (FTopZone.FFirstChild.FNextSibling = nil)))
  then begin
    Result := hsNone; //single client should have no header
    //DebugLn('client style: hsNone');
  end else begin
    Result := FStyle;
    //DebugLn('zones style: %d', [FStyle]);
  end;
end;

const
  OrthoOrientation: array[TDockOrientation] of TDockOrientation = (
    //doNoOrient, doHorizontal, doVertical, doPages
    doNoOrient, doVertical, doHorizontal, doPages
  );

procedure TEasyTree.InsertControl(Control: TControl; InsertAt: TAlign;
  DropCtl: TControl);
var
  DropZone, OldZone, NewZone, OldParent, NewParent: TEasyZone;
  OldOrientation, NewOrientation: TDockOrientation;
  r: TRect;
  NoteBook: TCustomDockSite;
(* special cases:
  1) first child in top zone - no orientation
  2) second child in top zone - determines orientation
In all other cases all zones have an orientation:
  3) insert isogonal
  4) insert orthogonal

Cases 2 and 3 can be merged, with an additional or redundant setting of the orientation.
*)

begin
{$IFDEF replace}
(* Problem: the control may be undocked prior to being replaced?
*)
  {$IFDEF old}
  if FReplacingControl <> nil then begin
    DropZone := FindControlZone(FTopZone, FReplacingControl);
    FReplacingControl := nil; //flag done
    if DropZone <> nil then begin
      DropZone.ChildControl := Control;
      //DropZone.update?
      exit;
    end;
  end;
  {$ELSE}
  if FReplaceZone <> nil then begin
    FReplaceZone.ChildControl := Control;
    FReplaceZone := nil;
    FReplacingControl := nil;
    Control.Align := alClient;
    ResetBounds(True);
    exit;
  end;
  {$ENDIF}
{$ELSE}
  if Control = FReplacingControl then begin
  (* hack for morphing DropCtl into notebook,
    or initial docking of undocked controls in the dock site.
    Everything is done by the caller, after ManualDock.
  *)
    FReplacingControl := nil;
    exit;
  end;
{$ENDIF}

//some checks
  if (Control = nil)
  //or (not Control.Visible)
  or (DropCtl = Control) then begin
  //bug? The dock site is changed when a control is dropped onto itself!?
    DebugLn('Redock-----');
    exit; //nothing changed
  end;

  if DropCtl = nil then begin
  //top level docking!
    //DropCtl := FDockSite; //the dock site
    DropZone := FTopZone; // FTopZone.FirstChild;
  end else begin
    DropZone := FindControlZone(FTopZone, DropCtl);
    if DropZone = nil then exit; //not here!?
  end;

  if Control.Name = '' then //name it - for header caption
    Control.Name := CreateUniqueComponentName(Control.ClassName, Control.Owner);

(* alCustom means: drop into notebook.
  Valid only when dropped onto an existing control, not into empty dock site.
  Create notebook, if required (put both controls into new notebook).

  Try: create notebook already for first dropped control (ifdef singleTab).

  Use custom handler? Per Site or per application?
*)
  if (InsertAt = alCustom) then begin
  //dock into book
    if (FTopZone.FirstChild <> nil) then begin
    //root zone is not empty
      if (DropCtl is TCustomDockSite) then begin
        NoteBook := TCustomDockSite(DropCtl);
      end else begin
      //create new book
        NoteBook := NoteBookCreate;
      {$IFDEF replace}
        NoteBook.ReplaceDockedControl(DropZone.ChildControl, NoteBook, nil, alCustom);
      {$ELSE}
        //NoteBook.ManualDock(nil, nil); //float it - purpose???
      //hack: manually dock the notebook
        FReplacingControl := NoteBook; //ignore insert (see above)
        NoteBook.ManualDock(FDockSite); //move into DockClients[]
        DropZone.ChildControl := NoteBook; //put into the zone
        NoteBook.DockOrientation := DropCtl.DockOrientation; //strange bug?
        r := DropZone.GetPartRect(zpClient);
        NoteBookAdd(NoteBook, DropCtl); //put the original control into the notebook
        NoteBook.BoundsRect := r;
      {$ENDIF}
        NoteBook.Show;
      end; //else use existing control
      DebugLn('DM:add to existing notebook ', DbgSName(NoteBook));
      NoteBookAdd(NoteBook, Control);
      FDockSite.Invalidate; //update notebook caption
      exit;
  {$IFDEF singleTab}
    end else if SingleTab and not (DropCtl is TEasyDockBook)  then begin
    //empty root zone, create new notebook
      NoteBook := NoteBookCreate;
      NoteBook.ManualDock(FDockSite, nil, alClient);
      NoteBookAdd(NoteBook, Control);
      NoteBook.Show;
      FDockSite.Invalidate; //update notebook caption
      exit;
  {$ELSE}
  {$ENDIF}
    end;  // else //continue docking of the notebook
    InsertAt := alNone; //force automatic orientation
  end;

  NewZone := TEasyZone.Create(self);
  NewZone.ChildControl := Control as TControl;
  Control.Align := alNone;

//special case: in root zone (empty dock site)

  if FTopZone.FirstChild = nil then begin
  //insert first, without orientation
    FTopZone.InsertAfter(nil, NewZone);
    NewZone.SetBounds(FDockSite.ClientRect);
  end else begin
  //more checks
    OldZone := FindControlZone(FTopZone, Control);
      //check after placing the control
    r := DropZone.GetBounds; //for later adjustment
  //get requested orientation, adjust align
    case InsertAt of
    alTop, alBottom: NewOrientation := doVertical;
    alLeft, alRight: NewOrientation := doHorizontal;
    else //unhandled or unspecific
    { TODO : DropCtl=nil - if docked into root zone }
      if (DropCtl = nil) or (DropCtl.DockOrientation = doNoOrient) then begin
        NewOrientation := DropZone.Orientation;
      end else
        NewOrientation := DropCtl.DockOrientation;
      if NewOrientation = doNoOrient then
        NewOrientation := doHorizontal; //assume something
    //fix alignment
      if NewOrientation = doVertical then
        InsertAt := alBottom
      else
        InsertAt := alRight;
    end;
    Control.DockOrientation := NewOrientation;
{
//check topzone now must have an orientation
    if FTopZone.Orientation = doNoOrient then begin
      FTopZone.Orientation := NewOrientation;
      FTopZone.FirstChild.ChildControl.DockOrientation := NewOrientation;
    end;
}
    (* Now Control.DockOrientation is the insert orientation,
      DropCtl.DockOrientation is the zone orientation,
      InsertAt is one of alLeft/Right/Top/Bottom
    *)

  //check orientation - control orientation cannot be doNone!
    OldParent := DropZone.Parent; //nil if docked into root zone!
    if OldParent = nil then begin
    //dock into rootzone - may have no orientation
      OldOrientation := FTopZone.Orientation; // OrthoOrientation[FTopZone.Orientation];
    end else
      OldOrientation := OldParent.Orientation;;
    if (OldOrientation = doNoOrient) then begin
    //second insert into root zone - fix zone and control orientation!
      //assert(OldParent = FTopZone, '???');
      OldOrientation := NewOrientation; // Control.DockOrientation; //easy
      FTopZone.Orientation := NewOrientation;
      FTopZone.FirstChild.ChildControl.DockOrientation := NewOrientation;
    end;
  //iso or orthogonal insert?
    if (OldOrientation <> NewOrientation) then begin
    //need intermediate zone
      NewParent := TEasyZone.Create(self);
      NewParent.Orientation := NewOrientation;
      NewParent.BR := r.BottomRight;
      if OldParent <> nil then
        OldParent.ReplaceChild(DropZone, NewParent) //unlink DropZone
      else begin
        //DropZone is FTopZone
        FTopZone := NewParent;
        { TODO : what more is required??? }
      end;
    //orthogonal orientation
      NewParent.InsertAfter(nil, DropZone);
    end;
  //set control orientation - !rootzone?
    if DropZone = FTopZone then begin
    //dropzone must have a parent
      DropZone := DropZone.FirstChild;
      case InsertAt of
      //alLeft, alTop:
      alBottom, alRight:
        while DropZone.NextSibling <> nil do
          DropZone := DropZone.NextSibling;
      end;
    end;
    DropZone.AddSibling(NewZone, InsertAt);
    //if FTopZone.Orientation = doNoOrient then FTopZone.Orientation := Control.DockOrientation;
  //clear eventually moved zone, when redocking within this site
    if OldZone <> nil then begin
      RemoveZone(OldZone); //must NOT modify moved control!
      OldZone.Free;
    end;
  end;
  Control.Visible := True;
  ResetBounds(True); //splitters may have to be inserted
end;

procedure TEasyTree.PositionDockRect(ADockObject: TDragDockObject);
var
  zone: TEasyZone;
  //ZoneExtent: TPoint;
  ADockRect: TRect;
begin
(* New DockManager interface, called instead of the old version.
  Determine exact target (zone) and DropAlign.

  For top-level docking: check mouse IN site!

Signal results:
  Prevent docking by setting DropOnControl=Control (prevent changes when dropped).
  DragTarget=nil means: become floating.

  Unfortunately there exists no way to signal invalid docking attempts :-(
*)
{ TODO -cdocking : why is this method not called for a docksite with 1 client?
  If exactly the client is moved over it?
-> by design of GetDockTarget in DockPerformer!
}
//debug only
  DockObj := ADockObject;

//determine the zone containing the DragTargetPos
  with ADockObject do begin
  //mouse position within dock site
    //DragTargetPos := DragTarget.ScreenToClient(DragPos);
  //find zone, handle empty site for elastic panels
    if (DockSite.DockClientCount = 0)
  {$IFDEF RootDock}
    or (not PtInRect(DockRect, DragPos))
  {$ENDIF}
    then
      zone := FTopZone
    else
      zone := ZoneFromPoint(DragTargetPos);

    if (zone = nil) or (Control = zone.ChildControl) then begin
      DropAlign := alNone; //prevent drop (below)
    end else begin
      ADockRect := zone.GetBounds; //include header
      DropOnControl := zone.ChildControl; //correct hit in header, not in control
      if DockSite.DockClientCount = 0 then
        DropAlign := alClient //always span empty site
      else
       DropAlign := DetectAlign(ADockRect, DragTargetPos);
    {$IFnDEF RootDock}
      if DropOnControl = nil then begin
      {$IFDEF singleTab}
        if SingleTab and (DropAlign = alCustom) then begin
          //notebook in top zone
        end else
      {$ENDIF}
          DropAlign := alClient; //first element in entire site
      end; //else //determine the alignment within the zone.
    {$ELSE}
    //allow for top-level docking
    {$ENDIF}
    //to screen coords
      ADockRect.TopLeft := FDockSite.ClientToScreen(ADockRect.TopLeft);
      ADockRect.BottomRight := FDockSite.ClientToScreen(ADockRect.BottomRight);
    end;
  //position DockRect
    if DropAlign = alNone then begin
    //force DockRect update by DockTrackNoTarget
      DropOnControl := Control; //prevent drop - signal drop onto self
    {$IFDEF NoDrop}
      NoDrop := True; //signal that nothing will happen on a drop
    {$ELSE}
    //all these are lousy features, do not allow to signal an invalid drop
      DragTarget := nil;
      //Control.DockTrackNoTarget
      //DragTarget := FDockSite; //prevent floating - doesn't work :-(
      //DockRect := Rect(MaxInt, MaxInt, 0, 0); //LTRB - very strange effect!
      //DockRect := Rect(MaxInt, 0, MaxInt, 0); //LTRB
    {$ENDIF}
    end else begin
      PositionDockRect(Control, DropOnControl, DropAlign, ADockRect);
      DockRect := ADockRect;
    end;
  end;
end;

procedure TEasyTree.MessageHandler(Sender: TControl; var Message: TLMessage);
//was: procedure TEasyTree.MouseMessage(var Message: TLMessage);
var
  r: TRect;
  Part: TEasyZonePart;
  Control: TControl;
  MouseMsg: TLMMouse absolute Message;
  Zone: TEasyZone;
  MousePos: TPoint;

  function FindZone(fButtonDown: boolean): TEasyZonePart;
  begin
    MousePos := SmallPointToPoint(MouseMsg.Pos);
    Zone := ZoneFromPoint(MousePos);
  //exact zone part
    if (Zone = nil) then begin
      Result := zpNowhere;
      Control := nil;
    end else begin
      Control := Zone.ChildControl;
      Result := FHeader.FindPart(zone, MousePos, fButtonDown);
    end;
    Part := Result;
  end;

  procedure ShowSplitter(z: TEasyZone);
  begin
  //move splitter into header
  //also set splitter range! (todo)
    FSizeZone := z; //now: the zone with the header (second sibling!)
    FSplitter.BoundsRect := FHeader.PartRect;
    if z.Parent.Orientation = doVertical then begin
      FSplitter.ResizeAnchor := akTop
    end else begin
      FSplitter.ResizeAnchor := akLeft;
    end;
    //FSplitter.??? - make topmost child?
    FSplitter.Show;
  end;

begin
  case Message.msg of
    LM_LBUTTONUP:
      case FindZone(True) of
    {$IFDEF restore}
      zpRestoreButton:
        Control.ManualDock(nil, nil, alNone);
    {$ENDIF}
      zpCloseButton:
        begin
        {$IFDEF visibility}
        //handling of invisible clients deserves dock manager notification!
          if Control is TCustomForm then
            TCustomForm(Control).Close
          else // not a form => doesnot have close => just hide
            Control.Visible := False;
          DockSite.Invalidate;
        {$ELSE}
        (* Definitely close a form, but other controls???
        *)
          if Control is TCustomForm then begin
            TCustomForm(Control).Close;
            Control.ManualDock(nil, nil, alNone); //do float
            TWinControlAccess(Control).DoEndDock(nil, Control.Left, Control.Top);
          end else begin
        { TODO -cLCL : OnEndDock not called by ManualDock? }
            Control.ManualDock(nil, nil, alNone); //do float
            TWinControlAccess(Control).DoEndDock(nil, Control.Left, Control.Top);
            Control.Visible := False;
          end;
        {$ENDIF}
        end;
      end;
    LM_LBUTTONDOWN:
      case FindZone(False) of
      zpCaption: // mouse down on not buttons => start drag
        begin //problem here - app hangs!
        (* perhaps the mousedown state flag gets into the way?
        *)
          DebugLn('start dragging from header: %s', [FDockSite.GetDockCaption(Control)]);
          //MousePos := Control.ClientToScreen(Point(1,1));
          //Mouse.CursorPos := MousePos; //todo: inside control?
          Control.BeginDrag(False);
          //Control.BeginDrag(True); //floats only - due to mouse outside control?
        end;
      end;
    LM_MOUSEMOVE:
      begin //what's Message.Keys???
        case FindZone(FHeader.MouseDown) of
        zpSizer:
          if Zone.HasSizer then begin
            ShowSplitter(zone);
          end;
        else
          FSplitter.Hide;
        end;

{ TODO : How to set the cursor, depending on the zone part? }
      case Part of
        zpCaption:
          //Screen.Cursor := crHandPoint;
          //FDockSite.SetTempCursor(crHandPoint);
          FDockSite.Cursor := crHandPoint; //seems to work
        //else  SetCursor(crNone); //seems not required?
        end;

      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;
}
  end;
end;

procedure TEasyTree.SplitterMoved(Sender: TObject);
var
  ptNew: TPoint;
begin
(* The unbound splitter has been moved.
  Reflect new sizes in FSizeZone and prev(!) sibling.
  ptOuter is the new parent extent, BR of the last sibling.
*)
  FSplitter.Hide;
  ptNew := FSizeZone.PrevSibling.BR;
  if FSizeZone.Parent.Orientation = doVertical then
    ptNew.y := FSplitter.Top //above splitter
  else
    ptNew.x := FSplitter.Left; //left of splitter
  FSizeZone.PrevSibling.ScaleTo(FSizeZone.PrevSibling.BR, ptNew, ptNew);
  FSizeZone.SetBounds(FSizeZone.GetBounds); //BR unchanged, only update the control
  FDockSite.Invalidate;
end;

procedure TEasyTree.PaintSite(DC: HDC);
var
  ACanvas: TCanvas;
  MousePos: TPoint;

  procedure PaintZone(z: TEasyZone);
  var
    ACaption: string;
  begin
    if z.ChildControl <> nil then begin
    //paint header
      ACaption := DockSite.GetDockCaption(z.ChildControl);
      FHeader.Draw(z, ACanvas, ACaption, MousePos);
    end else begin
    //paint children
      z := z.FirstChild;
      while z <> nil do begin
        PaintZone(z);
        z := z.NextSibling;
      end;
    end;
  end;

// paint bounds for each control and close button
begin
  if FTopZone.FirstChild = nil then
    exit; //no zones - nothing to paint
  ACanvas := TCanvas.Create;
  try
    ACanvas.Handle := DC;
    GetCursorPos(MousePos);
    MousePos := DockSite.ScreenToClient(MousePos);
    PaintZone(FTopZone);
  finally
    Acanvas.Free;
  end;
end;

procedure TEasyTree.RemoveControl(Control: TControl);
var
  zone: TEasyZone;
begin
//propagate changes into parent zones
  zone := FindControlZone(FTopZone, Control);
  if zone <> nil then begin
    RemoveZone(zone);
    ResetBounds(True);
  end;
end;

procedure TEasyTree.ResetBounds(Force: Boolean);
var
  rNew: TRect;
begin
//drop site resized - never called in Lazarus???
  if (csLoading in FDockSite.ComponentState) then
    exit; //not the right time to do anything
//how to determine old bounds?
  rNew := FDockSite.ClientRect;
//try catch bad calls (Win32)?????
  if (rNew.Right <= 0) or (rNew.Bottom <= 0) then
    exit;

  if not CompareMem(@rNew, @FSiteRect, sizeof(rNew)) then
    Force := True;  //something has changed
  if not Force then
    exit;
  if FTopZone.FirstChild = nil then begin
    FSiteRect := rNew;
    FTopZone.BR := rNew.BottomRight;
    exit; //zone is empty, all done
  end;
  FTopZone.ScaleTo(FSiteRect.BottomRight, rNew.BottomRight, rNew.BottomRight);
  FSiteRect := rNew;
  FSplitter.Hide;
  FDockSite.Invalidate; //force repaint of headers
end;


type
  RZone = packed record
    BottomRight: TPoint;
    Level: byte;
    Orientation: TDockOrientation;
    //NameLen: integer; //+chars, can be a complete notebook description
    //+ZoneName as AnsiString
  end;

var
  ZoneRec: RZone;
  ZoneName: string;

procedure TEasyTree.LoadFromStream(Stream: TStream);

  function GetRec: integer;
  //var NameLen: integer;
  begin
    Stream.Read(ZoneRec, SizeOf(ZoneRec));
    Result := ZoneRec.Level;
    if Result > 0 then begin
      ZoneName := Stream.ReadAnsiString;
      DockLoader.IdToRec(ZoneName);
    end;
  //debug
    if Result > 0 then
      DebugLn('reload %s @%d [%d,%d]', [ZoneName, Result, ZoneRec.BottomRight.x, ZoneRec.BottomRight.y])
    else
      DebugLn('reload done');
  end;

  procedure ClearSite;
  var
    i: integer;
    ctl: TControl;
  begin
  (* undock all currently docked clients, prior to restoring a layout
  *)
    for i := FDockSite.DockClientCount - 1 downto 0 do begin
      ctl := FDockSite.DockClients[i];
      ctl.Visible := True; //False?
      ctl.ManualDock(nil);  //restore undocked position and extent
    end;
  end;

  procedure MakeZones;
  var
    PrevZone, NewZone: TEasyZone;
    PrevLvl, NewLvl: byte;
    NewCtl: TControl;
    r: TRect;
  begin
    PrevZone := FTopZone;
    PrevLvl := 1;
    while GetRec > 0 do begin
      NewLvl := ZoneRec.Level;
      NewZone := TEasyZone.Create(self);
      NewZone.Orientation := ZoneRec.Orientation;
      NewZone.BR := ZoneRec.BottomRight;
      //if ZoneRec.NameLen > 0 then begin
      if ZoneName <> '' then begin
      //we can NOT expect that Reload... is overridden!?
        NewCtl := ReloadDockedControl(ZoneName);
      //do we need a control in any case?
        if NewCtl = nil then begin
        //debug: create some control
          NewCtl := TPanel.Create(DockSite);
          TryRename(NewCtl, DockLoader.ControlDescriptor.Name);   // ZoneName);
        end;
        if NewCtl <> nil then begin
          NewZone.ChildControl := NewCtl;
          SetReplacingControl(NewCtl); //prevent DockManager actions
          NewCtl.ManualDock(DockSite);
          //NewCtl.DisableAutoSizing; //forever?
          r := NewZone.GetPartRect(zpClient);
          NewCtl.BoundsRect := r;
          DebugLn('?NewCtl w=%d=%d h=%d=%d', [NewCtl.Width, ZoneRec.BottomRight.x,NewCtl.Height, ZoneRec.BottomRight.y]);
          NewCtl.Visible := True;
          //NewCtl.EnableAutoSizing;
          DebugLn('!NewCtl w=%d=%d h=%d=%d', [NewCtl.Width, ZoneRec.BottomRight.x,NewCtl.Height, ZoneRec.BottomRight.y]);
        end;
      {$IFDEF oldOrient}
      {$ELSE}
        NewZone.Orientation := doNoOrient;
        NewCtl.DockOrientation := ZoneRec.Orientation;
      {$ENDIF}
      end;
      while NewLvl < PrevLvl do begin
        PrevZone := PrevZone.Parent;
        dec(PrevLvl);
      end;
      if NewLvl = PrevLvl then //add sibling
        PrevZone.Parent.InsertAfter(PrevZone, NewZone)
      else begin //NewLvl > PrevLvl - make child
        PrevZone.InsertAfter(nil, NewZone);
        PrevLvl := NewLvl;
      end;
      PrevZone := NewZone;
    end;
  end;

begin
(* Problem: what if site doesn't match zone extent?
*)
//remove all docked controls
  ClearSite;
//read record
  if GetRec > 0 then begin
    FSiteRect.BottomRight := ZoneRec.BottomRight; //stored extent, not current one!
    FTopZone.BR := ZoneRec.BottomRight;
    FTopZone.Orientation := ZoneRec.Orientation;
    MakeZones;
  //now make the zone fit the current extent, and position all child controls
    //DebugLn('fit zone ', DbgS(FTopZone.BR), ' into site ', DbgS(FDockSite.ClientRect.BottomRight));
    ResetBounds(True);  //always position controls!
  //finish?
  //remove all leafs without a child control?
  end;
//assure everything is visible (recursive, until topmost parent)
  MakeVisible(FDockSite);
end;

function TEasyTree.ReloadDockedControl(const AName: string): TControl;
begin
(* Reload from
- saved site info (if CustomDockSite)
- AppLoadStore
- DockSite
*)
  Result := DockLoader.ReloadControl(AName, FDockSite);
end;

function TEasyTree.SaveDockedControl(Control: TControl): string;
begin
(* Create string descriptor for docked control.
  Override in sync with ReloadDockedControl!
*)
  Result := DockLoader.SaveControl(Control, FDockSite);
end;

procedure TEasyTree.SaveToStream(Stream: TStream);

  procedure DoSaveZone(Zone: TEasyZone; Level: byte);
  var
    child: TControl;
  begin
    while Zone <> nil do begin
    //fill ZoneRec
      ZoneRec.Level := Level;
      ZoneRec.Orientation := Zone.Orientation;
      ZoneRec.BottomRight := Zone.BR;
      child := Zone.ChildControl;
      if child = nil then
        ZoneName := ''
      else begin
        ZoneName := SaveDockedControl(child); //ctrl or entire site
      {$IFDEF oldOrient}
      {$ELSE}
        ZoneRec.Orientation := child.DockOrientation;
      {$ENDIF}
      end;
    //write descriptor
      Stream.Write(ZoneRec, sizeof(ZoneRec));
      Stream.WriteAnsiString(ZoneName);
    // recurse into first child
      if Zone.FirstChild <> nil then
        DoSaveZone(Zone.FirstChild, Level + 1); //all children of Level
    // recurse into next sibling
      Zone := Zone.NextSibling;
    end;
  end;

begin
// write all zones from tree
  DoSaveZone(FTopZone, 1);
//write end marker (dummy record of level 0)
  ZoneRec.Level := 0;
  Stream.Write(ZoneRec, sizeof(ZoneRec));
end;

procedure TEasyTree.DumpToStream(Stream: TStream);
var
  r: TRect;
  s: string;
const
  eol: string = #13#10; //to be replaced by system constant?
  OrientString: array[TDockOrientation] of char = ('N','H','V'
    {$IFDEF FPC} ,'P' {$ENDIF} );

  procedure WriteZone(zone: TEasyZone; level: integer);
  var
    ind: string;
    s: string;
    ctl: TControl;
  begin
    ind := StringOfChar(' ', level*2);
  //zone
    if zone.ChildControl <> nil then
      s := zone.ChildControl.ClassName + '.' + zone.ChildControl.Name
    else
      s := '''''';
    r := zone.GetBounds;
    s := Format('%s%s (%d,%d)-(%d,%d)%s', [ind, OrientString[zone.orientation],
      r.Top, r.Left, r.Bottom, r.Right, eol]);
    Stream.Write(s[1], length(s));
  //splitter
    if zone.HasSizer then begin
      r := zone.GetPartRect(zpSizer);
      s := Format('%sSplitter (%d,%d)-(%d,%d)%s', [ind,
        r.Top, r.Left, r.Bottom, r.Right, eol]);
      Stream.Write(s[1], length(s));
    end;
  //control
    ctl := zone.ChildControl;
    if ctl <> nil then begin
      r := ctl.BoundsRect;
      s := Format('%s%s %s.%s (%d,%d)-(%d,%d)%s', [ind, OrientString[ctl.DockOrientation],
        ctl.ClassName, ctl.Name,
        r.Top, r.Left, r.Bottom, r.Right, eol]);
      Stream.Write(s[1], length(s));
      if ctl.Visible then
        s := 'visible'
      else
        s := 'hidden';
      s := ind + s + eol;
      Stream.Write(s[1], length(s));
    end;
    zone := zone.FirstChild;
    while zone <> nil do begin
      WriteZone(zone, level+1);
      zone := zone.NextSibling;
    end;
    Stream.Write(eol[1], length(eol));
  end;

begin
//for now: dump tree
//splitter
  if FSplitter.Visible then begin
    r := FSplitter.BoundsRect;
    s := Format('Splitter (%d,%d)-(%d,%d)%s', [
      r.Top, r.Left, r.Bottom, r.Right, eol]);
    Stream.Write(s[1], length(s));
  end;
  WriteZone(FTopZone, 0);
end;

procedure TEasyTree.SetReplacingControl(Control: TControl);
begin
(* The Control may have been undocked, until the replace request is handled.
*)
  inherited SetReplacingControl(Control);
{$IFDEF replace}
  FReplaceZone := FindControlZone(FTopZone, Control);
{$ELSE}
{$ENDIF}
end;

procedure TEasyTree.SetSingleCaption(Value: boolean);
begin
(* Hide header if no more than one client is docked.
*)
  if FHideSingleCaption = Value then
    exit;
  FHideSingleCaption := Value;
  ResetBounds(True);
end;

procedure TEasyTree.SetStyle(NewStyle: TEasyHeaderStyle);
begin
  if NewStyle = FStyle then
    exit;
  FStyle := NewStyle;
  ResetBounds(True);
end;

procedure TEasyTree.UpdateTree;
begin
  //nothing to do?
  //FDockSite.Invalidate;
end;

procedure TEasyTree.RemoveZone(Zone: TEasyZone);

  procedure InlineKids(z: TEasyZone);
  var
    pp, p, ch: TEasyZone;
  begin
  (* move all children of z into z.parent.parent, in place of z.parent
  *)
    p := z.Parent;
    pp := p.Parent;
  //link first child
    ch := z.FirstChild;
    ch.FPrevSibling := p.FPrevSibling;
    if ch.PrevSibling <> nil then
      ch.PrevSibling.FNextSibling := ch
    else
      pp.FFirstChild := ch;
    ch.FParent := pp;
  //link last child
    while ch.NextSibling <> nil do begin
      ch := ch.NextSibling;
      ch.FParent := pp;
    end;
    ch.FNextSibling := p.NextSibling;
    if ch.NextSibling <> nil then
      ch.NextSibling.FPrevSibling := ch;
  //delete zones
    z.FFirstChild := nil;
    p.FParent := nil; //don't unlink!
    p.Free;
  end;

var
  p, ch: TEasyZone;
  affected: TEasyZone; //the zone whose children have changed
begin
//propagate changes into parents!
//parents only can have zones, no controls
  affected := nil;
  repeat
    p := zone.Parent;
    if p = nil then
      break; //exit; //reached top zone!
    zone.Free; //unlink
    zone := p;
    affected := p;
  until zone.FirstChild <> nil;
(* cases:
  zone without parent (top) - check orientation, exit
  zone with 0 children - excluded before
  zone with 1 child (ch),
    child is leaf -> looses orientation, move up
    child contains 1 child (cc) -> orientation fits, move child.child up
  zone with more children - exit
*)
  while (zone.Parent <> nil) do begin
    p := zone.Parent;
    ch := zone.FirstChild;
    if ch.NextSibling <> nil then begin
    //more than 1 child - check next level
    end else if ch.FirstChild = nil then begin
    //contains control, move up
      ch.ChildControl.DockOrientation := p.Orientation;
      p.ReplaceChild(zone, ch); //move control up
      zone.Free;
      affected := p;
    end else if ch.FirstChild.NextSibling = nil then begin
    //contains zone with 1 child: orientation fits, move up
      InlineKids(ch.FirstChild);
      affected := ch.Parent; //the new parent
      p := ch;  // affected;
    end;
    zone := p;
  end;
//update affected zone, to close the gap
  if affected <> nil then begin
    Zone := affected.FirstChild;
    while Zone <> nil do begin
      if Zone.NextSibling = nil then
        Zone.BR := affected.BR; //resize last zone
      zone.PositionControl;
      zone := Zone.NextSibling;
    end;
{
//root zone may loose orientation!
    if affected = FTopZone then begin
      if affected.FirstChild.NextSibling = nil then begin
        FTopZone.Orientation := doNoOrient;
        FTopZone.FirstChild.ChildControl.DockOrientation := doNoOrient; <--- non-leaf!?
      end;
    end;
    }
  end;
{$IFDEF RootDock}
  while FTopZone.FirstChild <> nil do begin
    Zone := FTopZone.FirstChild;
    if Zone.NextSibling <> nil then
      break; //has multiple kids - done
    if Zone.ChildControl <> nil then begin
    //single child, loose orientation
      FTopZone.Orientation := doNoOrient;
      Zone.ChildControl.DockOrientation := doNoOrient;
      break; //done
    end;
  //move zone up
    FTopZone.FFirstChild := nil;
    zone.Parent := nil;
    FTopZone.Free;
    FTopZone := zone;
  end;
{$ELSE}
{$ENDIF}
//check root empty
  if FTopZone.FirstChild = nil then
    FTopZone.Orientation := doNoOrient;

//update zone, here simply the whole dock site
  FSplitter.Hide;
  DockSite.Invalidate;
end;

procedure TEasyTree.MakeVisible(ctl: TControl);
begin
  while assigned(ctl) do begin
    ctl.Visible := True;
    ctl := ctl.Parent;
  end;
end;

{ TEasyZone }

constructor TEasyZone.Create(ATree: TEasyTree);
begin
  FTree := ATree;
end;

destructor TEasyZone.Destroy;
begin
  Clear;
  Parent := nil; //unlink
  inherited;
end;

procedure TEasyZone.Clear;
begin
//let parent care for updating its chain?
  while FirstChild <> nil do
    FirstChild.Free;
end;

function TEasyZone.DockSite: TWinControl;
begin
  Result := FTree.FDockSite;
end;


{$IFDEF visibility}
function TEasyZone.GetVisible: boolean;
begin
  Result := GetVisibleControl <> nil;
end;

function TEasyZone.GetVisibleControl: TControl;
var
  zone: TEasyZone;
begin
  Result := ChildControl;
  if (ChildControl <> nil) then begin
    if not ChildControl.Visible then
      Result := nil;
    exit;
  end;
//search children
  zone := FirstChild;
  while zone <> nil do begin
    Result := zone.GetVisibleControl;
    if Result <> nil then
      exit;
    zone := zone.NextSibling;
  end;
end;
{$ENDIF}

function TEasyZone.GetPartRect(APart: TEasyZonePart): TRect;
begin
(* Can zones have individual headers?
  For notebooks a caption text is not required!

  NewSplitter: non-leaf zones also can have an splitter!
  The higher level splitters have to be excluded from the zone rect.
    (done in GetBounds)
*)
  if (ChildControl <> nil) then
    Result := FTree.FHeader.GetRectOfPart(GetBounds, ChildControl.DockOrientation,
      APart, HasSizer, Style)
  else if (APart = zpSizer) and HasSizer then
    Result := FTree.FHeader.GetRectOfPart(GetBounds, Parent.Orientation,
      APart, HasSizer, Style)
  else
    Result := Rect(0,0,0,0);
end;

function TEasyZone.GetStyle: TEasyHeaderStyle;
begin
(* Get the effective header style.
  A single notebook client deserves no header at all.
  Other single clients can have no header (optional)
*)
  Result := FTree.GetEffectiveStyle;
end;

function TEasyZone.HasSizer: boolean;
begin
  Result := PrevSibling <> nil;
end;

//-------------- basic linking ----------------

procedure TEasyZone.SetParent(zone: TEasyZone);
begin
//for public use! unlink if parent changes.
  if zone <> Parent then begin
  //unlink, handle FirstChild
    if PrevSibling <> nil then
      PrevSibling.FNextSibling := NextSibling
    else if Parent <> nil then
      Parent.FFirstChild := NextSibling;
    if NextSibling <> nil then
      NextSibling.FPrevSibling := PrevSibling;
    FParent := zone;
    FNextSibling := nil;
    FPrevSibling := nil;
  end;
end;

procedure TEasyZone.InsertAfter(LinkAfter, NewZone: TEasyZone);
begin
//LinkAfter=nil for insert as first child.
  NewZone.Parent := self; //unlink if required
  if LinkAfter = nil then begin //as first child
    NewZone.FNextSibling := FirstChild;
    if FirstChild <> nil then
      FirstChild.FPrevSibling := NewZone;
    FFirstChild := NewZone;
  end else begin
    NewZone.FPrevSibling := LinkAfter;
    NewZone.FNextSibling := LinkAfter.NextSibling;
    if LinkAfter.NextSibling <> nil then
      LinkAfter.NextSibling.FPrevSibling := NewZone;
    LinkAfter.FNextSibling := NewZone;
  end;
  //NewZone.Orientation := LinkAfter.Orientation;
end;

procedure TEasyZone.PositionControl;
var
  r: TRect;
begin
//obsolete, part of SetBounds!
  if FChildControl = nil then
    exit;
  r := GetPartRect(zpClient);
  FChildControl.BoundsRect := r;
end;

procedure TEasyZone.AddSibling(NewZone: TEasyZone; where: TAlign);
var
  LinkAfter: TEasyZone;
  r, r2: TRect;
  NewOrientation: TDockOrientation;
begin
//orientation is NOT checked!
  r := GetBounds; //valid old values
  case where of
  alLeft, alTop:  LinkAfter := PrevSibling;
  alRight, alBottom: LinkAfter := self;
  else
    DebugLn('unhandled insertion');
    LinkAfter := nil; //must never happen!
  end;
  Parent.InsertAfter(LinkAfter, NewZone);
//resize?
  r2 := r;
{$IFDEF KeepSize}
{ TODO : update TControl to init the UndockWidth/Height properly }
  case where of
  alLeft:
    begin
      NewOrientation := doHorizontal;
      if (LinkAfter <> nil) and (LinkAfter.ChildControl <> nil) then
        r.Left := r.Left + (r.Right - r.Left) * NewZone.ChildControl.UndockWidth div (NewZone.ChildControl.UndockWidth + LinkAfter.ChildControl.UndockWidth)
      else
        r.Left := (r.Left+r.Right) div 2;
      r2.Right := r.Left;
    end;
  alRight:
    begin
      NewOrientation := doHorizontal;
      if (LinkAfter <> nil) and (LinkAfter.ChildControl <> nil) then
        r.Right := r.Left + (r.Right - r.Left) * LinkAfter.ChildControl.UndockWidth div (NewZone.ChildControl.UndockWidth + LinkAfter.ChildControl.UndockWidth)
      else
        r.Right := (r.Left+r.Right) div 2;
      r2.Left := r.Right;
    end;
  alTop:
    begin
      NewOrientation := doVertical;
      if (LinkAfter <> nil) and (LinkAfter.ChildControl <> nil) then
        r.Top := r.Top + (r.Bottom - r.Top) * NewZone.ChildControl.UndockHeight div (NewZone.ChildControl.UndockHeight + LinkAfter.ChildControl.UndockHeight)
      else
        r.Top := (r.Bottom+r.Top) div 2;
      r2.Bottom := r.Top;
    end;
  alBottom:
    begin
      NewOrientation := doVertical;
      if (LinkAfter <> nil) and (LinkAfter.ChildControl <> nil) then
        r.Bottom := r.Top + (r.Bottom - r.Top) * LinkAfter.ChildControl.UndockHeight div (NewZone.ChildControl.UndockHeight + LinkAfter.ChildControl.UndockHeight)
      else
        r.Bottom := (r.Bottom+r.Top) div 2;
      r2.Top := r.Bottom;
    end;
  else //keep compiler happy
    NewOrientation := doNoOrient;
  end;
{$ELSE}
  case where of
  alLeft:
    begin
      NewOrientation := doHorizontal;
      r.Left := (r.Left+r.Right) div 2;
      r2.Right := r.Left;
    end;
  alRight:
    begin
      NewOrientation := doHorizontal;
      r.Right := (r.Left+r.Right) div 2;
      r2.Left := r.Right;
    end;
  alTop:
    begin
      NewOrientation := doVertical;
      r.Top := (r.Bottom+r.Top) div 2;
      r2.Bottom := r.Top;
    end;
  alBottom:
    begin
      NewOrientation := doVertical;
      r.Bottom := (r.Bottom+r.Top) div 2;
      r2.Top := r.Bottom;
    end;
  else //keep compiler happy
    NewOrientation := doNoOrient;
  end;
{$ENDIF}
//parent orientation? (if in rootzone)
  //if parent.Orientation = doNoOrient then
  if Parent <> nil then
    Parent.Orientation := NewOrientation;
  if ChildControl <> nil then
    ChildControl.DockOrientation := NewOrientation;
  if NewZone.ChildControl <> nil then
    NewZone.ChildControl.DockOrientation := NewOrientation;
  SetBounds(r);
  NewZone.SetBounds(r2);
end;

procedure TEasyZone.ReplaceChild(OldChild, NewChild: TEasyZone);
begin
//usage: insert intermediate parent zone
  NewChild.Parent := nil; //unlink
  NewChild.Parent := Self;
  NewChild.FNextSibling := OldChild.NextSibling;
  NewChild.FPrevSibling := OldChild.PrevSibling;
  OldChild.Parent := nil; //unlink
  if NewChild.NextSibling <> nil then
    NewChild.NextSibling.FPrevSibling := NewChild;
//handle FirstChild
  if NewChild.PrevSibling <> nil then
    NewChild.PrevSibling.FNextSibling := NewChild
  else
    FFirstChild := NewChild;
//init size
  NewChild.Orientation := OldChild.Orientation; //propagate?
  NewChild.BR := OldChild.BR;
end;

//procedure TEasyZone.ScaleTo(const ptOld, ptNew, ptOuter: TPoint);
procedure TEasyZone.ScaleTo(ptOld, ptNew, ptOuter: TPoint);
var
  ch: TEasyZone;
begin
(* change all coordinates from old to new extent.
  Set exact values for last sibling.
  Must use floating point division, to keep rounding errors acceptable!
  ptOuter is the new BottomRight of the parent zone.
*)
(* "const" woes:
  aliased points (BR!) must not be passed as const (pointers!)
*)
  //DebugLn('scale (%d,%d) to (%d,%d)', [ptOld.y, ptOld.x, ptNew.y, ptNew.x]);

  //exact boundary in parent orientation
  if (Parent = nil) or (Parent.Orientation = doNoOrient) then
    br := ptOuter
  else if Parent.Orientation = doVertical then begin
    br.X := ptOuter.X;
    if NextSibling = nil then
      br.Y := ptOuter.Y
    else
      br.Y := round(br.Y * ptNew.Y / ptOld.Y);
  end else begin
    br.Y := ptOuter.Y;
    if NextSibling = nil then
      br.X := ptOuter.X
    else
      br.X := round(br.X * ptNew.X / ptOld.X);
  end;

  if ChildControl <> nil then begin
    PositionControl;
  end else begin
    ch := FirstChild;
    while ch <> nil do begin
      ch.ScaleTo(ptOld, ptNew, BR);
      ch := ch.NextSibling;
    end;
  end;
end;

procedure TEasyZone.SetControl(Control: TControl);
begin
// propagate orientation into control.
  FChildControl := Control;
  FOrientation := doNoOrient;
end;

procedure TEasyZone.SetOrientation(NewOrientation: TDockOrientation);
begin
  FZoneOrientation := NewOrientation; //independent from ChildControl
  if ChildControl = nil then
    FOrientation := NewOrientation
  else
    FOrientation := doNoOrient;
end;

//----------- prev sibling based coordinates ----------

function TEasyZone.GetTopOrLeft(fTop: boolean): Integer;
var
  zone, prev: TEasyZone;
begin
// In a parent zone of vertical orientation the zone.PrevSibling.Bottom is zone.Top
(* NewSplitter: exclude higher level splitters.
*)
  zone := self;
  if zone.Parent <> nil then begin
    if (fTop = (zone.Parent.Orientation = doVertical)) then begin
      prev := zone.PrevSibling;
      while prev <> nil do begin
      {$IFDEF visibility}
        if prev.Visible then
      {$ELSE}
        //zones are always visible
      {$ENDIF}
        begin
          if fTop then
            Result := prev.Bottom
          else
            Result := prev.Right;
          exit;
        end;
        prev := prev.PrevSibling;
      end;
    end;
  //no sibling, get from parent zone
    Result := Parent.GetTopOrLeft(fTop);
    if Parent.HasSizer and (fTop <> (Parent.Orientation = doVertical)) then
      inc(Result, dSizer); //exclude immediate parent's splitter (opposite orientation?)
  end else begin
    Result := 0;
  end;
end;

function TEasyZone.GetLeft: Integer;
begin
  Result := GetTopOrLeft(False);
end;

function TEasyZone.GetTop: Integer;
begin
  Result := GetTopOrLeft(True);
end;

function TEasyZone.GetBounds: TRect;
begin
//return defined extent
  Result.Top := Top;
  Result.Left := Left;
  Result.BottomRight := BR;
end;

function TEasyZone.GetHandle: HWND;
begin
  Result := FTree.FDockSite.Handle;
end;

procedure TEasyZone.SetBounds(TLBR: TRect);
var
  z: TEasyZone;
begin
(* Zone cannot be the root zone. If so, ignore?
  Recurse into child zones.
*)
  BR := TLBR.BottomRight;
  if ChildControl <> nil then begin //is control zone
    //FTree.AdjustDockRect(ChildControl, TLBR);
    TLBR := FTree.FHeader.GetRectOfPart(TLBR, ChildControl.DockOrientation, zpClient, HasSizer, Style);
    ChildControl.BoundsRect := TLBR;
  end else if FirstChild <> nil then begin
    z := FirstChild;
    while z <> nil do begin
    //resize - for splitter move only!
      if Orientation = doVertical then //left/right changed
        z.BR.x := TLBR.Right
      else
        z.BR.y := TLBR.Bottom;
      z.SetBounds(z.GetBounds);
      z := z.NextSibling;
    end;
  end; //else empty root zone?
end;

{ TEasyDockManager }

procedure TEasyDockManager.BeginUpdate;
begin
  //inherited BeginUpdate;
  inc(FUpdateCount);
end;

constructor TEasyDockManager.Create(ADockSite: TWinControl);
begin
(* Init DockSite and DragManager.
*)
  FDockSite := ADockSite;
  ADockSite.DockManager := self;
//reset inappropriate docking defaults - should be fixed in Controls/DragManager!
  DragManager.DragImmediate := False;
  inherited Create(ADockSite);
end;

class function TEasyDockManager.DetectAlign(ZoneRect: TRect;
  MousePos: TPoint): TAlign;
var
  w, h, zphi: integer;
  cx, cy: integer;
  dx, dy: integer;
  phi: double;
  izone: integer;
  dir: TAlign;
const
  k = 5; //matrix dimension
//mapping octants into aligns, assuming k=5
  cDir: array[-4..4] of TAlign = (
    alLeft, alLeft, alTop, alTop, alRight, alBottom, alBottom, alLeft, alLeft
  );
begin
(* Determine alignment from the position of the mouse within ZoneRect.
  ZoneRect in screen TLBR coordinates, MousePos in screen coordinates.
*)
//center and extent of dock zone
  cx := (ZoneRect.Right + ZoneRect.Left) div 2;
  cy := (ZoneRect.Top + ZoneRect.Bottom) div 2;
  w := ZoneRect.Right - ZoneRect.Left;
  h := ZoneRect.Bottom - ZoneRect.Top;
  if (w > 0) and (h > 0) then begin
  //mouse position within k*k rectangles (squares)
    dx := trunc((MousePos.x - cx) / w * k);
    dy := trunc((MousePos.y - cy) / h * k);
    izone := max(abs(dx), abs(dy)); //0..k
  //map into 0=innermost (custom), 1=inner, 2=outer
    if izone = 0 then begin
      //zone := zInnermost;
      dir := alCustom; //pages
    end else begin
      phi := arctan2(dy, dx); //zero at East (right), increasing clockwise
      zphi := trunc(radtodeg(phi)) div 45; //both EN and ES are zero
      dir := cDir[zphi];
    end;
  end else
    dir := alClient;
  Result := dir;
end;

procedure TEasyDockManager.EndUpdate;
begin
  //inherited EndUpdate;
  dec(FUpdateCount);
  if FUpdateCount = 0 then
    Update;
end;

function TEasyDockManager.GetDockEdge(ADockObject: TDragDockObject): boolean;
var
  CanDock: boolean; //dummy
  r: TRect;
  s: string;
begin
(* Determine dock target(?) and align.
  Called with current DockRect (should use InfluenceRect?)
  Usage: Only to prevent calls to the target control, in case of extended
    InfluenceRect.
*)
//test
  exit(false);

  if false then
    Result:=inherited GetDockEdge(ADockObject);
{$IFDEF old}
  //ADockObject.DockRect
  Result := DockSite.DockClientCount = 0; //do nothing if docked clients exist!
  if Result then begin
    ADockObject.DropAlign := DetectAlign(ADockObject.DockRect, ADockObject.DragPos);
  {$IFDEF VerboseDrag}
    WriteStr(s, ADockObject.DropAlign);
    DebugLn('dockedge x(%d-%d) y(%d-%d) %s', [
      ADockObject.DockRect.Left, ADockObject.DockRect.Right,
      ADockObject.DockRect.Top, ADockObject.DockRect.Bottom, s
      ]);
  {$ELSE}
  {$ENDIF}
  end else begin
  //init a valid DockRect?
    r := ADockObject.DockRect;
    TWinControlAccess(FDockSite).GetSiteInfo(nil, r, ADockObject.DragPos, CanDock);
    ADockObject.DockRect := r;
    Result := CanDock;
  end;
{$ELSE}
  DebugLn('DropOnControl ', DbgS(ADockObject.DropOnControl));
  ADockObject.DropAlign := DetectAlign(ADockObject.DockRect, ADockObject.DragPos);
  WriteStr(s, ADockObject.DropAlign);
  Result := True;
  DebugLn('dockedge x(%d-%d) y(%d-%d) %s', [
    ADockObject.DockRect.Left, ADockObject.DockRect.Right,
    ADockObject.DockRect.Top, ADockObject.DockRect.Bottom, s
    ]);
{$ENDIF}
end;

procedure TEasyDockManager.PositionDockRect(Client, DropCtl: TControl;
  DropAlign: TAlign; var DockRect: TRect);
var
  wh: integer;
begin
(* DockRect is initialized to the screen rect of the dock site by TControl,
  or to the zone rect by TEasyTree.

  DropCtl=Nil means: dock into the root zone.
*)
  //if False then inherited PositionDockRect(Client, DropCtl, DropAlign, DockRect);
{$IFDEF old}
  if (DropCtl = nil) {$IFDEF singleTab} and not SingleTab {$ENDIF}  then
  //if (DropCtl = nil) then
    exit; //entire dock site
{$ELSE}
{$ENDIF}

  case DropAlign of
  //alClient: as is
  alTop:    DockRect.Bottom := (DockRect.Top + DockRect.Bottom) div 2;
  alBottom: DockRect.Top := (DockRect.Top + DockRect.Bottom) div 2;
  alLeft:   DockRect.Right := (DockRect.Left + DockRect.Right) div 2;
  alRight:  DockRect.Left := (DockRect.Left + DockRect.Right) div 2;
  alCustom: //pages
    begin
      wh := (DockRect.Right - DockRect.Left) div 3;
      inc(DockRect.Left, wh);
      dec(DockRect.Right, wh);
      wh := (DockRect.Bottom - DockRect.Top) div 3;
      inc(DockRect.Top, wh);
      dec(DockRect.Bottom, wh);
    end;
  end;
end;

procedure TEasyDockManager.PositionDockRect(ADockObject: TDragDockObject);
var
  r: TRect;
begin
(* Something is wrong here?
ADockObject:
  DockRect is the site rect, to be replaced by the target control/zone rect.
*)

//test
  exit;

  if false then inherited PositionDockRect(ADockObject);
  with ADockObject do begin;
  //check target
    if DropOnControl <> nil then begin
    //init control rect
      r.TopLeft := DropOnControl.ClientOrigin;
      r.Bottom := r.Top + DropOnControl.Height;
      r.Right := r.Left + DropOnControl.Width;
    end else begin
      r := DockRect;
    end;
    DetectAlign(r, DragPos);
  end;
end;

procedure TEasyDockManager.SetReplacingControl(Control: TControl);
begin
//nop
  //inherited SetReplacingControl(Control);
  FReplacingControl := Control;
end;

procedure TEasyDockManager.Update;
begin
  //nop
end;

{ TCustomDockSite }

class function TCustomDockSite.ReloadSite(AName: string;
  AOwner: TComponent): TCustomDockSite;
var
  ss: TStringStream;
  tn: string;
  //tc: TClass;
  ct: TPersistentClass;
  dst: TDockSiteClass absolute ct;
begin
(* Restore from typename, then restore clients.
  Called when AName[1]=CustomDockSiteID.
*)
  Result := nil;
  ss := TStringStream.Create(AName);
  try
    if ss.ReadByte <> CustomDockSiteID then begin
      ShowMessage('bad stream format');
      exit; //bad format
    end;
    tn := ss.ReadAnsiString;
    ct := GetClass(tn);
    if ct = nil then begin
      ShowMessage('class not registered: ' + tn);
      exit;
    end;
    if ct.InheritsFrom(TCustomDockSite) then begin
      Result := dst.Create(AOwner);
      Result.LoadFromStream(ss);
    end;
  finally
    ss.Free;
  end;
end;

procedure TCustomDockSite.ShowForm(AForm: TControl);
begin
(* Notebooks activate this control
*)
  AForm.Visible := True;
end;

function TCustomDockSite.SaveSite: string;
var
  ss: TStringStream;
begin
(* Save typename and clients.
  Write to string:
  - CustomDockSiteID
  - ClassName
  - content (SaveToStream)
*)
  ss := TStringStream.Create('');
  try
    ss.WriteByte(CustomDockSiteID);
    ss.WriteAnsiString(ClassName);
    SaveToStream(ss);
    Result := ss.DataString;
  finally
    ss.Free;
  end;
end;

procedure TCustomDockSite.SaveToStream(strm: TStream);
var
  i, n: integer;
  ctl: TControl;
  s: string;
begin
(* Save all docked controls.
  Flag nested custom dock sites - how?
*)
  if assigned(DockManager) then begin
    DockManager.SaveToStream(strm);
    exit;
  end;
{$IFDEF new}
(* requires:
- flag unmanaged
- ctl.BoundsRect (within site!) -> translate for ManualDock
*)
  n := DockClientCount;
  strm.WriteByte(n);
  for i := 0 to n-1 do begin
    ctl := DockClients[i];
    s := DockLoader.SaveControl(ctl, self);
    strm.WriteAnsiString(s);
  end;
{$ELSE}
  //unmanaged docksites unhandled
{$ENDIF}
end;

procedure TCustomDockSite.LoadFromStream(strm: TStream);
var
  i, n: integer;
  ctl: TControl;
  cn: string;
begin
  if assigned(DockManager) then begin
    DockManager.LoadFromStream(strm);
    exit;
  end
{$IFDEF new}
//see SaveToStream!
  n := strm.ReadByte;
  for i := 1 to n do begin
    cn := strm.ReadAnsiString;
    ctl := DockLoader.ReloadControl(cn, self);
    if ctl <> nil then
      ctl.ManualDock(self); //orientation???
    //make visible?
  end;
{$ELSE}
  //unmanaged docksites unhandled
{$ENDIF}
end;

{ TCustomDockMaster }

function TCustomDockMaster.SaveControl(Control: TControl;
  Site: TWinControl): string;
begin
(* Create string descriptor for docked control.
*)
  Result := '';
  if Control is TCustomDockSite then
    Result := TCustomDockSite(Control).SaveSite
  else if Assigned(AppLoadStore)
  and AppLoadStore(alsSaveControl, Site, Control, Result) then begin
    //all done
  end else if Assigned(FOnSave) then
    Result := FOnSave(Control);
//last resort
  if Result = '' then begin
    CtlToRec(Control);
    Result := RecToId;
  end;
  //Result := Control.Name; //definitely child.Name
end;

procedure TCustomDockMaster.CtlToRec(ctl: TControl);
begin
//fill record with all names
  rc.Ctrl := ctl;
  rc.ClassName := ctl.ClassName;
  rc.Name := ctl.Name;
  rc.Caption := ctl.Caption; //general purpose
end;

procedure TCustomDockMaster.IdToRec(const ID: string);
var
  i: integer;
begin
  rc.Ctrl := nil; //flag: not yet found/created
//split <Name>':'<ClassName>'='<Caption>
  i := Pos(':', ID);
  if i > 0 then begin
    rc.Name := Copy(ID, 1, i-1);
    rc.ClassName := Copy(ID, i+1, Length(ID));
    i := Pos('=', rc.ClassName);
    if i > 0 then begin
      rc.Caption := Copy(rc.ClassName, i+1, Length(rc.Caption));
      SetLength(rc.ClassName, i-1);
    end else
      rc.Caption := rc.Name;
  end else begin
    rc.Caption := ID;
    rc.ClassName := 'T'+ID;
  //strip spaces from Caption
    rc.Name := StringReplace(rc.Caption, ' ', '', [rfReplaceAll]);
  end;
end;

function TCustomDockMaster.RecToId: string;
begin
  Result := rc.Name + ':' + rc.ClassName + '=' + rc.Caption
end;

function TCustomDockMaster.MakeDockable(AForm: TWinControl; fWrap: boolean;
  fVisible: boolean): TForm;
var
  wctl: TWinControlAccess absolute AForm;
begin
(* Result is the floating site, if created (fWrap).
  fWrap here is ignored.
To be overridden by final TDockMaster, for wrapping.
*)
//make it dockable
  wctl.DragKind := dkDock;
  wctl.DragMode := dmAutomatic;
  if fVisible then
    AForm.Show;
  Result := nil; //not wrapped
end;

function TCustomDockMaster.ReloadControl(const AName: string;
  Site: TWinControl): TControl;
var
  fc: TWinControlClass;
  fo: TComponent; //form owner
  cmp: TComponent absolute Result;
begin
(* Reload from:
- CustomDockSite (allow for nested layouts)
- AppLoadStore
- OnRestore
- our Owner
- create from descriptor (optionally)
- DockSite
*)
  Result := nil;
  IdToRec(AName); //make all information accessible to external subroutines
//first check for special CustomDockSite format
  if ord(AName[1]) = CustomDockSiteID then
    Result := TCustomDockSite.ReloadSite(AName, Site)
  else if assigned(AppLoadStore)
  and AppLoadStore(alsReloadControl, Site, Result, rc.Name) then begin
    //all done - string-argument questionable!
  end else if assigned(FOnRestore) then
    Result := FOnRestore(rc.Name, Site);
  if Result <> nil then
    exit;
//check existing control
  fo := Owner; //assume all freely dockable controls are owned by our owner (Application)
  cmp := FindOwnedComponent(rc.Name, fo);
  //if Result <> nil then
  if Result is TControl then
    exit;
  Result := nil; //exclude non-controls
//create from descriptor?
  if TryCreateControls then begin
    fc := TWinControlClass(GetClass(rc.ClassName));
    if not assigned(fc) then begin
      DebugLn(rc.ClassName, ' is not a registered class');
      //exit(nil); //bad form name
    end else begin
    //init from descriptor
      Result := fc.Create(fo);
      if Result.Name <> rc.Name then
        TryRename(Result, rc.Name);
      if Result.Caption <> rc.Caption then
        Result.Caption := rc.Caption; //really?
    end;
  end;
//last resort
  if Result = nil then
    TWinControlAccess(Site).ReloadDockedControl(rc.Name, Result);
end;

initialization
  //DefaultDockManagerClass := TEasyTree;
  CreateDockHeaderImages;
  if DockLoader = nil then
    DockLoader := TCustomDockMaster.Create(Application);
finalization
  DestroyDockHeaderImages;
  //FreeAndNil(LoadStore); - by owner!
end.