This file is indexed.

/usr/lib/lazarus/0.9.30.4/lcl/controls.pp 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
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
{  $Id: controls.pp 31590 2011-07-07 17:00:30Z juha $  }
{
 /***************************************************************************
                               Controls.pp
                             -------------------
                             Component Library Controls
                   Initial Revision : Sat Apr 10 22:49:32 CST 1999


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

 *****************************************************************************
 *                                                                           *
 *  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.                     *
 *                                                                           *
 *****************************************************************************
}
unit Controls;

{$mode objfpc}{$H+}
{$I lcl_defines.inc}
{off $DEFINE BUFFERED_WMPAINT}

interface

{$ifdef Trace}
{$ASSERTIONS ON}
{$endif}

{$IFOPT C-}
// Uncomment for local trace
//  {$C+}
//  {$DEFINE ASSERT_IS_ON}
{$ENDIF}

uses
  Classes, SysUtils, TypInfo, types, LCLStrConsts, LCLType, AvgLvlTree,
  LCLProc, GraphType, Graphics, LMessages, LCLIntf, InterfaceBase, ImgList,
  UTrace, PropertyStorage, Menus, ActnList, LCLClasses, LResources;


const
  mrNone = 0;
  mrOK = mrNone + 1;
  mrCancel = mrNone + 2;
  mrAbort = mrNone + 3;
  mrRetry = mrNone + 4;
  mrIgnore = mrNone + 5;
  mrYes = mrNone + 6;
  mrNo = mrNone + 7;
  mrAll = mrNone + 8;
  mrNoToAll = mrNone + 9;
  mrYesToAll = mrNone + 10;
  mrLast = mrYesToAll;

  // define aliases for Delphi compatibility
  fsSurface = GraphType.fsSurface;
  fsBorder = GraphType.fsBorder;

  bvNone = GraphType.bvNone;
  bvLowered = GraphType.bvLowered;
  bvRaised = GraphType.bvRaised;
  bvSpace = GraphType.bvSpace;

type
  TWinControl = class;
  TControl = class;
  TWinControlClass = class of TWinControl;
  TControlClass = class of TControl;

{$if (FPC_VERSION <= 2) and (FPC_RELEASE <= 4) and (FPC_PATCH < 2)}
  TDate = type TDateTime;
  TTime = type TDateTime;
{$endif}

  // ToDo: move this to a message definition unit
  TCMMouseWheel = record
    MSg: Cardinal;
    ShiftState: TShiftState;
    Unused: Byte;
    WheelData: SmallInt;
    case Integer of
    0: (
      XPos: SmallInt;
      YPos: SmallInt);
    1: (
      Pos: TSmallPoint;
      Result: LRESULT);
  end;

  TCMHitTest = TLMNCHitTest;

  TCMControlChange = record
    Msg: Cardinal;
    Control: TControl;
    Inserting: LongBool;
    Result: LRESULT;
  end;

  TCMControlListChange = record
    Msg: Cardinal;
    Control: TControl;
    Inserting: LongBool;
    Result: LRESULT;
  end;

  TCMDialogChar = TLMKEY;
  TCMDialogKey = TLMKEY;

  TAlign = (alNone, alTop, alBottom, alLeft, alRight, alClient, alCustom);
  TAlignSet = set of TAlign;
  TAnchorKind = (akTop, akLeft, akRight, akBottom);
  TAnchors = set of TAnchorKind;
  TAnchorSideReference = (asrTop, asrBottom, asrCenter);

const
  asrLeft = asrTop;
  asrRight = asrBottom;

type
  TCaption = TTranslateString;
  TCursor = -32768..32767;

  TFormStyle = (fsNormal, fsMDIChild, fsMDIForm, fsStayOnTop, fsSplash, fsSystemStayOnTop);
  TFormBorderStyle = (bsNone, bsSingle, bsSizeable, bsDialog, bsToolWindow,
                      bsSizeToolWin);
  TBorderStyle = bsNone..bsSingle;
  TControlBorderStyle = TBorderStyle;

  TControlRoleForForm = (
    crffDefault,// this control is notified when user presses Return
    crffCancel  // this control is notified when user presses Escape
    );
  TControlRolesForForm = set of TControlRoleForForm;

  TBevelCut = TGraphicsBevelCut;

  TMouseButton = (mbLeft, mbRight, mbMiddle, mbExtra1, mbExtra2);

const
  fsAllStayOnTop = [fsStayOnTop, fsSplash, fsSystemStayOnTop];
  fsAllNonSystemStayOnTop = [fsStayOnTop, fsSplash];

  // Cursor constants
  crHigh        = TCursor(0);

  crDefault     = TCursor(0);
  crNone        = TCursor(-1);
  crArrow       = TCursor(-2);
  crCross       = TCursor(-3);
  crIBeam       = TCursor(-4);
  crSize        = TCursor(-22);
  crSizeNESW    = TCursor(-6); // diagonal north east - south west
  crSizeNS      = TCursor(-7);
  crSizeNWSE    = TCursor(-8);
  crSizeWE      = TCursor(-9);
  crSizeNW      = TCursor(-23);
  crSizeN       = TCursor(-24);
  crSizeNE      = TCursor(-25);
  crSizeW       = TCursor(-26);
  crSizeE       = TCursor(-27);
  crSizeSW      = TCursor(-28);
  crSizeS       = TCursor(-29);
  crSizeSE      = TCursor(-30);
  crUpArrow     = TCursor(-10);
  crHourGlass   = TCursor(-11);
  crDrag        = TCursor(-12);
  crNoDrop      = TCursor(-13);
  crHSplit      = TCursor(-14);
  crVSplit      = TCursor(-15);
  crMultiDrag   = TCursor(-16);
  crSQLWait     = TCursor(-17);
  crNo          = TCursor(-18);
  crAppStart    = TCursor(-19);
  crHelp        = TCursor(-20);
  crHandPoint   = TCursor(-21);
  crSizeAll     = TCursor(-22);

  crLow         = TCursor(-30);

type
  TCaptureMouseButtons = set of TMouseButton;

  TWndMethod = procedure(var TheMessage: TLMessage) of Object;

  TControlStyleType = (
    csAcceptsControls,       // can have children in the designer
    csCaptureMouse,
    csDesignInteractive,     // wants mouse events in design mode
    csClickEvents,
    csFramed,
    csSetCaption,
    csOpaque,
    csDoubleClicks,          // control understands mouse double clicks
    csTripleClicks,          // control understands mouse triple clicks
    csQuadClicks,            // control understands mouse quad clicks
    csFixedWidth,
    csFixedHeight,           // control cannot change it height (for example combobox)
    csNoDesignVisible,       // control is invisible in the designer
    csReplicatable,
    csNoStdEvents,
    csDisplayDragImage,      // display images from dragimagelist during drag operation over control
    csReflector,
    csActionClient,
    csMenuEvents,
    csNoFocus,
    csNeedsBorderPaint,      // not implemented
    csParentBackground,      // not implemented
    csDesignNoSmoothResize,  // no WYSIWYG resizing in designer
    csDesignFixedBounds,     // control can not be moved nor resized in designer
    csHasDefaultAction,      // control implements useful ExecuteDefaultAction
    csHasCancelAction,       // control implements useful ExecuteCancelAction
    csNoDesignSelectable,    // control can not be selected at design time
    csOwnedChildrenNotSelectable, // child controls owned by this control are NOT selectable in the designer
    csAutoSize0x0,           // if the preferred size is 0x0 then control is shrinked ot 0x0
    csAutoSizeKeepChildLeft, // when AutoSize=true do not move children horizontally
    csAutoSizeKeepChildTop   // when AutoSize=true do not move children vertically
    );
  TControlStyle = set of TControlStyleType;

const
  csMultiClicks = [csDoubleClicks,csTripleClicks,csQuadClicks];


type
  TControlStateType = (
    csLButtonDown,
    csClicked,
    csPalette,
    csReadingState,
    csFocusing,
    csCreating, // not used, exists for Delphi compatibility
    csPaintCopy,
    csCustomPaint,
    csDestroyingHandle,
    csDocking,
    csVisibleSetInLoading
  );
  TControlState = set of TControlStateType;


  { TControlCanvas }

  TControlCanvas = class(TCanvas)
  private
    FControl: TControl;
    FDeviceContext: HDC;
    FWindowHandle: HWND;
    procedure SetControl(AControl: TControl);
  protected
    procedure CreateHandle; override;
    function GetDefaultColor(const ADefaultColorType: TDefaultColorType): TColor; override;
  public
    constructor Create;
    destructor Destroy; override;
    procedure FreeHandle;override;
    function ControlIsPainting: boolean;
    property Control: TControl read FControl write SetControl;
  end;

  { Hint stuff }

  PHintInfo = ^THintInfo;
  THintInfo = record
    HintControl: TControl;
    HintWindowClass: TWinControlClass;
    HintPos: TPoint;
    HintMaxWidth: Integer;
    HintColor: TColor;
    CursorRect: TRect;
    CursorPos: TPoint;
    ReshowTimeout: Integer;
    HideTimeout: Integer;
    HintStr: string;
    HintData: Pointer;
  end;


  { TDragImageList }

  TDragImageList = class(TCustomImageList)
  private
    FDragCursor: TCursor;
    FDragging: Boolean;
    FDragHotspot: TPoint;
    FOldCursor: TCursor;
    FImageIndex: Integer;
    FLastDragPos: TPoint;
    FLockedWindow: HWND;// window where drag started and locked via DragLock, invalid=NoLockedWindow=High(PtrInt)
    procedure SetDragCursor(const AValue: TCursor);
  protected
    class procedure WSRegisterClass; override;
    procedure Initialize; override;
  public
    function BeginDrag(Window: HWND; X, Y: Integer): Boolean;
    function DragLock(Window: HWND; XPos, YPos: Integer): Boolean;
    function DragMove(X, Y: Integer): Boolean;
    procedure DragUnlock;
    function EndDrag: Boolean;
    function GetHotSpot: TPoint; override;
    procedure HideDragImage;
    function SetDragImage(Index, HotSpotX, HotSpotY: Integer): Boolean;
    procedure ShowDragImage;
    property DragCursor: TCursor read FDragCursor write SetDragCursor;
    property DragHotspot: TPoint read FDragHotspot write FDragHotspot;
    property Dragging: Boolean read FDragging;
  end;

  TKeyEvent = procedure(Sender: TObject; var Key: Word; Shift: TShiftState) of Object;
  TKeyPressEvent = procedure(Sender: TObject; var Key: char) of Object;
  TUTF8KeyPressEvent = procedure(Sender: TObject; var UTF8Key: TUTF8Char) of Object;

  TMouseEvent = procedure(Sender: TObject; Button: TMouseButton;
                          Shift: TShiftState; X, Y: Integer) of Object;
  TMouseMoveEvent = procedure(Sender: TObject; Shift: TShiftState;
                              X, Y: Integer) of Object;
  TMouseWheelEvent = procedure(Sender: TObject; Shift: TShiftState;
         WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean) of Object;
  TMouseWheelUpDownEvent = procedure(Sender: TObject;
          Shift: TShiftState; MousePos: TPoint; var Handled: Boolean) of Object;

  TGetDockCaptionEvent = procedure(Sender: TObject; AControl: TControl;
    var ACaption: String) of Object;


  { TDragObject }

  TDragObject = class;

  TDragKind = (dkDrag, dkDock);
  TDragMode = (dmManual , dmAutomatic);
  TDragState = (dsDragEnter, dsDragLeave, dsDragMove);
  TDragMessage = (dmDragEnter, dmDragLeave, dmDragMove, dmDragDrop,
                  dmDragCancel,dmFindTarget);

  TDragOverEvent = procedure(Sender, Source: TObject;
               X,Y: Integer; State: TDragState; var Accept: Boolean) of object;
  TDragDropEvent = procedure(Sender, Source: TObject; X,Y: Integer) of object;
  TStartDragEvent = procedure(Sender: TObject; var DragObject: TDragObject) of object;
  TEndDragEvent = procedure(Sender, Target: TObject; X,Y: Integer) of object;

  TDragObject = class
  private
    FAlwaysShowDragImages: Boolean;
    FDragPos: TPoint;
    FControl: TControl;
    FDragTarget: TControl;
    FDragTargetPos: TPoint;
    FAutoFree: Boolean;
    FAutoCreated: Boolean;
    FDropped: Boolean;
  protected
    procedure EndDrag(Target: TObject; X, Y: Integer); virtual;
    function GetDragImages: TDragImageList; virtual;
    function GetDragCursor(Accepted: Boolean; X, Y: Integer): TCursor; virtual;
  public
    constructor Create(AControl: TControl); virtual;
    constructor AutoCreate(AControl: TControl);

    procedure HideDragImage; virtual;
    procedure ShowDragImage; virtual;

    property AlwaysShowDragImages: Boolean read FAlwaysShowDragImages write FAlwaysShowDragImages;
    property AutoCreated: Boolean read FAutoCreated;
    property AutoFree: Boolean read FAutoFree;
    property Control: TControl read FControl write FControl; // the dragged control
    property DragPos: TPoint read FDragPos write FDragPos;
    property DragTarget: TControl read FDragTarget write FDragTarget;
    property DragTargetPos: TPoint read FDragTargetPos write FDragTargetPos;
    property Dropped: Boolean read FDropped;
  end;

  TDragObjectClass = class of TDragObject;

  { TDragObjectEx }

  TDragObjectEx = class(TDragObject)
  public
    constructor Create(AControl: TControl); override;
  end;


  { TDragControlObject }

  TDragControlObject = class(TDragObject)
  protected
    function GetDragCursor(Accepted: Boolean; X, Y: Integer): TCursor; override;
    function GetDragImages: TDragImageList; override;
  end;

  { TDragControlObjectEx }

  TDragControlObjectEx = class(TDragControlObject)
  public
    constructor Create(AControl: TControl); override;
  end;

  { TDragDockObject }

  TDragDockObject = class;

  TDockOrientation = (
    doNoOrient,   // zone contains a TControl and no child zones.
    doHorizontal, // zone's children are stacked top-to-bottom.
    doVertical,   // zone's children are arranged left-to-right.
    doPages       // zone's children are pages arranged left-to-right.
    );
  TDockDropEvent = procedure(Sender: TObject; Source: TDragDockObject;
                             X, Y: Integer) of object;
  TDockOverEvent = procedure(Sender: TObject; Source: TDragDockObject;
                             X, Y: Integer; State: TDragState;
                             var Accept: Boolean) of object;
  TUnDockEvent = procedure(Sender: TObject; Client: TControl;
                          NewTarget: TWinControl; var Allow: Boolean) of object;
  TStartDockEvent = procedure(Sender: TObject;
                              var DragObject: TDragDockObject) of object;
  TGetSiteInfoEvent = procedure(Sender: TObject; DockClient: TControl;
    var InfluenceRect: TRect; MousePos: TPoint; var CanDock: Boolean) of object;

  TDragDockObject = class(TDragObject)
  private
    FDockOffset: TPoint;
    FDockRect: TRect;
    FDropAlign: TAlign;
    FDropOnControl: TControl;
    FEraseDockRect: TRect;
    FFloating: Boolean;
    FIncreaseDockArea: Boolean;
  protected
    procedure AdjustDockRect(ARect: TRect); virtual;
    function GetDragCursor(Accepted: Boolean; X, Y: Integer): TCursor; override;
    procedure EndDrag(Target: TObject; X, Y: Integer); override;

    // dock image drawing
    procedure InitDock(APosition: TPoint); virtual;
    procedure ShowDockImage; virtual;
    procedure HideDockImage; virtual;
    procedure MoveDockImage; virtual;
  public
    property DockOffset: TPoint read FDockOffset write FDockOffset;
    property DockRect: TRect read FDockRect write FDockRect; // where to drop Control, screen coordinates
    property DropAlign: TAlign read FDropAlign write FDropAlign; // how to align Control
    property DropOnControl: TControl read FDropOnControl write FDropOnControl; // drop on child control of Target (Target is a parameter, not a property)
    property Floating: Boolean read FFloating write FFloating;
    property IncreaseDockArea: Boolean read FIncreaseDockArea;
    property EraseDockRect: TRect read FEraseDockRect write FEraseDockRect;
  end;

  { TDragDockObjectEx }

  TDragDockObjectEx = class(TDragDockObject)
  public
    constructor Create(AControl: TControl); override;
  end;

  { TDragManager }

  TDragManager = class(TComponent)
  private
    FDragImmediate: Boolean;
    FDragThreshold: Integer;
  protected
    //input capture
    procedure KeyUp(var Key: Word; Shift : TShiftState); virtual;abstract;
    procedure KeyDown(var Key: Word; Shift: TShiftState); virtual;abstract;
    procedure CaptureChanged(OldCaptureControl: TControl); virtual;abstract;
    procedure MouseMove(Shift: TShiftState; X,Y: Integer); virtual;abstract;
    procedure MouseUp(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); virtual;abstract;
    procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); virtual;abstract;
  public
    constructor Create(TheOwner: TComponent); override;

    function IsDragging: boolean; virtual;abstract;
    function Dragging(AControl: TControl): boolean; virtual;abstract;
    procedure RegisterDockSite(Site: TWinControl; DoRegister: Boolean); virtual;abstract;

    procedure DragStart(AControl: TControl; AImmediate: Boolean; AThreshold: Integer);virtual;abstract;
    procedure DragMove(APosition: TPoint); virtual;abstract;
    procedure DragStop(ADrop: Boolean); virtual;abstract;

    property DragImmediate: Boolean read FDragImmediate write FDragImmediate default True;
    property DragThreshold: Integer read FDragThreshold write FDragThreshold default 5;
  end;

var
  DragManager: TDragManager = nil;// created in initialization

type
  { TDockManager is an abstract class for managing a dock site's docked
    controls. See TDockTree below for the more info.
    }
{ TODO -cdocking : More (flexible) event handlers are required, for:
- all docking related messages, based on a TDragDockObject parameter
- changed visibility of docked controls (and more?)
 }
  TDockManager = class(TPersistent)
  public
    constructor Create(ADockSite: TWinControl); virtual;
    procedure BeginUpdate; virtual;
    procedure EndUpdate; virtual;
    procedure GetControlBounds(Control: TControl;
                               out AControlBounds: TRect); virtual; abstract;
    function GetDockEdge(ADockObject: TDragDockObject): boolean; virtual;
    procedure InsertControl(ADockObject: TDragDockObject); virtual; overload;
    procedure InsertControl(Control: TControl; InsertAt: TAlign;
                            DropCtl: TControl); virtual; abstract; overload;
    procedure LoadFromStream(Stream: TStream); virtual; abstract;
    procedure PaintSite(DC: HDC); virtual;
    procedure MessageHandler(Sender: TControl; var Message: TLMessage); virtual;
    procedure PositionDockRect(ADockObject: TDragDockObject); virtual; overload;
    procedure PositionDockRect(Client, DropCtl: TControl; DropAlign: TAlign;
                               var DockRect: TRect); virtual; abstract; overload;
    procedure RemoveControl(Control: TControl); virtual; abstract;
    procedure ResetBounds(Force: Boolean); virtual; abstract;
    procedure SaveToStream(Stream: TStream); virtual; abstract;
    procedure SetReplacingControl(Control: TControl); virtual;
    function AutoFreeByControl: Boolean; virtual;
  end;

  TDockManagerClass = class of TDockManager;

  { TSizeConstraints }

  TConstraintSize = 0..MaxInt;

  TSizeConstraintsOption = (
    // not yet used
    scoAdviceWidthAsMin,
    scoAdviceWidthAsMax,
    scoAdviceHeightAsMin,
    scoAdviceHeightAsMax
    );
  TSizeConstraintsOptions = set of TSizeConstraintsOption;

  TSizeConstraints = class(TPersistent)
  private
    FControl: TControl;
    FMaxHeight: TConstraintSize;
    FMaxInterfaceHeight: integer;
    FMaxInterfaceWidth: integer;
    FMaxWidth: TConstraintSize;
    FMinHeight: TConstraintSize;
    FMinInterfaceHeight: integer;
    FMinInterfaceWidth: integer;
    FMinWidth: TConstraintSize;
    FOnChange: TNotifyEvent;
    FOptions: TSizeConstraintsOptions;
    procedure SetOptions(const AValue: TSizeConstraintsOptions);
  protected
    procedure Change; virtual;
    procedure AssignTo(Dest: TPersistent); override;
    procedure SetMaxHeight(Value: TConstraintSize); virtual;
    procedure SetMaxWidth(Value: TConstraintSize); virtual;
    procedure SetMinHeight(Value: TConstraintSize); virtual;
    procedure SetMinWidth(Value: TConstraintSize); virtual;
  public
    constructor Create(AControl: TControl); virtual;
    procedure UpdateInterfaceConstraints; virtual;
    procedure SetInterfaceConstraints(MinW, MinH, MaxW, MaxH: integer); virtual;
    function EffectiveMinWidth: integer; virtual;
    function EffectiveMinHeight: integer; virtual;
    function EffectiveMaxWidth: integer; virtual;
    function EffectiveMaxHeight: integer; virtual;
    function MinMaxWidth(Width: integer): integer;
    function MinMaxHeight(Height: integer): integer;
  public
    property MaxInterfaceHeight: integer read FMaxInterfaceHeight;
    property MaxInterfaceWidth: integer read FMaxInterfaceWidth;
    property MinInterfaceHeight: integer read FMinInterfaceHeight;
    property MinInterfaceWidth: integer read FMinInterfaceWidth;
    property Control: TControl read FControl;
    property Options: TSizeConstraintsOptions read FOptions write SetOptions default [];
  published
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property MaxHeight: TConstraintSize read FMaxHeight write SetMaxHeight default 0;
    property MaxWidth: TConstraintSize read FMaxWidth write SetMaxWidth default 0;
    property MinHeight: TConstraintSize read FMinHeight write SetMinHeight default 0;
    property MinWidth: TConstraintSize read FMinWidth write SetMinWidth default 0;
  end;

  TConstrainedResizeEvent = procedure(Sender: TObject;
      var MinWidth, MinHeight, MaxWidth, MaxHeight: TConstraintSize) of object;


  { TControlBorderSpacing }

  { TControlBorderSpacing defines the spacing around a control.
    The spacing around its children and between its children is defined in
    TWinControl.ChildSizing.

    Left, Top, Right, Bottom: integer;
        minimum space left to the autosized control.
        For example: Control A lies left of control B.
        A has borderspacing Right=10 and B has borderspacing Left=5.
        Then A and B will have a minimum space of 10 between.

    Around: integer;
        same as Left, Top, Right and Bottom all at once. This will be added to
        the effective Left, Top, Right and Bottom.
        Example: Left=3 and Around=5 results in a minimum spacing to the left
        of 8.

    InnerBorder: integer;
        This is added to the preferred size.
        For example: A buttons widget returns 75x25 on GetPreferredSize.
        CalculatePreferredSize adds 2 times the InnerBorder to the width and
        height.

    CellAlignHorizontal, CellAlignVertical: TControlCellAlign;
        Used for example when the Parents.ChildSizing.Layout defines a table
        layout.
  }

  TSpacingSize = 0..MaxInt;
  TControlCellAlign = (
    ccaFill,
    ccaLeftTop,
    ccaRightBottom,
    ccaCenter
    );
  TControlCellAligns = set of TControlCellAlign;

  { TControlBorderSpacingDefault defines the default values for TControlBorderSpacing
    so derived TControl classes can define their own default values }

  TControlBorderSpacingDefault = record
    Left: TSpacingSize;
    Top: TSpacingSize;
    Right: TSpacingSize;
    Bottom: TSpacingSize;
    Around: TSpacingSize;
  end;
  PControlBorderSpacingDefault = ^TControlBorderSpacingDefault;


  { TControlBorderSpacing }

  TControlBorderSpacing = class(TPersistent)
  private
    FAround: TSpacingSize;
    FBottom: TSpacingSize;
    FCellAlignHorizontal: TControlCellAlign;
    FCellAlignVertical: TControlCellAlign;
    FControl: TControl;
    FInnerBorder: Integer;
    FLeft: TSpacingSize;
    FOnChange: TNotifyEvent;
    FRight: TSpacingSize;
    FTop: TSpacingSize;
    FDefault: PControlBorderSpacingDefault;
    function IsAroundStored: boolean;
    function IsBottomStored: boolean;
    function IsInnerBorderStored: boolean;
    function IsLeftStored: boolean;
    function IsRightStored: boolean;
    function IsTopStored: boolean;
    procedure SetAround(const AValue: TSpacingSize);
    procedure SetBottom(const AValue: TSpacingSize);
    procedure SetCellAlignHorizontal(const AValue: TControlCellAlign);
    procedure SetCellAlignVertical(const AValue: TControlCellAlign);
    procedure SetInnerBorder(const AValue: Integer);
    procedure SetLeft(const AValue: TSpacingSize);
    procedure SetRight(const AValue: TSpacingSize);
    procedure SetSpace(Kind: TAnchorKind; const AValue: integer);
    procedure SetTop(const AValue: TSpacingSize);
  protected
    procedure Change(InnerSpaceChanged: Boolean); virtual;
  public
    constructor Create(OwnerControl: TControl; ADefault: PControlBorderSpacingDefault = nil);
    procedure Assign(Source: TPersistent); override;
    procedure AssignTo(Dest: TPersistent); override;
    function IsEqual(Spacing: TControlBorderSpacing): boolean;
    procedure GetSpaceAround(var SpaceAround: TRect);
    function GetSpace(Kind: TAnchorKind): Integer;
    function GetSideSpace(Kind: TAnchorKind): Integer;
  public
    property Control: TControl read FControl;
    property Space[Kind: TAnchorKind]: integer read GetSpace write SetSpace;
  published
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property Left: TSpacingSize read FLeft write SetLeft stored IsLeftStored;
    property Top: TSpacingSize read FTop write SetTop stored IsTopStored;
    property Right: TSpacingSize read FRight write SetRight stored IsRightStored;
    property Bottom: TSpacingSize read FBottom write SetBottom stored IsBottomStored;
    property Around: TSpacingSize read FAround write SetAround stored IsAroundStored;
    property InnerBorder: Integer read FInnerBorder write SetInnerBorder stored IsInnerBorderStored default 0;
    property CellAlignHorizontal: TControlCellAlign read FCellAlignHorizontal write SetCellAlignHorizontal default ccaFill;
    property CellAlignVertical: TControlCellAlign read FCellAlignVertical write SetCellAlignVertical default ccaFill;
  end;


  { TAnchorSide
    Class holding the reference sides of the anchors of a TControl.
    Every TControl has four AnchorSides:
    AnchorSide[akLeft], AnchorSide[akRight], AnchorSide[akTop] and
    AnchorSide[akBottom].
    Normally if Anchors contain akLeft, and the Parent is resized, the LCL
    tries to keep the distance between the left side of the control and the
    right side of its parent client area.
    With AnchorSide[akLeft] you can define a different reference side. The
    kept distance is defined by the BorderSpacing and Parent.ChildSizing.

    Example1:
       +-----+  +-----+
       |  B  |  |  C  |
       |     |  +-----+
       +-----+

      If you want to have the top of B the same as the top of C use
        B.AnchorSide[akTop].Side:=asrTop;
        B.AnchorSide[akTop].Control:=C;
      If you want to keep a distance of 10 pixels between B and C use
        B.BorderSpacing.Right:=10;
        B.AnchorSide[akRight].Side:=asrLeft;
        B.AnchorSide[akRight].Control:=C;

      Do not setup in both directions, because this will create a circle, and
      circles are not allowed.

    Example2:
            +-------+
      +---+ |       |
      | A | |   B   |
      +---+ |       |
            +-------+

      Centering A relative to B:
        A.AnchorSide[akTop].Side:=arsCenter;
        A.AnchorSide[akTop].Control:=B;
      Or use this. It's equivalent:
        A.AnchorSide[akBottom].Side:=arsCenter;
        A.AnchorSide[akBottom].Control:=B;
    }
  TAnchorSideChangeOperation = (ascoAdd, ascoRemove, ascoChangeSide);

  { TAnchorSide }

  TAnchorSide = class(TPersistent)
  private
    FKind: TAnchorKind; // keep FKind the first property. see bug 14364
    FControl: TControl;
    FOwner: TControl;
    FSide: TAnchorSideReference;
    function IsSideStored: boolean;
    procedure SetControl(const AValue: TControl);
    procedure SetSide(const AValue: TAnchorSideReference);
  protected
    function GetOwner: TPersistent; override;
  public
    constructor Create(TheOwner: TControl; TheKind: TAnchorKind);
    destructor Destroy; override;
    procedure GetSidePosition(out ReferenceControl: TControl;
                out ReferenceSide: TAnchorSideReference; out Position: Integer);
    function CheckSidePosition(NewControl: TControl; NewSide: TAnchorSideReference;
                out ReferenceControl: TControl;
                out ReferenceSide: TAnchorSideReference; out Position: Integer): boolean;
    procedure Assign(Source: TPersistent); override;
    function IsAnchoredToParent(ParentSide: TAnchorKind): boolean;
    procedure FixCenterAnchoring;
  public
    property Owner: TControl read FOwner;
    property Kind: TAnchorKind read FKind;
  published
    property Control: TControl read FControl write SetControl;
    property Side: TAnchorSideReference read FSide write SetSide default asrTop;
  end;

  { TControlActionLink }

  TControlActionLink = class(TActionLink)
  protected
    FClient: TControl;
    procedure AssignClient(AClient: TObject); override;
    procedure SetCaption(const Value: string); override;
    procedure SetEnabled(Value: Boolean); override;
    procedure SetHint(const Value: String); override;
    procedure SetHelpContext(Value: THelpContext); override;
    procedure SetHelpKeyword(const Value: string); override;
    procedure SetHelpType(Value: THelpType); override;
    procedure SetVisible(Value: Boolean); override;
    procedure SetOnExecute(Value: TNotifyEvent); override;
    function IsOnExecuteLinked: Boolean; override;
    function DoShowHint(var HintStr: string): Boolean; virtual;
  public
    function IsCaptionLinked: Boolean; override;
    function IsEnabledLinked: Boolean; override;
    function IsHelpLinked: Boolean;  override;
    function IsHintLinked: Boolean; override;
    function IsVisibleLinked: Boolean; override;
  end;

  TControlActionLinkClass = class of TControlActionLink;


  { TControl }

  TControlAutoSizePhase = (
    caspNone,
    caspChangingProperties,
    caspCreatingHandles, // create/destroy handles
    caspComputingBounds,
    caspRealizingBounds,
    caspShowing          // make handles visible
    );
  TControlAutoSizePhases = set of TControlAutoSizePhase;

  TTabOrder = -1..32767;

  TControlShowHintEvent = procedure(Sender: TObject; HintInfo: PHintInfo) of object;
  TContextPopupEvent = procedure(Sender: TObject; MousePos: TPoint;
                                 var Handled: Boolean) of object;

  TControlFlag = (
    cfLoading, // set by TControl.ReadState, unset by TControl.Loaded when all on form finished loading
    cfAutoSizeNeeded,
    cfLeftLoaded,  // cfLeftLoaded is set, when 'Left' is set during loading.
    cfTopLoaded,
    cfWidthLoaded,
    cfHeightLoaded,
    cfClientWidthLoaded,
    cfClientHeightLoaded,
    cfBoundsRectForNewParentValid,
    cfBaseBoundsValid,
    cfPreferredSizeValid,
    cfPreferredMinSizeValid,
    cfOnChangeBoundsNeeded,
    cfProcessingWMPaint,
    cfKillChangeBounds,
    cfKillInvalidatePreferredSize,
    cfKillAdjustSize
    );
  TControlFlags = set of TControlFlag;

  TControlHandlerType = (
    chtOnResize,
    chtOnChangeBounds,
    chtOnVisibleChanging,
    chtOnVisibleChanged,
    chtOnKeyDown
    );

{* Note on TControl.Caption
 * The VCL implementation relies on the virtual Get/SetTextBuf to
 * exchange text between widgets and VCL. This means a lot of
 * (unnecessary) text copies.
 * The LCL uses strings for exchanging text (more efficient).
 * To maintain VCL compatibility, the virtual RealGet/SetText is
 * introduced. These functions interface with the LCLInterface. The
 * default Get/SetTextbuf implementation calls the RealGet/SetText.
 * As long as the Get/SetTextBuf isn't overridden Get/SetText
 * calls RealGet/SetText to avoid PChar copying.
 * To keep things optimal, LCL implementations should always
 * override RealGet/SetText. Get/SetTextBuf is only kept for
 * compatibility.
 }

  TControl = class(TLCLComponent)
  private
    FActionLink: TControlActionLink;
    FAlign: TAlign;
    FAnchors: TAnchors;
    FAnchorSides: array[TAnchorKind] of TAnchorSide;
    FAnchoredControls: TFPList; // list of TControl anchored to this control
    FAutoSizingLockCount: Integer; // in/decreased by DisableAutoSizing/EnableAutoSizing
    {$IFDEF DebugDisableAutoSizing}
    FAutoSizingLockReasons: TStrings;
    {$ENDIF}
    FBaseBounds: TRect;
    FBaseBoundsLock: integer;
    FBaseParentClientSize: TSize;
    FBiDiMode: TBiDiMode;
    FBorderSpacing: TControlBorderSpacing;
    FBoundsRectForNewParent: TRect;
    FCaption: TCaption;
    FCaptureMouseButtons: TCaptureMouseButtons;
    FColor: TColor;
    FConstraints: TSizeConstraints;
    FControlFlags: TControlFlags;
    FControlHandlers: array[TControlHandlerType] of TMethodList;
    FControlStyle: TControlStyle;
    FDockOrientation: TDockOrientation;
    FDragCursor: TCursor;
    FDragKind: TDragKind;
    FDragMode: TDragMode;
    FFloatingDockSiteClass: TWinControlClass;
    FFont: TFont;
    FHeight: Integer;
    FHelpContext: THelpContext;
    FHelpKeyword: String;
    FHelpType: THelpType;
    FHint: TTranslateString;
    FHostDockSite: TWinControl;
    FLastDoChangeBounds: TRect;
    FLastDoChangeClientSize: TPoint;
    FLastResizeClientHeight: integer;
    FLastResizeClientWidth: integer;
    FLastResizeHeight: integer;
    FLastResizeWidth: integer;
    FLeft: Integer;
    FLoadedClientSize: TSize;
    FLRDockWidth: Integer;
    FOnChangeBounds: TNotifyEvent;
    FOnClick: TNotifyEvent;
    FOnConstrainedResize: TConstrainedResizeEvent;
    FOnContextPopup: TContextPopupEvent;
    FOnDblClick: TNotifyEvent;
    FOnDragDrop: TDragDropEvent;
    FOnDragOver: TDragOverEvent;
    FOnEditingDone: TNotifyEvent;
    FOnEndDock: TEndDragEvent;
    FOnEndDrag: TEndDragEvent;
    FOnMouseDown: TMouseEvent;
    FOnMouseEnter: TNotifyEvent;
    FOnMouseLeave: TNotifyEvent;
    FOnMouseMove: TMouseMoveEvent;
    FOnMouseUp: TMouseEvent;
    FOnMouseWheel: TMouseWheelEvent;
    FOnMouseWheelDown: TMouseWheelUpDownEvent;
    FOnMouseWheelUp: TMouseWheelUpDownEvent;
    FOnQuadClick: TNotifyEvent;
    FOnResize: TNotifyEvent;
    FOnShowHint: TControlShowHintEvent;
    FOnStartDock: TStartDockEvent;
    FOnStartDrag: TStartDragEvent;
    FOnTripleClick: TNotifyEvent;
    FParent: TWinControl;
    FParentBiDiMode: Boolean;
    FPopupMenu: TPopupMenu;
    FPreferredMinWidth: integer;// without theme space
    FPreferredMinHeight: integer;// without theme space
    FPreferredWidth: integer;// with theme space
    FPreferredHeight: integer;// with theme space
    FReadBounds: TRect;
    FSessionProperties: string;
    FSizeLock: integer;
    FTBDockHeight: Integer;
    FTop: Integer;
    FUndockHeight: Integer;
    FUndockWidth: Integer;
    FWidth: Integer;
    FWindowProc: TWndMethod;
    //boolean fields, keep together to save some bytes
    FIsControl: Boolean;
    FShowHint: Boolean;
    FParentColor: Boolean;
    FParentFont: Boolean;
    FParentShowHint: Boolean;
    FAutoSize: Boolean;
    FAutoSizingAll: boolean;
    FAutoSizingSelf: Boolean;
    FEnabled: Boolean;
    FMouseEntered: boolean;
    FVisible: Boolean;
    function CaptureMouseButtonsIsStored: boolean;
    procedure DoActionChange(Sender: TObject);
    function GetAutoSizingAll: Boolean;
    function GetAnchorSide(Kind: TAnchorKind): TAnchorSide;
    function GetAnchorSideIndex(Index: integer): TAnchorSide;
    function GetAnchoredControls(Index: integer): TControl;
    function GetBoundsRect: TRect;
    function GetClientHeight: Integer;
    function GetClientWidth: Integer;
    function GetLRDockWidth: Integer;
    function GetMouseCapture: Boolean;
    function GetTBDockHeight: Integer;
    function GetText: TCaption;
    function GetUndockHeight: Integer;
    function GetUndockWidth: Integer;
    function IsAnchorsStored: boolean;
    function IsBiDiModeStored: boolean;
    function IsCaptionStored: Boolean;
    function IsEnabledStored: Boolean;
    function IsFontStored: Boolean;
    function IsHintStored: Boolean;
    function IsHelpContextStored: Boolean;
    function IsHelpKeyWordStored: boolean;
    function IsOnClickStored: Boolean;
    function IsShowHintStored: Boolean;
    function IsVisibleStored: Boolean;
    procedure DoBeforeMouseMessage;
    procedure DoConstrainedResize(var NewLeft, NewTop, NewWidth, NewHeight: integer);
    procedure DoMouseDown(var Message: TLMMouse; Button: TMouseButton;
                          Shift: TShiftState);
    procedure DoMouseUp(var Message: TLMMouse; Button: TMouseButton);
    procedure SetAnchorSideIndex(Index: integer; const AValue: TAnchorSide);
    procedure SetBorderSpacing(const AValue: TControlBorderSpacing);
    procedure SetBoundsRect(const ARect: TRect);
    procedure SetBoundsRectForNewParent(const AValue: TRect);
    procedure SetClientHeight(Value: Integer);
    procedure SetClientSize(const Value: TPoint);
    procedure SetClientWidth(Value: Integer);
    procedure SetConstraints(const Value: TSizeConstraints);
    procedure SetDragCursor(const AValue: TCursor);
    procedure SetFont(Value: TFont);
    procedure SetHeight(Value: Integer);
    procedure SetHelpContext(const AValue: THelpContext);
    procedure SetHelpKeyword(const AValue: String);
    procedure SetHostDockSite(const AValue: TWinControl);
    procedure SetLeft(Value: Integer);
    procedure SetMouseCapture(Value: Boolean);
    procedure SetParentShowHint(Value: Boolean);
    procedure SetParentColor(Value: Boolean);
    procedure SetParentFont(Value: Boolean);
    procedure SetPopupMenu(Value: TPopupMenu);
    procedure SetShowHint(Value: Boolean);
    procedure SetText(const Value: TCaption);
    procedure SetTop(Value: Integer);
    procedure SetWidth(Value: Integer);
  protected
    FControlState: TControlState;
    FCursor: TCursor;
    class procedure WSRegisterClass; override;
    function GetCursor: TCursor; virtual;
    procedure SetCursor(Value: TCursor); virtual;
    procedure SetVisible(Value: Boolean); virtual;
    procedure DoOnParentHandleDestruction; virtual;
  protected
    // sizing/aligning
    procedure DoAutoSize; virtual;
    procedure DoAllAutoSize; virtual; // while autosize needed call DoAutoSize, used by AdjustSize and EnableAutoSizing
    procedure BeginAutoSizing; // set AutoSizing=true, can be used to prevent circles
    procedure EndAutoSizing;   // set AutoSizing=false
    procedure AnchorSideChanged(TheAnchorSide: TAnchorSide); virtual;
    procedure ForeignAnchorSideChanged(TheAnchorSide: TAnchorSide;
                                       Operation: TAnchorSideChangeOperation); virtual;
    procedure SetAlign(Value: TAlign); virtual;
    procedure SetAnchors(const AValue: TAnchors); virtual;
    procedure SetAutoSize(Value: Boolean); virtual;
    procedure BoundsChanged; virtual;
    function CreateControlBorderSpacing: TControlBorderSpacing; virtual;
    procedure DoConstraintsChange(Sender: TObject); virtual;
    procedure DoBorderSpacingChange(Sender: TObject;
                                    InnerSpaceChanged: Boolean); virtual;
    function IsBorderSpacingInnerBorderStored: Boolean; virtual;
    procedure SendMoveSizeMessages(SizeChanged, PosChanged: boolean); virtual;
    procedure ConstrainedResize(var MinWidth, MinHeight,
                                MaxWidth, MaxHeight: TConstraintSize); virtual;
    procedure CalculatePreferredSize(
                         var PreferredWidth, PreferredHeight: integer;
                         WithThemeSpace: Boolean); virtual;
    procedure DoOnResize; virtual;// call OnResize
    procedure DoOnChangeBounds; virtual;// call OnChangeBounds
    procedure CheckOnChangeBounds;// checks for changes and calls DoOnChangeBounds
    procedure Resize; virtual;// checks for changes and calls DoOnResize
    procedure RequestAlign; virtual;// smart calling Parent.AlignControls
    procedure UpdateAnchorRules;
    procedure ChangeBounds(ALeft, ATop, AWidth, AHeight: integer; KeepBase: boolean); virtual;
    procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); virtual;
    procedure ScaleConstraints(Multiplier, Divider: Integer);
    procedure ChangeScale(Multiplier, Divider: Integer); virtual;
    function CanAutoSize(var NewWidth, NewHeight: Integer): Boolean; virtual;
    procedure UpdateAlignIndex;
    procedure SetBiDiMode(AValue: TBiDiMode); virtual;
    procedure SetParentBiDiMode(AValue: Boolean); virtual;
    function IsAParentAligning: boolean;
    function GetClientOrigin: TPoint; virtual;
    function GetClientRect: TRect; virtual;// visual size of client area
    function GetLogicalClientRect: TRect; virtual;// logical size of client area (e.g. in a TScrollBox the logical client area can be bigger than the visual)
    function GetScrolledClientRect: TRect; virtual;// visual client area scrolled
    function GetClientScrollOffset: TPoint; virtual;
    function GetControlOrigin: TPoint; virtual;
    function IsClientHeightStored: boolean; virtual;
    function IsClientWidthStored: boolean; virtual;
    function WidthIsAnchored: boolean;
    function HeightIsAnchored: boolean;

    property AutoSizing: Boolean read FAutoSizingSelf;// see Begin/EndAutoSizing
    property AutoSizingAll: Boolean read GetAutoSizingAll;// set in DoAllAutoSize
    property AutoSizingLockCount: Integer read FAutoSizingLockCount;
  protected
    // protected messages
    procedure WMCancelMode(var Message: TLMessage); message LM_CANCELMODE;
    procedure WMContextMenu(var Message: TLMContextMenu); message LM_CONTEXTMENU;

    procedure WMLButtonDown(var Message: TLMLButtonDown); message LM_LBUTTONDOWN;
    procedure WMRButtonDown(var Message: TLMRButtonDown); message LM_RBUTTONDOWN;
    procedure WMMButtonDown(var Message: TLMMButtonDown); message LM_MBUTTONDOWN;
    procedure WMXButtonDown(var Message: TLMXButtonDown); message LM_XBUTTONDOWN;
    procedure WMLButtonDBLCLK(var Message: TLMLButtonDblClk); message LM_LBUTTONDBLCLK;
    procedure WMRButtonDBLCLK(var Message: TLMRButtonDblClk); message LM_RBUTTONDBLCLK;
    procedure WMMButtonDBLCLK(var Message: TLMMButtonDblClk); message LM_MBUTTONDBLCLK;
    procedure WMXButtonDBLCLK(var Message: TLMXButtonDblClk); message LM_XBUTTONDBLCLK;
    procedure WMLButtonTripleCLK(var Message: TLMLButtonTripleClk); message LM_LBUTTONTRIPLECLK;
    procedure WMRButtonTripleCLK(var Message: TLMRButtonTripleClk); message LM_RBUTTONTRIPLECLK;
    procedure WMMButtonTripleCLK(var Message: TLMMButtonTripleClk); message LM_MBUTTONTRIPLECLK;
    procedure WMXButtonTripleCLK(var Message: TLMXButtonTripleClk); message LM_XBUTTONTRIPLECLK;
    procedure WMLButtonQuadCLK(var Message: TLMLButtonQuadClk); message LM_LBUTTONQUADCLK;
    procedure WMRButtonQuadCLK(var Message: TLMRButtonQuadClk); message LM_RBUTTONQUADCLK;
    procedure WMMButtonQuadCLK(var Message: TLMMButtonQuadClk); message LM_MBUTTONQUADCLK;
    procedure WMXButtonQuadCLK(var Message: TLMXButtonQuadClk); message LM_XBUTTONQUADCLK;
    procedure WMMouseMove(var Message: TLMMouseMove); message LM_MOUSEMOVE;
    procedure WMLButtonUp(var Message: TLMLButtonUp); message LM_LBUTTONUP;
    procedure WMRButtonUp(var Message: TLMRButtonUp); message LM_RBUTTONUP;
    procedure WMMButtonUp(var Message: TLMMButtonUp); message LM_MBUTTONUP;
    procedure WMXButtonUp(var Message: TLMXButtonUp); message LM_XBUTTONUP;
    procedure WMMouseWheel(var Message: TLMMouseEvent); message LM_MOUSEWHEEL;
    procedure WMMove(var Message: TLMMove); message LM_MOVE;
    procedure WMSize(var Message: TLMSize); message LM_SIZE;
    procedure WMWindowPosChanged(var Message: TLMWindowPosChanged); message LM_WINDOWPOSCHANGED;
    procedure LMCaptureChanged(var Message: TLMessage); message LM_CaptureChanged;
    procedure CMBiDiModeChanged(var Message: TLMessage); message CM_BIDIMODECHANGED;
    procedure CMEnabledChanged(var Message: TLMEssage); message CM_ENABLEDCHANGED;
    procedure CMHitTest(var Message: TCMHittest) ; message CM_HITTEST;
    procedure CMMouseEnter(var Message :TLMessage); message CM_MOUSEENTER;
    procedure CMMouseLeave(var Message :TLMessage); message CM_MOUSELEAVE;
    procedure CMHintShow(var Message: TLMessage); message CM_HINTSHOW;
    procedure CMParentBiDiModeChanged(var Message: TLMessage); message CM_PARENTBIDIMODECHANGED;
    procedure CMParentColorChanged(var Message: TLMessage); message CM_PARENTCOLORCHANGED;
    procedure CMParentFontChanged(var Message: TLMessage); message CM_PARENTFONTCHANGED;
    procedure CMParentShowHintChanged(var Message: TLMessage); message CM_PARENTSHOWHINTCHANGED;
    procedure CMVisibleChanged(var Message: TLMessage); message CM_VISIBLECHANGED;
    procedure CMTextChanged(var Message: TLMessage); message CM_TEXTCHANGED;
    procedure CMWantSpecialKey(var Message: TLMessage); message CM_WANTSPECIALKEY;
    procedure CMCursorChanged(var Message: TLMessage); message CM_CURSORCHANGED;
  protected
    // drag and drop
    procedure CalculateDockSizes;
    function CreateFloatingDockSite(const Bounds: TRect): TWinControl;
    function GetDockEdge(const MousePos: TPoint): TAlign; virtual;
    function GetDragImages: TDragImageList; virtual;
    function GetFloating: Boolean; virtual;
    function GetFloatingDockSiteClass: TWinControlClass; virtual;
    procedure BeginAutoDrag; virtual;
    procedure DoFloatMsg(ADockSource: TDragDockObject);virtual;//CM_FLOAT
    procedure DockTrackNoTarget(Source: TDragDockObject; X, Y: Integer); virtual;
    procedure DoDock(NewDockSite: TWinControl; var ARect: TRect); virtual;
    function DoDragMsg(ADragMessage: TDragMessage; APosition: TPoint; ADragObject: TDragObject; ATarget: TControl; ADocking: Boolean):LRESULT; virtual;//Cm_Drag
    procedure DoEndDock(Target: TObject; X, Y: Integer); virtual;
    procedure DoEndDrag(Target: TObject; X,Y: Integer); virtual;
    procedure DoStartDock(var DragObject: TDragObject); virtual;
    procedure DoStartDrag(var DragObject: TDragObject); virtual;
    procedure DragCanceled; virtual;
    procedure DragOver(Source: TObject; X,Y: Integer; State: TDragState;
                       var Accept: Boolean); virtual;
    procedure PositionDockRect(DragDockObject: TDragDockObject); virtual;
    procedure SetDragMode(Value: TDragMode); virtual;
    function GetDefaultDockCaption: String; virtual;
    //procedure SendDockNotification; virtual; MG: probably not needed
  protected
    // key and mouse
    procedure Click; virtual;
    procedure DblClick; virtual;
    procedure TripleClick; virtual;
    procedure QuadClick; virtual;
    procedure MouseDown(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); virtual;
    procedure MouseMove(Shift: TShiftState; X,Y: Integer); virtual;
    procedure MouseUp(Button: TMouseButton; Shift:TShiftState; X,Y:Integer); virtual;
    procedure MouseEnter; virtual;
    procedure MouseLeave; virtual;
    function  DialogChar(var Message: TLMKey): boolean; virtual;
    procedure UpdateMouseCursor(X, Y: integer);
  protected
    procedure Changed;
    function  GetPalette: HPalette; virtual;
    function ChildClassAllowed(ChildClass: TClass): boolean; virtual;
    procedure ReadState(Reader: TReader); override; // called
    procedure Loaded; override;
    procedure LoadedAll; virtual; // called when all controls were Loaded and lost their csLoading
    procedure DefineProperties(Filer: TFiler); override;
    procedure AssignTo(Dest: TPersistent); override;
    procedure FormEndUpdated; virtual;
    procedure InvalidateControl(CtrlIsVisible, CtrlIsOpaque: Boolean);
    procedure InvalidateControl(CtrlIsVisible, CtrlIsOpaque, IgnoreWinControls: Boolean);
    procedure FontChanged(Sender: TObject); virtual;
    procedure ParentFontChanged; virtual;
    function GetAction: TBasicAction; virtual;
    function RealGetText: TCaption; virtual;
    procedure RealSetText(const Value: TCaption); virtual;
    procedure TextChanged; virtual;
    function GetCachedText(var CachedText: TCaption): boolean; virtual;
    procedure SetAction(Value: TBasicAction); virtual;
    procedure SetColor(Value: TColor); virtual;
    procedure SetEnabled(Value: Boolean); virtual;
    procedure SetHint(const Value: TTranslateString); virtual;
    procedure SetName(const Value: TComponentName); override;
    procedure SetParent(NewParent: TWinControl); virtual;
    procedure SetParentComponent(NewParentComponent: TComponent); override;
    procedure WndProc(var TheMessage: TLMessage); virtual;
    procedure ParentFormHandleInitialized; virtual; // called by ChildHandlesCreated of parent form
    procedure CaptureChanged; virtual;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    function CanTab: Boolean; virtual;
    function GetDeviceContext(var WindowHandle: HWND): HDC; virtual;
    function GetEnabled: Boolean; virtual;
    function GetPopupMenu: TPopupMenu; virtual;
    procedure DoOnShowHint(HintInfo: PHintInfo); virtual;
    function DoMouseWheel(Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint): Boolean; virtual;
    function DoMouseWheelDown(Shift: TShiftState; MousePos: TPoint): Boolean; virtual;
    function DoMouseWheelUp(Shift: TShiftState; MousePos: TPoint): Boolean; virtual;
    procedure VisibleChanging; virtual;
    procedure VisibleChanged; virtual;
    procedure AddHandler(HandlerType: TControlHandlerType;
                         const AMethod: TMethod; AsFirst: boolean = false);
    procedure RemoveHandler(HandlerType: TControlHandlerType;
                            const AMethod: TMethod);
    procedure DoCallNotifyHandler(HandlerType: TControlHandlerType);
    procedure DoContextPopup(const MousePos: TPoint; var Handled: Boolean); virtual;
    procedure SetZOrder(TopMost: Boolean); virtual;
    class function GetControlClassDefaultSize: TSize; virtual;
    function ColorIsStored: boolean; virtual;
  protected
    // actions
    function GetActionLinkClass: TControlActionLinkClass; virtual;
    procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); virtual;
  protected
    // optional properties (not every descendent supports them)
    property ActionLink: TControlActionLink read FActionLink write FActionLink;
    property DragCursor: TCursor read FDragCursor write SetDragCursor default crDrag;
    property DragKind: TDragKind read FDragKind write FDragKind default dkDrag;
    property DragMode: TDragMode read fDragMode write SetDragMode default dmManual;
    property MouseCapture: Boolean read GetMouseCapture write SetMouseCapture;
    property ParentColor: Boolean read FParentColor write SetParentColor default True;
    property ParentFont: Boolean  read FParentFont write SetParentFont default True;
    property ParentShowHint: Boolean read FParentShowHint write SetParentShowHint default True;
    property SessionProperties: string read FSessionProperties write FSessionProperties;
    property Text: TCaption read GetText write SetText;
    property OnConstrainedResize: TConstrainedResizeEvent read FOnConstrainedResize write FOnConstrainedResize;
    property OnContextPopup: TContextPopupEvent read FOnContextPopup write FOnContextPopup;
    property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
    property OnTripleClick: TNotifyEvent read FOnTripleClick write FOnTripleClick;
    property OnQuadClick: TNotifyEvent read FOnQuadClick write FOnQuadClick;
    property OnDragDrop: TDragDropEvent read FOnDragDrop write FOnDragDrop;
    property OnDragOver: TDragOverEvent read FOnDragOver write FOnDragOver;
    property OnEndDock: TEndDragEvent read FOnEndDock write FOnEndDock;
    property OnEndDrag: TEndDragEvent read FOnEndDrag write FOnEndDrag;
    property OnMouseDown: TMouseEvent read FOnMouseDown write FOnMouseDown;
    property OnMouseMove: TMouseMoveEvent read FOnMouseMove write FOnMouseMove;
    property OnMouseUp: TMouseEvent read FOnMouseUp write FOnMouseUp;
    property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
    property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
    property OnMouseWheel: TMouseWheelEvent read FOnMouseWheel write FOnMouseWheel;
    property OnMouseWheelDown: TMouseWheelUpDownEvent read FOnMouseWheelDown write FOnMouseWheelDown;
    property OnMouseWheelUp: TMouseWheelUpDownEvent read FOnMouseWheelUp write FOnMouseWheelUp;
    property OnStartDock: TStartDockEvent read FOnStartDock write FOnStartDock;
    property OnStartDrag: TStartDragEvent read FOnStartDrag write FOnStartDrag;
    property OnEditingDone: TNotifyEvent read FOnEditingDone write FOnEditingDone;
  public
    FCompStyle: Byte; // DEPRECATED. Enables (valid) use of 'IN' operator (this
      // is a hack for speed. It will be replaced by the use of the widgetset
      // classes.
      // So, don't use it anymore.
  public
    // drag and dock
    procedure DragDrop(Source: TObject; X,Y: Integer); virtual;
    procedure Dock(NewDockSite: TWinControl; ARect: TRect); virtual;
    function ManualDock(NewDockSite: TWinControl;
                        DropControl: TControl = nil;
                        ControlSide: TAlign = alNone;
                        KeepDockSiteSize: Boolean = true): Boolean; virtual;
    function ManualFloat(TheScreenRect: TRect;
                         KeepDockSiteSize: Boolean = true): Boolean; virtual;
    function ReplaceDockedControl(Control: TControl; NewDockSite: TWinControl;
                           DropControl: TControl; ControlSide: TAlign): Boolean;
    function Dragging: Boolean;
  public
    // size
    procedure AdjustSize; virtual;// smart calling DoAutoSize
    function AutoSizePhases: TControlAutoSizePhases; virtual;
    function AutoSizeDelayed: boolean; virtual;
    function AutoSizeCheckParent: Boolean; virtual;
    procedure AnchorToNeighbour(Side: TAnchorKind; Space: integer;
                                Sibling: TControl);
    procedure AnchorParallel(Side: TAnchorKind; Space: integer;
                             Sibling: TControl);
    procedure AnchorHorizontalCenterTo(Sibling: TControl);
    procedure AnchorVerticalCenterTo(Sibling: TControl);
    procedure AnchorToCompanion(Side: TAnchorKind; Space: integer;
                                Sibling: TControl;
                                FreeCompositeSide: boolean = true);
    procedure AnchorSame(Side: TAnchorKind; Sibling: TControl);
    procedure AnchorAsAlign(TheAlign: TAlign; Space: Integer);
    procedure AnchorClient(Space: Integer);
    function AnchoredControlCount: integer;
    property AnchoredControls[Index: integer]: TControl read GetAnchoredControls;
    procedure SetBounds(aLeft, aTop, aWidth, aHeight: integer); virtual;
    procedure SetInitialBounds(aLeft, aTop, aWidth, aHeight: integer); virtual;
    procedure SetBoundsKeepBase(aLeft, aTop, aWidth, aHeight: integer
            ); virtual; // if you use this, disable the LCL autosizing for this control
    procedure GetPreferredSize(var PreferredWidth, PreferredHeight: integer;
                               Raw: boolean = false;
                               WithThemeSpace: boolean = true); virtual;
    function GetDefaultWidth: integer;
    function GetDefaultHeight: integer;
    function GetDefaultColor(const DefaultColorType: TDefaultColorType): TColor; virtual;
    function GetSidePosition(Side: TAnchorKind): integer;
    procedure CNPreferredSizeChanged;
    procedure InvalidatePreferredSize; virtual;
    function GetAnchorsDependingOnParent(WithNormalAnchors: Boolean): TAnchors;
    procedure DisableAutoSizing{$IFDEF DebugDisableAutoSizing}(const Reason: string){$ENDIF};
    procedure EnableAutoSizing{$IFDEF DebugDisableAutoSizing}(const Reason: string){$ENDIF};
    {$IFDEF DebugDisableAutoSizing}
    procedure WriteAutoSizeReasons(NotIfEmpty: boolean);
    {$ENDIF}
    procedure UpdateBaseBounds(StoreBounds, StoreParentClientSize,
                               UseLoadedValues: boolean); virtual;
    property BaseBounds: TRect read FBaseBounds;
    property ReadBounds: TRect read FReadBounds;
    property BaseParentClientSize: TSize read FBaseParentClientSize;
    procedure WriteLayoutDebugReport(const Prefix: string); virtual;
  public
    constructor Create(TheOwner: TComponent);override;
    destructor Destroy; override;
    procedure EditingDone; virtual;
    procedure ExecuteDefaultAction; virtual;
    procedure ExecuteCancelAction; virtual;
    procedure BeginDrag(Immediate: Boolean; Threshold: Integer = -1);
    procedure BringToFront;
    function HasParent: Boolean; override;
    function GetParentComponent: TComponent; override;
    function IsParentOf(AControl: TControl): boolean; virtual;
    function GetTopParent: TControl;
    function IsVisible: Boolean; virtual;// checks parents too
    function IsControlVisible: Boolean; virtual;// does not check parents
    function FormIsUpdating: boolean; virtual;
    function IsProcessingPaintMsg: boolean;
    procedure Hide;
    procedure Refresh;
    procedure Repaint; virtual;
    procedure Invalidate; virtual;
    function CheckChildClassAllowed(ChildClass: TClass;
                                    ExceptionOnInvalid: boolean): boolean;
    procedure CheckNewParent(AParent: TWinControl); virtual;
    procedure SendToBack;
    procedure SetTempCursor(Value: TCursor); virtual;
    procedure UpdateRolesForForm; virtual;
    procedure ActiveDefaultControlChanged(NewControl: TControl); virtual;
    function  GetTextBuf(Buffer: PChar; BufSize: Integer): Integer; virtual;
    function  GetTextLen: Integer; virtual;
    procedure SetTextBuf(Buffer: PChar); virtual;
    function  Perform(Msg: Cardinal; WParam: WParam; LParam: LParam): LRESULT;
    function  ScreenToClient(const APoint: TPoint): TPoint;
    function  ClientToScreen(const APoint: TPoint): TPoint;
    function  ScreenToControl(const APoint: TPoint): TPoint;
    function  ControlToScreen(const APoint: TPoint): TPoint;
    function GetChildsRect(Scrolled: boolean): TRect; virtual;
    procedure Show;
    procedure Update; virtual;
    function HandleObjectShouldBeVisible: boolean; virtual;
    function ParentDestroyingHandle: boolean;
    function ParentHandlesAllocated: boolean; virtual;
    procedure InitiateAction; virtual;
    procedure ShowHelp; virtual;
    function HasHelp: Boolean;
  public
    // Event lists
    procedure RemoveAllHandlersOfObject(AnObject: TObject); override;
    procedure AddHandlerOnResize(const OnResizeEvent: TNotifyEvent;
                                 AsFirst: boolean = false);
    procedure RemoveHandlerOnResize(const OnResizeEvent: TNotifyEvent);
    procedure AddHandlerOnChangeBounds(const OnChangeBoundsEvent: TNotifyEvent;
                                       AsFirst: boolean = false);
    procedure RemoveHandlerOnChangeBounds(const OnChangeBoundsEvent: TNotifyEvent);
    procedure AddHandlerOnVisibleChanging(const OnVisibleChangingEvent: TNotifyEvent;
                                          AsFirst: boolean = false);
    procedure RemoveHandlerOnVisibleChanging(const OnVisibleChangingEvent: TNotifyEvent);
    procedure AddHandlerOnVisibleChanged(const OnVisibleChangedEvent: TNotifyEvent;
                                         AsFirst: boolean = false);
    procedure RemoveHandlerOnVisibleChanged(const OnVisibleChangedEvent: TNotifyEvent);
    procedure AddHandlerOnKeyDown(const OnKeyDownEvent: TKeyEvent;
                                  AsFirst: boolean = false);
    procedure RemoveHandlerOnKeyDown(const OnKeyDownEvent: TKeyEvent);
  public
    // standard properties, which should be supported by all descendants
    property Action: TBasicAction read GetAction write SetAction;
    property Align: TAlign read FAlign write SetAlign default alNone;
    property Anchors: TAnchors read FAnchors write SetAnchors stored IsAnchorsStored default [akLeft, akTop];
    property AnchorSide[Kind: TAnchorKind]: TAnchorSide read GetAnchorSide;
    property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
    property BorderSpacing: TControlBorderSpacing read FBorderSpacing write SetBorderSpacing;
    property BoundsRect: TRect read GetBoundsRect write SetBoundsRect;
    property BoundsRectForNewParent: TRect read FBoundsRectForNewParent write SetBoundsRectForNewParent;
    property Caption: TCaption read GetText write SetText stored IsCaptionStored;
    property CaptureMouseButtons: TCaptureMouseButtons read FCaptureMouseButtons
      write FCaptureMouseButtons stored CaptureMouseButtonsIsStored default [mbLeft];
    property ClientHeight: Integer read GetClientHeight write SetClientHeight stored  IsClientHeightStored;
    property ClientOrigin: TPoint read GetClientOrigin;
    property ClientRect: TRect read GetClientRect;
    property ClientWidth: Integer read GetClientWidth write SetClientWidth stored IsClientWidthStored;
    property Color: TColor read FColor write SetColor stored ColorIsStored default {$ifdef UseCLDefault}clDefault{$else}clWindow{$endif};
    property Constraints: TSizeConstraints read FConstraints write SetConstraints;
    property ControlOrigin: TPoint read GetControlOrigin;
    property ControlState: TControlState read FControlState write FControlState;
    property ControlStyle: TControlStyle read FControlStyle write FControlStyle;
    property Enabled: Boolean read GetEnabled write SetEnabled stored IsEnabledStored default True;
    property Font: TFont read FFont write SetFont stored IsFontStored;
    property IsControl: Boolean read FIsControl write FIsControl;
    property MouseEntered: Boolean read FMouseEntered;
    property OnChangeBounds: TNotifyEvent read FOnChangeBounds write FOnChangeBounds;
    property OnClick: TNotifyEvent read FOnClick write FOnClick stored IsOnClickStored;
    property OnResize: TNotifyEvent read FOnResize write FOnResize;
    property OnShowHint: TControlShowHintEvent read FOnShowHint write FOnShowHint;
    property Parent: TWinControl read FParent write SetParent;
    property PopupMenu: TPopupmenu read GetPopupmenu write SetPopupMenu;
    property ShowHint: Boolean read FShowHint write SetShowHint stored IsShowHintStored default False;
    property Visible: Boolean read FVisible write SetVisible stored IsVisibleStored default True;
    property WindowProc: TWndMethod read FWindowProc write FWindowProc;
  public
    // docking properties
    property DockOrientation: TDockOrientation read FDockOrientation write FDockOrientation;
    property Floating: Boolean read GetFloating;
    property FloatingDockSiteClass: TWinControlClass read GetFloatingDockSiteClass write FFloatingDockSiteClass;
    property HostDockSite: TWinControl read FHostDockSite write SetHostDockSite;
    property LRDockWidth: Integer read GetLRDockWidth write FLRDockWidth;
    property TBDockHeight: Integer read GetTBDockHeight write FTBDockHeight;
    property UndockHeight: Integer read GetUndockHeight write FUndockHeight;// Height used when undocked
    property UndockWidth: Integer read GetUndockWidth write FUndockWidth;// Width used when undocked
  public
    function UseRightToLeftAlignment: Boolean; virtual;
    function UseRightToLeftReading: Boolean; virtual;
    function UseRightToLeftScrollBar: Boolean;
    function IsRightToLeft: Boolean;
    property BiDiMode: TBiDiMode read FBiDiMode write SetBiDiMode stored IsBiDiModeStored default bdLeftToRight;
    property ParentBiDiMode: Boolean read FParentBiDiMode write SetParentBiDiMode default True;
  published
    property AnchorSideLeft: TAnchorSide index 0 read GetAnchorSideIndex write SetAnchorSideIndex;
    property AnchorSideTop: TAnchorSide index 1 read GetAnchorSideIndex write SetAnchorSideIndex;
    property AnchorSideRight: TAnchorSide index 2 read GetAnchorSideIndex write SetAnchorSideIndex;
    property AnchorSideBottom: TAnchorSide index 3 read GetAnchorSideIndex write SetAnchorSideIndex;
    property Cursor: TCursor read GetCursor write SetCursor default crDefault;
    property Left: Integer read FLeft write SetLeft; // no default value - controls usually placed to different positions
    property Height: Integer read FHeight write SetHeight; // no default value - controls usually have differnt sizes
    property Hint: TTranslateString read FHint write SetHint stored IsHintStored;
    property Top: Integer read FTop write SetTop; // no default value - controls usually placed to different positions
    property Width: Integer read FWidth write SetWidth; // no default value - controls usually have differnt sizes
    property HelpType: THelpType read FHelpType write FHelpType default htContext;
    property HelpKeyword: String read FHelpKeyword write SetHelpKeyword stored IsHelpKeyWordStored;
    property HelpContext: THelpContext read FHelpContext write SetHelpContext stored IsHelpContextStored default 0;
  end;


  TBorderWidth = 0..MaxInt;

  TGetChildProc = procedure(Child: TComponent) of Object;

  { TControlChildSizing }

  { LeftRightSpacing, TopBottomSpacing: integer;
        minimum space between left client border and left most children.
        For example: ClientLeftRight=5 means children Left position is at least 5.

    HorizontalSpacing, VerticalSpacing: integer;
        minimum space between each child horizontally
  }

  {   Defines how child controls are resized/aligned.

      cesAnchorAligning, cssAnchorAligning
        Anchors and Align work like Delphi. For example if Anchors property of
        the control is [akLeft], it means fixed distance between left border of
        parent's client area. [akRight] means fixed distance between right
        border of the control and the right border of the parent's client area.
        When the parent is resized the child is moved to keep the distance.
        [akLeft,akRight] means fixed distance to left border and fixed distance
        to right border. When the parent is resized, the controls width is
        changed (resized) to keep the left and right distance.
        Same for akTop,akBottom.

        Align=alLeft for a control means set Left leftmost, Top topmost and
        maximize Height. The width is kept, if akRight is not set. If akRight
        is set in the Anchors property, then the right distance is kept and
        the control's width is resized.
        If there several controls with Align=alLeft, they will not overlapp and
        be put side by side.
        Same for alRight, alTop, alBottom. (Always expand 3 sides).

        Align=alClient. The control will fill the whole remaining space.
        Setting two children to Align=alClient does only make sense, if you set
        maximum Constraints.

        Order: First all alTop children are resized, then alBottom, then alLeft,
        then alRight and finally alClient.

      cesScaleChilds, cssScaleChilds
        Scale children, keep space between them fixed.
        Children are resized to their normal/adviced size. If there is some space
        left in the client area of the parent, then the children are scaled to
        fill the space. You can set maximum Constraints. Then the other children
        are scaled more.
        For example: 3 child controls A, B, C with A.Width=10, B.Width=20 and
        C.Width=30 (total=60). If the Parent's client area has a ClientWidth of
        120, then the children are scaled with Factor 2.
        If B has a maximum constraint width of 30, then first the children will be
        scaled with 1.5 (A.Width=15, B.Width=30, C.Width=45). Then A and C
        (15+45=60 and 30 pixel space left) will be scaled by 1.5 again, to a
        final result of: A.Width=23, B.Width=30, C.Width=67 (23+30+67=120).

      cesHomogenousChildGrowth, cssHomogenousChildDecrease
        Enlarge children equally.
        Children are resized to their normal/adviced size. If there is some space
        left in the client area of the parent, then the remaining space is
        distributed equally to each child.
        For example: 3 child controls A, B, C with A.Width=10, B.Width=20 and
        C.Width=30 (total=60). If the Parent's client area has a ClientWidth of
        120, then 60/3=20 is added to each Child.
        If B has a maximum constraint width of 30, then first 10 is added to
        all children (A.Width=20, B.Width=30, C.Width=40). Then A and C
        (20+40=60 and 30 pixel space left) will get 30/2=15 additional,
        resulting in: A.Width=35, B.Width=30, C.Width=55 (35+30+55=120).

      cesHomogenousSpaceGrowth
        Enlarge space between children equally.
        Children are resized to their normal/adviced size. If there is some space
        left in the client area of the parent, then the space between the children
        is expanded.
        For example: 3 child controls A, B, C with A.Width=10, B.Width=20 and
        C.Width=30 (total=60). If the Parent's client area has a ClientWidth of
        120, then there will be 60/2=30 space between A and B and between
        B and C.
  }

  TChildControlResizeStyle = (
      crsAnchorAligning, // (like Delphi)
      crsScaleChilds, // scale children, keep space between children fixed
      crsHomogenousChildResize, // enlarge children equally (i.e. by the same amount of pixel)
      crsHomogenousSpaceResize  // enlarge space between children equally
    );

  TControlChildrenLayout = (
      cclNone,
      cclLeftToRightThenTopToBottom, // if BiDiMode <> bdLeftToRight then it becomes RightToLeft
      cclTopToBottomThenLeftToRight
    );

  TControlChildSizing = class(TPersistent)
  private
    FControl: TWinControl;
    FControlsPerLine: integer;
    FEnlargeHorizontal: TChildControlResizeStyle;
    FEnlargeVertical: TChildControlResizeStyle;
    FHorizontalSpacing: integer;
    FLayout: TControlChildrenLayout;
    FLeftRightSpacing: integer;
    FOnChange: TNotifyEvent;
    FShrinkHorizontal: TChildControlResizeStyle;
    FShrinkVertical: TChildControlResizeStyle;
    FTopBottomSpacing: integer;
    FVerticalSpacing: integer;
    procedure SetControlsPerLine(const AValue: integer);
    procedure SetEnlargeHorizontal(const AValue: TChildControlResizeStyle);
    procedure SetEnlargeVertical(const AValue: TChildControlResizeStyle);
    procedure SetHorizontalSpacing(const AValue: integer);
    procedure SetLayout(const AValue: TControlChildrenLayout);
    procedure SetLeftRightSpacing(const AValue: integer);
    procedure SetShrinkHorizontal(const AValue: TChildControlResizeStyle);
    procedure SetShrinkVertical(const AValue: TChildControlResizeStyle);
    procedure SetTopBottomSpacing(const AValue: integer);
    procedure SetVerticalSpacing(const AValue: integer);
  protected
    procedure Change; virtual;
  public
    constructor Create(OwnerControl: TWinControl);
    procedure Assign(Source: TPersistent); override;
    procedure AssignTo(Dest: TPersistent); override;
    function IsEqual(Sizing: TControlChildSizing): boolean;
    procedure SetGridSpacing(Spacing: integer);
  public
    property Control: TWinControl read FControl;
    property OnChange: TNotifyEvent read FOnChange write FOnChange;
  published
    property LeftRightSpacing: integer read FLeftRightSpacing write SetLeftRightSpacing default 0;
    property TopBottomSpacing: integer read FTopBottomSpacing write SetTopBottomSpacing default 0;
    property HorizontalSpacing: integer read FHorizontalSpacing write SetHorizontalSpacing default 0;
    property VerticalSpacing: integer read FVerticalSpacing write SetVerticalSpacing default 0;
    property EnlargeHorizontal: TChildControlResizeStyle read FEnlargeHorizontal
                           write SetEnlargeHorizontal default crsAnchorAligning;
    property EnlargeVertical: TChildControlResizeStyle read FEnlargeVertical
                             write SetEnlargeVertical default crsAnchorAligning;
    property ShrinkHorizontal: TChildControlResizeStyle read FShrinkHorizontal
                            write SetShrinkHorizontal default crsAnchorAligning;
    property ShrinkVertical: TChildControlResizeStyle read FShrinkVertical
                              write SetShrinkVertical default crsAnchorAligning;
    property Layout: TControlChildrenLayout read FLayout write SetLayout default cclNone;
    property ControlsPerLine: integer read FControlsPerLine write SetControlsPerLine default 0;
  end;


  { TWinControlActionLink }

  // Since HelpContext and HelpKeyword are properties of TControl,
  // this class is obsolete. In order not to break existing code,
  // its declaration is aliased to TControlActionLink.
  TWinControlActionLink = TControlActionLink;
  TWinControlActionLinkClass = class of TWinControlActionLink;


  { TWinControl }

  TWinControlFlag = (
    wcfClientRectNeedsUpdate,
    wcfColorChanged,
    wcfFontChanged,          // Set if font was changed before handle creation
    wcfAllAutoSizing,        // Set inside DoAllAutosize
    wcfAligningControls,
    wcfEraseBackground,
    wcfCreatingHandle,       // Set while constructing the handle of this control
    wcfInitializing,         // Set while initializing during handle creation
    wcfCreatingChildHandles, // Set while constructing the handles of the children
    wcfRealizingBounds,      // Set inside RealizeBoundsRecursive
    wcfBoundsRealized,       // bounds were sent to the interface
    wcfUpdateShowing,
    wcfHandleVisible,
    wcfAdjustedLogicalClientRectValid,
    wcfKillIntfSetBounds
    );
  TWinControlFlags = set of TWinControlFlag;

  TControlAtPosFlag = (
    capfAllowDisabled,   // include controls with Enabled=false
    capfAllowWinControls,// include TWinControls
    capfOnlyClientAreas, // use the client areas, not the whole child area
    capfRecursive,       // search recursively in grand childrens
    capfHasScrollOffset  // do not add the scroll offset to Pos (already included)
    );
  TControlAtPosFlags = set of TControlAtPosFlag;

  // needed for VCL compatibility on custom aligning
  TAlignInfo = record
    AlignList: TFPList;    // The list of controls currently being aligned
    ControlIndex: Integer; // Index of current control
    Align: TAlign;         // The kind of alignment currently processed
                           // since this info is only used for custom aligning,
                           // the value is always alCustom
    Scratch: Integer;      // ??? Declared in the VCL, not used and not documented
  end;

  TAlignInsertBeforeEvent = function (Sender: TWinControl; Control1, Control2: TControl): Boolean of object;
  TAlignPositionEvent = procedure (Sender: TWinControl; Control: TControl;
                                   var NewLeft, NewTop, NewWidth, NewHeight: Integer;
                                   var AlignRect: TRect; AlignInfo: TAlignInfo) of object;

  TWinControl = class(TControl)
  private
    FAlignOrder: TFPList; // list of TControl. Last moved (SetBounds) comes first. Used by AlignControls.
    FBorderWidth: TBorderWidth;
    FBoundsLockCount: integer;
    FBoundsRealized: TRect;
    FBorderStyle: TBorderStyle;
    FBrush: TBrush;
    FAdjustClientRectRealized: TRect;
    FAdjustClientRect: TRect; // valid if wcfAdjustClientRectValid
    FChildSizing: TControlChildSizing;
    FControls: TFPList;    // the child controls
    FOnGetDockCaption: TGetDockCaptionEvent;
    FDefWndProc: Pointer;
    FDockClients: TFPList;
    FClientWidth: Integer;
    FClientHeight: Integer;
    FDockManager: TDockManager;
    FOnAlignInsertBefore: TAlignInsertBeforeEvent;
    FOnAlignPosition: TAlignPositionEvent;
    FOnDockDrop: TDockDropEvent;
    FOnDockOver: TDockOverEvent;
    FOnGetSiteInfo: TGetSiteInfoEvent;
    FOnKeyDown: TKeyEvent;
    FOnKeyPress: TKeyPressEvent;
    FOnKeyUp: TKeyEvent;
    FOnEnter: TNotifyEvent;
    FOnExit: TNotifyEvent;
    FOnUnDock: TUnDockEvent;
    FOnUTF8KeyPress: TUTF8KeyPressEvent;
    FParentWindow: HWND;
    FRealizeBoundsLockCount: integer;
    FHandle: HWND;
    FTabOrder: integer;
    FTabList: TFPList;
    // keep small variables together to save some bytes
    FTabStop: Boolean;
    FShowing: Boolean;
    FDoubleBuffered: Boolean;
    FDockSite: Boolean;
    FUseDockManager: Boolean;
    procedure AlignControl(AControl: TControl);
    function GetBrush: TBrush;
    function GetControl(const Index: Integer): TControl;
    function GetControlCount: Integer;
    function GetDockClientCount: Integer;
    function GetDockClients(Index: Integer): TControl;
    function GetHandle: HWND;
    function GetIsResizing: boolean;
    function GetTabOrder: TTabOrder;
    function GetVisibleDockClientCount: Integer;
    procedure SetChildSizing(const AValue: TControlChildSizing);
    procedure SetDockSite(const NewDockSite: Boolean);
    procedure SetHandle(NewHandle: HWND);
    procedure SetBorderWidth(Value: TBorderWidth);
    procedure SetParentWindow(const AValue: HWND);
    procedure SetTabOrder(NewTabOrder: TTabOrder);
    procedure SetTabStop(NewTabStop: Boolean);
    procedure SetUseDockManager(const AValue: Boolean);
    procedure UpdateTabOrder(NewTabOrder: TTabOrder);
    function  WantsKeyBeforeInterface(Key: word; Shift: TShiftState): boolean;
    procedure Insert(AControl: TControl);
    procedure Insert(AControl: TControl; Index: integer);
    procedure Remove(AControl: TControl);
    procedure AlignNonAlignedControls(ListOfControls: TFPList;
                                      var BoundsModified: Boolean);
  protected
    FWinControlFlags: TWinControlFlags;
    class procedure WSRegisterClass; override;
    procedure AdjustClientRect(var ARect: TRect); virtual;
    procedure GetAdjustedLogicalClientRect(out ARect: TRect);
    procedure CreateControlAlignList(TheAlign: TAlign;
                                    AlignList: TFPList; StartControl: TControl);
    procedure AlignControls(AControl: TControl;
                            var RemainingClientRect: TRect); virtual;
    function CustomAlignInsertBefore(AControl1, AControl2: TControl): Boolean; virtual;
    procedure CustomAlignPosition(AControl: TControl; var ANewLeft, ANewTop, ANewWidth,
                                  ANewHeight: Integer; var AlignRect: TRect;
                                  AlignInfo: TAlignInfo); virtual;
    function DoAlignChildControls(TheAlign: TAlign; AControl: TControl;
                     AControlList: TFPList; var ARect: TRect): Boolean; virtual;
    procedure DoChildSizingChange(Sender: TObject); virtual;
    procedure InvalidatePreferredChildSizes;
    function CanTab: Boolean; override;
    function IsClientHeightStored: boolean; override;
    function IsClientWidthStored: boolean; override;
    procedure DoSendShowHideToInterface; virtual; // called by TWinControl.CMShowingChanged
    procedure ControlsAligned; virtual;// called by AlignControls after aligning controls
    procedure DoSendBoundsToInterface; virtual; // called by RealizeBounds
    procedure RealizeBounds; virtual;// checks for changes and calls DoSendBoundsToInterface
    procedure RealizeBoundsRecursive; // called by DoAllAutoSize
    procedure CreateSubClass(var Params: TCreateParams; ControlClassName: PChar);
    procedure DoConstraintsChange(Sender: TObject); override;
    procedure DoSetBounds(ALeft, ATop, AWidth, AHeight: integer); override;
    procedure DoAutoSize; override;
    procedure DoAllAutoSize; override;
    function AutoSizeCanStart: boolean; deprecated;
    procedure AllAutoSized; virtual; // called by DoAllAutoSize after all bounds are computed, see TCustomForm.AllAutoSized
    procedure CalculatePreferredSize(var PreferredWidth,
                                     PreferredHeight: integer;
                                     WithThemeSpace: Boolean); override;
    procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override;
    function ChildClassAllowed(ChildClass: TClass): boolean; override;
    procedure PaintControls(DC: HDC; First: TControl);
    procedure PaintHandler(var TheMessage: TLMPaint);
    procedure PaintWindow(DC: HDC); virtual;
    procedure CreateBrush; virtual;
    procedure ScaleControls(Multiplier, Divider: Integer); virtual;
    procedure ChangeScale(Multiplier, Divider: Integer); override;
  protected
    // messages
    procedure CMBiDiModeChanged(var Message: TLMessage); message CM_BIDIMODECHANGED;
    procedure CMBorderChanged(var Message: TLMessage); message CM_BORDERCHANGED;
    procedure CMEnabledChanged(var Message: TLMessage); message CM_ENABLEDCHANGED;
    procedure CMShowingChanged(var Message: TLMessage); message CM_SHOWINGCHANGED; // called by TWinControl.UpdateShowing
    procedure CMShowHintChanged(var Message: TLMessage); message CM_SHOWHINTCHANGED;
    procedure CMVisibleChanged(var Message: TLMessage); message CM_VISIBLECHANGED;
    procedure CMEnter(var Message: TLMessage); message CM_ENTER;
    procedure CMExit(var Message: TLMessage); message CM_EXIT;
    procedure WMContextMenu(var Message: TLMContextMenu); message LM_CONTEXTMENU;
    procedure WMEraseBkgnd(var Message: TLMEraseBkgnd); message LM_ERASEBKGND;
    procedure WMNotify(var Message: TLMNotify); message LM_NOTIFY;
    procedure WMSetFocus(var Message: TLMSetFocus); message LM_SETFOCUS;
    procedure WMKillFocus(var Message: TLMKillFocus); message LM_KILLFOCUS;
    procedure WMShowWindow(var Message: TLMShowWindow); message LM_SHOWWINDOW;
    procedure WMEnter(var Message: TLMEnter); message LM_ENTER;
    procedure WMExit(var Message: TLMExit); message LM_EXIT;
    procedure WMKeyDown(var Message: TLMKeyDown); message LM_KEYDOWN;
    procedure WMSysKeyDown(var Message: TLMKeyDown); message LM_SYSKEYDOWN;
    procedure WMKeyUp(var Message: TLMKeyUp); message LM_KEYUP;
    procedure WMSysKeyUp(var Message: TLMKeyUp); message LM_SYSKEYUP;
    procedure WMChar(var Message: TLMChar); message LM_CHAR;
    procedure WMSysChar(var Message: TLMKeyUp); message LM_SYSCHAR;
    procedure WMPaint(var Msg: TLMPaint); message LM_PAINT;
    procedure WMDestroy(var Message: TLMDestroy); message LM_DESTROY;
    procedure WMMove(var Message: TLMMove); message LM_MOVE;
    procedure WMSize(var Message: TLMSize); message LM_SIZE;
    procedure WMWindowPosChanged(var Message: TLMWindowPosChanged); message LM_WINDOWPOSCHANGED;
    procedure CNKeyDown(var Message: TLMKeyDown); message CN_KEYDOWN;
    procedure CNSysKeyDown(var Message: TLMKeyDown); message CN_SYSKEYDOWN;
    procedure CNKeyUp(var Message: TLMKeyUp); message CN_KEYUP;
    procedure CNSysKeyUp(var Message: TLMKeyUp); message CN_SYSKEYUP;
    procedure CNChar(var Message: TLMKeyUp); message CN_CHAR;
  protected
    // drag and drop/dock
    function DoDragMsg(ADragMessage: TDragMessage; APosition: TPoint;
                       ADragObject: TDragObject; ATarget:
                       TControl; ADocking: Boolean): LRESULT; override;
    function DoDockClientMsg(DragDockObject: TDragDockObject; aPosition: TPoint): boolean; virtual;
    function DoUndockClientMsg(NewTarget, Client: TControl):boolean; virtual;
    procedure DoAddDockClient(Client: TControl; const ARect: TRect); virtual;
    procedure DockOver(Source: TDragDockObject; X, Y: Integer;
                       State: TDragState; var Accept: Boolean); virtual;
    procedure DoDockOver(Source: TDragDockObject; X, Y: Integer;
                         State: TDragState; var Accept: Boolean); virtual;
    procedure DoRemoveDockClient(Client: TControl); virtual;
    function  DoUnDock(NewTarget: TWinControl; Client: TControl;
                       KeepDockSiteSize: Boolean = true): Boolean; virtual;
    procedure GetSiteInfo(Client: TControl; var InfluenceRect: TRect;
                          MousePos: TPoint; var CanDock: Boolean); virtual;
    procedure ReloadDockedControl(const AControlName: string;
                                  var AControl: TControl); virtual;
    function CreateDockManager: TDockManager; virtual;
    procedure SetDockManager(AMgr: TDockManager);
    procedure DoFloatMsg(ADockSource: TDragDockObject); override;//CM_FLOAT
    procedure DoGetDockCaption(AControl: TControl; var ACaption: String); virtual;
  protected
    // mouse and keyboard
    procedure DoEnter; virtual;
    procedure DoExit; virtual;
    function  DoKeyDownBeforeInterface(var Message: TLMKey; IsRecurseCall: Boolean): Boolean;
    function  DoRemainingKeyDown(var Message: TLMKeyDown): Boolean;
    function  DoRemainingKeyUp(var Message: TLMKeyDown): Boolean;
    function  DoKeyPress(var Message: TLMKey): Boolean;
    function  DoUTF8KeyPress(var UTF8Key: TUTF8Char): boolean; virtual;
    function  DoKeyUpBeforeInterface(var Message: TLMKey): Boolean;
    function  ChildKey(var Message: TLMKey): boolean; virtual;
    function  SendDialogChar(var Message: TLMKey): Boolean;
    function  DialogChar(var Message: TLMKey): boolean; override;
    procedure ControlKeyDown(var Key: Word; Shift: TShiftState); virtual;
    procedure ControlKeyUp(var Key: Word; Shift: TShiftState); virtual;
    procedure KeyDown(var Key: Word; Shift: TShiftState); virtual;
    procedure KeyDownBeforeInterface(var Key: Word; Shift: TShiftState); virtual;
    procedure KeyDownAfterInterface(var Key: Word; Shift: TShiftState); virtual;
    procedure KeyPress(var Key: char); virtual;
    procedure KeyUp(var Key: Word; Shift: TShiftState); virtual;
    procedure KeyUpBeforeInterface(var Key: Word; Shift: TShiftState); virtual;
    procedure KeyUpAfterInterface(var Key: Word; Shift: TShiftState); virtual;
    procedure UTF8KeyPress(var UTF8Key: TUTF8Char); virtual;
  protected
    function  FindNextControl(CurrentControl: TWinControl; GoForward,
                              CheckTabStop, CheckParent: Boolean): TWinControl;
    procedure SelectFirst;
    function  RealGetText: TCaption; override;
    function  GetBorderStyle: TBorderStyle;
    function  GetClientOrigin: TPoint; override;
    function  GetClientRect: TRect; override;
    function  GetControlOrigin: TPoint; override;
    function  GetDeviceContext(var WindowHandle: HWND): HDC; override;
    function  IsControlMouseMsg(var TheMessage): Boolean;
    procedure CreateHandle; virtual;
    procedure CreateParams(var Params: TCreateParams); virtual;
    procedure CreateWnd; virtual; //creates the window
    procedure DestroyHandle; virtual;
    procedure DestroyWnd; virtual;
    procedure DoFlipChildren; virtual;
    procedure FinalizeWnd; virtual; // gets called before the Handle is destroyed.
    procedure FixupTabList;
    procedure FontChanged(Sender: TObject); override;
    procedure InitializeWnd; virtual; // gets called after the Handle is created and before the missing child handles are created
    procedure Loaded; override;
    procedure FormEndUpdated; override;
    procedure MainWndProc(var Msg: TLMessage);
    procedure ParentFormHandleInitialized; override;
    procedure ChildHandlesCreated; virtual;// called after children handles are created
    procedure RealSetText(const AValue: TCaption); override;
    procedure RemoveFocus(Removing: Boolean);
    procedure SendMoveSizeMessages(SizeChanged, PosChanged: boolean); override;
    procedure SetBorderStyle(NewStyle: TBorderStyle); virtual;
    procedure SetColor(Value: TColor); override;
    procedure SetChildZPosition(const AChild: TControl; const APosition: Integer);
    procedure ShowControl(AControl: TControl); virtual;
    procedure UpdateControlState;
    procedure UpdateShowing; virtual; // checks control's handle visibility, called by DoAllAutoSize and UpdateControlState
    procedure WndProc(var Message: TLMessage); override;
    procedure WSSetText(const AText: String); virtual;
  protected
    property WindowHandle: HWND read FHandle write FHandle;
    // properties which are not supported by all descendents
    property BorderStyle: TBorderStyle read GetBorderStyle write SetBorderStyle default bsNone;
    property OnGetSiteInfo: TGetSiteInfoEvent read FOnGetSiteInfo write FOnGetSiteInfo;
    property OnGetDockCaption: TGetDockCaptionEvent read FOnGetDockCaption write FOnGetDockCaption;
  public
    // properties which are supported by all descendents
    property BorderWidth: TBorderWidth read FBorderWidth write SetBorderWidth default 0;
    property BoundsLockCount: integer read FBoundsLockCount;
    property Brush: TBrush read GetBrush;
    property CachedClientHeight: integer read FClientHeight;
    property CachedClientWidth: integer read FClientWidth;
    property ChildSizing: TControlChildSizing read FChildSizing write SetChildSizing;
    property ControlCount: Integer read GetControlCount;
    property Controls[Index: Integer]: TControl read GetControl;
    property DefWndProc: Pointer read FDefWndProc write FDefWndPRoc;
    property DockClientCount: Integer read GetDockClientCount;
    property DockClients[Index: Integer]: TControl read GetDockClients;
    property DockManager: TDockManager read FDockManager write SetDockManager;
    property DockSite: Boolean read FDockSite write SetDockSite default False;
    property DoubleBuffered: Boolean read FDoubleBuffered write FDoubleBuffered default False;
    property Handle: HWND read GetHandle write SetHandle;
    property IsResizing: Boolean read GetIsResizing;
    property TabOrder: TTabOrder read GetTabOrder write SetTaborder default -1;
    property TabStop: Boolean read FTabStop write SetTabStop default false;
    property OnAlignInsertBefore: TAlignInsertBeforeEvent read FOnAlignInsertBefore write FOnAlignInsertBefore;
    property OnAlignPosition: TAlignPositionEvent read FOnAlignPosition write FOnAlignPosition;
    property OnDockDrop: TDockDropEvent read FOnDockDrop write FOnDockDrop;
    property OnDockOver: TDockOverEvent read FOnDockOver write FOnDockOver;
    property OnEnter: TNotifyEvent read FOnEnter write FOnEnter;
    property OnExit: TNotifyEvent read FOnExit write FOnExit;
    property OnKeyDown: TKeyEvent read FOnKeyDown write FOnKeyDown;
    property OnKeyPress: TKeyPressEvent read FOnKeyPress write FOnKeyPress;
    property OnKeyUp: TKeyEvent read FOnKeyUp write FOnKeyUp;
    property OnUnDock: TUnDockEvent read FOnUnDock write FOnUnDock;
    property OnUTF8KeyPress: TUTF8KeyPressEvent read FOnUTF8KeyPress write FOnUTF8KeyPress;
    property ParentWindow: HWND read FParentWindow write SetParentWindow;
    property Showing: Boolean read FShowing; // handle visible
    property UseDockManager: Boolean read FUseDockManager
                                     write SetUseDockManager default False;
    property VisibleDockClientCount: Integer read GetVisibleDockClientCount;
  public
    // size, position, bounds
    function AutoSizePhases: TControlAutoSizePhases; override;
    function AutoSizeDelayed: boolean; override;
    function AutoSizeCheckParent: Boolean; override;
    procedure BeginUpdateBounds; // disable SetBounds
    procedure EndUpdateBounds;   // enable SetBounds
    procedure LockRealizeBounds; // disable sending bounds to widgetset
    procedure UnlockRealizeBounds; // enable sending bounds to widgetset, changes will now be sent
    function ControlAtPos(const Pos: TPoint; AllowDisabled: Boolean): TControl;
    function ControlAtPos(const Pos: TPoint;
                          AllowDisabled, AllowWinControls: Boolean): TControl;
    function ControlAtPos(const Pos: TPoint; Flags: TControlAtPosFlags): TControl;
    function  ContainsControl(Control: TControl): Boolean;
    procedure DoAdjustClientRectChange(const InvalidateRect: Boolean = True);
    procedure InvalidateClientRectCache(WithChildControls: boolean);
    function ClientRectNeedsInterfaceUpdate: boolean;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: integer); override;
    function  GetChildsRect(Scrolled: boolean): TRect; override;
    procedure DisableAlign;
    procedure EnableAlign;
    procedure ReAlign; // realign all children
    procedure WriteLayoutDebugReport(const Prefix: string); override;
  public
    constructor Create(TheOwner: TComponent);override;
    constructor CreateParented(AParentWindow: HWND);
    class function CreateParentedControl(AParentWindow: HWND): TWinControl;
    destructor Destroy; override;
    procedure DockDrop(DragDockObject: TDragDockObject; X, Y: Integer); virtual;
    function CanFocus: Boolean; virtual;
    function GetControlIndex(AControl: TControl): integer;
    procedure SetControlIndex(AControl: TControl; NewIndex: integer);
    function Focused: Boolean; virtual;
    function PerformTab(ForwardTab: boolean): boolean; virtual;
    function FindChildControl(const ControlName: String): TControl;
    procedure SelectNext(CurControl: TWinControl;
                         GoForward, CheckTabStop: Boolean);
    procedure SetTempCursor(Value: TCursor); override;
    procedure BroadCast(var ToAllMessage);
    procedure NotifyControls(Msg: Word);
    procedure DefaultHandler(var AMessage); override;
    function  GetTextLen: Integer; override;
    procedure Invalidate; override;
    procedure AddControl; virtual; // tell widgetset
    procedure InsertControl(AControl: TControl);
    procedure InsertControl(AControl: TControl; Index: integer); virtual;
    procedure RemoveControl(AControl: TControl); virtual;
    procedure Repaint; override;
    procedure Update; override;
    procedure SetFocus; virtual;
    procedure FlipChildren(AllLevels: Boolean); virtual;
    procedure ScaleBy(Multiplier, Divider: Integer);
    function GetDockCaption(AControl: TControl): String; virtual;
    procedure UpdateDockCaption(Exclude: TControl = nil); virtual;
    procedure GetTabOrderList(List: TFPList);
    function HandleAllocated: Boolean;
    function ParentHandlesAllocated: boolean; override;
    procedure HandleNeeded;
    function BrushCreated: Boolean;
    procedure EraseBackground(DC: HDC); virtual;
    function IntfUTF8KeyPress(var UTF8Key: TUTF8Char;
                              RepeatCount: integer; SystemKey: boolean): boolean; virtual;
    procedure PaintTo(DC: HDC; X, Y: Integer); virtual; overload;
    procedure PaintTo(ACanvas: TCanvas; X, Y: Integer); overload;
    procedure SetShape(AShape: TBitmap); overload;
    procedure SetShape(AShape: TRegion); overload;
  end;


  { TGraphicControl }

  TGraphicControl = class(TControl)
  private
    FCanvas: TCanvas;
    FOnPaint: TNotifyEvent;
    procedure WMPaint(var Message: TLMPaint); message LM_PAINT;
  protected
    class procedure WSRegisterClass; override;
    procedure FontChanged(Sender: TObject); override;
    procedure Paint; virtual;
    procedure DoOnChangeBounds; override;
    procedure DoOnParentHandleDestruction; override;
    procedure Update; override;

    property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    property Canvas: TCanvas read FCanvas;
  end;


  { TCustomControl }

  TCustomControl = class(TWinControl)
  private
    FCanvas: TCanvas;
    FOnPaint: TNotifyEvent;
  protected
    class procedure WSRegisterClass; override;
    procedure WMPaint(var Message: TLMPaint); message LM_PAINT;
    procedure DestroyWnd; override;
    procedure PaintWindow(DC: HDC); override;
    procedure FontChanged(Sender: TObject); override;
    procedure SetColor(Value: TColor); override;
    procedure Paint; virtual;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  public
    property Canvas: TCanvas read FCanvas write FCanvas;
    property BorderStyle;
    property OnPaint: TNotifyEvent read FOnPaint write FOnPaint;
  end;


  { TImageList }

  TImageList = class(TDragImageList)
  published
    property AllocBy;
    property BlendColor;
    property BkColor;
    property DrawingStyle;
    property Height;
    property ImageType;
    property Masked;
    property ShareImages;
    property Width;
    property OnChange;
  end;


  { TControlPropertyStorage - abstract base class }

  TControlPropertyStorage = class(TCustomPropertyStorage)
  protected
    procedure GetPropertyList(List: TStrings); override;
  end;


  { TDockZone }

  TDockTree = class;

  { TDockZone is a node in the TDockTree and encapsulates a region into which
    other zones or a single control are contained. }

  TDockZone = class
  private
    FChildControl: TControl;
    FChildCount: integer;
    FFirstChildZone: TDockZone;
    FTree: TDockTree;
    FParentZone: TDockZone;
    FOrientation: TDockOrientation;
    FNextSibling: TDockZone;
    FPrevSibling: TDockZone;
    FBounds: TRect;
  protected
    function GetHeight: Integer; virtual;
    function GetLeft: Integer; virtual;
    function GetLimitBegin: Integer; virtual;
    function GetLimitSize: Integer; virtual;
    function GetTop: Integer; virtual;
    function GetVisible: Boolean; virtual;
    function GetVisibleChildCount: Integer; virtual;
    function GetWidth: Integer; virtual;
    procedure SetLimitBegin(const AValue: Integer); virtual;
    procedure SetLimitSize(const AValue: Integer); virtual;
    procedure SetHeight(const AValue: Integer); virtual;
    procedure SetLeft(const AValue: Integer); virtual;
    procedure SetTop(const AValue: Integer); virtual;
    procedure SetWidth(const AValue: Integer); virtual;
  public
    constructor Create(TheTree: TDockTree; TheChildControl: TControl);
    function FindZone(AControl: TControl): TDockZone;
    function FirstVisibleChild: TDockZone;
    function GetNextVisibleZone: TDockZone;
    function NextVisible: TDockZone;
    function PrevVisible: TDockZone;
    procedure AddSibling(NewZone: TDockZone; InsertAt: TAlign);
    procedure AddAsFirstChild(NewChildZone: TDockZone);
    procedure AddAsLastChild(NewChildZone: TDockZone);
    procedure ReplaceChild(OldChild, NewChild: TDockZone);
    function GetLastChild: TDockZone;
    function GetIndex: Integer;
    procedure Remove(ChildZone: TDockZone);
  public
    property ChildControl: TControl read FChildControl;
    property ChildCount: Integer read FChildCount;
    property FirstChild: TDockZone read FFirstChildZone;
    property Height: Integer read GetHeight write SetHeight;
    property Left: Integer read GetLeft write SetLeft;
    property LimitBegin: Integer read GetLimitBegin write SetLimitBegin; // returns Left or Top
    property LimitSize: Integer read GetLimitSize write SetLimitSize;    // returns Width or Height
    property Orientation: TDockOrientation read FOrientation write FOrientation;
    property Parent: TDockZone read FParentZone;
    property Top: Integer read GetTop write SetTop;
    property Tree: TDockTree read FTree;
    property Visible: Boolean read GetVisible;
    property VisibleChildCount: Integer read GetVisibleChildCount;
    property Width: Integer read GetWidth write SetWidth;
    property NextSibling: TDockZone read FNextSibling;
    property PrevSibling: TDockZone read FPrevSibling;
  end;
  TDockZoneClass = class of TDockZone;


  { TDockTree - a tree of TDockZones - Every docked window has one tree

    This is an abstract class.
    A real implementation can be found for example in ldocktree.pas.

    Docking means here: Combining several windows to one. A window can here be
    a TCustomForm or a floating control (undocked) or a TDockForm.
    A window can be docked to another to the left, right, top, bottom or "into".
    The docking source window will be resized, to fit to the docking target
    window.

    Example1: Docking "A" (source window) left to "B" (target window)

       +---+    +----+
       | A | -> | B  |
       +---+    |    |
                +----+
      Result: A new docktree will be created. Height of "A" will be resized to
              the height of "B".
              A splitter will be inserted between "A" and "B".
              And all three are children of the newly created TLazDockForm of the
              newly created TDockTree.

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

      If "A" or "B" were floating controls, the floating dock sites are freed.
      If "A" or "B" were forms, their decorations (title bars and borders) are
      replaced by docked decorations.
      If "A" had a TDockTree, it is freed and its child dockzones are merged to
      the docktree of "B". Analog for docking "C" left to "A":

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



    Example2: Docking A into B
                +-----+
       +---+    |     |
       | A | ---+-> B |
       +---+    |     |
                +-----+

      Result: A new docktree will be created. "A" will be resized to the size
              of "B". Both will be put into a TLazDockPages control which is the
              child of the newly created TDockTree.

       +-------+
       |[B][A] |
       |+-----+|
       ||     ||
       || A   ||
       ||     ||
       |+-----+|
       +-------+

    Every DockZone has siblings and children. Siblings can either be
    - horizontally (left to right, splitter),
    - vertically (top to bottom, splitter)
    - or upon each other (as pages, left to right).


    InsertControl - undock control and dock it into the manager. For example
                    dock Form1 left to a Form2:
                    InsertControl(Form1,alLeft,Form2);
                    To dock "into", into a TDockPage, use Align=alNone.
    PositionDockRect - calculates where a control would be placed, if it would
                       be docked via InsertControl.
    RemoveControl - removes a control from the dock manager.

    GetControlBounds - TODO for Delphi compatibility
    ResetBounds - TODO for Delphi compatibility
    SetReplacingControl - TODO for Delphi compatibility
    PaintSite - TODO for Delphi compatibility
  }

  TForEachZoneProc = procedure(Zone: TDockZone) of object;

  TDockTreeFlag = (
    dtfUpdateAllNeeded
    );
  TDockTreeFlags = set of TDockTreeFlag;

  { TDockTree - see comment above }

  TDockTree = class(TDockManager)
  private
    FBorderWidth: Integer; // width of the border of the preview rectangle
    FDockSite: TWinControl;
    FDockZoneClass: TDockZoneClass;
    FFlags: TDockTreeFlags;
    FUpdateCount: Integer;
    procedure DeleteZone(Zone: TDockZone);
    procedure SetDockSite(const AValue: TWinControl);
  protected
    FRootZone: TDockZone;
    function HitTest(const MousePos: TPoint; var HTFlag: Integer): TControl; virtual;
    procedure PaintDockFrame(ACanvas: TCanvas; AControl: TControl;
                             const ARect: TRect); virtual;
    procedure UpdateAll;
    procedure SetDockZoneClass(const AValue: TDockZoneClass);
  public
    constructor Create(TheDockSite: TWinControl); override;
    destructor Destroy; override;
    procedure BeginUpdate; override;
    procedure EndUpdate; override;
    procedure AdjustDockRect(AControl: TControl; var ARect: TRect); virtual;
    procedure GetControlBounds(AControl: TControl;
                               out ControlBounds: TRect); override;
    procedure InsertControl(AControl: TControl; InsertAt: TAlign;
                            DropControl: TControl); override;
    procedure LoadFromStream(SrcStream: TStream); override;
    procedure MessageHandler(Sender: TControl; var Message: TLMessage); override;
    procedure PositionDockRect(AClient, DropCtl: TControl; DropAlign: TAlign;
                               var DockRect: TRect); override;
    procedure RemoveControl(AControl: TControl); override;
    procedure SaveToStream(DestStream: TStream); override;
    procedure SetReplacingControl(AControl: TControl); override;
    procedure ResetBounds(Force: Boolean); override;
    procedure PaintSite(DC: HDC); override;
    procedure DumpLayout(FileName: String); virtual;
  public
    property DockZoneClass: TDockZoneClass read FDockZoneClass;
    property DockSite: TWinControl read FDockSite write SetDockSite;
    property RootZone: TDockZone read FRootZone;
  end;

var
  DockSplitterClass: TControlClass = nil;

type
  { TMouse }

  TMouse = class
  private
    FCapture: HWND;
    FWheelScrollLines: Integer;
    procedure SetCapture(const Value: HWND);
    function GetCapture: HWND;
    function GetCursorPos: TPoint;
    function GetIsDragging: Boolean;
    procedure SetCursorPos(AValue: TPoint);
    function GetWheelScrollLines: Integer;
    function GetDragImmediate: Boolean;
    procedure SetDragImmediate(const AValue: Boolean);
    function GetDragThreshold: Integer;
    procedure SetDragThreshold(const AValue: Integer);
  public
    property Capture: HWND read GetCapture write SetCapture;
    property CursorPos: TPoint read GetCursorPos write SetCursorPos;
    property IsDragging: Boolean read GetIsDragging;
    property WheelScrollLines: Integer read GetWheelScrollLines;
    property DragImmediate: Boolean read GetDragImmediate write SetDragImmediate;
    property DragThreshold: Integer read GetDragThreshold write SetDragThreshold;
  end;


const
  AnchorAlign: array[TAlign] of TAnchors = (
    [akLeft, akTop],                   // alNone
    [akLeft, akTop, akRight],          // alTop
    [akLeft, akRight, akBottom],       // alBottom
    [akLeft, akTop, akBottom],         // alLeft
    [akRight, akTop, akBottom],        // alRight
    [akLeft, akTop, akRight, akBottom],// alClient
    [akLeft, akTop]                    // alCustom
    );
  MainAlignAnchor: array[TAlign] of TAnchorKind = (
    akLeft,   // alNone
    akTop,    // alTop
    akBottom, // alBottom
    akLeft,   // alLeft
    akRight,  // alRight
    akLeft,   // alClient
    akLeft    // alCustom
    );
  OppositeAnchor: array[TAnchorKind] of TAnchorKind = (
    akBottom, // akTop,
    akRight,  // akLeft,
    akLeft,   // akRight,
    akTop     // akBottom
    );
  ClockwiseAnchor: array[TAnchorKind] of TAnchorKind = (
    akRight,  // akTop,
    akTop,    // akLeft,
    akBottom, // akRight,
    akLeft    // akBottom
    );
  DefaultSideForAnchorKind: array[TAnchorKind] of TAnchorSideReference = (
    asrBottom, // akTop
    asrBottom, // akLeft
    asrTop,    // akRight
    asrTop     // akBottom
    );
  AnchorReferenceSide: array[TAnchorKind,TAnchorSideReference] of TAnchorKind =(
    // akTop -> asrTop, asrBottom, asrCenter
    (akTop,akBottom,akTop),
    // akLeft -> asrTop, asrBottom, asrCenter
    (akLeft,akRight,akLeft),
    // akRight -> asrTop, asrBottom, asrCenter
    (akTop,akBottom,akTop),
    // akBottom -> asrTop, asrBottom, asrCenter
    (akLeft,akRight,akLeft)
    );
  AlignNames: array[TAlign] of string = (
    'alNone', 'alTop', 'alBottom', 'alLeft', 'alRight', 'alClient', 'alCustom');
  AnchorNames: array[TAnchorKind] of string = (
    'akTop', 'akLeft', 'akRight', 'akBottom');
  AutoSizePhaseNames: array[TControlAutoSizePhase] of string = (
    'caspNone',
    'caspChangingProperties',
    'caspCreatingHandles',
    'caspComputingBounds',
    'caspRealizingBounds',
    'caspShowing'
    );

function FindDragTarget(const Position: TPoint; AllowDisabled: Boolean): TControl;
function FindControlAtPosition(const Position: TPoint; AllowDisabled: Boolean): TControl;
function FindLCLWindow(const ScreenPos: TPoint): TWinControl;
function FindControl(Handle: HWND): TWinControl;
function FindOwnerControl(Handle: HWND): TWinControl;
function FindLCLControl(const ScreenPos: TPoint): TControl;

function SendAppMessage(Msg: Cardinal; WParam: WParam; LParam: LParam): Longint;
procedure MoveWindowOrg(dc: hdc; X,Y: Integer);

// Interface support.
procedure RecreateWnd(const AWinControl:TWinControl);


// drag and drop
var
  DefaultDockManagerClass: TDockManagerClass;

procedure CancelDrag;
procedure SetCaptureControl(AWinControl: TWinControl; const Position: TPoint);
procedure SetCaptureControl(Control: TControl);
function GetCaptureControl: TControl;

var
  NewStyleControls: Boolean;
  Mouse: TMouse;

// mouse cursor
function CursorToString(Cursor: TCursor): string;
function StringToCursor(const S: string): TCursor;
procedure GetCursorValues(Proc: TGetStrProc);
function CursorToIdent(Cursor: Longint; var Ident: string): Boolean;
function IdentToCursor(const Ident: string; var Cursor: Longint): Boolean;

// shiftstate
function GetKeyShiftState: TShiftState;

procedure AdjustBorderSpace(var RemainingClientRect, CurBorderSpace: TRect;
  Left, Top, Right, Bottom: integer);
procedure AdjustBorderSpace(var RemainingClientRect, CurBorderSpace: TRect;
  const Space: TRect);

function IsColorDefault(AControl: TControl): Boolean;

function BidiFlipAlignment(Alignment: TAlignment; Flip: Boolean = True): TAlignment;
function BidiFlipAnchors(Control: TControl; Flip: Boolean): TAnchors;
function BidiFlipRect(const Rect: TRect; const ParentRect: TRect; const Flip: Boolean): TRect;
procedure ChangeBiDiModeAlignment(var Alignment: TAlignment);

function DbgS(a: TAnchorKind): string; overload;
function DbgS(Anchors: TAnchors): string; overload;
function DbgS(a: TAlign): string; overload;
function DbgS(a: TAnchorKind; Side: TAnchorSideReference): string; overload;
function DbgS(p: TControlAutoSizePhase): string; overload;
function DbgS(Phases: TControlAutoSizePhases): string; overload;

operator := (AVariant: Variant): TCaption;

// register (called by the package initialization in design mode)
procedure Register;


implementation

uses
  WSControls, // circle with base widgetset is allowed
  Forms, // the circle can't be broken without breaking Delphi compatibility
  Math;  // Math is in RTL and only a few functions are used.

var
  // The interface knows, which TWinControl has the capture. This stores
  // what child control of this TWinControl has actually the capture.
  CaptureControl: TControl=nil;

operator := (AVariant: Variant): TCaption;
begin
  Result := String(AVariant);
end;

procedure AdjustBorderSpace(var RemainingClientRect, CurBorderSpace: TRect;
  Left, Top, Right, Bottom: integer);
// RemainingClientRect: remaining clientrect without CurBorderSpace
// CurBorderSpace: current borderspace around RemainingClientRect
// Left, Top, Right, Bottom: apply these borderspaces to CurBorderSpace
//
// CurBorderSpace will be set to the maximum of CurBorderSpace and Left, Top,
// Right, Bottom.
// RemainingClientRect will shrink.
// RemainingClientRect will not shrink to negative size.
var
  NewWidth: Integer;
  NewHeight: Integer;
  NewLeft: Integer;
  NewTop: Integer;
begin
  // set CurBorderSpace to maximum border spacing and adjust RemainingClientRect
  if CurBorderSpace.Left<Left then begin
    inc(RemainingClientRect.Left,Left-CurBorderSpace.Left);
    CurBorderSpace.Left:=Left;
  end;
  if CurBorderSpace.Right<Right then begin
    dec(RemainingClientRect.Right,Right-CurBorderSpace.Right);
    CurBorderSpace.Right:=Right;
  end;
  if CurBorderSpace.Top<Top then begin
    inc(RemainingClientRect.Top,Top-CurBorderSpace.Top);
    CurBorderSpace.Top:=Top;
  end;
  if CurBorderSpace.Bottom<Bottom then begin
    dec(RemainingClientRect.Bottom,Bottom-CurBorderSpace.Bottom);
    CurBorderSpace.Bottom:=Bottom;
  end;

  // make sure RemainingClientRect has no negative Size
  NewWidth:=RemainingClientRect.Right-RemainingClientRect.Left;
  if NewWidth<0 then begin
    // Width is negative
    // set Width to 0 and adjust borderspace. Set Left/Right to center.
    // Example: RemainingClientRect.Left=20, RemainingClientRect.Right=10,
    //          CurBorderSpace.Left:=17, CurBorderSpace.Right:=18
    // Result: RemainingClientRect.Left=RemainingClientRect.Right=15;
    //         CurBorderSpace.Left:=17, CurBorderSpace.Right:=18
    NewLeft:=(RemainingClientRect.Left+RemainingClientRect.Right) div 2;
    dec(CurBorderSpace.Left,RemainingClientRect.Left-NewLeft);
    dec(CurBorderSpace.Right,NewLeft-RemainingClientRect.Right);
    RemainingClientRect.Left:=NewLeft;
    RemainingClientRect.Right:=RemainingClientRect.Left;
  end;
  NewHeight:=RemainingClientRect.Bottom-RemainingClientRect.Top;
  if NewHeight<0 then begin
    // Height is negative
    NewTop:=(RemainingClientRect.Top+RemainingClientRect.Bottom) div 2;
    dec(CurBorderSpace.Top,RemainingClientRect.Top-NewTop);
    dec(CurBorderSpace.Bottom,NewTop-RemainingClientRect.Bottom);
    RemainingClientRect.Top:=NewTop;
    RemainingClientRect.Bottom:=RemainingClientRect.Top;
  end;
end;

procedure AdjustBorderSpace(var RemainingClientRect, CurBorderSpace: TRect;
  const Space: TRect);
begin
  AdjustBorderSpace(RemainingClientRect,CurBorderSpace,Space.Left,Space.Top,
                    Space.Right,Space.Bottom);
end;

function IsColorDefault(AControl: TControl): Boolean;
const
  NoDefaultValue = Longint($80000000);
var
  Info: PPropInfo;
begin
  Result := not AControl.ColorIsStored;
  if not Result then
  begin
    Info := GetPropInfo(AControl, 'Color');
    if Info <> nil then
      Result := (Info^.Default <> NoDefaultValue) and (Info^.Default = AControl.Color);
  end;
end;

function BidiFlipAlignment(Alignment: TAlignment; Flip: Boolean): TAlignment;
const
  BidiAlignment: array[Boolean, TAlignment] of TAlignment =
  (
    ( taLeftJustify, taRightJustify, taCenter ),
    ( taRightJustify, taLeftJustify, taCenter )
  );
begin
  Result := BidiAlignment[Flip, Alignment];
end;

function BidiFlipAnchors(Control: TControl; Flip: Boolean): TAnchors;
begin
  Result := Control.Anchors;
  if Flip then
  begin
    if (akLeft in Result) and (Control.AnchorSide[akLeft].Control=nil)
    and not (akRight in Result) then
      Result := Result - [akLeft] + [akRight]
    else if (akRight in Result) and (Control.AnchorSide[akRight].Control=nil)
    and not (akLeft in Result) then
      Result := Result - [akRight] + [akLeft];
  end;
end;

function BidiFlipRect(const Rect: TRect; const ParentRect: TRect; const Flip: Boolean): TRect;
var
  W: Integer;
begin
  Result := Rect;
  if Flip then
  begin
    W := Result.Right - Result.Left;
    Result.Left := ParentRect.Right - (Result.Left - ParentRect.Left) - W;
    Result.Right := Result.Left + W;
  end;
end;

procedure ChangeBiDiModeAlignment(var Alignment: TAlignment);
begin
  case Alignment of
    taLeftJustify: Alignment := taRightJustify;
    taRightJustify: Alignment := taLeftJustify;
  end;
end;

function DbgS(a: TAnchorKind): string;
begin
  Result:=AnchorNames[a];
end;

function DbgS(Anchors: TAnchors): string;
var
  a: TAnchorKind;
begin
  Result:='';
  for a:=Low(TAnchorKind) to High(TAnchorKind) do begin
    if a in Anchors then begin
      if Result<>'' then Result:=Result+',';
      Result:=Result+AnchorNames[a];
    end;
  end;
  Result:='['+Result+']';
end;

function DbgS(a: TAlign): string;
begin
  Result:=AlignNames[a];
end;

function DbgS(a: TAnchorKind; Side: TAnchorSideReference): string;
begin
  case Side of
  asrTop: if a in [akLeft,akRight] then Result:='asrLeft' else Result:='asrTop';
  asrBottom: if a in [akLeft,akRight] then Result:='asrRight' else Result:='asrBottom';
  asrCenter: Result:='asrCenter';
  else Result:='asr???';
  end;
end;

function DbgS(p: TControlAutoSizePhase): string; overload;
begin
  Result:=AutoSizePhaseNames[p];
end;

function DbgS(Phases: TControlAutoSizePhases): string; overload;
var
  p: TControlAutoSizePhase;
begin
  Result:='';
  for p:=Low(TControlAutoSizePhase) to High(TControlAutoSizePhase) do begin
    if p in Phases then begin
      if Result<>'' then Result:=Result+',';
      Result:=Result+AutoSizePhaseNames[p];
    end;
  end;
  Result:='['+Result+']';
end;

{------------------------------------------------------------------------------
 RecreateWnd
 This function was originally member of TWincontrol. From a VCL point of view
 that made perfectly sense since the VCL knows when a win32 widget has to be
 recreated when properties have changed.
 The LCL however doesn't know, the widgetset does. To avoid old VCL behaviour
 and to provide a central function to the widgetset, it is moved here.
 MWE.
------------------------------------------------------------------------------}
procedure RecreateWnd(const AWinControl:TWinControl);
var
  IsFocused: Boolean;
begin
  if csDestroying in AWinControl.ComponentState then Exit;
  if wcfCreatingHandle in AWinControl.FWinControlFlags then exit;

  if not AWinControl.HandleAllocated
  then begin
    // since only the interface (or custom interface dependent controls) should
    // call us, the handle is always created
    {$IFNDEF DisableChecks}
    DebugLN('WARNING: obsolete call to RecreateWnd for %s', [AWinControl.ClassName]);
    {$ENDIF}
    //DumpStack;
  end;

  IsFocused := AWinControl.Focused;
  AWinControl.DestroyHandle;
  AWinControl.UpdateControlState;
  if IsFocused and AWinControl.HandleAllocated
  then SetFocus(AWinControl.FHandle);
end;

procedure Register;
begin
  RegisterComponents('Common Controls',[TImageList]);
  RegisterNoIcon([TCustomControl,TGraphicControl]);
end;

function SendAppMessage(Msg: Cardinal; WParam: WParam; LParam: LParam): Longint;
begin
  Result:=LCLProc.SendApplicationMessage(Msg,WParam,LParam);
end;

procedure MoveWindowOrg(dc: hdc; X, Y: Integer);
begin
  MoveWindowOrgEx(DC,X,Y);
end;

function GetKeyShiftState: TShiftState;
begin
  Result:=[];
  if (GetKeyState(VK_CONTROL) and $8000)<>0 then
    Include(Result,ssCtrl);
  if (GetKeyState(VK_SHIFT) and $8000)<>0 then
    Include(Result,ssShift);
  if (GetKeyState(VK_MENU) and $8000)<>0 then
    Include(Result,ssAlt);
end;

{------------------------------------------------------------------------------
  FindControl

  Returns the TWinControl associated with the Handle.
  This is very interface specific. Better use FindOwnerControl.

  Handle can also be a child handle, and does not need to be the Handle
  property of the Result.
  IMPORTANT: So, in most cases: Result.Handle <> Handle in the params.

------------------------------------------------------------------------------}
function FindControl(Handle: HWND): TWinControl;
begin
  if Handle <> 0
  then Result := TWinControl(GetProp(Handle,'WinControl'))
  else Result := nil;
end;

{------------------------------------------------------------------------------
  FindOwnerControl

  Returns the TWinControl owning the Handle. Handle can also be a child handle,
  and does not need to be the Handle property of the Result.
  IMPORTANT: Therefore, in most cases: parameter Handle <> Result.Handle
------------------------------------------------------------------------------}
function FindOwnerControl(Handle: HWND): TWinControl;
begin
  while Handle<>0 do
  begin
    Result := FindControl(Handle);
    if Result <> nil then
      Exit;
    Handle := GetParent(Handle);
  end;
  Result := nil;
end;

{------------------------------------------------------------------------------
  FindLCLControl

  Returns the TControl that it at the moment at the visible screen position.
  This is not reliable during resizing.
------------------------------------------------------------------------------}
function FindLCLControl(const ScreenPos: TPoint): TControl;
var
  AWinControl: TWinControl;
  ClientPos: TPoint;
begin
  Result:=nil;
  // find wincontrol at mouse cursor
  AWinControl:=FindLCLWindow(ScreenPos);
  if AWinControl=nil then exit;
  // find control at mouse cursor
  ClientPos:=AWinControl.ScreenToClient(ScreenPos);
  Result:=AWinControl.ControlAtPos(ClientPos,
                        [capfAllowDisabled,capfAllowWinControls,capfRecursive]);
  if Result=nil then Result:=AWinControl;
end;

{-------------------------------------------------------------------------------
  function DoControlMsg(Handle: HWND; var Message): Boolean;

  Find the owner wincontrol and Perform the Message.
-------------------------------------------------------------------------------}
function DoControlMsg(Handle: HWND; var Message): Boolean;
var
  AWinControl: TWinControl;
begin
  Result := false;
  AWinControl := FindOwnerControl(Handle);
  if AWinControl <> nil then
  begin
    { do not use Perform, use WndProc so we can save the Result }
    Inc(TLMessage(Message).Msg, CN_BASE);
    AWinControl.WindowProc(TLMessage(Message));
    Dec(TLMessage(Message).Msg, CN_BASE);
    Result := true;
  end;
end;

{------------------------------------------------------------------------------
  Function: FindLCLWindow
  Params:
  Returns:

 ------------------------------------------------------------------------------}
function FindLCLWindow(const ScreenPos: TPoint): TWinControl;
var
  Handle: HWND;
begin
  Handle := WindowFromPoint(ScreenPos);
  Result := FindOwnerControl(Handle);
end;

function FindDragTarget(const Position: TPoint;
  AllowDisabled: Boolean): TControl;
begin
  Result:=FindControlAtPosition(Position,AllowDisabled);
end;

{------------------------------------------------------------------------------
  Function: FindControlAtPosition
  Params:
  Returns:

 ------------------------------------------------------------------------------}
function FindControlAtPosition(const Position: TPoint;
  AllowDisabled: Boolean): TControl;
var
  WinControl: TWinControl;
  Control: TControl;
begin
  Result := nil;
  WinControl := FindLCLWindow(Position);
  if WinControl <> nil then
  begin
    Result := WinControl;
    Control := WinControl.ControlAtPos(WinControl.ScreenToClient(Position),
                        [capfAllowDisabled, capfAllowWinControls, capfRecursive,
                        capfHasScrollOffset]);
    //debugln(['FindControlAtPosition ',dbgs(Position),' ',DbgSName(WinControl),' ',dbgs(WinControl.ScreenToClient(Position)),' ',DbgSName(Control)]);
    if Control <> nil then
      Result := Control;
  end;
end;

{------------------------------------------------------------------------------
  Function: GetCaptureControl
  Params:

  Returns the current capturing TControl.
  Note: For the interface only a Handle = TWinControl can capture. The LCL
  extends this to allow TControl capture the mouse.
 ------------------------------------------------------------------------------}
function GetCaptureControl: TControl;
begin
  Result := FindOwnerControl(GetCapture);
  if (Result <> nil)
  and (CaptureControl <> nil)
  and (CaptureControl.Parent = Result)
  then Result := CaptureControl;
end;

procedure CancelDrag;
begin
  if (DragManager <> nil) and DragManager.IsDragging then
    DragManager.DragStop(False);
end;

procedure SetCaptureControl(AWinControl: TWinControl; const Position: TPoint);
var
  Control: TControl;
begin
  Control:=AWinControl;
  if (AWinControl<>nil) then begin
    Control:=AWinControl.ControlAtPos(Position,
                                      [capfAllowWinControls,capfRecursive]);
    if Control=nil then
      Control:=AWinControl;
  end;
  SetCaptureControl(Control);
end;

procedure SetCaptureControl(Control: TControl);
var
  // OldCaptureWinControl: TWinControl;
  NewCaptureWinControl: TWinControl;
begin
  //DebugLn('SetCaptureControl Old=',DbgSName(CaptureControl),' New=',DbgSName(Control));
  if (CaptureControl=Control) then exit;

  if Control = nil then
  begin
    {$IFDEF VerboseMouseCapture}
    DebugLn('SetCaptureControl Only ReleaseCapture');
    {$ENDIF}
    // just unset the capturing, intf call not needed
    CaptureControl := nil;
    ReleaseCapture;
    Exit;
  end;

  // OldCaptureWinControl := FindOwnerControl(GetCapture);
  if Control is TWinControl then
    NewCaptureWinControl := TWinControl(Control)
  else
    NewCaptureWinControl := Control.Parent;

  if NewCaptureWinControl = nil then
  begin
    {$IFDEF VerboseMouseCapture}
    DebugLN('SetCaptureControl Only ReleaseCapture');
    {$ENDIF}
    // just unset the capturing, intf call not needed
    CaptureControl:=nil;
    ReleaseCapture;
    Exit;
  end;

  // Paul: don't uncomment. Intf call is needed since some widgetsets can install
  // capture themselves and release capture. Thus we can be in situation when we
  // get widgetset installed capture and don't install our own, later widgetset
  // releases its own capture and we have no capture. Such behavior was registered
  // on windows and it cased a bug #13615

// if NewCaptureWinControl = OldCaptureWinControl then
// begin
//  {$IFDEF VerboseMouseCapture}
//    DebugLN('SetCaptureControl Keep WinControl ',DbgSName(NewCaptureWinControl),
//    ' switch Control ',DbgSName(Control));
//  {$ENDIF}
//   CaptureControl := Control;
//   Exit;
// end;


  // switch capture control
  {$IFDEF VerboseMouseCapture}
  DebugLN('SetCaptureControl Switch to WinControl=',DbgSName(NewCaptureWinControl),
    ' and Control=',DbgSName(Control));
  {$ENDIF}
  CaptureControl := Control;
  ReleaseCapture;
  SetCapture(TWinControl(NewCaptureWinControl).Handle);
end;

{ Cursor translation function }

const
  DeadCursors = 1;

const
  Cursors: array[0..22] of TIdentMapEntry = (
    (Value: crDefault;      Name: 'crDefault'),
    (Value: crNone;         Name: 'crNone'),
    (Value: crArrow;        Name: 'crArrow'),
    (Value: crCross;        Name: 'crCross'),
    (Value: crIBeam;        Name: 'crIBeam'),
    (Value: crSizeNESW;     Name: 'crSizeNESW'),
    (Value: crSizeNS;       Name: 'crSizeNS'),
    (Value: crSizeNWSE;     Name: 'crSizeNWSE'),
    (Value: crSizeWE;       Name: 'crSizeWE'),
    (Value: crUpArrow;      Name: 'crUpArrow'),
    (Value: crHourGlass;    Name: 'crHourGlass'),
    (Value: crDrag;         Name: 'crDrag'),
    (Value: crNoDrop;       Name: 'crNoDrop'),
    (Value: crHSplit;       Name: 'crHSplit'),
    (Value: crVSplit;       Name: 'crVSplit'),
    (Value: crMultiDrag;    Name: 'crMultiDrag'),
    (Value: crSQLWait;      Name: 'crSQLWait'),
    (Value: crNo;           Name: 'crNo'),
    (Value: crAppStart;     Name: 'crAppStart'),
    (Value: crHelp;         Name: 'crHelp'),
    (Value: crHandPoint;    Name: 'crHandPoint'),
    (Value: crSizeAll;      Name: 'crSizeAll'),

    { Dead cursors }
    (Value: crSize;         Name: 'crSize'));

function CursorToString(Cursor: TCursor): string;
begin
  Result := '';
  if not CursorToIdent(Cursor, Result) then FmtStr(Result, '%d', [Cursor]);
end;

function StringToCursor(const S: string): TCursor;
var
  L: Longint;
begin
  if not IdentToCursor(S, L) then L := StrToInt(S);
  Result := TCursor(L);
end;

procedure GetCursorValues(Proc: TGetStrProc);
var
  I: Integer;
begin
  for I := Low(Cursors) to High(Cursors) - DeadCursors do Proc(Cursors[I].Name);
end;

function CursorToIdent(Cursor: Longint; var Ident: string): Boolean;
begin
  Result := IntToIdent(Cursor, Ident, Cursors);
end;

function IdentToCursor(const Ident: string; var Cursor: Longint): Boolean;
begin
  Result := IdentToInt(Ident, Cursor, Cursors);
end;

// turn off before includes !!
{$IFDEF ASSERT_IS_ON}
  {$UNDEF ASSERT_IS_ON}
  {$C-}
{$ENDIF}

// helper types and functions
{$I dragdock.inc}
{$I controlsproc.inc}

// components
{$I sizeconstraints.inc}
{$I dragmanager.inc}
{$I controlcanvas.inc}
{$I wincontrol.inc}
{$I controlactionlink.inc}
{$I control.inc}
{$I graphiccontrol.inc}
{$I customcontrol.inc}
{$I dockzone.inc}
{$I docktree.inc}
{$I mouse.inc}
{$I dragobject.inc}
{$I dragimagelist.inc}

{ TControlBorderSpacing }

procedure TControlBorderSpacing.SetAround(const AValue: TSpacingSize);
begin
  if FAround=AValue then exit;
  FAround:=AValue;
  Change(false);
end;

function TControlBorderSpacing.IsAroundStored: boolean;
begin
  if FDefault = nil
  then Result := FAround <> 0
  else Result := FAround <> FDefault^.Around;
end;

function TControlBorderSpacing.IsBottomStored: boolean;
begin
  if FDefault = nil
  then Result := FBottom <> 0
  else Result := FBottom <> FDefault^.Bottom;
end;

function TControlBorderSpacing.IsInnerBorderStored: boolean;
begin
  Result:=Control.IsBorderSpacingInnerBorderStored;
end;

function TControlBorderSpacing.IsLeftStored: boolean;
begin
  if FDefault = nil
  then Result := FLeft <> 0
  else Result := FLeft <> FDefault^.Left;
end;

function TControlBorderSpacing.IsRightStored: boolean;
begin
  if FDefault = nil
  then Result := FRight <> 0
  else Result := FRight <> FDefault^.Right;
end;

function TControlBorderSpacing.IsTopStored: boolean;
begin
  if FDefault = nil
  then Result := FTop <> 0
  else Result := FTop <> FDefault^.Top;
end;

procedure TControlBorderSpacing.SetBottom(const AValue: TSpacingSize);
begin
  if FBottom=AValue then exit;
  FBottom:=AValue;
  Change(false);
end;

procedure TControlBorderSpacing.SetCellAlignHorizontal(
  const AValue: TControlCellAlign);
begin
  if FCellAlignHorizontal=AValue then exit;
  FCellAlignHorizontal:=AValue;
  Change(false);
end;

procedure TControlBorderSpacing.SetCellAlignVertical(
  const AValue: TControlCellAlign);
begin
  if FCellAlignVertical=AValue then exit;
  FCellAlignVertical:=AValue;
  Change(false);
end;

procedure TControlBorderSpacing.SetInnerBorder(const AValue: Integer);
begin
  if FInnerBorder=AValue then exit;
  FInnerBorder:=AValue;
  if Control<>nil then Control.InvalidatePreferredSize;
  Change(true);
end;

procedure TControlBorderSpacing.SetLeft(const AValue: TSpacingSize);
begin
  if FLeft=AValue then exit;
  FLeft:=AValue;
  Change(false);
end;

procedure TControlBorderSpacing.SetRight(const AValue: TSpacingSize);
begin
  if FRight=AValue then exit;
  FRight:=AValue;
  Change(false);
end;

procedure TControlBorderSpacing.SetSpace(Kind: TAnchorKind;
  const AValue: integer);
begin
  case Kind of
  akLeft: Left:=AValue;
  akTop: Top:=AValue;
  akBottom: Bottom:=AValue;
  akRight: Right:=AValue;
  end;
end;

procedure TControlBorderSpacing.SetTop(const AValue: TSpacingSize);
begin
  if FTop=AValue then exit;
  FTop:=AValue;
  Change(false);
end;

constructor TControlBorderSpacing.Create(OwnerControl: TControl; ADefault: PControlBorderSpacingDefault);
begin
  FControl := OwnerControl;
  FDefault := ADefault;
  if FDefault = nil
  then begin
    FLeft := 0;
    FRight := 0;
    FTop := 0;
    FBottom := 0;
    FAround := 0;
  end
  else begin
    FLeft := FDefault^.Left;
    FRight := FDefault^.Right;
    FTop := FDefault^.Top;
    FBottom := FDefault^.Bottom;
    FAround := FDefault^.Around;
  end;
  FCellAlignHorizontal := ccaFill;
  FCellAlignVertical := ccaFill;
  inherited Create;
end;

procedure TControlBorderSpacing.Assign(Source: TPersistent);
var
  SrcSpacing: TControlBorderSpacing;
begin
  if Source is TControlBorderSpacing then begin
    SrcSpacing:=TControlBorderSpacing(Source);
    if IsEqual(SrcSpacing) then exit;

    FAround:=SrcSpacing.Around;
    FBottom:=SrcSpacing.Bottom;
    FLeft:=SrcSpacing.Left;
    FRight:=SrcSpacing.Right;
    FTop:=SrcSpacing.Top;
    FInnerBorder:=SrcSpacing.InnerBorder;
    FCellAlignHorizontal:=SrcSpacing.CellAlignHorizontal;
    FCellAlignVertical:=SrcSpacing.CellAlignVertical;

    Change(false);
  end else
    inherited Assign(Source);
end;

procedure TControlBorderSpacing.AssignTo(Dest: TPersistent);
begin
  Dest.Assign(Self);
end;

function TControlBorderSpacing.IsEqual(Spacing: TControlBorderSpacing
  ): boolean;
begin
  Result:=(FAround=Spacing.Around)
      and (FBottom=Spacing.Bottom)
      and (FLeft=Spacing.Left)
      and (FRight=Spacing.Right)
      and (FTop=Spacing.Top);
end;

procedure TControlBorderSpacing.GetSpaceAround(var SpaceAround: TRect);
begin
  SpaceAround.Left:=Left+Around;
  SpaceAround.Top:=Top+Around;
  SpaceAround.Right:=Right+Around;
  SpaceAround.Bottom:=Bottom+Around;
end;


function TControlBorderSpacing.GetSpace(Kind: TAnchorKind): Integer;
begin
  Result:=Around+GetSideSpace(Kind);
end;

function TControlBorderSpacing.GetSideSpace(Kind: TAnchorKind): Integer;
begin
  case Kind of
  akLeft: Result:=Left;
  akTop: Result:=Top;
  akRight: Result:=Right;
  akBottom: Result:=Bottom;
  end;
end;

procedure TControlBorderSpacing.Change(InnerSpaceChanged: Boolean);
begin
  FControl.DoBorderSpacingChange(Self,InnerSpaceChanged);
  if Assigned(OnChange) then OnChange(Self);
end;

{ TControlChildSizing }

procedure TControlChildSizing.SetEnlargeHorizontal(
  const AValue: TChildControlResizeStyle);
begin
  if FEnlargeHorizontal=AValue then exit;
  FEnlargeHorizontal:=AValue;
  Change;
end;

procedure TControlChildSizing.SetControlsPerLine(const AValue: integer);
begin
  if FControlsPerLine=AValue then exit;
  FControlsPerLine:=AValue;
  Change;
end;

procedure TControlChildSizing.SetEnlargeVertical(
  const AValue: TChildControlResizeStyle);
begin
  if FEnlargeVertical=AValue then exit;
  FEnlargeVertical:=AValue;
  Change;
end;

procedure TControlChildSizing.SetHorizontalSpacing(const AValue: integer);
begin
  if FHorizontalSpacing=AValue then exit;
  FHorizontalSpacing:=AValue;
  Change;
end;

procedure TControlChildSizing.SetLayout(const AValue: TControlChildrenLayout);
begin
  if FLayout=AValue then exit;
  FLayout:=AValue;
  //debugln('TControlChildSizing.SetLayout ',DbgSName(Control));
  Change;
end;

procedure TControlChildSizing.SetLeftRightSpacing(const AValue: integer);
begin
  if FLeftRightSpacing=AValue then exit;
  FLeftRightSpacing:=AValue;
  Change;
end;

procedure TControlChildSizing.SetShrinkHorizontal(
  const AValue: TChildControlResizeStyle);
begin
  if FShrinkHorizontal=AValue then exit;
  FShrinkHorizontal:=AValue;
  Change;
end;

procedure TControlChildSizing.SetShrinkVertical(
  const AValue: TChildControlResizeStyle);
begin
  if FShrinkVertical=AValue then exit;
  FShrinkVertical:=AValue;
  Change;
end;

procedure TControlChildSizing.SetTopBottomSpacing(const AValue: integer);
begin
  if FTopBottomSpacing=AValue then exit;
  FTopBottomSpacing:=AValue;
  Change;
end;

procedure TControlChildSizing.SetVerticalSpacing(const AValue: integer);
begin
  if FVerticalSpacing=AValue then exit;
  FVerticalSpacing:=AValue;
  Change;
end;

constructor TControlChildSizing.Create(OwnerControl: TWinControl);
begin
  FControl := OwnerControl;
  inherited Create;
  FLayout := cclNone;
  FEnlargeHorizontal :=crsAnchorAligning;
  FEnlargeVertical := crsAnchorAligning;
  FShrinkHorizontal := crsAnchorAligning;
  FShrinkVertical := crsAnchorAligning;
  FLeftRightSpacing := 0;
  FTopBottomSpacing := 0;
  FHorizontalSpacing := 0;
  FVerticalSpacing := 0;
  FControlsPerLine := 0;
end;

procedure TControlChildSizing.Assign(Source: TPersistent);
var
  SrcSizing: TControlChildSizing;
begin
  if Source is TControlChildSizing then begin
    SrcSizing:=TControlChildSizing(Source);
    if IsEqual(SrcSizing) then exit;

    FEnlargeHorizontal:=SrcSizing.EnlargeHorizontal;
    FEnlargeVertical:=SrcSizing.EnlargeVertical;
    FShrinkHorizontal:=SrcSizing.ShrinkHorizontal;
    FShrinkVertical:=SrcSizing.ShrinkVertical;
    FEnlargeHorizontal:=SrcSizing.EnlargeHorizontal;
    FEnlargeVertical:=SrcSizing.EnlargeVertical;
    FShrinkHorizontal:=SrcSizing.ShrinkHorizontal;
    FShrinkVertical:=SrcSizing.ShrinkVertical;
    FControlsPerLine:=SrcSizing.ControlsPerLine;
    FLayout:=SrcSizing.Layout;
    FLeftRightSpacing:=SrcSizing.LeftRightSpacing;
    FTopBottomSpacing:=SrcSizing.TopBottomSpacing;
    FHorizontalSpacing:=SrcSizing.HorizontalSpacing;
    FVerticalSpacing:=SrcSizing.VerticalSpacing;

    Change;
  end else
    inherited Assign(Source);
end;

procedure TControlChildSizing.AssignTo(Dest: TPersistent);
begin
  Dest.Assign(Self);
end;

function TControlChildSizing.IsEqual(Sizing: TControlChildSizing): boolean;
begin
  Result:=(FEnlargeHorizontal=Sizing.EnlargeHorizontal)
      and (FEnlargeVertical=Sizing.EnlargeVertical)
      and (FShrinkHorizontal=Sizing.ShrinkHorizontal)
      and (FShrinkVertical=Sizing.ShrinkVertical)
      and (FEnlargeHorizontal=Sizing.EnlargeHorizontal)
      and (FEnlargeVertical=Sizing.EnlargeVertical)
      and (FShrinkHorizontal=Sizing.ShrinkHorizontal)
      and (FShrinkVertical=Sizing.ShrinkVertical)
      and (FControlsPerLine=Sizing.ControlsPerLine)
      and (FLayout=Sizing.Layout)
      and (FLeftRightSpacing=Sizing.LeftRightSpacing)
      and (FTopBottomSpacing=Sizing.TopBottomSpacing)
      and (FHorizontalSpacing=Sizing.HorizontalSpacing)
      and (FVerticalSpacing=Sizing.VerticalSpacing);
end;

procedure TControlChildSizing.SetGridSpacing(Spacing: integer);
begin
  if (LeftRightSpacing=Spacing)
  and (TopBottomSpacing=Spacing)
  and (HorizontalSpacing=Spacing)
  and (VerticalSpacing=Spacing) then exit;
  fLeftRightSpacing:=Spacing;
  fTopBottomSpacing:=Spacing;
  fHorizontalSpacing:=Spacing;
  fVerticalSpacing:=Spacing;
  Change;
end;

procedure TControlChildSizing.Change;
begin
  if Control<>nil then
    Control.DoChildSizingChange(Self);
  if Assigned(FOnChange) then FOnChange(Self);
end;

{ TAnchorSide }

procedure TAnchorSide.SetControl(const AValue: TControl);

  {$IFNDEF DisableChecks}
  procedure RaiseOwnerCircle;
  begin
    DebugLN('RaiseOwnerCircle AValue=',DbgSName(AValue),' FOwner=',DbgSName(FOwner));
    raise Exception.Create('TAnchorSide.SetControl AValue=FOwner');
  end;
  {$ENDIF}

var
  OldControl: TControl;
begin
  {$IFNDEF DisableChecks}
  if (AValue=FOwner) then RaiseOwnerCircle;
  {$ENDIF}
  if FControl=AValue then exit;
  OldControl:=FControl;
  if Side=asrCenter then begin
    FixCenterAnchoring;
    if Control<>OldControl then exit;
  end;
  FControl:=nil;
  if OldControl<>nil then
    OldControl.ForeignAnchorSideChanged(Self,ascoRemove);
  FControl:=AValue;
  //debugln('TAnchorSide.SetControl A ',DbgSName(FOwner),' FControl=',DbgSName(FControl));
  if FControl<>nil then
    FControl.ForeignAnchorSideChanged(Self,ascoAdd);
  FOwner.AnchorSideChanged(Self);
end;

function TAnchorSide.IsSideStored: boolean;
begin
  Result:=(Control<>nil) and (Side<>DefaultSideForAnchorKind[Kind]);
end;

procedure TAnchorSide.SetSide(const AValue: TAnchorSideReference);
var
  OldSide: TAnchorSideReference;
begin
  if FSide=AValue then exit;
  FOwner.DisableAutoSizing{$IFDEF DebugDisableAutoSizing}('TAnchorSide.SetSide'){$ENDIF};
  if AValue=asrCenter then begin
    OldSide:=FSide;
    FixCenterAnchoring;
    if OldSide<>FSide then exit;
  end;
  FSide:=AValue;
  FOwner.AnchorSideChanged(Self);
  if FControl<>nil then
    FControl.ForeignAnchorSideChanged(Self,ascoChangeSide);
  FOwner.EnableAutoSizing{$IFDEF DebugDisableAutoSizing}('TAnchorSide.SetSide'){$ENDIF};
end;

function TAnchorSide.GetOwner: TPersistent;
begin
  Result := FOwner;
end;

constructor TAnchorSide.Create(TheOwner: TControl; TheKind: TAnchorKind);
begin
  inherited Create;
  FOwner := TheOwner;
  FKind := TheKind;
  FSide := asrTop;
end;

destructor TAnchorSide.Destroy;
var
  OldControl: TControl;
begin
  OldControl:=Control;
  FControl:=nil;
  //DebugLN('TAnchorSide.Destroy A ',DbgSName(Owner));
  if OldControl<>nil then
    OldControl.ForeignAnchorSideChanged(Self,ascoRemove);
  inherited Destroy;
end;

procedure TAnchorSide.GetSidePosition(out ReferenceControl: TControl; out
  ReferenceSide: TAnchorSideReference; out Position: Integer);
begin
  CheckSidePosition(Control,Side,ReferenceControl,ReferenceSide,Position);
end;

function TAnchorSide.CheckSidePosition(NewControl: TControl;
  NewSide: TAnchorSideReference;
  out ReferenceControl: TControl;
  out ReferenceSide: TAnchorSideReference; out Position: Integer): boolean;
var
  ParentRect: TRect;
  ParentRectValid: boolean;

  procedure RaiseInvalidSide;
  begin
    raise Exception.Create('TAnchorSide.CheckSidePosition invalid Side');
  end;

  function GetNextCentered(ReferenceControl: TControl; Side: TAnchorKind;
    var NextReferenceSide: TAnchorSide): boolean;
  begin
    if (Side in ReferenceControl.Anchors)
    and (ReferenceControl.AnchorSide[Side].Control<>nil)
    and (ReferenceControl.AnchorSide[Side].Side=asrCenter) then begin
      Result:=true;
      NextReferenceSide:=ReferenceControl.AnchorSide[Side];
    end else
      Result:=false;
  end;

  function GetParentSidePos(Side: TAnchorKind): integer;
  begin
    if not ParentRectValid then begin
      FOwner.Parent.GetAdjustedLogicalClientRect(ParentRect);
      ParentRectValid:=true;
    end;
    case Side of
    akTop: Result:=ParentRect.Top;
    akLeft: Result:=ParentRect.Left;
    akRight: Result:=ParentRect.Right;
    akBottom: Result:=ParentRect.Bottom;
    end;
  end;

var
  NextReferenceSide: TAnchorSide;
  ChainLength: Integer;
  MaxChainLength: LongInt;
  OwnerBorderSpacing: LongInt;
  OwnerParent: TWinControl;
  Found: Boolean;
  CurReferenceControl: TControl;
  CurReferenceSide: TAnchorSideReference;
begin
  ReferenceControl:=nil;
  ReferenceSide:=Side;
  Position:=0;
  OwnerParent:=FOwner.Parent;
  if OwnerParent=nil then begin
    // AnchorSide is only between siblings or its direct parent allowed
    //if CheckPosition(Owner) then DebugLn(['TAnchorSide.GetSidePosition OwnerParent=nil']);
    exit;
  end;
  ParentRectValid:=false;
  ChainLength:=0;
  MaxChainLength:=OwnerParent.ControlCount;
  Found:=false;
  CurReferenceControl:=NewControl;
  CurReferenceSide:=NewSide;
  while CurReferenceControl<>nil do begin

    // check for circles
    if CurReferenceControl=Owner then begin
      // circle
      {$IFNDEF DisableChecks}
      DebugLn(['TAnchorSide.GetSidePosition Circle, ',DbgSName(Owner),' ',dbgs(Kind)]);
      {$ENDIF}
      ReferenceControl:=nil;
      exit(false);
    end;

    inc(ChainLength);
    if ChainLength>MaxChainLength then begin
      // the chain has more elements than there are siblings -> circle
      //if CheckPosition(Owner) then
      {$IFNDEF DisableChecks}
      DebugLn(['TAnchorSide.GetSidePosition Circle, ',DbgSName(Owner),' ',dbgs(Kind)]);
      {$ENDIF}
      ReferenceControl:=nil;
      exit(false);
    end;

    // check if ReferenceControl is valid
    if (CurReferenceControl.Parent<>OwnerParent)
    and (CurReferenceControl<>OwnerParent) then begin
      // not a sibling and not the parent -> invalid AnchorSide
      //if CheckPosition(Owner) then DebugLn(['TAnchorSide.GetSidePosition invalid AnchorSide ',dbgsName(ReferenceControl)]);
      {$IFNDEF DisableChecks}
      DebugLn(['TAnchorSide.GetSidePosition invalid anchor control, ',DbgSName(Owner),' ',dbgs(Kind)]);
      {$ENDIF}
      ReferenceControl:=nil;
      exit(false);
    end;

    //debugln(['TAnchorSide.CheckSidePosition CurReferenceControl=',DbgSName(CurReferenceControl),' Kind=',dbgs(Kind),' Visible=',CurReferenceControl.IsControlVisible]);

    if CurReferenceControl.IsControlVisible then begin
      // ReferenceControl is visible
      if not Found then begin
        Found:=true;
        ReferenceControl:=CurReferenceControl;
        ReferenceSide:=CurReferenceSide;

        // -> calculate Position
        OwnerBorderSpacing:=FOwner.BorderSpacing.GetSpace(Kind);
        //if CheckPosition(Owner) then DebugLn(['TAnchorSide.GetSidePosition ',dbgsName(Owner),' ReferenceControl=',dbgsName(ReferenceControl),' ',dbgs(ReferenceControl.BoundsRect),' OwnerBorderSpacing=',OwnerBorderSpacing,' Kind=',dbgs(Kind),' ReferenceSide=',dbgs(Kind,ReferenceSide)]);
        case ReferenceSide of

        asrTop: // asrTop = asrLeft
          if Kind in [akLeft,akRight] then begin
            // anchor to left side of ReferenceControl
            if ReferenceControl=OwnerParent then
              Position:=GetParentSidePos(akLeft)
            else
              Position:=ReferenceControl.Left;
            if ReferenceControl=OwnerParent then
              OwnerBorderSpacing:=Max(OwnerBorderSpacing,
                                      OwnerParent.ChildSizing.LeftRightSpacing)
            else if Kind=akRight then
              OwnerBorderSpacing:=Max(Max(OwnerBorderSpacing,
                   ReferenceControl.BorderSpacing.GetSpace(OppositeAnchor[Kind])),
                   OwnerParent.ChildSizing.HorizontalSpacing);
            if Kind=akLeft then begin
              // anchor left of ReferenceControl and left of Owner
              inc(Position,OwnerBorderSpacing);
            end else begin
              // anchor left of ReferenceControl and right of Owner
              dec(Position,OwnerBorderSpacing);
            end;
          end else begin
            // anchor to top side of ReferenceControl
            if ReferenceControl=OwnerParent then
              Position:=GetParentSidePos(akTop)
            else
              Position:=ReferenceControl.Top;
            if ReferenceControl=OwnerParent then
              OwnerBorderSpacing:=Max(OwnerBorderSpacing,
                                      OwnerParent.ChildSizing.TopBottomSpacing)
            else if Kind=akBottom then
              OwnerBorderSpacing:=Max(Max(OwnerBorderSpacing,
                   ReferenceControl.BorderSpacing.GetSpace(OppositeAnchor[Kind])),
                   OwnerParent.ChildSizing.VerticalSpacing);
            if Kind=akTop then begin
              // anchor top of ReferenceControl and top of Owner
              inc(Position,OwnerBorderSpacing);
            end else begin
              // anchor top of ReferenceControl and bottom of Owner
              dec(Position,OwnerBorderSpacing);
            end;
          end;

        asrBottom: // asrBottom = asrRight
          if Kind in [akLeft,akRight] then begin
            // anchor to right side of ReferenceControl
            if ReferenceControl=OwnerParent then
              Position:=GetParentSidePos(akRight)
            else
              Position:=ReferenceControl.Left+ReferenceControl.Width;
            if ReferenceControl=OwnerParent then
              OwnerBorderSpacing:=Max(OwnerBorderSpacing,
                                      OwnerParent.ChildSizing.LeftRightSpacing)
            else if Kind=akLeft then
              OwnerBorderSpacing:=Max(Max(OwnerBorderSpacing,
                   ReferenceControl.BorderSpacing.GetSpace(OppositeAnchor[Kind])),
                   OwnerParent.ChildSizing.HorizontalSpacing);
            if Kind=akLeft then begin
              // anchor right of ReferenceControl and left of Owner
              inc(Position,OwnerBorderSpacing);
            end else begin
              // anchor right of ReferenceControl and right of Owner
              dec(Position,OwnerBorderSpacing);
            end;
          end else begin
            // anchor to bottom side of ReferenceControl
            if ReferenceControl=OwnerParent then
              Position:=GetParentSidePos(akBottom)
            else
              Position:=ReferenceControl.Top+ReferenceControl.Height;
            if ReferenceControl=OwnerParent then
              OwnerBorderSpacing:=Max(OwnerBorderSpacing,
                                      OwnerParent.ChildSizing.TopBottomSpacing)
            else if Kind=akTop then
              OwnerBorderSpacing:=Max(Max(OwnerBorderSpacing,
                   ReferenceControl.BorderSpacing.GetSpace(OppositeAnchor[Kind])),
                   OwnerParent.ChildSizing.VerticalSpacing);
            if Kind=akTop then begin
              // anchor bottom of ReferenceControl and top of Owner
              inc(Position,OwnerBorderSpacing);
            end else begin
              // anchor bottom of ReferenceControl and bottom of Owner
              dec(Position,OwnerBorderSpacing);
            end;
          end;

        asrCenter:
          if Kind in [akLeft,akRight] then begin
            // center horizontally
            if ReferenceControl=OwnerParent then
              Position:=(GetParentSidePos(akRight)+GetParentSidePos(akLeft)) div 2
            else
              Position:=ReferenceControl.Left+(ReferenceControl.Width div 2);
            if Kind=akLeft then
              dec(Position,FOwner.Width div 2)
            else
              inc(Position,FOwner.Width div 2);
          end else begin
            // center vertically
            if ReferenceControl=OwnerParent then
              Position:=OwnerParent.ClientHeight div 2
            else
              Position:=ReferenceControl.Top+(ReferenceControl.Height div 2);
            if Kind=akTop then
              dec(Position,FOwner.Height div 2)
            else
              inc(Position,FOwner.Height div 2);
          end;

        else
          RaiseInvalidSide;
        end;
      end;
      // side found
      // continue to detect circles
    end;

    // try next
    NextReferenceSide:=nil;
    //debugln(['TAnchorSide.CheckSidePosition CurReferenceControl=',DbgSName(CurReferenceControl),' OwnerParent=',DbgSName(OwnerParent)]);
    if CurReferenceControl<>OwnerParent then
    begin
      // anchored to an invisible control
      //debugln(['TAnchorSide.CheckSidePosition skip invisible, try next CurReferenceControl=',DbgSName(CurReferenceControl),' Kind=',dbgs(Kind),' CurReferenceSide=',dbgs(Kind,CurReferenceSide)]);
      if CurReferenceSide=asrCenter then
      begin
        // center can only be anchored to another centered anchor
        if Kind in [akLeft,akRight] then
        begin
          if not GetNextCentered(CurReferenceControl,akLeft,NextReferenceSide)
          then   GetNextCentered(CurReferenceControl,akRight,NextReferenceSide);
        end else begin
          if not GetNextCentered(CurReferenceControl,akTop,NextReferenceSide)
          then   GetNextCentered(CurReferenceControl,akBottom,NextReferenceSide);
        end;
      end else if (CurReferenceSide=asrLeft) = (Kind in [akLeft,akTop]) then
      begin
        //debugln(['TAnchorSide.CheckSidePosition parallel CurReferenceControl=',DbgSName(CurReferenceControl),' Kind=',dbgs(Kind),' Anchors=',dbgs(CurReferenceControl.Anchors)]);
        // anchor parallel (e.g. a left side to a left side)
        if Kind in CurReferenceControl.Anchors then
          NextReferenceSide:=CurReferenceControl.AnchorSide[Kind]
        else if OppositeAnchor[Kind] in CurReferenceControl.Anchors then
          NextReferenceSide:=CurReferenceControl.AnchorSide[OppositeAnchor[Kind]];
      end else begin
        //debugln(['TAnchorSide.CheckSidePosition opposite CurReferenceControl=',DbgSName(CurReferenceControl),' Kind=',dbgs(Kind),' Anchors=',dbgs(CurReferenceControl.Anchors)]);
        // anchor opposite (e.g. a left side to a right side)
        if OppositeAnchor[Kind] in CurReferenceControl.Anchors then
          NextReferenceSide:=CurReferenceControl.AnchorSide[OppositeAnchor[Kind]]
        else if Kind in CurReferenceControl.Anchors then
          NextReferenceSide:=CurReferenceControl.AnchorSide[Kind];
      end;
    end;
    if (NextReferenceSide=nil) then
    begin
      // no further side => anchor ok
      // Note: if anchored control is not visible, it is anchored to the parent
      //if CheckPosition(Owner) and (Kind=akRight) then
      //if Owner.Name='ClassPartInsertPolicyRadioGroup' then
      //  DebugLn(['TAnchorSide.GetSidePosition Success ',DbgSName(Owner),' ReferenceControl=',dbgsName(ReferenceControl),' CurReferenceControl=',DbgSName(CurReferenceControl),' CurReferenceSide=',dbgs(Kind,CurReferenceSide)]);
      exit(true);
    end;
    if NextReferenceSide=Self then begin
      CurReferenceControl:=NewControl;
      CurReferenceSide:=NewSide;
    end else begin
      CurReferenceControl:=NextReferenceSide.Control;
      CurReferenceSide:=NextReferenceSide.Side;
    end;
    //DebugLn(['TAnchorSide.GetSidePosition ',DbgSName(FOwner),' ReferenceControl=',DbgSName(ReferenceControl),' Kind=',dbgs(Kind),' ReferenceSide=',dbgs(Kind,ReferenceSide)]);
  end;
end;

procedure TAnchorSide.Assign(Source: TPersistent);
var
  Src: TAnchorSide;
begin
  if Source is TAnchorSide then begin
    Src:=TAnchorSide(Source);
    Side:=Src.Side;
    Control:=Src.Control;
  end else
    inherited Assign(Source);
end;

function TAnchorSide.IsAnchoredToParent(ParentSide: TAnchorKind): boolean;
var
  ReferenceControl: TControl;
  ReferenceSide: TAnchorSideReference;
  p: Integer;
begin
  if (Owner.Align in [alClient,alLeft,alRight,alTop,alBottom])
  and (Kind in AnchorAlign[Owner.Align]) then
    exit(true); // aligned
  if not (Kind in Owner.Anchors) then
    exit(false); // not anchored
  GetSidePosition(ReferenceControl,ReferenceSide,p);
  if ReferenceControl=nil then
    exit(true); // default anchored to parent
  if Owner.Parent=nil then
    exit(false); // no parent
  if (ReferenceControl=Owner.Parent) and (Kind=ParentSide) then
    exit(true);
  Result:=false;
end;

procedure TAnchorSide.FixCenterAnchoring;
begin
  if (Side=asrCenter) and (Control<>nil) and (Kind in FOwner.Anchors) then
  begin
    // in case asrCenter, both sides are controlled by one anchor
    // -> disable opposite anchor and aligning
    if FOwner.Align in [alLeft,alTop,alRight,alBottom,alClient] then begin
      FOwner.Align:=alNone;
    end;
    FOwner.Anchors:=FOwner.Anchors-[OppositeAnchor[Kind]];
  end;
end;

{ TControlPropertyStorage }

procedure TControlPropertyStorage.GetPropertyList(List: TStrings);
var
  ARoot: TPersistent;
  PropsAsStr: String;
  StartPos: Integer;
  EndPos: LongInt;
  PropertyStr: String;
  AControl: TControl;
  PointPos: LongInt;
begin
  ARoot:=Root;
  if ARoot is TControl then begin
    AControl:=TControl(ARoot);
    PropsAsStr:=AControl.SessionProperties;
    //debugln('PropsAsStr=',PropsAsStr);
    StartPos:=1;
    while (StartPos<=length(PropsAsStr)) do begin
      EndPos:=StartPos;
      while (EndPos<=length(PropsAsStr)) and (PropsAsStr[EndPos]<>';') do
        inc(EndPos);
      if (EndPos>StartPos) then begin
        PropertyStr:=copy(PropsAsStr,StartPos,EndPos-StartPos);
        //debugln('A PropertyStr=',PropertyStr);
        // if no point char, then prepend the owner name as default
        PointPos:=StartPos;
        while (PointPos<EndPos) and (PropsAsStr[PointPos]<>'.') do
          inc(PointPos);
        if PointPos=EndPos then
          PropertyStr:=AControl.Name+'.'+PropertyStr;
        // add to list
        //debugln('B PropertyStr=',PropertyStr);
        List.Add(PropertyStr);
      end;
      StartPos:=EndPos+1;
    end;
  end;
end;

{ TDragManager }

constructor TDragManager.Create(TheOwner: TComponent);
begin
{ TODO -cdocking : DragImmediate should apply to drag-drop only, while drag-dock never should start immediately
 }
  inherited Create(TheOwner);
  FDragImmediate := True;
  FDragThreshold := 5;
end;

{ TDockManager }

procedure TDockManager.PositionDockRect(ADockObject: TDragDockObject);
begin
(* for now: defer to old PositionDockRect.
  Overridden methods should determine DropOnControl and DropAlign, before
    calling inherited method.
*)
  with ADockObject do
  begin
    if DropAlign = alNone then
    begin
      if DropOnControl <> nil then
        DropAlign := DropOnControl.GetDockEdge(DropOnControl.ScreenToClient(DragPos))
      else
        DropAlign := Control.GetDockEdge(DragTargetPos);
    end;
    PositionDockRect(Control, DropOnControl, DropAlign, FDockRect);
  end;
end;

procedure TDockManager.SetReplacingControl(Control: TControl);
begin

end;

function TDockManager.AutoFreeByControl: Boolean;
begin
  Result := True;
end;

constructor TDockManager.Create(ADockSite: TWinControl);
begin
  inherited Create;
end;

procedure TDockManager.BeginUpdate;
begin

end;

procedure TDockManager.EndUpdate;
begin

end;

function TDockManager.GetDockEdge(ADockObject: TDragDockObject): boolean;
begin
  { Determine the DropAlign.
    ADockObject contains valid DragTarget, DragPos, DragTargetPos relative
    dock site, and DropOnControl.
    Return True if ADockObject.DropAlign has been determined.
  }
  Result := False; // use the DockSite.GetDockEdge
end;

procedure TDockManager.InsertControl(ADockObject: TDragDockObject);
begin
  InsertControl(ADockObject.Control,ADockObject.DropAlign,
                ADockObject.DropOnControl);
end;

procedure TDockManager.PaintSite(DC: HDC);
begin

end;

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

end;

initialization
  //DebugLn('controls.pp - initialization');
  RegisterPropertyToSkip(TControl, 'Ctl3D', 'VCL compatibility property', '');
  RegisterPropertyToSkip(TControl, 'ParentCtl3D', 'VCL compatibility property', '');
  RegisterPropertyToSkip(TControl, 'IsControl', 'VCL compatibility property', '');
  RegisterPropertyToSkip(TControl, 'DesignSize', 'VCL compatibility property', '');
  Mouse := TMouse.Create;
  DefaultDockManagerClass := TDockTree;
  DragManager := TDragManagerDefault.Create(nil);
  RegisterIntegerConsts(TypeInfo(TCursor), @IdentToCursor, @CursorToIdent);

finalization
  FreeThenNil(DragManager);
  FreeThenNil(Mouse);

end.