File: controlselection.pp

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (3472 lines) | stat: -rw-r--r-- 106,942 bytes parent folder | download
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
{/***************************************************************************
                             ControlSelection.pp
                             -------------------
                         cointains selected controls.


                 Initial Revision  : Mon June 19 23:15:32 CST 2000


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

 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code 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.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
 *                                                                         *
 ***************************************************************************
}
unit ControlSelection;

{$mode objfpc}{$H+}

interface

{ $DEFINE VerboseDesigner}

uses
  Classes, SysUtils, Math, types,
  // LCL
  LCLIntf, LCLType, LCLProc, Controls, Forms, GraphType, Graphics, Menus, ComCtrls,
  // IDEIntf
  PropEditUtils, ComponentEditors, FormEditingIntf,
  // IDE
  EnvironmentOpts, DesignerProcs;

type
  TArrSize = array of array [0 .. 3] of integer;

  TControlSelection = class;
  TGrabber = class;

  { TGrabber }

  TGrabIndex = 0..7;

  TGrabPosition = (gpTop, gpBottom, gpLeft, gpRight);
  TGrabPositions = set of TGrabPosition;

  TGrabberMoveEvent = procedure(Grabber: TGrabber;
                                const OldRect, NewRect: TRect) of object;

  // A TGrabber is one of the 8 small black rectangles at the boundaries of
  // a selection
  TGrabber = class
  private
    FOnMove: TGrabberMoveEvent;
    FPositions: TGrabPositions;
    FHeight: integer;
    FTop: integer;
    FWidth: integer;
    FLeft: integer;
    FOldLeft: integer;
    FOldTop: integer;
    FOldWidth: integer;
    FOldHeight: integer;
    FGrabIndex: TGrabIndex;
    FCursor: TCursor;
  public
    procedure SaveBounds;
    procedure Move(NewLeft, NewTop: integer);
    procedure GetRect(out ARect: TRect);
    procedure InvalidateOnForm(AForm: TCustomForm);

    property Positions: TGrabPositions read FPositions write FPositions;
    property Left:integer read FLeft write FLeft;
    property Top:integer read FTop write FTop;
    property Width:integer read FWidth write FWidth;
    property Height:integer read FHeight write FHeight;
    property OldLeft:integer read FOldLeft write FOldLeft;
    property OldTop:integer read FOldTop write FOldTop;
    property OldWidth:integer read FOldWidth write FOldWidth;
    property OldHeight:integer read FOldHeight write FOldHeight;
    property GrabIndex: TGrabIndex read FGrabIndex write FGrabIndex;
    property Cursor: TCursor read FCursor write FCursor;
    property OnMove: TGrabberMoveEvent read FOnMove write FOnMove;
  end;


  { TSelectedControl }

  TSelectedControlFlag = (
    scfParentInSelection,
    scfChildInSelection,
    scfMarkersPainted
    );
  TSelectedControlFlags = set of TSelectedControlFlag;

  { TSelectedControl }

  TSelectedControl = class
  private
    FDesignerForm: TCustomForm;
    FFlags: TSelectedControlFlags;
    FIsNonVisualComponent: boolean;
    FIsTComponent: boolean;
    FIsTControl: boolean;
    FIsTWinControl: boolean;
    FIsVisible: boolean;
    FMarkerPaintedBounds: TRect;
    FMovedResizedBounds: TRect;
    FOldFormRelativeLeftTop: TPoint;
    FOldHeight: integer;
    FOldLeft: integer;
    FOldTop: integer;
    FOldWidth: integer;
    FOwner: TControlSelection;
    FPersistent: TPersistent;
    FUsedHeight: integer;
    FUsedLeft: integer;
    FUsedTop: integer;
    FUsedWidth: integer;
    function GetIsNonVisualComponent: boolean;
    function GetLeft: integer;
    procedure SetLeft(ALeft: integer);
    function GetTop: integer;
    procedure SetTop(ATop: integer);
    function GetWidth: integer;
    procedure SetWidth(AWidth: integer);
    function GetHeight: integer;
    procedure SetHeight(AHeight: integer);
  public
    constructor Create(AnOwner: TControlSelection; APersistent: TPersistent);
    destructor Destroy; override;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: integer);
    function GetBounds: TRect;
    procedure SetFormRelativeBounds(ALeft, ATop, AWidth, AHeight: integer);
    procedure GetFormRelativeBounds(out ALeft, ATop, AWidth, AHeight: integer;
                                    StoreAsUsed: boolean = false);
    procedure SetUsedBounds(ALeft, ATop, AWidth, AHeight: integer);
    procedure SaveBounds;
    function BoundsHaveChangedSinceLastResize: boolean;
    function IsTopLvl: boolean;
    function ChildInSelection: boolean;
    function ParentInSelection: boolean;
    procedure InvalidateNonVisualPersistent;

    property Persistent: TPersistent read FPersistent;
    property Owner: TControlSelection read FOwner;
    // current bounds
    property Left: integer read GetLeft write SetLeft;
    property Top: integer read GetTop write SetTop;
    property Width: integer read GetWidth write SetWidth;
    property Height: integer read GetHeight write SetHeight;
    // bounds at start of moving/resizing
    property OldLeft:integer read FOldLeft write FOldLeft;
    property OldTop:integer read FOldTop write FOldTop;
    property OldWidth:integer read FOldWidth write FOldWidth;
    property OldHeight:integer read FOldHeight write FOldHeight;
    property OldFormRelativeLeftTop: TPoint read FOldFormRelativeLeftTop
                                            write FOldFormRelativeLeftTop;
    property MovedResizedBounds: TRect read FMovedResizedBounds write FMovedResizedBounds;
    // bounds last used for painting helpers, e.g. guidelines
    property UsedLeft: integer read FUsedLeft write FUsedLeft;// form relative (not Left)
    property UsedTop: integer read FUsedTop write FUsedTop;// form relative (not Top)
    property UsedWidth: integer read FUsedWidth write FUsedWidth;
    property UsedHeight: integer read FUsedHeight write FUsedHeight;
    property MarkerPaintedBounds: TRect read FMarkerPaintedBounds write FMarkerPaintedBounds;

    property Flags: TSelectedControlFlags read FFlags write FFlags;
    property IsVisible: boolean read FIsVisible;
    property IsTComponent: boolean read FIsTComponent;
    property IsTControl: boolean read FIsTControl;
    property IsTWinControl: boolean read FIsTWinControl;
    property IsNonVisualComponent: boolean read GetIsNonVisualComponent;
    property DesignerForm: TCustomForm read FDesignerForm;
  end;


  TComponentAlignment = (
    csaNone,
    csaSides1,
    csaCenters,
    csaSides2,
    csaCenterInWindow,
    csaSpaceEqually,
    csaSide1SpaceEqually,
    csaSide2SpaceEqually
    );
  TComponentSizing = (
    cssNone,
    cssShrinkToSmallest,
    cssGrowToLargest,
    cssFixed
    );
  TSelectionSortCompare = function(Index1, Index2: integer): integer of object;
  TOnSelectionFormChanged = procedure(Sender: TObject;
    OldForm, NewForm: TCustomForm) of object;
  TOnSelectionUpdate = procedure(Sender: TObject; ForceUpdate: Boolean) of object;

  TNearestInt = record
    OldValue: integer;
    NewValue: integer;
    Valid: boolean;
  end;

  TGuideLineCache = record
    CacheValid: boolean;
    LineValid: boolean;
    Line: TRect;
    PaintedLineValid: boolean;
    PaintedLine: TRect;
  end;

  TGuideLineType = (glLeft, glTop, glRight, glBottom);

  TRubberbandType = (
    rbtSelection,
    rbtCreating
    );


  { TControlSelection }

  TControlSelState = (
    cssLookupRootSelected,
    cssOnlyNonVisualNeedsUpdate,
    cssOnlyNonVisualSelected,
    cssOnlyVisualNeedsUpdate,
    cssOnlyVisualNeedsSelected,
    cssOnlyInvisibleNeedsUpdate,
    cssOnlyInvisibleSelected,
    cssOnlyBoundLessNeedsUpdate,
    cssOnlyBoundLessSelected,
    cssBoundsNeedsUpdate,
    cssBoundsNeedsSaving,
    cssParentLevelNeedsUpdate,
    cssGridParentNeedsUpdate,
    cssGridRectNeedsUpdate,
    cssDoNotSaveBounds,
    cssSnapping,
    cssChangedDuringLock,
    cssRubberbandActive,
    cssRubberbandPainted,
    cssCacheGuideLines,
    cssVisible,
    cssParentChildFlagsNeedUpdate,
    cssGrabbersPainted,
    cssGuideLinesPainted
    );
  TControlSelStates = set of TControlSelState;
  
const
  cssSelectionChangeFlags =
   [cssOnlyNonVisualNeedsUpdate,cssOnlyVisualNeedsUpdate,
    cssOnlyInvisibleNeedsUpdate,cssOnlyBoundLessNeedsUpdate,
    cssParentLevelNeedsUpdate,cssParentChildFlagsNeedUpdate,
    cssGridParentNeedsUpdate,cssGridRectNeedsUpdate];

type

  { TControlSelection }

  TControlSelection = class(TComponent)
  private
    FControls: TList;  // list of TSelectedControl
    FDesigner: TComponentEditorDesigner;
    FMediator: TDesignerMediator;

    // current bounds of the selection (only valid if Count>0)
    // These are the values set by the user
    // But due to snapping and lcl aligning the components can have other bounds
    FLeft: Integer;
    FTop: Integer;
    FWidth: Integer;
    FHeight: Integer;

    // These are the real bounds of the selection (only valid if Count>0)
    FRealLeft: integer;
    FRealTop: integer;
    FRealWidth: integer;
    FRealHeight: integer;

    // saved bounds of the selection (only valid if Count>0)
    FOldLeft: integer;
    FOldTop: integer;
    FOldWidth: integer;
    FOldHeight: integer;

    // caches
    FGuideLinesCache: array[TGuideLineType] of TGuideLineCache;
    FParentLevel: integer;
    FGridParent: TComponent;
    FGridRect: TRect;

    FActiveGrabber: TGrabber;
    FForm: TCustomForm;// form to draw on (not necessarily the root)
    FGrabbers: array[TGrabIndex] of TGrabber;
    FGrabberSize: integer;
    FMarkerSize: integer;
    FOnChange: TOnSelectionUpdate;
    FOnPropertiesChanged: TNotifyEvent;
    FOnSelectionFormChanged: TOnSelectionFormChanged;
    FResizeLockCount: integer;
    FRubberBandBounds: TRect;
    FRubberbandCreationColor: TColor;
    FRubberbandSelectionColor: TColor;
    FRubberbandType: TRubberbandType;
    FLookupRoot: TComponent;// component owning the selected components
    FStates: TControlSelStates;
    FUpdateLock: integer;
    FChangeStamp: int64;

    function CompareBottom(Index1, Index2: integer): integer;
    function CompareHorCenter(Index1, Index2: integer): integer;
    function CompareInts(i1, i2: integer): integer;
    function CompareLeft(Index1, Index2: integer): integer;
    function CompareRight(Index1, Index2: integer): integer;
    function CompareTop(Index1, Index2: integer): integer;
    function CompareVertCenter(Index1, Index2: integer): integer;
    function GetCacheGuideLines: boolean;
    function GetGrabberColor: TColor;
    function GetGrabbers(AGrabIndex:TGrabIndex): TGrabber;
    function GetItems(Index:integer):TSelectedControl;
    function GetMarkerColor: TColor;
    function GetRubberbandActive: boolean;
    function GetRubberbandCreationColor: TColor;
    function GetRubberbandSelectionColor: TColor;
    function GetSelectionOwner: TComponent;
    function GetSnapping: boolean;
    function GetVisible: boolean;
    procedure DoChangeProperties;
    procedure GrabberMove({%H-}Grabber: TGrabber; const OldRect, NewRect: TRect);
    procedure SetActiveGrabber(AGrabber: TGrabber);
    procedure SetCacheGuideLines(const AValue: boolean);
    procedure SetCustomForm;
    procedure SetGrabbers(AGrabIndex: TGrabIndex; const AGrabber: TGrabber);
    procedure SetGrabberSize(const NewSize: integer);
    procedure SetItems(Index:integer; ASelectedControl:TSelectedControl);
    procedure SetRubberbandActive(const AValue: boolean);
    procedure SetRubberBandBounds(ARect: TRect);
    procedure SetRubberbandType(const AValue: TRubberbandType);
    procedure SetSnapping(const AValue: boolean);
    procedure SetVisible(const AValue: Boolean);
    function GetParentFormRelativeBounds(AComponent: TComponent): TRect;
    procedure GetCompSize(var arr: TArrSize);
  protected
    procedure AdjustGrabbers;
    procedure InvalidateGrabbers;
    procedure InvalidateGuideLines;
    procedure DoApplyUserBounds;
    procedure UpdateRealBounds;
    procedure UpdateParentChildFlags;
    procedure DoDrawMarker(Index: integer; DC: TDesignerDeviceContext);
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;

    // snapping
    function CleanGridSizeX: integer;
    function CleanGridSizeY: integer;
    function PersistentAlignable(APersistent: TPersistent): boolean;
    function GetBottomGuideLine(var ALine: TRect): boolean;
    function GetLeftGuideLine(var ALine: TRect): boolean;
    function GetRightGuideLine(var ALine: TRect): boolean;
    function GetRealGrabberSize: integer;
    function GetTopGuideLine(var ALine: TRect): boolean;
    procedure FindNearestBottomGuideLine(var NearestInt: TNearestInt);
    procedure FindNearestClientLeftRight(var NearestInt: TNearestInt);
    procedure FindNearestClientTopBottom(var NearestInt: TNearestInt);
    procedure FindNearestGridX(var NearestInt: TNearestInt);
    procedure FindNearestGridY(var NearestInt: TNearestInt);
    procedure FindNearestLeftGuideLine(var NearestInt: TNearestInt);
    procedure FindNearestOldBottom(var NearestInt: TNearestInt);
    procedure FindNearestOldLeft(var NearestInt: TNearestInt);
    procedure FindNearestOldRight(var NearestInt: TNearestInt);
    procedure FindNearestOldTop(var NearestInt: TNearestInt);
    procedure FindNearestRightGuideLine(var NearestInt: TNearestInt);
    procedure FindNearestTopGuideLine(var NearestInt: TNearestInt);
    procedure ImproveNearestInt(var NearestInt: TNearestInt; Candidate: integer);
    function GetFirstGridParent: TComponent;
    function GetFirstGridRect: TRect;
  public
    arrOldSize, arrNewSize: TArrSize;

    constructor Create; reintroduce;
    destructor Destroy; override;
    procedure OnIdle(Sender: TObject; var {%H-}Done: Boolean);

    procedure BeginUpdate;
    procedure EndUpdate;
    procedure DoChange(ForceUpdate: Boolean = False);
    property UpdateLock: integer read FUpdateLock;

    // items
    property Items[Index:integer]: TSelectedControl
      read GetItems write SetItems; default;
    function Count: integer;
    procedure Sort(SortProc: TSelectionSortCompare);
    function IndexOf(APersistent: TPersistent): integer;
    function Add(APersistent: TPersistent): integer;
    procedure Remove(APersistent: TPersistent);
    procedure Delete(Index: integer);
    procedure Clear;
    function Equals(const ASelection: TPersistentSelectionList): boolean; reintroduce;
    function AssignPersistent(APersistent: TPersistent): boolean;
    procedure Assign(AControlSelection: TControlSelection); reintroduce;
    procedure AssignSelection(const ASelection: TPersistentSelectionList); // set selection
    procedure GetSelection(const ASelection: TPersistentSelectionList);
    function IsSelected(APersistent: TPersistent): Boolean;
    function IsOnlySelected(APersistent: TPersistent): Boolean;
    function ParentLevel: integer;
    function OkToCopy: boolean;
    function OnlyNonVisualPersistentsSelected: boolean;
    function OnlyVisualComponentsSelected: boolean;
    function OnlyInvisiblePersistentsSelected: boolean;
    function OnlyBoundlessComponentsSelected: boolean;
    function LookupRootSelected: boolean;

    // resizing, moving, aligning, mirroring, ...
    function IsResizing: boolean;
    procedure BeginResizing(IsStartUndo: boolean);
    procedure EndResizing(ApplyUserBounds, ActionIsProcess: boolean);
    procedure SaveBounds(OnlyIfChanged: boolean = true); // store current bounds as base for resizing
    function BoundsHaveChangedSinceLastResize: boolean;
    procedure UpdateBounds;
    procedure RestoreBounds;

    function MoveSelection(dx, dy: integer; TotalDeltas: Boolean): Boolean;
    function MoveSelectionWithSnapping(TotalDx, TotalDy: integer): Boolean;
    procedure SizeSelection(dx, dy: integer);
    procedure SetBounds(NewLeft,NewTop,NewWidth,NewHeight: integer);
    procedure AlignComponents(HorizAlignment,VertAlignment:TComponentAlignment);
    procedure MirrorHorizontal;
    procedure MirrorVertical;
    procedure SizeComponents(HorizSizing: TComponentSizing; AWidth: integer;
                             VertSizing: TComponentSizing; AHeight: integer);
    procedure ScaleComponents(Percent: integer);
    function CheckForLCLChanges(Update: boolean): boolean;

    // snapping
    function FindNearestSnapLeft(ALeft, AWidth: integer): integer;
    function FindNearestSnapLeft(ALeft: integer): integer;
    function FindNearestSnapRight(ARight: integer): integer;
    function FindNearestSnapTop(ATop, AHeight: integer): integer;
    function FindNearestSnapTop(ATop: integer): integer;
    function FindNearestSnapBottom(ABottom: integer): integer;
    function SnapGrabberMousePos(const CurMousePos: TPoint): TPoint;
    property Snapping: boolean read GetSnapping write SetSnapping;
    procedure DrawGuideLines(DC: TDesignerDeviceContext);
    property CacheGuideLines: boolean
      read GetCacheGuideLines write SetCacheGuideLines;
    procedure InvalidateGuideLinesCache;

    // grabbers and markers
    property GrabberSize: integer read FGrabberSize write SetGrabberSize;
    property GrabberColor: TColor read GetGrabberColor;
    procedure DrawGrabbers(DC: TDesignerDeviceContext);
    function GrabberAtPos(X,Y: integer):TGrabber;
    property Grabbers[AGrabIndex: TGrabIndex]:TGrabber
      read GetGrabbers write SetGrabbers;
    property MarkerSize:integer read FMarkerSize write FMarkerSize;
    property MarkerColor: TColor read GetMarkerColor;
    property OnChange: TOnSelectionUpdate read FOnChange write FOnChange;
    property OnPropertiesChanged: TNotifyEvent
      read FOnPropertiesChanged write FOnPropertiesChanged;
    procedure DrawMarker(AComponent: TComponent; DC: TDesignerDeviceContext);
    procedure DrawMarkerAt(DC: TDesignerDeviceContext;
      ALeft, ATop, AWidth, AHeight: integer);
    procedure DrawMarkers(DC: TDesignerDeviceContext);
    property ActiveGrabber: TGrabber read FActiveGrabber write SetActiveGrabber;
    procedure InvalidateMarkers;
    procedure InvalidateMarkersForComponent(AComponent: TComponent);

    // user wished bounds:
    property Left:integer read FLeft;
    property Top:integer read FTop;
    property Width:integer read FWidth;
    property Height:integer read FHeight;

    // real current bounds
    property RealLeft:integer read FRealLeft;
    property RealTop:integer read FRealTop;
    property RealWidth:integer read FRealWidth;
    property RealHeight:integer read FRealHeight;

    // bounds before resizing
    property OldLeft:integer read FOldLeft;
    property OldTop:integer read FOldTop;
    property OldWidth:integer read FOldWidth;
    property OldHeight:integer read FOldHeight;

    // rubberband
    property RubberbandBounds:TRect read FRubberbandBounds
                                    write SetRubberbandBounds;
    property RubberbandActive: boolean read GetRubberbandActive
                                       write SetRubberbandActive;
    property RubberbandType: TRubberbandType read FRubberbandType
                                             write SetRubberbandType;
    property RubberbandSelectionColor: TColor read GetRubberbandSelectionColor;
    property RubberbandCreationColor: TColor read GetRubberbandCreationColor;
    procedure DrawRubberband(DC: TDesignerDeviceContext);

    procedure SelectAll(ALookupRoot: TComponent);
    procedure SelectWithRubberBand(ALookupRoot: TComponent;
                                   AMediator: TDesignerMediator;
                                   ClearBefore, ExclusiveOr: boolean;
                                   var SelectionChanged: boolean;
                                   MaxParentComponent: TComponent);

    property Visible:boolean read GetVisible write SetVisible;

    property SelectionForm: TCustomForm read FForm;
    property Designer: TComponentEditorDesigner read FDesigner;
    property Mediator: TDesignerMediator read FMediator;
    property OnSelectionFormChanged: TOnSelectionFormChanged
      read FOnSelectionFormChanged write FOnSelectionFormChanged;
    property LookupRoot: TComponent read FLookupRoot;
    property ChangeStamp: int64 read FChangeStamp;
  end;



var TheControlSelection: TControlSelection;


implementation

const
  GRAB_CURSOR: array[TGrabIndex] of TCursor = (
    crSizeNW,   crSizeN,  crSizeNE,
    crSizeW,              crSizeE,
    crSizeSW,   crSizeS,  crSizeSE
  );

  GRAB_POSITIONS:  array [TGrabIndex] of TGrabPositions = (
    [gpLeft, gpTop   ], [gpTop   ], [gpTop,    gpRight],
    [gpLeft          ],             [          gpRight],
    [gpLeft, gpBottom], [gpBottom], [gpBottom, gpRight]
  );

function RoundToGrid(p, GridOrigin, GridStep: integer): integer;
begin
  if GridStep<=1 then
    exit(p);
  GridOrigin:=GridOrigin mod GridStep;
  Result:=p - GridOrigin + GridStep div 2;
  Result:=Result - Result mod GridStep + GridOrigin;
end;

{ TGrabber }

procedure TGrabber.SaveBounds;
begin
  FOldLeft:=FLeft;
  FOldTop:=FTop;
  FOldWidth:=FWidth;
  FOldHeight:=FHeight;
end;

procedure TGrabber.Move(NewLeft, NewTop: integer);
var
  OldRect, NewRect: TRect;
begin
  if (NewLeft=FLeft) and (NewTop=FTop) then exit;
  GetRect(OldRect);
  FLeft:=NewLeft;
  FTop:=NewTop;
  GetRect(NewRect);
  if Assigned(FOnMove) then FOnMove(Self,OldRect,NewRect);
end;

procedure TGrabber.GetRect(out ARect: TRect);
begin
  ARect.Left:=FLeft;
  ARect.Top:=FTop;
  ARect.Right:=FLeft+FWidth;
  ARect.Bottom:=FTop+FHeight;
end;

procedure TGrabber.InvalidateOnForm(AForm: TCustomForm);
var
  ARect: TRect;
begin
  GetRect(ARect);
  if AForm.HandleAllocated then
    InvalidateDesignerRect(AForm.Handle,@ARect);
end;


{ TSelectedControl }

constructor TSelectedControl.Create(AnOwner: TControlSelection;
  APersistent: TPersistent);
begin
  inherited Create;
  FOwner:=AnOwner;
  FPersistent:=APersistent;
  FIsTComponent:=FPersistent is TComponent;
  FIsTControl:=FPersistent is TControl;
  FIsTWinControl:=FPersistent is TWinControl;
  FDesignerForm:=GetDesignerForm(FPersistent);
  GetIsNonVisualComponent;
  FIsVisible:=FIsTComponent
              and (not ComponentIsInvisible(TComponent(APersistent)));
end;

function TSelectedControl.GetIsNonVisualComponent: boolean;
//recalculate because FIsNonVisualComponent doesn't work properly for Non LCL
begin
  FIsNonVisualComponent:=FIsTComponent and (not FIsTControl);
  if (Owner.Mediator<>nil) and FIsTComponent then
    FIsNonVisualComponent:=Owner.Mediator.ComponentIsIcon(TComponent(FPersistent));
  Result := FIsNonVisualComponent;
end;

destructor TSelectedControl.Destroy;
begin
  inherited Destroy;
end;

procedure TSelectedControl.SetBounds(ALeft, ATop, AWidth, AHeight: integer);
begin
  FMovedResizedBounds:=Bounds(ALeft,ATop,AWidth,AHeight);
  if Owner.Mediator<>nil then begin
    Owner.Mediator.SetBounds(TComponent(FPersistent),FMovedResizedBounds);
  end
  else if FIsTControl then begin
    TControl(FPersistent).SetBounds(ALeft, ATop, AWidth, AHeight);
  end else if FIsNonVisualComponent then begin
    if (Left<>ALeft) or (Top<>ATop) then begin
      //debugln(['TSelectedControl.SetBounds Old=',Left,',',Top,' New=',ALeft,',',ATop]);
      InvalidateNonVisualPersistent;
      Left:=ALeft;
      Top:=ATop;
      InvalidateNonVisualPersistent;
      //debugln(['TSelectedControl.SetBounds Now=',Left,',',Top,' Expected=',ALeft,',',ATop]);
    end;
  end;
end;

function TSelectedControl.GetBounds: TRect;
var
  aLeft: integer;
  aTop: integer;
  aWidth: integer;
  aHeight: integer;
begin
  if FIsTComponent then begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),Result);
    end else begin
      GetComponentBounds(TComponent(FPersistent),aLeft,aTop,aWidth,aHeight);
      Result:=Bounds(aLeft,aTop,aWidth,aHeight);
    end;
  end else
    Result:=Rect(0,0,0,0);
end;

procedure TSelectedControl.SetFormRelativeBounds(ALeft, ATop, AWidth,
  AHeight: integer);
var
  ParentOffset: TPoint;
  OldBounds: TRect;
begin
  if not FIsTComponent then exit;
  if Owner.Mediator <> nil then 
  begin
    if Owner.Mediator.ComponentIsIcon(TComponent(FPersistent)) then
    begin
      SetBounds(ALeft, ATop, AWidth, AHeight);
    end
    else begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),OldBounds);
      ParentOffset:=Owner.Mediator.GetComponentOriginOnForm(TComponent(FPersistent));
      dec(ParentOffset.X,OldBounds.Left);
      dec(ParentOffset.Y,OldBounds.Top);
      SetBounds(ALeft-ParentOffset.X,ATop-ParentOffset.Y,AWidth,AHeight);
    end;
  end 
  else 
  begin
    ParentOffset := GetParentFormRelativeParentClientOrigin(TComponent(FPersistent));
    SetBounds(ALeft - ParentOffset.X, ATop - ParentOffset.Y, AWidth, AHeight);
  end;
end;

procedure TSelectedControl.GetFormRelativeBounds(out ALeft, ATop, AWidth,
  AHeight: integer; StoreAsUsed: boolean);
var
  ALeftTop: TPoint;
  CurBounds: TRect;
begin
  if FIsTComponent then
  begin
    if Owner.Mediator<>nil then begin
      if Owner.Mediator.ComponentIsIcon(TComponent(FPersistent)) then
      begin
        GetComponentBounds(TComponent(FPersistent),ALeft, ATop, AWidth, AHeight);
      end
      else
      begin
        ALeftTop:=Owner.Mediator.GetComponentOriginOnForm(TComponent(FPersistent));
        Owner.Mediator.GetBounds(TComponent(FPersistent),CurBounds);
        ALeft:=ALeftTop.X;
        ATop:=ALeftTop.Y;
        AWidth:=CurBounds.Right-CurBounds.Left;
        AHeight:=CurBounds.Bottom-CurBounds.Top;
      end;
    end else begin
      ALeftTop := GetParentFormRelativeTopLeft(TComponent(FPersistent));
      ALeft := ALeftTop.X;
      ATop := ALeftTop.Y;
      AWidth := GetComponentWidth(TComponent(FPersistent));
      AHeight := GetComponentHeight(TComponent(FPersistent));
    end;
  end else
  begin
    ALeft := 0;
    ATop := 0;
    AWidth := 0;
    AHeight := 0;
  end;
  if StoreAsUsed then
    SetUsedBounds(ALeft, ATop, AWidth, AHeight);
end;

procedure TSelectedControl.SetUsedBounds(ALeft, ATop, AWidth, AHeight: integer);
begin
  FUsedLeft:=ALeft;
  FUsedTop:=ATop;
  FUsedWidth:=AWidth;
  FUsedHeight:=AHeight;
end;

procedure TSelectedControl.SaveBounds;
var
  r: TRect;
begin
  if not FIsTComponent then exit;
  if Owner.Mediator<>nil then begin
    if Owner.Mediator.ComponentIsIcon(TComponent(FPersistent)) then
    begin
      GetComponentBounds(TComponent(FPersistent),
                       FOldLeft,FOldTop,FOldWidth,FOldHeight);
    end else begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      FOldLeft:=r.Left;
      FOldTop:=r.Top;
      FOldWidth:=r.Right-r.Left;
      FOldHeight:=r.Bottom-r.Top;
    end;
    FOldFormRelativeLeftTop:=Owner.Mediator.GetComponentOriginOnForm(TComponent(FPersistent));
  end else begin
    GetComponentBounds(TComponent(FPersistent),
                       FOldLeft,FOldTop,FOldWidth,FOldHeight);
    FOldFormRelativeLeftTop:=GetParentFormRelativeTopLeft(TComponent(FPersistent));
  end;
end;

function TSelectedControl.BoundsHaveChangedSinceLastResize: boolean;
var
  r: TRect;
begin
  r:=GetBounds;
  Result:=not CompareRect(@r,@FMovedResizedBounds);
end;

function TSelectedControl.IsTopLvl: boolean;
begin
  Result:=(not FIsTComponent)
          or (TComponent(FPersistent).Owner=nil)
          or (FIsTControl and (TControl(FPersistent).Parent=nil));
end;

function TSelectedControl.ChildInSelection: boolean;
begin
  if Owner<>nil then begin
    Owner.UpdateParentChildFlags;
    Result:=scfChildInSelection in FFlags;
  end else begin
    Result:=false;
  end;
end;

function TSelectedControl.ParentInSelection: boolean;
begin
  if Owner<>nil then begin
    Owner.UpdateParentChildFlags;
    Result:=scfParentInSelection in FFlags;
  end else begin
    Result:=false;
  end;
end;

procedure TSelectedControl.InvalidateNonVisualPersistent;
var
  AForm: TCustomForm;
  CompRect: TRect;
begin
  AForm := DesignerForm;
  if (AForm = nil) or (not FIsTComponent) then Exit;

  CompRect.Left := LeftFromDesignInfo(TComponent(FPersistent).DesignInfo);
  CompRect.Top := TopFromDesignInfo(TComponent(FPersistent).DesignInfo);
  CompRect.Right := CompRect.Left+NonVisualCompWidth;
  CompRect.Bottom := CompRect.Top+NonVisualCompWidth;

  if AForm.HandleAllocated then
    InvalidateDesignerRect(AForm.Handle, @CompRect);
end;

function TSelectedControl.GetLeft: integer;
var
  r: TRect;
begin
  if FIsTComponent then begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      Result:=r.Left;
    end else begin
      Result:=GetComponentLeft(TComponent(FPersistent))
    end;
  end else
    Result:=0;
end;

procedure TSelectedControl.SetLeft(ALeft: integer);
var
  r: TRect;
begin
  if FIsTControl then
    TControl(FPersistent).Left := Aleft
  else
  if FIsTComponent then
  begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      r.Left:=ALeft;
      Owner.Mediator.SetBounds(TComponent(FPersistent),r)
    end else begin
      ALeft := Max(Low(SmallInt), Min(ALeft, High(SmallInt)));
      TComponent(FPersistent).DesignInfo := LeftTopToDesignInfo(ALeft, Top);
    end;
  end;
end;

function TSelectedControl.GetTop: integer;
var
  r: TRect;
begin
  if FIsTComponent then begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      Result:=r.Top;
    end else begin
      Result := GetComponentTop(TComponent(FPersistent));
    end;
  end else
    Result := 0;
end;

procedure TSelectedControl.SetTop(ATop: integer);
var
  r: TRect;
begin
  if FIsTControl then
    TControl(FPersistent).Top := ATop
  else
  if FIsTComponent then
  begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      r.Top:=ATop;
      Owner.Mediator.SetBounds(TComponent(FPersistent),r);
    end else begin
      ATop := Max(Low(SmallInt), Min(ATop, High(SmallInt)));
      TComponent(FPersistent).DesignInfo := LeftTopToDesignInfo(Left, ATop);
    end;
  end;
end;

function TSelectedControl.GetWidth: integer;
var
  r: TRect;
begin
  Result := 0;
  if FIsTComponent then begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      Result:=r.Right-r.Left;
    end else begin
      Result := GetComponentWidth(TComponent(FPersistent));
    end;
  end;
end;

procedure TSelectedControl.SetWidth(AWidth: integer);
var
  r: TRect;
begin
  if FIsTControl then
    TControl(FPersistent).Width:=AWidth
  else if FIsTComponent and (Owner.Mediator<>nil) then begin
    Owner.Mediator.GetBounds(TComponent(FPersistent),r);
    r.Right:=r.Left+AWidth;
    Owner.Mediator.SetBounds(TComponent(FPersistent),r);
  end;
end;

function TSelectedControl.GetHeight: integer;
var
  r: TRect;
begin
  if FIsTComponent then begin
    if Owner.Mediator<>nil then begin
      Owner.Mediator.GetBounds(TComponent(FPersistent),r);
      Result:=r.Bottom-r.Top;
    end else begin
      Result := GetComponentHeight(TComponent(FPersistent));
    end;
  end else
    Result:=0;
end;

procedure TSelectedControl.SetHeight(AHeight: integer);
var
  r: TRect;
begin
  if FIsTControl then
    TControl(FPersistent).Height:=AHeight
  else if FIsTComponent and (Owner.Mediator<>nil) then begin
    Owner.Mediator.GetBounds(TComponent(FPersistent),r);
    r.Bottom:=r.Top+AHeight;
    Owner.Mediator.SetBounds(TComponent(FPersistent),r);
  end;
end;


{ TControlSelection }

constructor TControlSelection.Create;
var g:TGrabIndex;
begin
  inherited Create(nil);
  FControls:=TList.Create;
  FGrabberSize:=5;
  FMarkerSize:=5;
  for g:=Low(TGrabIndex) to High(TGrabIndex) do begin
    FGrabbers[g]:=TGrabber.Create;
    FGrabbers[g].Positions:=GRAB_POSITIONS[g];
    FGrabbers[g].GrabIndex:=g;
    FGrabbers[g].Cursor:=GRAB_CURSOR[g];
    FGrabbers[g].OnMove:=@GrabberMove;
  end;
  FForm:=nil;
  FLookupRoot:=nil;
  FActiveGrabber:=nil;
  FUpdateLock:=0;
  FStates:=[cssOnlyNonVisualNeedsUpdate,cssOnlyVisualNeedsUpdate,
            cssOnlyInvisibleNeedsUpdate,cssOnlyBoundLessNeedsUpdate,
            cssParentLevelNeedsUpdate,cssCacheGuideLines];
  FRubberbandType:=rbtSelection;
  FRubberbandCreationColor:=clMaroon;
  FRubberbandSelectionColor:=clNavy;
  Application.AddOnIdleHandler(@OnIdle);
end;

destructor TControlSelection.Destroy;
var g:TGrabIndex;
begin
  Application.RemoveAllHandlersOfObject(Self);
  Clear;
  FControls.Free;
  for g:=Low(TGrabIndex) to High(TGrabIndex) do FGrabbers[g].Free;
  inherited Destroy;
end;

procedure TControlSelection.OnIdle(Sender: TObject; var Done: Boolean);
begin
  CheckForLCLChanges(true);
end;

procedure TControlSelection.BeginUpdate;
begin
  inc(FUpdateLock);
end;

procedure TControlSelection.EndUpdate;
begin
  if FUpdateLock<=0 then begin
    DebugLn('WARNING: TControlSelection.EndUpdate FUpdateLock=',IntToStr(FUpdateLock));
    exit;
  end;
  dec(FUpdateLock);
  if FUpdateLock=0 then begin
    if cssChangedDuringLock in FStates then DoChange;
    if cssBoundsNeedsUpdate in FStates then UpdateBounds;
    if cssBoundsNeedsSaving in FStates then SaveBounds;
  end;
end;

procedure TControlSelection.BeginResizing(IsStartUndo: boolean);
begin
  if FResizeLockCount=0 then BeginUpdate;
  inc(FResizeLockCount);

  SetLength(arrOldSize, Count);
  GetCompSize(arrOldSize);

  if (Designer<>nil) and (Count > 0) and (Designer.FUndoState = ucsNone) and IsStartUndo then
    Designer.FUndoState := ucsStartChange;
end;

procedure TControlSelection.EndResizing(ApplyUserBounds, ActionIsProcess: boolean);
var
  IsActionsBegin: boolean;

  function SaveAct(AIndex: integer): boolean;
  var
    CurrComp: TComponent;
  begin
    Result := false;
    if (Designer.FUndoState = ucsStartChange)
      and Items[AIndex].IsTComponent then
    begin
      CurrComp := TComponent(Items[AIndex].Persistent);
      if (SelectionForm <> CurrComp) and (CurrComp.Owner<>SelectionForm) then
        exit;
      Result :=
         ((arrOldSize[AIndex, 0] <> arrNewSize[AIndex, 0]) or
          (arrOldSize[AIndex, 1] <> arrNewSize[AIndex, 1]) or
          (arrOldSize[AIndex, 2] <> arrNewSize[AIndex, 2]) or
          (arrOldSize[AIndex, 3] <> arrNewSize[AIndex, 3]));
      if Result then
        with Designer do
        begin
          AddUndoAction(CurrComp, uopChange, not(IsActionsBegin), 'Top',
            arrOldSize[AIndex, 0], arrNewSize[AIndex, 0]);
          AddUndoAction(CurrComp, uopChange, false, 'Left',
            arrOldSize[AIndex, 1], arrNewSize[AIndex, 1]);
          AddUndoAction(CurrComp, uopChange, false, 'Height',
            arrOldSize[AIndex, 2], arrNewSize[AIndex, 2]);
          AddUndoAction(CurrComp, uopChange, false, 'Width',
            arrOldSize[AIndex, 3], arrNewSize[AIndex, 3]);
        end;
    end;
  end;

var
  i: integer;
begin
  if FResizeLockCount<=0 then begin
    DebugLn('WARNING: TControlSelection.EndResizing FResizeLockCount=',IntToStr(FResizeLockCount));
    exit;
  end;
  if FResizeLockCount=1 then
    if ApplyUserBounds then DoApplyUserBounds;

  IsActionsBegin := false;
  SetLength(arrNewSize, Count);
  GetCompSize(arrNewSize);
  for i := 0 to Count - 1 do
    IsActionsBegin := SaveAct(i) or IsActionsBegin;
  if ActionIsProcess then
  begin
    if IsActionsBegin then
      (FindRootDesigner(Items[0].Persistent) as TComponentEditorDesigner).FUndoState := ucsSaveChange
  end
  else
    (FindRootDesigner(Items[0].Persistent) as TComponentEditorDesigner).FUndoState := ucsNone;

  dec(FResizeLockCount);
  if FResizeLockCount>0 then exit;
  EndUpdate;
end;

procedure TControlSelection.SetCacheGuideLines(const AValue: boolean);
begin
  if CacheGuideLines=AValue then exit;
  if AValue then
    Include(FStates,cssCacheGuideLines)
  else
    Exclude(FStates,cssCacheGuideLines);
  InvalidateGuideLinesCache;
end;

function TControlSelection.GetSnapping: boolean;
begin
  Result:=cssSnapping in FStates;
end;

function TControlSelection.GetVisible: boolean;
begin
  Result:=cssVisible in FStates;
end;

function TControlSelection.GetRubberbandActive: boolean;
begin
  Result:=cssRubberbandActive in FStates;
end;

function TControlSelection.GetRubberbandCreationColor: TColor;
begin
  Result:=EnvironmentOptions.RubberbandCreationColor;
end;

function TControlSelection.GetRubberbandSelectionColor: TColor;
begin
  Result:=EnvironmentOptions.RubberbandSelectionColor;
end;

procedure TControlSelection.GrabberMove(Grabber: TGrabber; const OldRect,
  NewRect: TRect);
begin
  if FForm=nil then exit;
  {if Grabber.Positions=[gpTop,gpLeft] then begin
    writeln('TControlSelection.GrabberMove ',
      ' OldRect=',OldRect.Left,',',OldRect.Top,',',OldRect.Right,',',OldRect.Bottom,
      ' NewRect=',NewRect.Left,',',NewRect.Top,',',NewRect.Right,',',NewRect.Bottom,
      ' ');
  end;}
  if FForm.HandleAllocated then begin
    InvalidateDesignerRect(FForm.Handle,@OldRect);
    InvalidateDesignerRect(FForm.Handle,@NewRect);
  end;
end;

function TControlSelection.GetCacheGuideLines: boolean;
begin
  Result:=cssCacheGuideLines in FStates;
end;

function TControlSelection.GetGrabberColor: TColor;
begin
  Result:=EnvironmentOptions.GrabberColor;
end;

function TControlSelection.GetMarkerColor: TColor;
begin
  Result:=EnvironmentOptions.MarkerColor;
end;

procedure TControlSelection.SetCustomForm;
var
  OldCustomForm, NewCustomForm: TCustomForm;
begin
  if Count>0 then
    NewCustomForm:=Items[0].DesignerForm
  else
    NewCustomForm:=nil;
  if NewCustomForm=FForm then exit;
  // form changed
  InvalidateGuideLines;
  InvalidateGrabbers;
  OldCustomForm:=FForm;
  FForm:=NewCustomForm;
  if FForm is FormEditingHook.NonFormProxyDesignerForm[NonControlProxyDesignerFormId] then
    FMediator:=(FForm as INonControlDesigner).Mediator
  else
    FMediator:=nil;
  FLookupRoot:=GetSelectionOwner;
  FDesigner:=nil;
  if Count>0 then
    FDesigner:=TComponentEditorDesigner(FindRootDesigner(Items[0].Persistent));
  if Assigned(FOnSelectionFormChanged) then
    FOnSelectionFormChanged(Self,OldCustomForm,NewCustomForm);
end;

function TControlSelection.GetGrabbers(AGrabIndex:TGrabIndex): TGrabber;
begin
  Result:=FGrabbers[AGrabIndex];
end;

procedure TControlSelection.SetGrabbers(AGrabIndex:TGrabIndex; const AGrabber: TGrabber);
begin
  FGrabbers[AGrabIndex]:=AGrabber;
end;

procedure TControlSelection.SetGrabberSize(const NewSize: integer);
begin
  if NewSize=FGrabberSize then exit;
  FGrabberSize:=NewSize;
end;

procedure TControlSelection.UpdateBounds;
begin
  if FUpdateLock>0 then begin
    Include(FStates,cssBoundsNeedsUpdate);
    exit;
  end;
  UpdateRealBounds;
  FLeft:=FRealLeft;
  FTop:=FRealTop;
  FWidth:=FRealWidth;
  FHeight:=FRealHeight;
  InvalidateGuideLinesCache;
  Exclude(FStates,cssBoundsNeedsUpdate);
  DoChangeProperties;
end;

procedure TControlSelection.RestoreBounds;
var
  i: integer;
  OldLeftTop: TPoint;
begin
  BeginUpdate;
  FLeft := OldLeft;
  FTop := OldTop;
  FWidth := FOldWidth;
  FHeight := FOldHeight;
  for i := 0 to Count - 1 do
  begin
    with Items[i] do
    begin
      OldLeftTop := OldFormRelativeLeftTop;
      SetFormRelativeBounds(OldLeftTop.X, OldLeftTop.Y, OldWidth, OldHeight);
    end;
  end;
  UpdateBounds;
  EndUpdate;
end;

procedure TControlSelection.AdjustGrabbers;
var g:TGrabIndex;
  OutPix, InPix, NewGrabberLeft, NewGrabberTop, AGrabberSize: integer;
begin
  AGrabberSize := GetRealGrabberSize;
  OutPix:=AGrabberSize div 2;
  InPix:=AGrabberSize-OutPix;
  for g:=Low(TGrabIndex) to High(TGrabIndex) do begin
    if gpLeft in FGrabbers[g].Positions then
      NewGrabberLeft:=FRealLeft-OutPix
    else if gpRight in FGrabbers[g].Positions then
      NewGrabberLeft:=FRealLeft+FRealWidth-InPix
    else
      NewGrabberLeft:=FRealLeft+((FRealWidth-AGrabberSize) div 2);
    if gpTop in FGrabbers[g].Positions then
      NewGrabberTop:=FRealTop-OutPix
    else if gpBottom in FGrabbers[g].Positions then
      NewGrabberTop:=FRealTop+FRealHeight-InPix
    else
      NewGrabberTop:=FRealTop+((FRealHeight-AGrabberSize) div 2);
    FGrabbers[g].Width:=AGrabberSize;
    FGrabbers[g].Height:=AGrabberSize;
    FGrabbers[g].Move(NewGrabberLeft,NewGrabberTop);
  end;
end;

procedure TControlSelection.InvalidateGrabbers;
var g: TGrabIndex;
begin
  if cssGrabbersPainted in FStates then begin
    for g:=Low(TGrabIndex) to High(TGrabIndex) do
      FGrabbers[g].InvalidateOnForm(FForm);
    Exclude(FStates,cssGrabbersPainted);
  end;
end;

procedure TControlSelection.InvalidateGuideLines;
var
  g: TGuideLineType;
  LineRect: TRect;
begin
  if (FForm=nil) or (not FForm.HandleAllocated) then exit;
  if (cssGuideLinesPainted in FStates) then begin
    if (FForm<>nil) and CacheGuideLines then
      for g:=Low(TGuideLineType) to High(TGuideLineType) do begin
        if FGuideLinesCache[g].PaintedLineValid then
        begin
          LineRect:=FGuideLinesCache[g].PaintedLine;
          if LineRect.Top=LineRect.Bottom then inc(LineRect.Bottom);
          if LineRect.Left=LineRect.Right then inc(LineRect.Right);
          InvalidateDesignerRect(FForm.Handle,@LineRect);
        end;
      end;
    Exclude(FStates,cssGuideLinesPainted);
  end;
end;

procedure TControlSelection.DoApplyUserBounds;
var
  i: integer;
  OldLeftTop: TPoint;
  NewLeft, NewTop, NewRight, NewBottom, NewWidth, NewHeight: integer;
  Item: TSelectedControl;
begin
  BeginUpdate;
  try
    if Count=1 then begin
      // single selection
      NewLeft:=FLeft;
      NewTop:=FTop;
      NewRight:=FLeft+FWidth;
      NewBottom:=FTop+FHeight;
      {$IFDEF VerboseDesigner}
      DebugLn('[TControlSelection.DoApplyUserBounds] S Old=',
        DbgS(FOldLeft,FOldTop,FOldWidth,FOldHeight),
        ' User=',Dbgs(FLeft,FTop,FWidth,FHeight));
      {$ENDIF}
      Item:=Items[0];
      //DebugLn(['TControlSelection.DoApplyUserBounds BEFORE ',Items.Left,' ',Items[0].Top]);
      if Item.IsTComponent
      and (not ComponentBoundsDesignable(TComponent(Item.Persistent))) then
        exit;
      Item.SetFormRelativeBounds(
        Min(NewLeft,NewRight),
        Min(NewTop,NewBottom),
        Abs(FWidth),
        Abs(FHeight)
      );
      //DebugLn(['TControlSelection.DoApplyUserBounds AFTER ',Items.Left,' ',Items[0].Top]);
      InvalidateGuideLinesCache;
    end else if Count>1 then begin
      // multi selection
      {$IFDEF VerboseDesigner}
      DebugLn('[TControlSelection.DoApplyUserBounds] M Old=',
        DbgS(FOldLeft,FOldTop,FOldWidth,FOldHeight),
        ' User=',DbgS(FLeft,FTop,FWidth,FHeight));
      {$ENDIF}

      // ToDo: sort selection with parent level and size/move parents first

      if (FOldWidth<>0) and (FOldHeight<>0) then begin
        for i:=0 to Count-1 do begin
          Item:=Items[i];
          if Item.IsTComponent
          and (not ComponentBoundsDesignable(TComponent(Item.Persistent))) then
            continue;
          OldLeftTop:=Items[i].OldFormRelativeLeftTop;
          //if i=0 then debugln(['TControlSelection.DoApplyUserBounds OldLeftTop=',dbgs(OldLeftTop),' FWidth=',FWidth,' FHeight=',FHeight]);
          NewLeft:=FLeft + round((single(OldLeftTop.X-FOldLeft) * single(FWidth))/single(FOldWidth));
          NewTop:=FTop + round((single(OldLeftTop.Y-FOldTop) * single(FHeight))/single(FOldHeight));
          NewWidth:=round(single(Item.OldWidth*FWidth)/single(FOldWidth));
          NewHeight:=round(single(Item.OldHeight*FHeight)/single(FOldHeight));
          if NewWidth<0 then begin
            NewWidth:=-NewWidth;
            dec(NewLeft,NewWidth);
          end;
          if NewWidth<1 then NewWidth:=1;
          if NewHeight<0 then begin
            NewHeight:=-NewHeight;
            dec(NewTop,NewHeight);
          end;
          if NewHeight<1 then NewHeight:=1;
          Item.SetFormRelativeBounds(NewLeft,NewTop,NewWidth,NewHeight);
          {$IFDEF VerboseDesigner}
          DebugLn(['  i=',i,' ',DbgSName(Item.Persistent),
          ' Expected=',NewLeft,',',NewTop,',',NewWidth,'x',NewHeight,
          ' Actual=',Item.Left,',',Item.Top,',',Item.Width,'x',Item.Height]);
          {$ENDIF}
        end;
        InvalidateGuideLinesCache;
      end;
    end;
  finally
    UpdateBounds;
    EndUpdate;
  end;
end;

procedure TControlSelection.UpdateRealBounds;
var
  i: integer;
  NextRealLeft, NextRealTop, NextRealHeight, NextRealWidth: integer;
begin
  if FControls.Count>=1 then begin
    Items[0].GetFormRelativeBounds(FRealLeft,FRealTop,FRealWidth,FRealHeight,
                                   true);
    //DebugLn(['TControlSelection.UpdateRealBounds ',FRealLeft,',',FRealTop,',',FRealWidth,'x',FRealHeight]);
    for i:=1 to FControls.Count-1 do begin
      Items[i].GetFormRelativeBounds(
                    NextRealLeft,NextRealTop,NextRealWidth,NextRealHeight,true);
      if FRealLeft>NextRealLeft then begin
        inc(FRealWidth,FRealLeft-NextRealLeft);
        FRealLeft:=NextRealLeft;
      end;
      if FRealTop>NextRealTop then begin
        inc(FRealHeight,FRealTop-NextRealTop);
        FRealTop:=NextRealTop;
      end;
      FRealWidth:=Max(FRealLeft+FRealWidth,NextRealLeft+NextRealWidth)-FRealLeft;
      FRealHeight:=Max(FRealTop+FRealHeight,NextRealTop+NextRealHeight)-FRealTop;
    end;
    AdjustGrabbers;
    InvalidateGuideLines;
  end;
end;

procedure TControlSelection.UpdateParentChildFlags;
var
  i, j, Cnt: integer;
  Control1, Control2: TControl;
begin
  if not (cssParentChildFlagsNeedUpdate in FStates) then exit;
  Cnt:=Count;
  for i:=0 to Cnt-1 do begin
    Items[i].FFlags:=Items[i].FFlags-[scfParentInSelection,scfChildInSelection];
  end;
  for i:=0 to Cnt-1 do begin
    if not Items[i].IsTControl then continue;
    Control1:=TControl(Items[i].Persistent);
    for j:=0 to Cnt-1 do begin
      if not Items[j].IsTControl then continue;
      Control2:=TControl(Items[j].Persistent);
      if i=j then continue;
      if Control1.IsParentOf(Control2) then begin
        Include(Items[i].FFlags,scfChildInSelection);
        Include(Items[j].FFlags,scfParentInSelection);
      end;
    end;
  end;
  Exclude(FStates,cssParentChildFlagsNeedUpdate);
end;

procedure TControlSelection.DoDrawMarker(Index: integer;
  DC: TDesignerDeviceContext);
var
  CompLeft, CompTop, CompWidth, CompHeight: integer;
  DCOrigin: TPoint;
  CurItem: TSelectedControl;
begin
  CurItem:=Items[Index];
  if not CurItem.IsTComponent then exit;

  CurItem.GetFormRelativeBounds(CompLeft,CompTop,CompWidth,CompHeight);
  DCOrigin:=DC.FormOrigin;
  CompLeft:=CompLeft-DCOrigin.X;
  CompTop:=CompTop-DCOrigin.Y;

  {writeln('DoDrawMarker A ',FForm.Name
    ,' Component',AComponent.Name,',',CompLeft,',',CompLeft
    ,' DCOrigin=',DCOrigin.X,',',DCOrigin.Y
    );}

  DrawMarkerAt(DC,CompLeft,CompTop,CompWidth,CompHeight);
  CurItem.Flags:=CurItem.Flags+[scfMarkersPainted];
  CurItem.MarkerPaintedBounds:=Bounds(CompLeft,CompTop,CompWidth,CompHeight);
end;

procedure TControlSelection.Notification(AComponent: TComponent;
  Operation: TOperation);
begin
  inherited Notification(AComponent, Operation);
  if Operation=opRemove then begin
    Remove(AComponent);
  end;
end;

function TControlSelection.CleanGridSizeX: integer;
begin
  Result:=EnvironmentOptions.GridSizeX;
  if Result<1 then Result:=1;
end;

function TControlSelection.CleanGridSizeY: integer;
begin
  Result:=EnvironmentOptions.GridSizeY;
  if Result<1 then Result:=1;
end;

function TControlSelection.PersistentAlignable(
  APersistent: TPersistent): boolean;
var
  CurParentLevel: integer;
  AComponent: TComponent;
begin
  Result:=false;
  if not (APersistent is TComponent) then exit;
  AComponent:=TComponent(APersistent);
  if AComponent=nil then exit;
  if AComponent is TControl then begin
    if not ControlIsInDesignerVisible(TControl(AComponent)) then begin
      //writeln('not alignable: A not ControlIsDesignerVisible ',AComponent.Name);
      exit;
    end;
    if Count>0 then begin
      if OnlyNonVisualPersistentsSelected then begin
        //writeln('not alignable: B OnlyNonVisualPersistentsSelected ',AComponent.Name);
        exit;
      end;
    end;
    if ParentLevel>0 then begin
      CurParentLevel:=GetParentLevel(TControl(AComponent));
      if CurParentLevel<>ParentLevel then begin
        //writeln('not alignable: C CurParentLevel<>ParentLevel ',AComponent.Name,' ',CurParentLevel,'<>',ParentLevel);
        exit;
      end;
    end;
  end else begin
    if ComponentIsInvisible(AComponent) then exit;
    if Count>0 then begin
      if OnlyVisualComponentsSelected then exit;
    end;
  end;
  if IsSelected(AComponent) then exit;

  Result:=true;
end;

procedure TControlSelection.ImproveNearestInt(var NearestInt: TNearestInt;
  Candidate: integer);
begin
  if (not NearestInt.Valid)
  or (Abs(NearestInt.OldValue-NearestInt.NewValue)>Abs(NearestInt.OldValue-Candidate))
  then begin
    NearestInt.Valid:=true;
    NearestInt.NewValue:=Candidate;
  end;
end;

function TControlSelection.GetFirstGridParent: TComponent;
var
  aControl: TControl;
  i: Integer;
begin
  if cssGridParentNeedsUpdate in FStates then begin
    if LookupRootSelected or OnlyNonVisualPersistentsSelected then
      FGridParent:=LookupRoot
    else begin
      FGridParent:=nil;
      for i:=0 to Count-1 do
      begin
        if not Items[i].IsTControl then continue;
        aControl:=TControl(Items[i].Persistent);
        if aControl.Parent<>nil then
          aControl:=aControl.Parent;
        if (FGridParent=nil) or aControl.IsParentOf(TControl(FGridParent)) then
          FGridParent:=aControl;
      end;
    end;
    Exclude(FStates,cssGridParentNeedsUpdate);
  end;
  Result:=FGridParent;
end;

function TControlSelection.GetFirstGridRect: TRect;
var
  GridParent: TComponent;
  p: types.TPoint;
begin
  if cssGridRectNeedsUpdate in FStates then begin
    GridParent:=GetFirstGridParent;
    if GridParent is TWinControl then begin
      FGridRect:=TWinControl(GridParent).ClientRect;
      p:=GetParentFormRelativeClientOrigin(GridParent);
      FGridRect.Left+=p.x;
      FGridRect.Top+=p.y;
      FGridRect.Right+=p.x;
      FGridRect.Bottom+=p.y;
    end else begin
      FGridRect:=FForm.ClientRect;
    end;
    Exclude(FStates,cssGridRectNeedsUpdate);
  end;
  Result:=FGridRect;
end;

procedure TControlSelection.FindNearestClientLeftRight(var NearestInt: TNearestInt);
var MaxDist: integer;
begin
  MaxDist:=(CleanGridSizeX+1) div 2;
  if NearestInt.OldValue<MaxDist then
    ImproveNearestInt(NearestInt,0);
  if (FForm<>nil) and (Abs(NearestInt.OldValue-FForm.ClientWidth)<MaxDist) then
    ImproveNearestInt(NearestInt,FForm.ClientWidth);
end;

procedure TControlSelection.FindNearestClientTopBottom(var NearestInt: TNearestInt);
var MaxDist: integer;
begin
  MaxDist:=(CleanGridSizeY+1) div 2;
  if NearestInt.OldValue<MaxDist then
    ImproveNearestInt(NearestInt,0);
  if (FForm<>nil) and (Abs(NearestInt.OldValue-FForm.ClientHeight)<MaxDist) then
    ImproveNearestInt(NearestInt,FForm.ClientHeight);
end;

procedure TControlSelection.FindNearestOldLeft(var NearestInt: TNearestInt);
var MaxDist: integer;
begin
  MaxDist:=(CleanGridSizeX+1) div 2;
  if Abs(NearestInt.OldValue-FOldLeft)<MaxDist then
    ImproveNearestInt(NearestInt,FOldLeft);
end;

procedure TControlSelection.FindNearestOldRight(var NearestInt: TNearestInt);
var MaxDist, FOldRight: integer;
begin
  MaxDist:=(CleanGridSizeX+1) div 2;
  FOldRight:=FOldLeft+FOldWidth;
  if Abs(NearestInt.OldValue-FOldRight)<MaxDist then
    ImproveNearestInt(NearestInt,FOldRight);
end;

procedure TControlSelection.FindNearestOldTop(var NearestInt: TNearestInt);
var MaxDist: integer;
begin
  MaxDist:=(CleanGridSizeY+1) div 2;
  if Abs(NearestInt.OldValue-FOldTop)<MaxDist then
    ImproveNearestInt(NearestInt,FOldTop);
end;

procedure TControlSelection.FindNearestOldBottom(var NearestInt: TNearestInt);
var MaxDist, FOldBottom: integer;
begin
  MaxDist:=(CleanGridSizeY+1) div 2;
  FOldBottom:=FOldTop+FOldHeight;
  if Abs(NearestInt.OldValue-FOldBottom)<MaxDist then
    ImproveNearestInt(NearestInt,FOldBottom);
end;

procedure TControlSelection.FindNearestLeftGuideLine(
  var NearestInt: TNearestInt);
var
  i, CurLeft, MaxDist, CurDist: integer;
  AComponent: TComponent;
begin
  if (not EnvironmentOptions.SnapToGuideLines) or (FLookupRoot=nil) then exit;
  // search in all not selected components
  MaxDist:=(CleanGridSizeX+1) div 2;
  for i:=0 to FLookupRoot.ComponentCount-1 do begin
    AComponent:=FLookupRoot.Components[i];
    if not PersistentAlignable(AComponent) then continue;
    if IsSelected(AComponent) then continue;
    if FMediator <> nil then
      CurLeft := FMediator.GetComponentOriginOnForm(AComponent).X
    else
      CurLeft:=GetParentFormRelativeTopLeft(AComponent).X;
    CurDist:=Abs(CurLeft-NearestInt.OldValue);
    if CurDist>MaxDist then continue; // skip components far away
    ImproveNearestInt(NearestInt,CurLeft);
  end;
end;

procedure TControlSelection.FindNearestRightGuideLine(
  var NearestInt: TNearestInt);
var i, CurRight, MaxDist, CurDist: integer;
  R : TRect;
  AComponent: TComponent;
begin
  if (not EnvironmentOptions.SnapToGuideLines) or (FLookupRoot=nil) then exit;
  // search in all not selected components
  MaxDist:=(CleanGridSizeX+1) div 2;
  for i:=0 to FLookupRoot.ComponentCount-1 do begin
    AComponent:=FLookupRoot.Components[i];
    if not PersistentAlignable(AComponent) then continue;
    if IsSelected(AComponent) then continue;
    if FMediator <> nil then
    begin
      FMediator.GetBounds(AComponent,R);
      CurRight := FMediator.GetComponentOriginOnForm(AComponent).X+ R.Right;
    end
    else
      CurRight:=GetParentFormRelativeTopLeft(AComponent).X
                +GetComponentWidth(AComponent);
    CurDist:=Abs(CurRight-NearestInt.OldValue);
    if CurDist>MaxDist then continue; // skip components far away
    ImproveNearestInt(NearestInt,CurRight);
  end;
end;

procedure TControlSelection.FindNearestTopGuideLine(var NearestInt: TNearestInt);
var i, CurTop, MaxDist, CurDist: integer;
  AComponent: TComponent;
begin
  if (not EnvironmentOptions.SnapToGuideLines) or (FLookupRoot=nil) then exit;
  // search in all not selected components
  MaxDist:=(CleanGridSizeY+1) div 2;
  for i:=0 to FLookupRoot.ComponentCount-1 do begin
    AComponent:=FLookupRoot.Components[i];
    if not PersistentAlignable(AComponent) then continue;
    if IsSelected(AComponent) then continue;
    if FMediator <> nil then
      CurTop := FMediator.GetComponentOriginOnForm(AComponent).Y
    else
      CurTop:=GetParentFormRelativeTopLeft(AComponent).Y;
    CurDist:=Abs(CurTop-NearestInt.OldValue);
    if CurDist>MaxDist then continue; // skip components far away
    ImproveNearestInt(NearestInt,CurTop);
  end;
end;

procedure TControlSelection.FindNearestBottomGuideLine(
  var NearestInt: TNearestInt);
var i, CurBottom, MaxDist, CurDist: integer;
  R: TRect;
  AComponent: TComponent;
begin
  if (not EnvironmentOptions.SnapToGuideLines) or (FLookupRoot=nil) then exit;
  // search in all not selected components
  MaxDist:=(CleanGridSizeY+1) div 2;
  for i:=0 to FLookupRoot.ComponentCount-1 do begin
    AComponent:=FLookupRoot.Components[i];
    if not PersistentAlignable(AComponent) then continue;
    if IsSelected(AComponent) then continue;
    if FMediator <> nil then
    begin
      FMediator.GetBounds(AComponent,R);
      CurBottom := FMediator.GetComponentOriginOnForm(AComponent).Y+ R.Bottom;
    end
    else
     CurBottom:=GetParentFormRelativeTopLeft(AComponent).Y
                +GetComponentHeight(AComponent);
    CurDist:=Abs(CurBottom-NearestInt.OldValue);
    if CurDist>MaxDist then continue; // skip components far away
    ImproveNearestInt(NearestInt,CurBottom);
  end;
end;

function TControlSelection.FindNearestSnapLeft(ALeft, AWidth: integer): integer;
var
  NearestLeft, NearestRight: TNearestInt;
begin
  // snap left
  NearestLeft.OldValue:=ALeft;
  NearestLeft.Valid:=false;
  FindNearestGridX(NearestLeft);
  FindNearestLeftGuideLine(NearestLeft);
  FindNearestClientLeftRight(NearestLeft);
  FindNearestOldLeft(NearestLeft);
  // snap right
  NearestRight.OldValue:=ALeft+AWidth;
  NearestRight.Valid:=false;
  FindNearestRightGuideLine(NearestRight);
  FindNearestClientLeftRight(NearestRight);
  FindNearestOldRight(NearestRight);
  // combine left and right snap
  if NearestRight.Valid then
    ImproveNearestInt(NearestLeft,NearestRight.NewValue-AWidth);
  // return best snap
  if NearestLeft.Valid then
    Result:=NearestLeft.NewValue
  else
    Result:=ALeft;
end;

function TControlSelection.FindNearestSnapLeft(ALeft: integer): integer;
var
  NearestLeft: TNearestInt;
begin
  // snap left
  NearestLeft.OldValue:=ALeft;
  NearestLeft.Valid:=false;
  FindNearestGridX(NearestLeft);
  FindNearestLeftGuideLine(NearestLeft);
  FindNearestClientLeftRight(NearestLeft);
  FindNearestOldLeft(NearestLeft);
  // return best snap
  if NearestLeft.Valid then
    Result:=NearestLeft.NewValue
  else
    Result:=ALeft;
end;

function TControlSelection.FindNearestSnapRight(ARight: integer): integer;
var
  NearestRight: TNearestInt;
begin
  // snap right
  NearestRight.OldValue:=ARight;
  NearestRight.Valid:=false;
  FindNearestGridX(NearestRight);
  FindNearestRightGuideLine(NearestRight);
  FindNearestClientLeftRight(NearestRight);
  FindNearestOldRight(NearestRight);
  // return best snap
  if NearestRight.Valid then
    Result:=NearestRight.NewValue
  else
    Result:=ARight;
end;

function TControlSelection.FindNearestSnapTop(ATop, AHeight: integer): integer;
var
  NearestTop, NearestBottom: TNearestInt;
begin
  // snap top
  NearestTop.OldValue:=ATop;
  NearestTop.Valid:=false;
  FindNearestGridY(NearestTop);
  FindNearestTopGuideLine(NearestTop);
  FindNearestClientTopBottom(NearestTop);
  FindNearestOldTop(NearestTop);
  // snap bottom
  NearestBottom.OldValue:=ATop+AHeight;
  NearestBottom.Valid:=false;
  FindNearestBottomGuideLine(NearestBottom);
  FindNearestClientTopBottom(NearestBottom);
  FindNearestOldBottom(NearestBottom);
  // combine top and bottom snap
  if NearestBottom.Valid then
    ImproveNearestInt(NearestTop,NearestBottom.NewValue-AHeight);
  // return best snap
  if NearestTop.Valid then
    Result:=NearestTop.NewValue
  else
    Result:=ATop;
end;

function TControlSelection.FindNearestSnapTop(ATop: integer): integer;
var
  NearestTop: TNearestInt;
begin
  // snap top
  NearestTop.OldValue:=ATop;
  NearestTop.Valid:=false;
  FindNearestGridY(NearestTop);
  FindNearestTopGuideLine(NearestTop);
  FindNearestClientTopBottom(NearestTop);
  FindNearestOldTop(NearestTop);
  // return best snap
  if NearestTop.Valid then
    Result:=NearestTop.NewValue
  else
    Result:=ATop;
end;

function TControlSelection.FindNearestSnapBottom(ABottom: integer): integer;
var
  NearestBottom: TNearestInt;
begin
  // snap bottom
  NearestBottom.OldValue:=ABottom;
  NearestBottom.Valid:=false;
  FindNearestGridY(NearestBottom);
  FindNearestBottomGuideLine(NearestBottom);
  FindNearestClientTopBottom(NearestBottom);
  FindNearestOldBottom(NearestBottom);
  // return best snap
  if NearestBottom.Valid then
    Result:=NearestBottom.NewValue
  else
    Result:=ABottom;
end;

function TControlSelection.SnapGrabberMousePos(const CurMousePos: TPoint): TPoint;
begin
  Result := CurMousePos;
  if (not EnvironmentOptions.SnapToGrid) or (ActiveGrabber = nil) then exit;
  if gpLeft in ActiveGrabber.Positions then
    Result.X := FindNearestSnapLeft(Result.X)
  else
  if gpRight in ActiveGrabber.Positions then
    Result.X := FindNearestSnapRight(Result.X);
  if gpTop in ActiveGrabber.Positions then
    Result.Y := FindNearestSnapTop(Result.Y)
  else
  if gpBottom in ActiveGrabber.Positions then
    Result.Y := FindNearestSnapBottom(Result.Y);
end;

function TControlSelection.GetLeftGuideLine(var ALine: TRect): boolean;
var i, LineTop, LineBottom: integer;
  CRect: TRect;
  AComponent: TComponent;
begin
  if CacheGuideLines and FGuideLinesCache[glLeft].CacheValid then begin
    Result:=FGuideLinesCache[glLeft].LineValid;
    if Result then
      ALine:=FGuideLinesCache[glLeft].Line;
  end else begin
    Result:=false;
    if FForm=nil then exit;
    for i:=0 to FLookupRoot.ComponentCount-1 do begin
      AComponent:=FLookupRoot.Components[i];
      if not PersistentAlignable(AComponent) then continue;
      CRect:=GetParentFormRelativeBounds(AComponent);
      if CRect.Left=FRealLeft then begin
        ALine.Left:=FRealLeft;
        ALine.Right:=ALine.Left;
        LineTop:=Min(Min(Min(FRealTop,
                             FRealTop+FRealHeight),
                             CRect.Top),
                             CRect.Bottom);
        LineBottom:=Max(Max(Max(FRealTop,
                                FRealTop+FRealHeight),
                                CRect.Top),
                                CRect.Bottom);
        if Result then begin
          LineTop:=Min(ALine.Top,LineTop);
          LineBottom:=Max(ALine.Bottom,LineBottom);
        end else
          Result:=true;
        ALine.Top:=LineTop;
        ALine.Bottom:=LineBottom;
      end;
    end;
    if CacheGuideLines then begin
      FGuideLinesCache[glLeft].LineValid:=Result;
      FGuideLinesCache[glLeft].Line:=ALine;
      FGuideLinesCache[glLeft].CacheValid:=true;
    end;
  end;
end;

function TControlSelection.GetRightGuideLine(var ALine: TRect): boolean;
var i, LineTop, LineBottom: integer;
  CRect: TRect;
  AComponent: TComponent;
begin
  if CacheGuideLines and FGuideLinesCache[glRight].CacheValid then begin
    Result:=FGuideLinesCache[glRight].LineValid;
    if Result then
      ALine:=FGuideLinesCache[glRight].Line;
  end else begin
    Result:=false;
    if FLookupRoot=nil then exit;
    for i:=0 to FLookupRoot.ComponentCount-1 do begin
      AComponent:=FLookupRoot.Components[i];
      if not PersistentAlignable(AComponent) then continue;
      CRect:=GetParentFormRelativeBounds(AComponent);
      if (CRect.Right=FRealLeft+FRealWidth) then begin
        ALine.Left:=CRect.Right;
        ALine.Right:=ALine.Left;
        LineTop:=Min(Min(Min(FRealTop,
                             FRealTop+FRealHeight),
                             CRect.Top),
                             CRect.Bottom);
        LineBottom:=Max(Max(Max(FRealTop,
                                FRealTop+FRealHeight),
                                CRect.Top),
                                CRect.Bottom);
        if Result then begin
          LineTop:=Min(ALine.Top,LineTop);
          LineBottom:=Max(ALine.Bottom,LineBottom);
        end else
          Result:=true;
        ALine.Top:=LineTop;
        ALine.Bottom:=LineBottom;
      end;
    end;
    if CacheGuideLines then begin
      FGuideLinesCache[glRight].LineValid:=Result;
      FGuideLinesCache[glRight].Line:=ALine;
      FGuideLinesCache[glRight].CacheValid:=true;
    end;
  end;
end;

function TControlSelection.GetTopGuideLine(var ALine: TRect): boolean;
var i, LineLeft, LineRight: integer;
  CRect: TRect;
  AComponent: TComponent;
begin
  if CacheGuideLines and FGuideLinesCache[glTop].CacheValid then begin
    Result:=FGuideLinesCache[glTop].LineValid;
    if Result then
      ALine:=FGuideLinesCache[glTop].Line;
  end else begin
    Result:=false;
    if FLookupRoot=nil then exit;
    for i:=0 to FLookupRoot.ComponentCount-1 do begin
      AComponent:=FLookupRoot.Components[i];
      if not PersistentAlignable(AComponent) then continue;
      CRect:=GetParentFormRelativeBounds(AComponent);
      if CRect.Top=FRealTop then begin
        ALine.Top:=FRealTop;
        ALine.Bottom:=ALine.Top;
        LineLeft:=Min(Min(Min(FRealLeft,
                                FRealLeft+FRealWidth),
                                CRect.Left),
                                CRect.Right);
        LineRight:=Max(Max(Max(FRealLeft,
                                 FRealLeft+FRealWidth),
                                 CRect.Left),
                                 CRect.Right);
        if Result then begin
          LineLeft:=Min(ALine.Left,LineLeft);
          LineRight:=Max(ALine.Right,LineRight);
        end else
          Result:=true;
        ALine.Left:=LineLeft;
        ALine.Right:=LineRight;
      end;
    end;
    if CacheGuideLines then begin
      FGuideLinesCache[glTop].LineValid:=Result;
      FGuideLinesCache[glTop].Line:=ALine;
      FGuideLinesCache[glTop].CacheValid:=true;
    end;
  end;
end;

function TControlSelection.GetBottomGuideLine(var ALine: TRect): boolean;
var i, LineLeft, LineRight: integer;
  CRect: TRect;
  AComponent: TComponent;
begin
  if CacheGuideLines and FGuideLinesCache[glBottom].CacheValid then begin
    Result:=FGuideLinesCache[glBottom].LineValid;
    if Result then
      ALine:=FGuideLinesCache[glBottom].Line;
  end else begin
    Result:=false;
    if FLookupRoot=nil then exit;
    for i:=0 to FLookupRoot.ComponentCount-1 do begin
      AComponent:=FLookupRoot.Components[i];
      if not PersistentAlignable(AComponent) then continue;
      CRect:=GetParentFormRelativeBounds(AComponent);
      if CRect.Bottom=FRealTop+FRealHeight then begin
        ALine.Top:=CRect.Bottom;
        ALine.Bottom:=ALine.Top;
        LineLeft:=Min(Min(Min(FRealLeft,
                              FRealLeft+FRealWidth),
                              CRect.Left),
                              CRect.Right);
        LineRight:=Max(Max(Max(FRealLeft,
                               FRealLeft+FRealWidth),
                               CRect.Left),
                               CRect.Right);
        if Result then begin
          LineLeft:=Min(ALine.Left,LineLeft);
          LineRight:=Max(ALine.Right,LineRight);
        end else
          Result:=true;
        ALine.Left:=LineLeft;
        ALine.Right:=LineRight;
      end;
    end;
    if CacheGuideLines then begin
      FGuideLinesCache[glBottom].LineValid:=Result;
      FGuideLinesCache[glBottom].Line:=ALine;
      FGuideLinesCache[glBottom].CacheValid:=true;
    end;
  end;
end;

procedure TControlSelection.InvalidateGuideLinesCache;
var
  t: TGuideLineType;
begin
  InvalidateGuideLines;
  for t:=Low(TGuideLineType) to High(TGuideLineType) do
    FGuideLinesCache[t].CacheValid:=false;
end;

function TControlSelection.ParentLevel: integer;
begin
  if (cssParentLevelNeedsUpdate in FStates) then begin
    if (Count>0) and OnlyVisualComponentsSelected
    and (Items[0].IsTControl) then
      FParentLevel:=GetParentLevel(TControl(Items[0].Persistent))
    else
      FParentLevel:=0;
    Exclude(FStates,cssParentLevelNeedsUpdate);
  end;
  Result:=FParentLevel;
end;

procedure TControlSelection.FindNearestGridX(var NearestInt: TNearestInt);
var
  GridSizeX, NearestGridX: integer;
  GridRect: TRect;
begin
  if not EnvironmentOptions.SnapToGrid then exit;
  GridRect:=GetFirstGridRect;
  GridSizeX:=CleanGridSizeX;
  NearestGridX := RoundToGrid(NearestInt.OldValue,GridRect.Left,GridSizeX);
  ImproveNearestInt(NearestInt,NearestGridX);
end;

procedure TControlSelection.FindNearestGridY(var NearestInt: TNearestInt);
var
  GridSizeY, NearestGridY: integer;
  GridRect: TRect;
begin
  if not EnvironmentOptions.SnapToGrid then exit;
  GridRect:=GetFirstGridRect;
  GridSizeY:=CleanGridSizeY;
  NearestGridY := RoundToGrid(NearestInt.OldValue,GridRect.Top,GridSizeY);
  ImproveNearestInt(NearestInt,NearestGridY);
end;

procedure TControlSelection.DoChange(ForceUpdate: Boolean = False);
begin
  if (FUpdateLock > 0) then
    Include(FStates, cssChangedDuringLock)
  else
  begin
    Exclude(FStates, cssChangedDuringLock);
    {$push}{$R-}  // range check off
    Inc(FChangeStamp);
    {$pop}
    if Assigned(FOnChange) then
      FOnChange(Self, ForceUpdate);
  end;
end;

procedure TControlSelection.DoChangeProperties;
begin
  if Assigned(OnPropertiesChanged) then OnPropertiesChanged(Self);
end;

procedure TControlSelection.SetRubberbandActive(const AValue: boolean);
begin
  if RubberbandActive=AValue then exit;
  if AValue then
    Include(FStates,cssRubberbandActive)
  else
    Exclude(FStates,cssRubberbandActive);
end;

procedure TControlSelection.SetRubberbandType(const AValue: TRubberbandType);
begin
  if FRubberbandType=AValue then exit;
  FRubberbandType:=AValue;
end;

procedure TControlSelection.SetSnapping(const AValue: boolean);
begin
  if Snapping=AValue then exit;
  if AValue then
    Include(FStates,cssSnapping)
  else
    Exclude(FStates,cssSnapping);
end;

procedure TControlSelection.SetVisible(const AValue: Boolean);
begin
  if Visible=AValue then exit;
  if AValue then
    Include(FStates,cssVisible)
  else
    Exclude(FStates,cssVisible);
end;

procedure TControlSelection.GetCompSize(var arr: TArrSize);
var
  i: integer;
begin
  for i := 0 to Count - 1 do
    if Items[i].IsTComponent then
     begin
       arr[i, 0] := Items[i].Top;
       arr[i, 1] := Items[i].Left;
       arr[i, 2] := Items[i].Height;
       arr[i, 3] := Items[i].Width;
     end;
end;

function TControlSelection.GetParentFormRelativeBounds(AComponent: TComponent): TRect;
var
  R:TRect;
  P : TPoint;
begin
  if FMediator <> nil then
  begin
    FMediator.GetBounds(AComponent,R);
    P := FMediator.GetComponentOriginOnForm(AComponent);
    Result :=Bounds(P.X, P.Y, R.Right - R.Left, R.Bottom - R.Top); 
  end
  else
    Result := DesignerProcs.GetParentFormRelativeBounds(AComponent);
end;

function TControlSelection.GetRealGrabberSize: integer;
begin
  Result := FGrabberSize;
  if Assigned(FForm) and Application.Scaled then
    Result := FForm.Scale96ToScreen(FGrabberSize);
end;

function TControlSelection.GetItems(Index:integer):TSelectedControl;
begin
  Result:=TSelectedControl(FControls[Index]);
end;

procedure TControlSelection.SetItems(Index:integer; ASelectedControl:TSelectedControl);
begin
  FControls[Index]:=ASelectedControl;
end;

procedure TControlSelection.SaveBounds(OnlyIfChanged: boolean);
var
  i: integer;
  g: TGrabIndex;
begin
  if cssDoNotSaveBounds in FStates then exit;
  //debugln('TControlSelection.SaveBounds');
  if OnlyIfChanged and not BoundsHaveChangedSinceLastResize then exit;

  if FUpdateLock > 0 then
  begin
    Include(FStates, cssBoundsNeedsSaving);
    Exit;
  end;

  for i := 0 to FControls.Count - 1 do Items[i].SaveBounds;
  for g := Low(TGrabIndex) to High(TGrabIndex) do FGrabbers[g].SaveBounds;
  FOldLeft := FRealLeft;
  FOldTop := FRealTop;
  FOldWidth := FRealWidth;
  FOldHeight := FRealHeight;
  Exclude(FStates, cssBoundsNeedsSaving);
end;

function TControlSelection.BoundsHaveChangedSinceLastResize: boolean;
var
  i: Integer;
begin
  for i:=0 to FControls.Count-1 do
    if Items[i].BoundsHaveChangedSinceLastResize then
      exit(true);
  Result:=false;
end;

function TControlSelection.IsResizing: boolean;
begin
  Result:=FResizeLockCount>0;
end;

procedure TControlSelection.SetActiveGrabber(AGrabber:TGrabber);
begin
  FActiveGrabber:=AGrabber;
end;

function TControlSelection.Count:integer;
begin
  Result:=FControls.Count;
end;

function TControlSelection.IndexOf(APersistent: TPersistent): integer;
begin
  Result:=Count-1;
  while (Result>=0) and (Items[Result].Persistent<>APersistent) do dec(Result);
end;

function TControlSelection.Add(APersistent: TPersistent): integer;
var
  NewSelectedControl: TSelectedControl;
begin
  BeginUpdate;
  NewSelectedControl:=TSelectedControl.Create(Self,APersistent);
  if NewSelectedControl.DesignerForm<>FForm then Clear;
  Result:=FControls.Add(NewSelectedControl);
  FStates:=FStates+cssSelectionChangeFlags;
  if Count=1 then SetCustomForm;
  if APersistent=FLookupRoot then Include(FStates,cssLookupRootSelected);
  if APersistent is TComponent then
    TComponent(APersistent).FreeNotification(Self);
  DoChange;
  UpdateBounds;
  SaveBounds;
  EndUpdate;
end;

function TControlSelection.AssignPersistent(APersistent: TPersistent): boolean;
begin
  Result:=not IsOnlySelected(APersistent);
  if not Result then exit;
  {$IFDEF VerboseDesigner}
    DebugLn(['TControlSelection.AssignPersistent ',DbgSName(APersistent)]);
  {$ENDIF}
  BeginUpdate;
  Clear;
  Add(APersistent);
  EndUpdate;
end;

procedure TControlSelection.Remove(APersistent: TPersistent);
var i:integer;
begin
  i:=IndexOf(APersistent);
  if i>=0 then Delete(i);
end;

// remove a component from the selection
procedure TControlSelection.Delete(Index:integer);
begin
  if Index<0 then exit;
  BeginUpdate;
  if Count=1 then begin
    InvalidateGrabbers;
    InvalidateGuideLines;
  end;
  if Items[Index].Persistent=FLookupRoot then
    Exclude(FStates,cssLookupRootSelected);
  Items[Index].Free;
  FControls.Delete(Index);
  FStates:=FStates+cssSelectionChangeFlags;

  if Count=0 then
    SetCustomForm;
  UpdateBounds;
  SaveBounds;
  DoChange;
  EndUpdate;
end;

procedure TControlSelection.Clear;
var i:integer;
begin
  if FControls.Count=0 then exit;
  InvalidateGrabbers;
  InvalidateGuideLines;
  InvalidateMarkers;
  for i:=0 to FControls.Count-1 do
    Items[i].Free;
  FControls.Clear;
  FStates:=FStates+cssSelectionChangeFlags-[cssLookupRootSelected];
  FForm:=nil;
  FMediator:=nil;
  FDesigner:=nil;
  UpdateBounds;
  SaveBounds;
  DoChange;
end;

function TControlSelection.Equals(const ASelection: TPersistentSelectionList): boolean;
var
  i: Integer;
  Instance: TPersistent;
begin
  if (ASelection=nil) then begin
    Result:=Count=0;
    exit;
  end;
  Result:=Count=ASelection.Count;
  if not Result then
    exit;
  for i:=0 to ASelection.Count-1 do
  begin
    Instance := ASelection[i];
    if Items[i].Persistent<>Instance then exit(false);
  end;
end;

procedure TControlSelection.Assign(AControlSelection: TControlSelection);
var i:integer;
begin
  if (AControlSelection=Self) or (cssDoNotSaveBounds in FStates) then exit;
  Include(FStates,cssDoNotSaveBounds);
  BeginUpdate;
  Clear;
  FControls.Capacity:=AControlSelection.Count;
  for i:=0 to AControlSelection.Count-1 do
    Add(AControlSelection[i].Persistent);
  SetCustomForm;
  UpdateBounds;
  Exclude(FStates,cssDoNotSaveBounds);
  SaveBounds;
  EndUpdate;
  DoChange;
end;

procedure TControlSelection.AssignSelection(
  const ASelection: TPersistentSelectionList);
var
  i:integer;
  instance: TPersistent;
begin
  if Equals(ASelection) then exit;
  if (cssDoNotSaveBounds in FStates) then exit;
  Include(FStates,cssDoNotSaveBounds);
  BeginUpdate;
  Clear;
  FControls.Capacity:=ASelection.Count;
  for i:=0 to ASelection.Count-1 do
  begin
    Instance := ASelection[i];
    if Instance is TPersistent then Add(Instance);
  end;
  SetCustomForm;
  UpdateBounds;
  Exclude(FStates,cssDoNotSaveBounds);
  SaveBounds;
  EndUpdate;
  DoChange;
end;

procedure TControlSelection.GetSelection(
  const ASelection: TPersistentSelectionList);
var
  i: Integer;
begin
  if ASelection=nil then exit;
  if Equals(ASelection) then exit;
  ASelection.Clear;
  for i:=0 to Count-1 do
    ASelection.Add(Items[i].Persistent);
end;

function TControlSelection.IsSelected(APersistent: TPersistent): Boolean;
begin
  Result:=(IndexOf(APersistent)>=0);
end;

function TControlSelection.IsOnlySelected(APersistent: TPersistent): Boolean;
begin
  Result:=(Count=1) and (Items[0].Persistent=APersistent);
end;

function TControlSelection.MoveSelection(dx, dy: integer; TotalDeltas: Boolean): Boolean;
var
  NewLeft, NewTop: integer;
begin
  Result := False;
  if (Count = 0) or IsResizing then Exit;
  //DebugLn('[TControlSelection.MoveSelection] A  %d,%d',[dx,dy]);
  //DebugLn('[TControlSelection.MoveSelection] B  %d',[FResizeLockCount]);
  if TotalDeltas then
  begin
    NewLeft := FOldLeft + dx;
    NewTop := FOldTop + dy;
  end
  else
  begin
    NewLeft := FLeft + dx;
    NewTop := FTop + dy
  end;
  if (NewLeft <> FLeft) or (NewTop <> FTop) then
  begin
    Result := True;
    BeginResizing(false);
    FLeft := NewLeft;
    FTop := NewTop;
    EndResizing(True, False);
  end;
end;

function TControlSelection.MoveSelectionWithSnapping(TotalDx, TotalDy: integer
  ): Boolean;
var
  NewLeft, NewTop: integer;
begin
  Result := False;
  if (Count = 0) or IsResizing then Exit;
  NewLeft := FindNearestSnapLeft(FOldLeft + TotalDx, FWidth);
  NewTop := FindNearestSnapTop(FOldTop + TotalDy, FHeight);
  {$IFDEF VerboseDesigner}
  DebugLn('[TControlSelection.MoveSelectionWithSnapping] A  ',
    'TotalD='+dbgs(TotalDx)+','+dbgs(TotalDy),
    ' CurBounds='+dbgs(FLeft)+','+dbgs(FTop)+','+dbgs(FWidth)+','+dbgs(FHeight),
    ' OldBounds='+dbgs(FOldLeft)+','+dbgs(FOldTop)+','+dbgs(FOldWidth)+','+dbgs(FOldHeight)
    +' NewPos='+dbgs(NewLeft)+','+dbgs(NewTop));
  {$ENDIF}
  if (NewLeft <> FLeft) or (NewTop <> FTop) then
  begin
    Result := True;
    BeginResizing(True);
    FLeft := NewLeft;
    FTop := NewTop;
    {$IFDEF VerboseDesigner}
    DebugLn('[TControlSelection.MoveSelectionWithSnapping] B  ',
      ' Bounds='+dbgs(FLeft)+','+dbgs(FTop)+','+dbgs(FWidth)+','+dbgs(FHeight));
    {$ENDIF}
    EndResizing(True, True);
  end;
end;

procedure TControlSelection.SizeSelection(dx, dy: integer);
// size all controls depending on ActiveGrabber.
// if ActiveGrabber=nil then Left,Top
var
  GrabberPos:TGrabPositions;
begin
  if (Count=0) or (IsResizing) then exit;
  if (dx=0) and (dy=0) then exit;
  {$IFDEF VerboseDesigner}
  DebugLn('[TControlSelection.SizeSelection] A  ',DbgS(dx),',',DbgS(dy));
  {$ENDIF}
  if FActiveGrabber<>nil then
    GrabberPos:=FActiveGrabber.Positions
  else
    GrabberPos:=[gpRight,gpBottom];
  if [gpTop,gpBottom] * GrabberPos = [] then dy:=0;
  if [gpLeft,gpRight] * GrabberPos = [] then dx:=0;
  if (dx=0) and (dy=0) then exit;

  BeginResizing(true);
  if gpLeft in GrabberPos then begin
    FLeft:=FLeft+dx;
    FWidth:=FWidth-dx;
  end
  else if gpRight in GrabberPos then begin
    FWidth:=FWidth+dx;
  end;
  if gpTop in GrabberPos then begin
    FTop:=FTop+dy;
    FHeight:=FHeight-dy;
  end
  else if gpBottom in GrabberPos then begin
    FHeight:=FHeight+dy;
  end;
  EndResizing(true, true);
end;

procedure TControlSelection.SetBounds(NewLeft, NewTop,
  NewWidth, NewHeight: integer);
begin
  if (Count=0) or (IsResizing) then exit;
  BeginResizing(false);
  FLeft:=NewLeft;
  FTop:=NewTop;
  FWidth:=NewWidth;
  FHeight:=NewHeight;
  EndResizing(true, false);
end;

function TControlSelection.GrabberAtPos(X,Y:integer):TGrabber;
var
  g: TGrabIndex;
begin
  if FControls.Count > 0 then
  begin
    {$IFDEF VerboseDesigner}
    DebugLn('[TControlSelection.GrabberAtPos] ',Dbgs(x),',',Dbgs(y),'  '
    ,Dbgs(FGrabbers[4].Left),',',DbgS(FGrabbers[4].Top));
    {$ENDIF}
    for g := Low(TGrabIndex) to High(TGrabIndex) do
      if (FGrabbers[g].Left <= x) and
         (FGrabbers[g].Top <= y) and
         (FGrabbers[g].Left + FGrabbers[g].Width > x) and
         (FGrabbers[g].Top + FGrabbers[g].Height > y) then
      begin
        Result := FGrabbers[g];
        Exit;
      end;
  end;
  Result := nil;
end;

procedure TControlSelection.DrawGrabbers(DC: TDesignerDeviceContext);
var
  OldBrushColor: TColor;
  g: TGrabIndex;
  Diff: TPoint;
  RestoreBrush: boolean;

  procedure FillRect(RLeft, RTop, RRight, RBottom: integer);
  begin
    if not DC.RectVisible(RLeft, RTop, RRight, RBottom) then Exit;
    if not RestoreBrush then
    begin
      DC.BeginPainting;
      RestoreBrush := True;
      with DC.Canvas do
      begin
        OldBrushColor := Brush.Color;
        Brush.Color := GrabberColor;
      end;
    end;
    DC.Canvas.FillRect(Rect(RLeft, RTop, RRight, RBottom));
    //DC.Canvas.TextOut(RLeft,RTop,dbgs(ord(g)));
  end;

begin
  if (Count=0) or (FForm=nil) or LookupRootSelected or
     OnlyInvisiblePersistentsSelected then Exit;

  Diff := DC.FormOrigin;

  // debugln(['[DrawGrabbers] ',' DC=',Diff.X,',',Diff.Y,' Grabber1=',FGrabbers[0].Left,',',FGrabbers[0].Top]);

  RestoreBrush := False;
  for g := Low(TGrabIndex) to High(TGrabIndex) do
    FillRect(
       FGrabbers[g].Left-Diff.X
      ,FGrabbers[g].Top-Diff.Y
      ,FGrabbers[g].Left-Diff.X+FGrabbers[g].Width
      ,FGrabbers[g].Top-Diff.Y+FGrabbers[g].Height
    );
  Include(FStates, cssGrabbersPainted);

  if RestoreBrush then
  begin
    DC.Canvas.Brush.Color:=OldBrushColor;
    DC.EndPainting;
  end;
end;

procedure TControlSelection.DrawMarkerAt(DC: TDesignerDeviceContext;
  ALeft, ATop, AWidth, AHeight: integer);
var
  OldBrushColor: TColor;
  RestoreBrush: boolean;

  procedure FillRect(RLeft, RTop, RRight, RBottom: integer);
  begin
    if not DC.RectVisible(RLeft, RTop, RRight, RBottom) then exit;
    if not RestoreBrush then
    begin
      DC.BeginPainting;
      OldBrushColor:=DC.Canvas.Brush.Color;
      DC.Canvas.Brush.Color:=MarkerColor;
      RestoreBrush := True;
    end;
    DC.Canvas.FillRect(Rect(RLeft,RTop,RRight,RBottom));
  end;

begin
  RestoreBrush:=false;
  FillRect(ALeft,ATop,ALeft+MarkerSize,ATop+MarkerSize);
  FillRect(ALeft,ATop+AHeight-MarkerSize,ALeft+MarkerSize,ATop+AHeight);
  FillRect(ALeft+AWidth-MarkerSize,ATop,ALeft+AWidth,ATop+MarkerSize);
  FillRect(ALeft+AWidth-MarkerSize,ATop+AHeight-MarkerSize
               ,ALeft+AWidth,ATop+AHeight);
  if RestoreBrush then
  begin
    DC.Canvas.Brush.Color:=OldBrushColor;
    DC.EndPainting;
  end;
end;

procedure TControlSelection.DrawMarkers(DC: TDesignerDeviceContext);
var
  i: Integer;
  AComponent: TComponent;
begin
  if (Count<2) or (FForm=nil) then exit;
  for i:=0 to Count-1 do begin
    if not Items[i].IsTComponent then continue;
    AComponent:=TComponent(Items[i].Persistent);
    if (AComponent=FLookupRoot)
    or (not Items[i].IsVisible) then continue;
    DoDrawMarker(i,DC);
  end;
end;

procedure TControlSelection.InvalidateMarkers;
var
  I: integer;
begin
  for I := 0 to Count - 1 do
    If Items[I].IsTComponent then
      InvalidateMarkersForComponent(TComponent(Items[I].Persistent));
end;

procedure TControlSelection.InvalidateMarkersForComponent(AComponent: TComponent);

  procedure InvalidateMarker(x,y: integer);
  var
    R: TRect;
  begin
    R:=Rect(x,y,x+MarkerSize,y+MarkerSize);
    InvalidateRect(FForm.Handle,@R,true);
  end;
  
var
  i: Integer;
  CurItem: TSelectedControl;
  ComponentBounds: TRect;
  LeftMarker: Integer;
  TopMarker: Integer;
  RightMarker: Integer;
  BottomMarker: Integer;
begin
  if (FForm=nil) or (not FForm.HandleAllocated) then exit;
  i:=IndexOf(AComponent);
  if (i>=0) then begin
    CurItem:=Items[i];
    if scfMarkersPainted in CurItem.Flags then begin
      ComponentBounds:=CurItem.MarkerPaintedBounds;
      LeftMarker:=ComponentBounds.Left;
      TopMarker:=ComponentBounds.Top;
      RightMarker:=ComponentBounds.Right-MarkerSize;
      BottomMarker:=ComponentBounds.Bottom-MarkerSize;
      InvalidateMarker(LeftMarker,TopMarker);
      InvalidateMarker(LeftMarker,BottomMarker);
      InvalidateMarker(RightMarker,TopMarker);
      InvalidateMarker(RightMarker,BottomMarker);
      CurItem.Flags:=CurItem.Flags-[scfMarkersPainted];
    end;
  end;
end;

procedure TControlSelection.DrawMarker(AComponent: TComponent;
  DC: TDesignerDeviceContext);
var
  i: Integer;
begin
  if (Count<2)
  or (FForm=nil)
  or (AComponent=FLookupRoot) then exit;
  i:=IndexOf(AComponent);
  if i<0 then exit;

  DoDrawMarker(i,DC);
end;

procedure TControlSelection.DrawRubberband(DC: TDesignerDeviceContext);
var
  Diff: TPoint;

  procedure DrawInvertFrameRect(x1,y1,x2,y2:integer);
  var i:integer;
  var
    OldPenColor: TColor;
    RestorePen: boolean;

    procedure InvertPixel(x,y:integer);
    //var c:TColor;
    begin
      //c:=DC.Canvas.Pixels[x,y];
      //c:=c xor $ffffff;
      //DC.Canvas.Pixels[x,y]:=c;
      DC.Canvas.MoveTo(x,y);
      DC.Canvas.LineTo(x+1,y);
    end;

    procedure DrawRubberLine(StartX, StartY, EndX, EndY: integer);
    begin
      if not DC.RectVisible(StartX, StartY, EndX, EndY) then exit;
      if not RestorePen then begin
        DC.BeginPainting;
        with DC.Canvas do begin
          OldPenColor:=Pen.Color;
          if RubberbandType=rbtSelection then
            Pen.Color:=RubberbandSelectionColor
          else
            Pen.Color:=RubberbandCreationColor;
        end;
        RestorePen:=true;
      end;
      if StartX<EndX then begin
        while StartX<EndX do begin
          InvertPixel(StartX,StartY);
          inc(StartX,3);
        end;
      end else begin
        while StartY<EndY do begin
          InvertPixel(StartX,StartY);
          inc(StartY,3);
        end;
      end;
    end;

  begin
    RestorePen:=false;
    if x1>x2 then begin i:=x1; x1:=x2; x2:=i; end;
    if y1>y2 then begin i:=y1; y1:=y2; y2:=i; end;
    DrawRubberLine(x1,y1,x2,y1);
    DrawRubberLine(x1,y2,x2,y2);
    DrawRubberLine(x1,y1,x1,y2);
    DrawRubberLine(x2,y1,x2,y2);
    if RestorePen then
    begin
      DC.Canvas.Pen.Color:=OldPenColor;
      DC.EndPainting;
      Include(FStates,cssRubberbandPainted);
    end;
  end;

// DrawRubberband
begin
  Diff:=DC.FormOrigin;
  with FRubberBandBounds do
    DrawInvertFrameRect(Left-Diff.X,Top-Diff.Y,Right-Diff.X,Bottom-Diff.Y);
end;

procedure TControlSelection.SelectAll(ALookupRoot: TComponent);
var
  i: integer;
  AComponent: TComponent;
begin
  for i := 0 to ALookupRoot.ComponentCount - 1 do
  begin
    AComponent := ALookupRoot.Components[i];
    if not IsSelected(AComponent) then
      Add(AComponent);
  end;
end;

procedure TControlSelection.SelectWithRubberBand(ALookupRoot: TComponent;
  AMediator: TDesignerMediator; ClearBefore, ExclusiveOr: boolean;
  var SelectionChanged: boolean; MaxParentComponent: TComponent);
var
  i: integer;
  AComponent: TComponent;

  function ComponentInRubberBand(AComponent: TComponent): boolean;
  var
    ALeft, ATop, ARight, ABottom: integer;
    Origin: TPoint;
    AControl: TControl;
    CurBounds: TRect;
    CurParent: TComponent;
  begin
    Result:=false;
    if AMediator<>nil then begin
      // check if component is visible on form
      if not AMediator.ComponentIsVisible(AComponent) then exit;
      if MaxParentComponent<>nil then begin
        // check if component is a grand child
        CurParent:=AComponent.GetParentComponent;
        if (not EnvironmentOptions.RubberbandSelectsGrandChilds)
        and (CurParent<>MaxParentComponent) then exit;
        // check if component is a child (direct or grand)
        while (CurParent<>nil) and (CurParent<>MaxParentComponent) do
          CurParent:=CurParent.GetParentComponent;
        if CurParent=nil then exit;
      end;
      AMediator.GetBounds(AComponent,CurBounds);
      Origin:=AMediator.GetComponentOriginOnForm(AComponent);
      ALeft:=Origin.X;
      ATop:=Origin.Y;
      ARight:=ALeft+CurBounds.Right-CurBounds.Left;
      ABottom:=ATop+CurBounds.Bottom-CurBounds.Top;
    end else begin
      if ComponentIsInvisible(AComponent) then exit;
      if (AComponent is TControl) then begin
        AControl:=TControl(AComponent);
        // check if control is visible on form
        if not ControlIsInDesignerVisible(AControl) then exit;
        // check if control
        if (MaxParentComponent is TWinControl) then begin
          // select only controls, that are children of MaxParentComponent
          if (not TWinControl(MaxParentComponent).IsParentOf(AControl)) then exit;
          // check if control is a grand child
          if (not EnvironmentOptions.RubberbandSelectsGrandChilds)
          and (AControl.Parent<>MaxParentComponent) then exit;
        end;
      end;
      Origin:=GetParentFormRelativeTopLeft(AComponent);
      ALeft:=Origin.X;
      ATop:=Origin.Y;
      if AComponent is TControl then begin
        ARight:=ALeft+TControl(AComponent).Width;
        ABottom:=ATop+TControl(AComponent).Height;
      end else begin
        if Assigned(IDEComponentsMaster) then
          if not IDEComponentsMaster.DrawNonVisualComponents(ALookupRoot) then
            Exit;
        ARight:=ALeft+NonVisualCompWidth;
        ABottom:=ATop+NonVisualCompWidth;
      end;
    end;
    Result:=(ALeft<FRubberBandBounds.Right)
        and (ATop<FRubberBandBounds.Bottom)
        and (ARight>=FRubberBandBounds.Left)
        and (ABottom>=FRubberBandBounds.Top);
  end;

// SelectWithRubberBand
begin
  SelectionChanged:=false;
  if ClearBefore then begin
    if IsSelected(ALookupRoot) then begin
      Remove(ALookupRoot);
      SelectionChanged:=true;
    end;
    for i:=0 to ALookupRoot.ComponentCount-1 do begin
      AComponent:=ALookupRoot.Components[i];
      if not ComponentInRubberBand(AComponent) then begin
        if IsSelected(AComponent) then begin
          Remove(AComponent);
          SelectionChanged:=true;
        end;
      end;
    end;
  end;
  for i:=0 to ALookupRoot.ComponentCount-1 do begin
    AComponent:=ALookupRoot.Components[i];
    if ComponentInRubberBand(AComponent) then begin
      if IsSelected(AComponent) then begin
        if ExclusiveOr then begin
          Remove(AComponent);
          SelectionChanged:=true;
        end;
      end else begin
        Add(AComponent);
        SelectionChanged:=true;
      end;
    end;
  end;
end;

procedure TControlSelection.SetRubberBandBounds(ARect:TRect);
var
  i :integer;
  InvFrame: TRect;
begin
  if (FForm=nil) or (not FForm.HandleAllocated) then exit;
  with ARect do begin
    if Right<Left then begin
      i:=Left;
      Left:=Right;
      Right:=i;
    end;
    if Bottom<Top then begin
      i:=Top;
      Top:=Bottom;
      Bottom:=i;
    end;
  end;
  if (FRubberBandBounds.Left<>ARect.Left)
  or (FRubberBandBounds.Top<>ARect.Top)
  or (FRubberBandBounds.Right<>ARect.Right)
  or (FRubberBandBounds.Bottom<>ARect.Bottom)
  then begin
    if (FForm<>nil) and (cssRubberbandPainted in FStates) then begin
      InvFrame:=FRubberBandBounds;
      inc(InvFrame.Right);
      inc(InvFrame.Bottom);
      InvalidateFrame(FForm.Handle,@InvFrame,false,1);
      Exclude(FStates,cssRubberbandPainted);
    end;
    FRubberBandBounds:=ARect;
    if (FForm<>nil) and RubberbandActive then begin
      InvFrame:=FRubberBandBounds;
      inc(InvFrame.Right);
      inc(InvFrame.Bottom);
      InvalidateFrame(FForm.Handle,@InvFrame,false,1);
    end;
  end;
end;

function TControlSelection.OkToCopy: boolean;
// Prevent copying / cutting components that would lead to a crash or halt.
var
  i: Integer;
begin
  for i:=0 to FControls.Count-1 do
    if (Items[i].Persistent is TCustomTabControl)
    {$IFDEF LCLGTK2}   // Copying PageControl (TCustomPage) fails with GTK2
    // in Destroy with LCLRefCount>0 due to some messages used. Issue #r51950.
    or (Items[i].Persistent is TCustomPage)
    {$ENDIF}
    then
      Exit(False);
  Result:=True;
end;

function TControlSelection.OnlyNonVisualPersistentsSelected: boolean;
var i: integer;
begin
  if cssOnlyNonVisualNeedsUpdate in FStates then begin
    Result:=true;
    for i:=0 to FControls.Count-1 do
      if not Items[i].IsNonVisualComponent then begin
        Result:=false;
        break;
      end;
    if Result then
      Include(FStates,cssOnlyNonVisualSelected)
    else
      Exclude(FStates,cssOnlyNonVisualSelected);
    Exclude(FStates,cssOnlyNonVisualNeedsUpdate);
  end else
    Result:=cssOnlyNonVisualSelected in FStates;
end;

function TControlSelection.OnlyVisualComponentsSelected: boolean;
var i: integer;
begin
  if cssOnlyVisualNeedsUpdate in FStates then begin
    Result:=true;
    for i:=0 to FControls.Count-1 do
      if not Items[i].IsTControl then begin
        Result:=false;
        break;
      end;
    if Result then
      Include(FStates,cssOnlyVisualNeedsSelected)
    else
      Exclude(FStates,cssOnlyVisualNeedsSelected);
    Exclude(FStates,cssOnlyVisualNeedsUpdate);
  end else
    Result:=cssOnlyVisualNeedsSelected in FStates;
end;

function TControlSelection.OnlyInvisiblePersistentsSelected: boolean;
var i: integer;
begin
  if cssOnlyInvisibleNeedsUpdate in FStates then begin
    Result:=true;
    for i:=0 to FControls.Count-1 do begin
      if Items[i].IsVisible then begin
        Result:=false;
        break;
      end;
    end;
    if Result then
      Include(FStates,cssOnlyInvisibleSelected)
    else
      Exclude(FStates,cssOnlyInvisibleSelected);
    Exclude(FStates,cssOnlyInvisibleNeedsUpdate);
  end else
    Result:=cssOnlyInvisibleSelected in FStates;
end;

function TControlSelection.OnlyBoundlessComponentsSelected: boolean;
var
  i: Integer;
begin
  if cssOnlyBoundLessNeedsUpdate in FStates then begin
    Result:=true;
    for i:=0 to FControls.Count-1 do
      if Items[i].IsTComponent
      and ComponentBoundsDesignable(TComponent(Items[i].Persistent)) then begin
        Result:=false;
        break;
      end;
    if Result then
      Include(FStates,cssOnlyBoundLessSelected)
    else
      Exclude(FStates,cssOnlyBoundLessSelected);
    Exclude(FStates,cssOnlyBoundLessNeedsUpdate);
  end else
    Result:=cssOnlyBoundLessSelected in FStates;
end;

function TControlSelection.LookupRootSelected: boolean;
begin
  Result:=cssLookupRootSelected in FStates;
end;

function TControlSelection.CompareInts(i1, i2: integer): integer;
begin
  if i1<i2 then Result:=-1
  else if i1=i2 then Result:=0
  else Result:=1;
end;

function TControlSelection.CompareLeft(Index1, Index2: integer): integer;
begin
  Result:=CompareInts(Items[Index1].Left,Items[Index2].Left);
end;

function TControlSelection.CompareTop(Index1, Index2: integer): integer;
begin
  Result:=CompareInts(Items[Index1].Top,Items[Index2].Top);
end;

function TControlSelection.CompareRight(Index1, Index2: integer): integer;
begin
  Result:=CompareInts(Items[Index1].Left+Items[Index1].Width
                     ,Items[Index2].Left+Items[Index2].Width);
end;

function TControlSelection.CompareBottom(Index1, Index2: integer): integer;
begin
  Result:=CompareInts(Items[Index1].Top+Items[Index1].Height
                     ,Items[Index2].Top+Items[Index2].Height);
end;

function TControlSelection.CompareHorCenter(Index1, Index2: integer): integer;
begin
  Result:=CompareInts(Items[Index1].Left+(Items[Index1].Width div 2)
                     ,Items[Index2].Left+(Items[Index2].Width div 2));
end;

function TControlSelection.CompareVertCenter(Index1, Index2: integer): integer;
begin
  Result:=CompareInts(Items[Index1].Top+(Items[Index1].Height div 2)
                     ,Items[Index2].Top+(Items[Index2].Height div 2));
end;

procedure TControlSelection.AlignComponents(
  HorizAlignment, VertAlignment: TComponentAlignment);
var i, ALeft, ATop, ARight, ABottom, HorCenter, VertCenter,
  HorDiff, VertDiff, TotalWidth, TotalHeight, HorSpacing, VertSpacing,
  x, y: integer;
begin
  if (Count=0) or (IsResizing) then exit;
  // to space equally, you need at least two controls
  if (Count<2)
    and ((HorizAlignment=csaSpaceEqually) or (VertAlignment=csaSpaceEqually))
  then exit;
  
  if (Items[0].IsTopLvl)
    or ((HorizAlignment=csaNone) and (VertAlignment=csaNone)) then exit;

  BeginResizing(true);

  // initializing
  ALeft:=Items[0].Left;
  ATop:=Items[0].Top;
  ARight:=ALeft+Items[0].Width;
  ABottom:=ATop+Items[0].Height;
  TotalWidth:=Items[0].Width;
  TotalHeight:=Items[0].Height;
  for i:=1 to FControls.Count-1 do begin
    ALeft:=Min(ALeft,Items[i].Left);
    ATop:=Min(ATop,Items[i].Top);
    ARight:=Max(ARight,Items[i].Left+Items[i].Width);
    ABottom:=Max(ABottom,Items[i].Top+Items[i].Height);
    if Items[i].IsTopLvl then continue;
    inc(TotalWidth,Items[i].Width);
    inc(TotalHeight,Items[i].Height);
  end;

  // move components horizontally
  case HorizAlignment of
    csaSides1, csaCenters, csaSides2, csaCenterInWindow:
      begin
        HorCenter:=(ALeft+ARight) div 2;
        HorDiff:=(FForm.Width div 2)-HorCenter;
        for i:=0 to FControls.Count-1 do begin
          if Items[i].IsTopLvl then continue;
          case HorizAlignment of
           csaSides1:  Items[i].Left:=ALeft;
           csaCenters: Items[i].Left:=HorCenter-(Items[i].Width div 2);
           csaSides2:  Items[i].Left:=ARight-Items[i].Width;
           csaCenterInWindow: Items[i].Left:=Items[i].Left+HorDiff;
          end;
        end;
      end;
    csaSpaceEqually:
      begin
        HorSpacing:=(ARight-ALeft-TotalWidth) div (FControls.Count-1);
        x:=ALeft;
        Sort(@CompareHorCenter);
        for i:=0 to FControls.Count-1 do begin
          if Items[i].IsTopLvl then continue;
          Items[i].Left:=x;
          Inc(x,Items[i].Width+HorSpacing);
        end;
      end;
    csaSide1SpaceEqually:
      begin
        Sort(@CompareLeft);
        HorSpacing:=(Items[Count-1].Left-ALeft) div FControls.Count;
        x:=ALeft;
        for i:=0 to FControls.Count-1 do begin
          if Items[i].IsTopLvl then continue;
          Items[i].Left:=x;
          inc(x,HorSpacing);
        end;
      end;
    csaSide2SpaceEqually:
      begin
        Sort(@CompareRight);
        HorSpacing:=(ARight-ALeft-Items[0].Width) div FControls.Count;
        x:=ARight;
        for i:=FControls.Count-1 downto 0 do begin
          if Items[i].IsTopLvl then continue;
          Items[i].Left:=x-Items[i].Width;
          dec(x,HorSpacing);
        end;
      end;
  end;

  // move components vertically
  case VertAlignment of
    csaSides1, csaCenters, csaSides2, csaCenterInWindow:
      begin
        VertCenter:=(ATop+ABottom) div 2;
        VertDiff:=(FForm.Height div 2)-VertCenter;
        for i:=0 to FControls.Count-1 do begin
          if Items[i].IsTopLvl then continue;
          case VertAlignment of
           csaSides1:  Items[i].Top:=ATop;
           csaCenters: Items[i].Top:=VertCenter-(Items[i].Height div 2);
           csaSides2:  Items[i].Top:=ABottom-Items[i].Height;
           csaCenterInWindow: Items[i].Top:=Items[i].Top+VertDiff;
          end;
        end;
      end;
    csaSpaceEqually:
      begin
        VertSpacing:=(ABottom-ATop-TotalHeight) div (FControls.Count-1);
        y:=ATop;
        Sort(@CompareVertCenter);
        for i:=0 to FControls.Count-1 do begin
          if Items[i].IsTopLvl then continue;
          Items[i].Top:=y;
          Inc(y,Items[i].Height+VertSpacing);
        end;
      end;
    csaSide1SpaceEqually:
      begin
        Sort(@CompareTop);
        VertSpacing:=(Items[Count-1].Top-ATop) div FControls.Count;
        y:=ATop;
        for i:=0 to FControls.Count-1 do begin
          if Items[i].IsTopLvl then continue;
          Items[i].Top:=y;
          inc(y,VertSpacing);
        end;
      end;
    csaSide2SpaceEqually:
      begin
        Sort(@CompareBottom);
        VertSpacing:=(ABottom-ATop-Items[0].Height) div FControls.Count;
        y:=ABottom;
        for i:=FControls.Count-1 downto 0 do begin
          if Items[i].IsTopLvl then continue;
          Items[i].Top:=y-Items[i].Height;
          dec(y,VertSpacing);
        end;
      end;
  end;

  EndResizing(false, false);
end;

procedure TControlSelection.MirrorHorizontal;
var
  i, ALeft, ARight, Middle, NewLeft: integer;
begin
  if (FControls.Count=0) or (Items[0].IsTopLvl) then exit;
  BeginResizing(true);

  // initializing
  ALeft:=Items[0].Left;
  ARight:=ALeft+Items[0].Width;
  for i:=1 to FControls.Count-1 do begin
    ALeft:=Min(ALeft,Items[i].Left);
    ARight:=Max(ARight,Items[i].Left+Items[i].Width);
  end;
  Middle:=(ALeft+ARight) div 2;

  // move components
  for i:=0 to FControls.Count-1 do begin
    if Items[i].IsTopLvl then continue;
    NewLeft:=2*Middle-Items[i].Left-Items[i].Width;
    NewLeft:=Max(NewLeft,ALeft);
    NewLeft:=Min(NewLeft,ARight-Items[i].Width);
    Items[i].Left:=NewLeft;
  end;

  UpdateBounds;
  EndResizing(false, false);
end;

procedure TControlSelection.MirrorVertical;
var
  i, ATop, ABottom, Middle, NewTop: integer;
begin
  if (FControls.Count=0) or (Items[0].IsTopLvl) then exit;
  BeginResizing(true);

  // initializing
  ATop:=Items[0].Top;
  ABottom:=ATop+Items[0].Height;
  for i:=1 to FControls.Count-1 do begin
    ATop:=Min(ATop,Items[i].Top);
    ABottom:=Max(ABottom,Items[i].Top+Items[i].Height);
  end;
  Middle:=(ATop+ABottom) div 2;

  // move components
  for i:=0 to FControls.Count-1 do begin
    if Items[i].IsTopLvl then continue;
    NewTop:=2*Middle-Items[i].Top-Items[i].Height;
    NewTop:=Max(NewTop,ATop);
    NewTop:=Min(NewTop,ABottom-Items[i].Height);
    Items[i].Top:=NewTop;
  end;

  UpdateBounds;
  EndResizing(false, false);
end;

procedure TControlSelection.SizeComponents(
  HorizSizing: TComponentSizing; AWidth: integer;
  VertSizing: TComponentSizing; AHeight: integer);
var i: integer;
begin
  if (FControls.Count=0) or (Items[0].IsTopLvl) then exit;
  BeginResizing(true);

  // initialize
  case HorizSizing of
    cssShrinkToSmallest, cssGrowToLargest:
      AWidth:=Items[0].Width;
    cssFixed:
      if AWidth<1 then HorizSizing:=cssNone;
  end;
  case VertSizing of
    cssShrinkToSmallest, cssGrowToLargest:
      AHeight:=Items[0].Height;
    cssFixed:
      if AHeight<1 then VertSizing:=cssNone;
  end;
  for i:=1 to FControls.Count-1 do begin
    case HorizSizing of
     cssShrinkToSmallest: AWidth:=Min(AWidth,Items[i].Width);
     cssGrowToLargest:    AWidth:=Max(AWidth,Items[i].Width);
    end;
    case VertSizing of
     cssShrinkToSmallest: AHeight:=Min(AHeight,Items[i].Height);
     cssGrowToLargest:    AHeight:=Max(AHeight,Items[i].Height);
    end;
  end;

  // size components
  for i:=0 to FControls.Count-1 do begin
    if Items[i].IsTopLvl then continue;
    if (Items[i].IsTControl) then begin
      if HorizSizing=cssNone then AWidth:=Items[i].Width;
      if VertSizing=cssNone then AHeight:=Items[i].Height;
      TControl(Items[i].Persistent).SetBounds(Items[i].Left,Items[i].Top,
        Max(1,AWidth), Max(1,AHeight));
    end;
  end;

  EndResizing(false, false);
end;

procedure TControlSelection.ScaleComponents(Percent: integer);
var i: integer;
begin
  if (FControls.Count=0) then exit;
  BeginResizing(true);

  if Percent<1 then Percent:=1;
  if Percent>1000 then Percent:=1000;
  // size components
  for i:=0 to FControls.Count-1 do begin
    if Items[i].IsTControl then begin
      TControl(Items[i].Persistent).SetBounds(
          Items[i].Left,
          Items[i].Top,
          Max(1,(Items[i].Width*Percent) div 100),
          Max(1,(Items[i].Height*Percent) div 100)
        );
    end;
  end;

  EndResizing(false, false);
end;

function TControlSelection.CheckForLCLChanges(Update: boolean): boolean;

  function BoundsChanged(CurItem: TSelectedControl): boolean;
  var CurLeft, CurTop, CurWidth, CurHeight: integer;
  begin
    CurItem.GetFormRelativeBounds(CurLeft,CurTop,CurWidth,CurHeight);
    Result:=(CurLeft<>CurItem.UsedLeft)
          or (CurTop<>CurItem.UsedTop)
          or (CurWidth<>CurItem.UsedWidth)
          or (CurHeight<>CurItem.UsedHeight);
  end;

var
  i: Integer;
begin
  Result:=false;
  if FControls.Count>=1 then begin
    for i:=0 to FControls.Count-1 do begin
      if BoundsChanged(Items[i]) then begin
        Result:=true;
        break;
      end;
    end;
  end;
  if Update and Result then
  begin
    //debugln('TControlSelection.CheckForLCLChanges');
    for i:=0 to FControls.Count-1 do
      if Items[i].IsTComponent and BoundsChanged(Items[i]) then
        InvalidateMarkersForComponent(TComponent(Items[i].Persistent));
    InvalidateGuideLinesCache;
    if not IsResizing then begin
      UpdateBounds;
      DoChangeProperties;
    end;
  end;
end;

procedure TControlSelection.DrawGuideLines(DC: TDesignerDeviceContext);
var
  DCOrigin: TPoint;
  OldPenColor:TColor;
  RestorePen: boolean;

  procedure DrawLine(ARect: TRect; AColor: TColor);
  begin
    dec(ARect.Left,DCOrigin.X);
    dec(ARect.Top,DCOrigin.Y);
    dec(ARect.Right,DCOrigin.X);
    dec(ARect.Bottom,DCOrigin.Y);
    if not DC.RectVisible(ARect.Left,ARect.Top,ARect.Right,ARect.Bottom) then
      exit;
    if not RestorePen then begin
      DC.BeginPainting;
      OldPenColor:=DC.Canvas.Pen.Color;
      RestorePen:=true;
    end;
    with DC.Canvas do begin
      Pen.Color:=AColor;
      MoveTo(ARect.Left,ARect.Top);
      LineTo(ARect.Right,ARect.Bottom);
    end;
  end;

var
  LineExists: array[TGuideLineType] of boolean;
  Line: array[TGuideLineType] of TRect;
  g: TGuideLineType;
begin
  if (Count=0) or (FForm=nil) or LookupRootSelected then exit;
  for g:=Low(TGuideLineType) to high(TGuideLineType) do
    Line[g]:=Rect(0,0,0,0);
  LineExists[glLeft]:=GetLeftGuideLine(Line[glLeft]);
  LineExists[glRight]:=GetRightGuideLine(Line[glRight]);
  LineExists[glTop]:=GetTopGuideLine(Line[glTop]);
  LineExists[glBottom]:=GetBottomGuideLine(Line[glBottom]);
  if (not LineExists[glLeft]) and (not LineExists[glRight])
  and (not LineExists[glTop]) and (not LineExists[glBottom])
  then exit;

  RestorePen:=false;

  DCOrigin:=DC.FormOrigin;
  OldPenColor:=DC.Canvas.Pen.Color;
  // draw bottom guideline
  if LineExists[glBottom] then
    DrawLine(Line[glBottom],EnvironmentOptions.GuideLineColorRightBottom);
  // draw top guideline
  if LineExists[glTop] then
    DrawLine(Line[glTop],EnvironmentOptions.GuideLineColorLeftTop);
  // draw right guideline
  if LineExists[glRight] then
    DrawLine(Line[glRight],EnvironmentOptions.GuideLineColorRightBottom);
  // draw left guideline
  if LineExists[glLeft] then
    DrawLine(Line[glLeft],EnvironmentOptions.GuideLineColorLeftTop);

  for g:=Low(TGuideLineType) to High(TGuideLineType) do begin
    FGuideLinesCache[g].PaintedLineValid:=LineExists[g];
    FGuideLinesCache[g].PaintedLine:=Line[g];
  end;

  if RestorePen then
  begin
    DC.Canvas.Pen.Color:=OldPenColor;
    DC.EndPainting;
  end;
  Include(FStates,cssGuideLinesPainted);
end;

procedure TControlSelection.Sort(SortProc: TSelectionSortCompare);
var a, b: integer;
  h: Pointer;
  Changed: boolean;
begin
  Changed:=false;
  // bubble sort: slow, but the selection is rarely bigger than few dozens
  // and does not change very often
  for a:=0 to FControls.Count-1 do begin
    for b:=a+1 to FControls.Count-1 do begin
      if SortProc(a,b)>0 then begin
        h:=FControls[a];
        FControls[a]:=FControls[b];
        FControls[b]:=h;
        Changed:=true;
      end;
    end;
  end;
  if Changed then DoChange;
end;

function TControlSelection.GetSelectionOwner: TComponent;
var
  APersistent: TPersistent;
begin
  if FControls.Count > 0 then
  begin
    APersistent := GetLookupRootForComponent(Items[0].Persistent);
    if APersistent is TComponent then
      Result := TComponent(APersistent)
    else
      Result := nil;
  end
  else
    Result := nil;
end;

end.