This file is indexed.

/usr/src/castle-game-engine-6.4/ui/castleuicontrols.pas is in castle-game-engine-src 6.4+dfsg1-2.

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

The actual contents of the file can be viewed below.

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

  This file is part of "Castle Game Engine".

  "Castle Game Engine" is free software; see the file COPYING.txt,
  included in this distribution, for details about the copyright.

  "Castle Game Engine" 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.

  ----------------------------------------------------------------------------
}

{ User interface (2D) basic classes: @link(TUIControl) and @link(TUIContainer). }
unit CastleUIControls;

{$I castleconf.inc}

interface

uses SysUtils, Classes, Generics.Collections,
  CastleKeysMouse, CastleUtils, CastleClassUtils,
  CastleRectangles, CastleTimeUtils, CastleInternalPk3DConnexion,
  CastleImages, CastleVectors, CastleJoysticks, CastleApplicationProperties;

const
  { Default value for container's Dpi, as is usually set on desktops. }
  DefaultDpi = 96;
  DefaultTooltipDelay = 1.0;
  DefaultTooltipDistance = 10;

type
  { Determines the order in which TUIControl.Render is called.
    All 3D controls are always under all 2D controls.
    See TUIControl.Render, TUIControl.RenderStyle. }
  TRenderStyle = (rs2D, rs3D) deprecated 'do not use this to control front-back UI controls order, better to use controls order and TUIControl.KeepInFront';

  TUIControl = class;
  TChildrenControls = class;
  TUIContainer = class;

  TContainerEvent = procedure (Container: TUIContainer);
  TContainerObjectEvent = procedure (Container: TUIContainer) of object;
  TInputPressReleaseEvent = procedure (Container: TUIContainer; const Event: TInputPressRelease);
  TInputMotionEvent = procedure (Container: TUIContainer; const Event: TInputMotion);

  { Tracking of a touch by a single finger, used by TTouchList. }
  TTouch = object
  public
    { Index of the finger/mouse. Always simply zero on traditional desktops with
      just a single mouse device. For devices with multi-touch
      (and/or possible multiple mouse pointers) this is actually useful
      to connect touches from different frames into a single move action.
      In other words: the FinderIndex stays constant while user moves
      a finger over a touch device.

      All the touches on a TUIContainer.Touches array always have different
      FingerIndex value.

      Note that the index of TTouch structure in TUIContainer.Touches array is
      @italic(not) necessarily equal to the FingerIndex. It cannot be ---
      imagine you press 1st finger, then press 2nd finger, then let go of
      the 1st finger. The FingerIndex of the 2nd finger cannot change
      (to keep events sensibly reporting the same touch),
      so there has to be a temporary "hole" in FinderIndex numeration. }
    FingerIndex: TFingerIndex;

    { Position of the touch over a device.

      Position (0, 0) is the window's bottom-left corner.
      This is consistent with how our 2D controls (TUIControl)
      treat all positions.

      The position is expressed as a float value, to support backends
      that can report positions with sub-pixel accuracy.
      For example GTK and Android can do it, although it depends on
      underlying hardware capabilities as well.
      The top-right corner or the top-right pixel has the coordinates
      (Width, Height).
      Note that if you want to actually draw something at the window's
      edge (for example, paint the top-right pixel of the window with some
      color), then the pixel coordinates are (Width - 1, Height - 1).
      The idea is that the whole top-right pixel is an area starting
      in (Width - 1, Height - 1) and ending in (Width, Height).

      Note that we have mouse capturing (when user presses and holds
      the mouse button, all the following mouse events are reported to this
      window, even when user moves the mouse outside of the window).
      This is typical of all window libraries (GTK, LCL etc.).
      This implicates that mouse positions are sometimes tracked also
      when mouse is outside the window, which means that mouse position
      may be outside the rectangle (0, 0) - (Width, Height),
      so it may even be negative. }
    Position: TVector2;
  end;
  PTouch = ^TTouch;

  { Tracking of multi-touch, a position of each finger on the screen. }
  TTouchList = class({$ifdef CASTLE_OBJFPC}specialize{$endif} TStructList<TTouch>)
  private
    { Find an item with given FingerIndex, or -1 if not found. }
    function FindFingerIndex(const FingerIndex: TFingerIndex): Integer;
    function GetFingerIndexPosition(const FingerIndex: TFingerIndex): TVector2;
    procedure SetFingerIndexPosition(const FingerIndex: TFingerIndex;
      const Value: TVector2);
  public
    { Gets or sets a position corresponding to given FingerIndex.
      If there is no information for given FingerIndex on the list,
      the getter will return zero, and the setter will automatically create
      and add appropriate information. }
    property FingerIndexPosition[const FingerIndex: TFingerIndex]: TVector2
      read GetFingerIndexPosition write SetFingerIndexPosition;
    { Remove a touch item for given FingerIndex. }
    procedure RemoveFingerIndex(const FingerIndex: TFingerIndex);
  end;

  TUIControlList = class;

  { Possible values for TUIContainer.UIScaling. }
  TUIScaling = (
    { Do not scale UI. }
    usNone,

    { Scale to fake that the container sizes enclose
      @link(TUIContainer.UIReferenceWidth) and
      @link(TUIContainer.UIReferenceHeight).
      So one size will be equal to reference size, and the other will be equal
      or larger to reference.

      Controls that look at @link(TUIControl.UIScale) will be affected by this.
      Together with anchors (see @link(TUIControl.HasHorizontalAnchor)
      and friends), this allows to easily design a scalable UI. }
    usEncloseReferenceSize,

    { Scale to fake that the container sizes fit inside
      @link(TUIContainer.UIReferenceWidth) and
      @link(TUIContainer.UIReferenceHeight).
      So one size will be equal to reference size, and the other will be equal
      or smaller to reference.

      Controls that look at @link(TUIControl.UIScale) will be affected by this.
      Together with anchors (see @link(TUIControl.HasHorizontalAnchor)
      and friends), this allows to easily design a scalable UI. }
    usFitReferenceSize,

    { Scale to fake that the container sizes are smaller/larger
      by an explicit factor @link(TUIContainer.UIExplicitScale).
      Controls that look at @link(TUIControl.UIScale) will be affected by this.

      Like usEncloseReferenceSize or usFitReferenceSize,
      this allows to design a scalable UI.
      In this case, the scale factor has to be calculated by your code
      (by default @link(TUIContainer.UIExplicitScale) is 1.0 and the engine will
      not modify it automatically in any way),
      which allows customizing the scale to your requirements.

      For example derive the @link(TUIContainer.UIExplicitScale) from
      the @link(TUIContainer.Dpi) value to keep UI controls at constant
      @italic(physical) (real-world) size, at least on devices where
      @link(TUIContainer.Dpi) is a real value (right now: iOS). }
    usExplicitScale
  );

  { Abstract user interface container. Connects OpenGL context management
    code with Castle Game Engine controls (TUIControl, that is the basis
    for all our 2D and 3D rendering). When you use TCastleWindowCustom
    (a window) or TCastleControlCustom (Lazarus component), they provide
    you a non-abstact implementation of TUIContainer.

    Basically, this class manages a @link(Controls) list.

    We pass our inputs (mouse / key / touch events) to the controls
    on this list. Input goes to the front-most
    (that is, last on the @link(Controls) list) control under
    the event position (or mouse position, or the appropriate touch position).
    We use @link(TUIControl.CapturesEventsAtPosition) to decide this
    (by default it simply checks control's @link(TUIControl.ScreenRect)
    vs the given position).
    As long as the event is not handled,
    we search for the next control that can handle this event and
    returns @link(TUIControl.CapturesEventsAtPosition) = @true.

    We also call various methods to every control.
    These include @link(TInputListener.Update), @link(TUIControl.Render),
    @link(TInputListener.Resize). }
  TUIContainer = class abstract(TComponent)
  private
    type
      TFingerIndexCaptureMap = {$ifdef CASTLE_OBJFPC}specialize{$endif} TDictionary<TFingerIndex, TUIControl>;
    var
    FOnOpen, FOnClose: TContainerEvent;
    FOnOpenObject, FOnCloseObject: TContainerObjectEvent;
    FOnBeforeRender, FOnRender: TContainerEvent;
    FOnResize: TContainerEvent;
    FOnPress, FOnRelease: TInputPressReleaseEvent;
    FOnMotion: TInputMotionEvent;
    FOnUpdate: TContainerEvent;
    { FControls cannot be declared as TChildrenControls to avoid
      http://bugs.freepascal.org/view.php?id=22495 }
    FControls: TObject;
    {$warnings off} // knowingly using deprecated stuff
    FRenderStyle: TRenderStyle;
    {$warnings on}
    FFocus, FNewFocus: TUIControlList;
    { Capture controls, for each FingerIndex.
      The values in this map are never nil. }
    FCaptureInput: TFingerIndexCaptureMap;
    FForceCaptureInput: TUIControl;
    FTooltipDelay: Single;
    FTooltipDistance: Cardinal;
    FTooltipVisible: boolean;
    FTooltipPosition: TVector2;
    HasLastPositionForTooltip: boolean;
    LastPositionForTooltip: TVector2;
    LastPositionForTooltipTime: TTimerResult;
    Mouse3d: T3DConnexionDevice;
    Mouse3dPollTimer: Single;
    FUIScaling: TUIScaling;
    FUIReferenceWidth: Integer;
    FUIReferenceHeight: Integer;
    FUIExplicitScale: Single;
    FCalculatedUIScale: Single; //< set on all children
    FFps: TFramesPerSecond;
    FPressed: TKeysPressed;
    FMousePressed: CastleKeysMouse.TMouseButtons;
    procedure ControlsVisibleChange(Sender: TObject);
    { Called when the control C is destroyed or just removed from Controls list. }
    procedure DetachNotification(const C: TUIControl);
    function UseForceCaptureInput: boolean;
    function TryGetFingerOfControl(const C: TUIControl; out Finger: TFingerIndex): boolean;
    procedure SetUIScaling(const Value: TUIScaling);
    procedure SetUIReferenceWidth(const Value: Integer);
    procedure SetUIReferenceHeight(const Value: Integer);
    procedure SetUIExplicitScale(const Value: Single);
    procedure UpdateUIScale;
    procedure SetForceCaptureInput(const Value: TUIControl);
  protected
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;

    { These should only be get/set by a container provider,
      like TCastleWindow or TCastleControl.
      @groupBegin }
    property OnOpen: TContainerEvent read FOnOpen write FOnOpen;
    property OnOpenObject: TContainerObjectEvent read FOnOpenObject write FOnOpenObject;
    property OnBeforeRender: TContainerEvent read FOnBeforeRender write FOnBeforeRender;
    property OnRender: TContainerEvent read FOnRender write FOnRender;
    property OnResize: TContainerEvent read FOnResize write FOnResize;
    property OnClose: TContainerEvent read FOnClose write FOnClose;
    property OnCloseObject: TContainerObjectEvent read FOnCloseObject write FOnCloseObject;
    property OnPress: TInputPressReleaseEvent read FOnPress write FOnPress;
    property OnRelease: TInputPressReleaseEvent read FOnRelease write FOnRelease;
    property OnMotion: TInputMotionEvent read FOnMotion write FOnMotion;
    property OnUpdate: TContainerEvent read FOnUpdate write FOnUpdate;
    { @groupEnd }

    procedure SetInternalCursor(const Value: TMouseCursor); virtual;
    property Cursor: TMouseCursor write SetInternalCursor;
      deprecated 'do not set this, engine will override this. Set TUIControl.Cursor of your UI controls to control the Cursor.';
    property InternalCursor: TMouseCursor write SetInternalCursor;

    function GetMousePosition: TVector2; virtual;
    procedure SetMousePosition(const Value: TVector2); virtual;
    function GetTouches(const Index: Integer): TTouch; virtual;

    { Get the default UI scale of controls.
      Useful only when GLInitialized, when we know that our size is sensible.
      Most UI code should rather be placed in TUIControl, and use TUIControl.UIScale. }
    function DefaultUIScale: Single;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    { Propagate the event to all the @link(Controls) and to our own OnXxx callbacks.

      These methods are called automatically when necessary,
      so usually you don't call them. But in rare cases, it makes sense
      to "fake" some event by calling these methods.

      Most of these methods are called automatically
      by the container owner, like TCastleWindow or TCastleControl.
      Some are called by @link(EventUpdate),
      which is special in this regard, as @link(EventUpdate) is not only
      responsible for calling @link(TInputListener.Update) on all @link(Controls),
      it also calls
      @link(EventJoyAxisMove),
      @link(EventJoyButtonPress),
      @link(EventSensorRotation),
      @link(EventSensorTranslation).

      @groupBegin }
    procedure EventOpen(const OpenWindowsCount: Cardinal); virtual;
    procedure EventClose(const OpenWindowsCount: Cardinal); virtual;
    function EventPress(const Event: TInputPressRelease): boolean; virtual;
    function EventRelease(const Event: TInputPressRelease): boolean; virtual;
    procedure EventUpdate; virtual;
    procedure EventMotion(const Event: TInputMotion); virtual;
    function AllowSuspendForInput: boolean;
    procedure EventBeforeRender; virtual;
    procedure EventRender; virtual; abstract;
    procedure EventResize; virtual;
    function EventJoyAxisMove(const JoyID, Axis: Byte): boolean; virtual;
    function EventJoyButtonPress(const JoyID, Button: Byte): boolean; virtual;
    function EventSensorRotation(const X, Y, Z, Angle: Double; const SecondsPassed: Single): boolean; virtual;
    function EventSensorTranslation(const X, Y, Z, Length: Double; const SecondsPassed: Single): boolean; virtual;
    { @groupEnd }

    { Controls listening for events (user input, resize, and such) of this container.

      Usually you explicitly add / remove controls to this list
      using the @link(TChildrenControls.InsertFront Controls.InsertFront) or
      @link(TChildrenControls.InsertBack Controls.InsertBack) methods.
      Freeing any control that is on this list
      automatically removes it from this list (we use the TComponent.Notification
      mechanism).

      Controls on the list should be specified in back-to-front order.
      That is, controls at the beginning of this list
      are rendered first, and are last to catch some events, since the rest
      of controls cover them. }
    function Controls: TChildrenControls;

    { Returns the controls that should receive input events,
      from back to front. So the front-most control, that should receive events first,
      is last on this list. }
    property Focus: TUIControlList read FFocus;

    { When the tooltip should be shown (mouse hovers over a control
      with a tooltip) then the TooltipVisible is set to @true,
      and TooltipPosition indicate left-bottom (in screen space, regardless of UIScaling)
      suggested position of the tooltip.

      The tooltip is only detected when TUIControl.TooltipExists.
      See TUIControl.TooltipExists and TUIControl.TooltipStyle and
      TUIControl.TooltipRender.
      For simple purposes just set TUIControlFont.Tooltip to something
      non-empty.
      @groupBegin }
    property TooltipVisible: boolean read FTooltipVisible;
    property TooltipPosition: TVector2 read FTooltipPosition;
    { @groupEnd }

    { Redraw the contents of of this window, at the nearest suitable time.
      This method does not redraw immediately
      (it does not call @link(EventBeforeRender) and @link(EventRender) inside),
      it only makes sure that they will be called @italic(very soon).
      Calling this on a closed container (with GLInitialized = @false)
      is allowed and ignored. }
    procedure Invalidate; virtual;

    { Is the OpenGL context initialized. }
    function GLInitialized: boolean; virtual;

    { Container size, in pixels.
      This is expressed in real device pixels.
      Prefer using @link(UnscaledWidth) instead of this. @link(UnscaledWidth)
      is more natural when you use UI scaling (@link(UIScaling)),
      and it's simply equal to @name when UI scaling is not used. }
    function Width: Integer; virtual; abstract;

    { Container size, in pixels.
      This is expressed in real device pixels.
      Prefer using @link(UnscaledHeight) instead of this. @link(UnscaledHeight)
      is more natural when you use UI scaling (@link(UIScaling)),
      and it's simply equal to @name when UI scaling is not used. }
    function Height: Integer; virtual; abstract;

    { Container size, in pixels.
      This is expressed in real device pixels, using @link(Width) and @link(Height).
      Prefer using @link(UnscaledRect) instead of this. @link(UnscaledRect)
      is more natural when you use UI scaling (@link(UIScaling)),
      and it's simply equal to @name when UI scaling is not used. }
    function Rect: TRectangle; virtual;

    { Container width as seen by controls with UI scaling.
      In other words, this is the real @link(Width) with UI scaling
      reversed (divided). Suitable to adjust size of your UI controls
      to container, when UI scaling is used.

      This is equivalent to just @link(Width) when UIScaling is usNone
      (default).

      Note: the name "unscaled" may seem a little unintuitive, but it's consistent.
      We call UI sizes "scaled" when they are expressed in real device pixels,
      because they are usually calculated as "desired size * UIScaling".
      So the UI size is "unscaled" when it's expressed in your "desired size".
      We usually don't use the prefix "unscaled" (e.g. @link(TCastleButton.Width)
      is "unscaled" by we don't call it "UnscaledWidth"; every property inside
      TCastleButton is actually "unscaled"). But here, we use prefix "unscaled",
      because the @link(TUIContainer.Width) is (for historic reasons) the "real" size.

      @seealso UnscaledHeight }
    function UnscaledWidth: Cardinal;

    { Container height as seen by controls with UI scaling.
      @seealso UnscaledWidth }
    function UnscaledHeight: Cardinal;

    { Container rectangle as seen by controls with UI scaling.
      @seealso UnscaledWidth }
    function UnscaledRect: TRectangle;

    { Current mouse position.
      See @link(TTouch.Position) for a documentation how this is expressed. }
    property MousePosition: TVector2
      read GetMousePosition write SetMousePosition;

    { Dots per inch, specifying the relation of screen pixels to physical size. }
    function Dpi: Integer; virtual;

    { Currently pressed mouse buttons. When this changes, you're always
      notified by @link(OnPress) or @link(OnRelease) events.

      This value is always current, in particular it's already updated
      before we call events @link(OnPress) or @link(OnRelease). }
    property MousePressed: TMouseButtons read FMousePressed write FMousePressed;

    { Is the window focused now, which means that keys/mouse events
      are directed to this window. }
    function Focused: boolean; virtual;

    { Keys currently pressed. }
    property Pressed: TKeysPressed read FPressed;

    { Measures application speed. }
    property Fps: TFramesPerSecond read FFps;

    { Currently active touches on the screen.
      This tracks currently pressed fingers, in case of touch devices
      (mobile, like Android and iOS).
      In case of desktops, it tracks the current mouse position,
      regardless if any mouse button is currently pressed.

      Indexed from 0 to TouchesCount - 1.
      @seealso TouchesCount
      @seealso TTouch }
    property Touches[Index: Integer]: TTouch read GetTouches;

    { Count of currently active touches (mouse or fingers pressed) on the screen.
      @seealso Touches }
    function TouchesCount: Integer; virtual;

    { Capture the current container (window) contents to an image
      (or straight to an image file, like png).

      Note that only capturing from the double-buffered OpenGL
      windows (which the default for our TCastleWindow and TCastleControl)
      is reliable. Internally, these methods may need to redraw the screen
      to the back buffer, because that's the only guaranteed way to capture
      OpenGL drawing (you have to capture the back buffer, before swap).

      @groupBegin }
    procedure SaveScreen(const URL: string); overload;
    function SaveScreen: TRGBImage; overload;
    function SaveScreen(const SaveRect: TRectangle): TRGBImage; overload; virtual; abstract;
    { @groupEnd }

    { Called by controls within this container when something could
      change the container focused control (in @link(TUIContainer.Focus))
      (or it's cursor) or @link(TUIContainer.Focused) or MouseLook.
      In practice, called when TUIControl.Cursor or
      @link(TUIControl.CapturesEventsAtPosition) (and so also
      @link(TUIControl.ScreenRect)) results change.

      This recalculates the focused control and the final cursor of
      the container, looking at Container's Controls,
      testing @link(TUIControl.CapturesEventsAtPosition) with current mouse position,
      and looking at Cursor property of various controls.

      When you add / remove some control
      from the Controls list, or when you move mouse (focused changes)
      this will also be automatically called
      (since focused control or final container cursor may also change then). }
    procedure UpdateFocusAndMouseCursor;

    { Internal for implementing mouse look in cameras. }
    function IsMousePositionForMouseLook: boolean;
    { Internal for implementing mouse look in cameras. }
    procedure MakeMousePositionForMouseLook;

    { Force passing events to given control first,
      regardless if this control is under mouse cursor.
      This control also always has focus.

      An example when this is useful is when you use camera MouseLook,
      and the associated viewport does not fill the full window
      (TCastleAbstractViewport.FullSize is @false, and actual sizes are smaller
      than window, and may not include window center). In this case you want
      to make sure that motion events get passed to this control,
      and that this control has focus (to keep mouse cursor hidden). }
    property ForceCaptureInput: TUIControl
      read FForceCaptureInput write SetForceCaptureInput;

    { When the control accepts the "press" event, it automatically captures
      the following motion and release events, hijacking them from other controls,
      regardless of the mouse cursor position. This is usually desirable,
      to allow the control to handle the dragging.
      But sometimes you want to cancel the dragging, and allow other controls
      to handle the following motion and release events, in which case calling this
      method helps. }
    procedure ReleaseCapture(const C: TUIControl);
  published
    { How OnRender callback fits within various Render methods of our
      @link(Controls).

      @unorderedList(
        @item(rs2D means that OnRender is called at the end,
          after all our @link(Controls) (3D and 2D) are drawn.)

        @item(rs3D means that OnRender is called after all other
          @link(Controls) with rs3D draw style, but before any 2D
          controls.

          This is suitable if you want to draw something 3D,
          that may be later covered by 2D controls.)
      )

      @deprecated Do not use this to control the order of rendering,
      better to use proper InsertFront or InsertBack or KeepInFront.
    }
    property RenderStyle: TRenderStyle
      read FRenderStyle write FRenderStyle default rs2D;
      deprecated 'do not use this to control front-back UI controls order, better to use controls order and TUIControl.KeepInFront';

    { Delay in seconds before showing the tooltip. }
    property TooltipDelay: Single read FTooltipDelay write FTooltipDelay
      default DefaultTooltipDelay;
    property TooltipDistance: Cardinal read FTooltipDistance write FTooltipDistance
      default DefaultTooltipDistance;

    { Enable automatic scaling of the UI.
      This is great when the container size may vary widly (for example,
      on mobile devices, although it becomes more and more sensible for desktops
      too). See @link(TUIScaling) values for precise description how it works. }
    property UIScaling: TUIScaling
      read FUIScaling write SetUIScaling default usNone;

    { Reference width and height to which we fit the container size
      (as seen by TUIControl implementations) when UIScaling is
      usEncloseReferenceSize or usFitReferenceSize.
      See @link(usEncloseReferenceSize) and @link(usFitReferenceSize)
      for precise description how this works.
      Set both these properties, or set only one (and leave the other as zero).
      @groupBegin }
    property UIReferenceWidth: Integer
      read FUIReferenceWidth write SetUIReferenceWidth default 0;
    property UIReferenceHeight: Integer
      read FUIReferenceHeight write SetUIReferenceHeight default 0;
    { @groupEnd }

    { Scale of the container size (as seen by TUIControl implementations)
      when UIScaling is usExplicitScale.
      See @link(usExplicitScale) for precise description how this works. }
    property UIExplicitScale: Single
      read FUIExplicitScale write SetUIExplicitScale default 1.0;
  end;

  { Base class for things that listen to user input. }
  TInputListener = class(TComponent)
  private
    FOnVisibleChange: TNotifyEvent;
    FContainer: TUIContainer;
    FCursor: TMouseCursor;
    FOnCursorChange: TNotifyEvent;
    FExclusiveEvents: boolean;
    procedure SetCursor(const Value: TMouseCursor);
  protected
    { Container sizes.
      @groupBegin }
    function ContainerWidth: Cardinal;
    function ContainerHeight: Cardinal;
    function ContainerRect: TRectangle;
    function ContainerSizeKnown: boolean;
    { @groupEnd }

    procedure SetContainer(const Value: TUIContainer); virtual;
    { Called when @link(Cursor) changed.
      In TUIControl class, just calls OnCursorChange. }
    procedure DoCursorChange; virtual;
  public
    constructor Create(AOwner: TComponent); override;

    (*Handle press or release of a key, mouse button or mouse wheel.
      Return @true if the event was somehow handled.

      In this class this always returns @false, when implementing
      in descendants you should override it like

      @longCode(#
        Result := inherited;
        if Result then Exit;
        { ... And do the job here.
          In other words, the handling of events in inherited
          class should have a priority. }
      #)

      Note that releasing of mouse wheel is not implemented for now,
      neither by CastleWindow or Lazarus CastleControl.
      @groupBegin *)
    function Press(const Event: TInputPressRelease): boolean; virtual;
    function Release(const Event: TInputPressRelease): boolean; virtual;
    { @groupEnd }

    { Motion of mouse or touch. }
    function Motion(const Event: TInputMotion): boolean; virtual;

    { Rotation detected by sensor.
      Used for example by 3Dconnexion devices or touch controls.

      @param X   X axis (tilt forward/backwards)
      @param Y   Y axis (rotate)
      @param Z   Z axis (tilt sidewards)
      @param Angle   Angle of rotation
      @param(SecondsPassed The time passed since last SensorRotation call.
        This is necessary because some sensors, e.g. 3Dconnexion,
        may *not* reported as often as normal @link(Update) calls.) }
    function SensorRotation(const X, Y, Z, Angle: Double; const SecondsPassed: Single): boolean; virtual;

    { Translation detected by sensor.
      Used for example by 3Dconnexion devices or touch controls.

      @param X   X axis (move left/right)
      @param Y   Y axis (move up/down)
      @param Z   Z axis (move forward/backwards)
      @param Length   Length of the vector consisting of the above
      @param(SecondsPassed The time passed since last SensorRotation call.
        This is necessary because some sensors, e.g. 3Dconnexion,
        may *not* reported as often as normal @link(Update) calls.) }
    function SensorTranslation(const X, Y, Z, Length: Double; const SecondsPassed: Single): boolean; virtual;

    { Axis movement detected by joystick

      @param JoyID ID of joystick with pressed button
      @param Axis Number of moved axis }
    function JoyAxisMove(const JoyID, Axis: Byte): boolean; virtual;

    { Joystick button pressed.

      @param JoyID ID of joystick with pressed button
      @param Button Number of pressed button }
    function JoyButtonPress(const JoyID, Button: Byte): boolean; virtual;

    { Control may do here anything that must be continously repeated.
      E.g. camera handles here falling down due to gravity,
      rotating model in Examine mode, and many more.

      @param(SecondsPassed Should be calculated like TFramesPerSecond.SecondsPassed,
        and usually it's in fact just taken from TCastleWindowCustom.Fps.SecondsPassed.)

      This method may be used, among many other things, to continously
      react to the fact that user pressed some key (or mouse button).
      For example, if holding some key should move some 3D object,
      you should do something like:

      @longCode(#
        if HandleInput then
        begin
          if Container.Pressed[K_Right] then
            Transform.Position := Transform.Position + Vector3(SecondsPassed * 10, 0, 0);
          HandleInput := not ExclusiveEvents;
        end;
      #)

      Instead of directly using a key code, consider also
      using TInputShortcut that makes the input key nicely configurable.
      See engine tutorial about handling inputs.

      Multiplying movement by SecondsPassed makes your
      operation frame-rate independent. Object will move by 10
      units in a second, regardless of how many FPS your game has.

      The code related to HandleInput is important if you write
      a generally-useful control that should nicely cooperate with all other
      controls, even when placed on top of them or under them.
      The correct approach is to only look at pressed keys/mouse buttons
      if HandleInput is @true. Moreover, if you did check
      that HandleInput is @true, and you did actually handle some keys,
      then you have to set @code(HandleInput := not ExclusiveEvents).
      As ExclusiveEvents is @true in normal circumstances,
      this will prevent the other controls (behind the current control)
      from handling the keys (they will get HandleInput = @false).
      And this is important to avoid doubly-processing the same key press,
      e.g. if two controls react to the same key, only the one on top should
      process it.

      Note that to handle a single press / release (like "switch
      light on when pressing a key") you should rather
      use @link(Press) and @link(Release) methods. Use this method
      only for continous handling (like "holding this key makes
      the light brighter and brighter").

      To understand why such HandleInput approach is needed,
      realize that the "Update" events are called
      differently than simple mouse and key events like "Press" and "Release".
      "Press" and "Release" events
      return whether the event was somehow "handled", and the container
      passes them only to the controls under the mouse (decided by
      @link(TUIControl.CapturesEventsAtPosition)). And as soon as some control says it "handled"
      the event, other controls (even if under the mouse) will not
      receive the event.

      This approach is not suitable for Update events. Some controls
      need to do the Update job all the time,
      regardless of whether the control is under the mouse and regardless
      of what other controls already did. So all controls (well,
      all controls that exist, in case of TUIControl,
      see TUIControl.GetExists) receive Update calls.

      So the "handled" status is passed through HandleInput.
      If a control is not under the mouse, it will receive HandleInput
      = @false. If a control is under the mouse, it will receive HandleInput
      = @true as long as no other control on top of it didn't already
      change it to @false. }
    procedure Update(const SecondsPassed: Single;
      var HandleInput: boolean); virtual;

    { Called always when some visible part of this control
      changes. In the simplest case, this is used by the controls manager to
      know when we need to redraw the control.

      In this class this simply calls OnVisibleChange (if assigned).

      @param(RectOrCursorChanged Set to @true if the final control size
        or position on the screen, or cursor, changed. This simply causes a call
        to @link(TUIContainer.UpdateFocusAndMouseCursor).) }
    procedure VisibleChange(const RectOrCursorChanged: boolean = false); virtual;

    { Called always when some visible part of this control
      changes. In the simplest case, this is used by the controls manager to
      know when we need to redraw the control.

      Be careful when handling this event, various changes may cause this,
      so be prepared to handle OnVisibleChange at every time.

      @seealso VisibleChange }
    property OnVisibleChange: TNotifyEvent
      read FOnVisibleChange write FOnVisibleChange;

    { Allow window containing this control to suspend waiting for user input.
      Typically you want to override this to return @false when you do
      something in the overridden @link(Update) method.

      In this class, this simply returns always @true.

      @seeAlso TCastleWindowCustom.AllowSuspendForInput }
    function AllowSuspendForInput: boolean; virtual;

    { You can resize/reposition your component here,
      for example set @link(TUIControl.Left) or @link(TUIControl.Bottom), to react to parent
      size changes.
      Called always when the container (component or window with OpenGL context)
      size changes. Called only when the OpenGL context of the container
      is initialized, so you can be sure that this is called only between
      GLContextOpen and GLContextClose.

      We also make sure to call this once when inserting into
      the controls list
      (like @link(TCastleWindowCustom.Controls) or
      @link(TCastleControlCustom.Controls) or inside parent TUIControl),
      if inserting into the container/parent
      with already initialized OpenGL context. If inserting into the container/parent
      without OpenGL context initialized, it will be called later,
      when OpenGL context will get initialized, right after GLContextOpen.

      In other words, this is always called to let the control know
      the size of the container, if and only if the OpenGL context is
      initialized. }
    procedure Resize; virtual;

    procedure ContainerResize(const AContainerWidth, AContainerHeight: Cardinal); virtual; deprecated 'use Resize';

    { Container of this control. When adding control to container's Controls
      list (like TCastleWindowCustom.Controls) container will automatically
      set itself here, and when removing from container this will be changed
      back to @nil.

      May be @nil if this control is not yet inserted into any container. }
    property Container: TUIContainer read FContainer write SetContainer;

    { Mouse cursor over this control.
      When user moves mouse over the Container, the currently focused
      (topmost under the cursor) control determines the mouse cursor look. }
    property Cursor: TMouseCursor read FCursor write SetCursor default mcDefault;

    { Event called when the @link(Cursor) property changes.
      This event is, in normal circumstances, used by the Container,
      so you should not use it in your own programs. }
    property OnCursorChange: TNotifyEvent
      read FOnCursorChange write FOnCursorChange;

    { Design note: ExclusiveEvents is not published now, as it's too "obscure"
      (for normal usage you don't want to deal with it). Also, it's confusing
      on TCastleSceneCore, the name suggests it relates to ProcessEvents (VRML events,
      totally not related to this property that is concerned with handling
      TUIControl events.) }

    { Should we disable further mouse / keys handling for events that
      we already handled in this control. If @true, then our events will
      return @true for mouse and key events handled.

      This means that events will not be simultaneously handled by both this
      control and some other (or camera or normal window callbacks),
      which is usually more sensible, but sometimes somewhat limiting. }
    property ExclusiveEvents: boolean
      read FExclusiveEvents write FExclusiveEvents default true;
  end;

  { Position for relative layout of one control in respect to another.
    @deprecated Deprecated, rather use cleaner
    THorizontalPosition and TVerticalPosition.
  }
  TPositionRelative = (
    prLow,
    prMiddle,
    prHigh
  ) deprecated;

  { Basic 2D control class. All controls derive from this class,
    overriding chosen methods to react to some events.
    Various user interface containers (things that directly receive messages
    from something outside, like operating system, windowing library etc.)
    implement support for such controls.

    Control has children controls, see @link(Controls) and @link(ControlsCount).
    Parent control is recorded inside @link(Parent). A control
    may only be a child of one other control --- that is, you cannot
    insert to the 2D hierarchy the same control multiple times
    (in TCastleTransform hierarchy, such trick is allowed).

    Control may handle mouse/keyboard input, see @link(Press) and @link(Release)
    methods.

    Various methods return boolean saying if input event is handled.
    The idea is that not handled events are passed to the next
    control suitable. Handled events are generally not processed more
    --- otherwise the same event could be handled by more than one listener,
    which is bad. Generally, return ExclusiveEvents if anything (possibly)
    was done (you changed any field value etc.) as a result of this,
    and only return @false when you're absolutely sure that nothing was done
    by this control.

    Every control also has a position and takes some rectangular space
    on the container.

    The position is controlled using the @link(Left), @link(Bottom) fields.
    The rectangle where the control is visible can be queried using
    the @link(Rect) or @link(ScreenRect) methods.

    Note that each descendant has it's own definition of the size of the control.
    E.g. some descendants may automatically calculate the size
    (based on text or images or such placed within the control).
    Some descendants may allow to control the size explicitly
    using fields like Width, Height, FullSize.
    Some descendants may allow both approaches, switchable by
    property like TCastleButton.AutoSize or TCastleImageControl.Stretch.
    The base @link(TUIControl.Rect) returns always an empty rectangle,
    most descendants will want to override it (you can also ignore the issue
    in your own TUIControl descendants, if the given control size will
    never be used for anything).

    All screen (mouse etc.) coordinates passed here should be in the usual
    window system coordinates, that is (0, 0) is left-top window corner.
    (Note that this is contrary to the usual OpenGL 2D system,
    where (0, 0) is left-bottom window corner.) }
  TUIControl = class abstract(TInputListener)
  private
    FDisableContextOpenClose: Cardinal;
    FFocused: boolean;
    FGLInitialized: boolean;
    FExists: boolean;
    {$warnings off} // knowingly using deprecated stuff
    FRenderStyle: TRenderStyle;
    {$warnings on}
    FControls: TChildrenControls;
    FLeft: Integer;
    FBottom: Integer;
    FParent: TUIControl; //< null means that parent is our owner
    FHasHorizontalAnchor: boolean;
    FHorizontalAnchorSelf, FHorizontalAnchorParent: THorizontalPosition;
    FHorizontalAnchorDelta: Integer;
    FHasVerticalAnchor: boolean;
    FVerticalAnchorSelf, FVerticalAnchorParent: TVerticalPosition;
    FVerticalAnchorDelta: Integer;
    FEnableUIScaling: boolean;
    FKeepInFront, FCapturesEvents: boolean;
    procedure SetExists(const Value: boolean);
    function GetControls(const I: Integer): TUIControl;
    procedure SetControls(const I: Integer; const Item: TUIControl);
    procedure CreateControls;

    { This takes care of some internal quirks with saving Left property
      correctly. (Because TComponent doesn't declare, but saves/loads a "magic"
      property named Left during streaming. This is used to place non-visual
      components on the form. Our Left is completely independent from this.) }
    procedure ReadRealLeft(Reader: TReader);
    procedure WriteRealLeft(Writer: TWriter);

    procedure ReadLeft(Reader: TReader);
    procedure ReadTop(Reader: TReader);
    procedure WriteLeft(Writer: TWriter);
    procedure WriteTop(Writer: TWriter);

    procedure SetLeft(const Value: Integer);
    procedure SetBottom(const Value: Integer);

    procedure SetHasHorizontalAnchor(const Value: boolean);
    procedure SetHorizontalAnchorSelf(const Value: THorizontalPosition);
    procedure SetHorizontalAnchorParent(const Value: THorizontalPosition);
    procedure SetHorizontalAnchorDelta(const Value: Integer);
    procedure SetHasVerticalAnchor(const Value: boolean);
    procedure SetVerticalAnchorSelf(const Value: TVerticalPosition);
    procedure SetVerticalAnchorParent(const Value: TVerticalPosition);
    procedure SetVerticalAnchorDelta(const Value: Integer);
    procedure SetEnableUIScaling(const Value: boolean);
    { Like @link(Rect) but with anchors effect applied. }
    function RectWithAnchors(const CalculateEvenWithoutContainer: boolean = false): TRectangle;
  protected
    procedure DefineProperties(Filer: TFiler); override;
    procedure SetContainer(const Value: TUIContainer); override;

    { The left-bottom corner scaled by UIScale,
      useful for implementing overridden @code(Rect) methods. }
    function LeftBottomScaled: TVector2Integer;

    procedure UIScaleChanged; virtual;

    //procedure DoCursorChange; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    property Controls [Index: Integer]: TUIControl read GetControls write SetControls;
    function ControlsCount: Integer;

    { Add child control, at the front of other children. }
    procedure InsertFront(const NewItem: TUIControl); overload;
    procedure InsertFrontIfNotExists(const NewItem: TUIControl);
    procedure InsertFront(const NewItems: TUIControlList); overload;

    { Add child control, at the back of other children. }
    procedure InsertBack(const NewItem: TUIControl); overload;
    procedure InsertBackIfNotExists(const NewItem: TUIControl);
    procedure InsertBack(const NewItems: TUIControlList); overload;

    { Remove control added by @link(InsertFront) or @link(InsertBack). }
    procedure RemoveControl(Item: TUIControl);

    { Remove all child controls added by @link(InsertFront) or @link(InsertBack). }
    procedure ClearControls;

    { Return whether item really exists, see @link(Exists).
      Non-existing item does not receive any of the render or input or update calls.
      They only receive @link(GLContextOpen), @link(GLContextClose), @link(Resize)
      calls.

      It TUIControl class, this returns the value of @link(Exists) property.
      May be overridden in descendants, to return something more complicated,
      but it should always be a logical "and" with the inherited @link(GetExists)
      implementation (so setting the @code(Exists := false) will always work),
      like

      @longCode(#
        Result := (inherited GetExists) and MyComplicatedConditionForExists;
      #) }
    function GetExists: boolean; virtual;

    { Does this control capture events under this screen position.
      The default implementation simply checks whether Position
      is inside ScreenRect now. It also checks whether @link(CapturesEvents) is @true.

      Always treated like @false when GetExists returns @false,
      so the implementation of this method only needs to make checks assuming that
      GetExists = @true.  }
    function CapturesEventsAtPosition(const Position: TVector2): boolean; virtual;

    { Prepare your resources, right before drawing.
      Called only when @link(GetExists) and GLInitialized.

      @bold(Do not explicitly call this method.)
      Instead, render controls by adding them to the
      @link(TUIContainer.Controls) list, or render them explicitly
      (for off-screen rendering) by @link(TGLContainer.RenderControl).
    }
    procedure BeforeRender; virtual;

    { Render a control. Called only when @link(GetExists) and GLInitialized,
      you can depend on it in the implementation of this method.

      @bold(Do not explicitly call this method.)
      Instead, render controls by adding them to the
      @link(TUIContainer.Controls) list, or render them explicitly
      (for off-screen rendering) by @link(TGLContainer.RenderControl).
      This is method should only be overridden in your own code.

      Before calling this method we always set some OpenGL state,
      and you can depend on it (and you can carelessly change it,
      as it will be reset again before rendering other control).

      OpenGL state always set:

      @unorderedList(
        @item(glViewport is set to include whole container.)

        @item(Depth test is off.)

        @item(@italic((For fixed-function pipeline:))
          The 2D orthographic projection is always set at the beginning.
          Useful for 2D controls, 3D controls can just override projection
          matrix, e.g. use @link(CastleGLUtils.PerspectiveProjection).)

        @item(@italic((For fixed-function pipeline:))
          The modelview matrix is set to identity. The matrix mode
          is always modelview.)

        @item(@italic((For fixed-function pipeline:))
          The raster position is set to (0,0).
          The (deprecated) WindowPos is also set to (0,0).)

        @item(@italic((For fixed-function pipeline:))
          Texturing, lighting, fog is off.)
      )

      Beware that GLSL @link(TGLSLProgram.Current) has undefined value when this is called.
      You should always set it, before making direct OpenGL drawing calls
      (all the engine drawing routines of course do it already, this is only a concern
      if you make direct OpenGL / OpenGLES calls). }
    procedure Render; virtual;

    { Render a control contents @italic(over the children controls).
      This is analogous to @link(Render), but it executes after children are drawn.
      You should usually prefer to override @link(Render) instead of this method,
      as the convention is that the parent is underneath children. }
    procedure RenderOverChildren; virtual;

    { Determines the rendering order.
      All controls with RenderStyle = rs3D are drawn first.
      Then all the controls with RenderStyle = rs2D are drawn.
      Among the controls with equal RenderStyle, their order
      on TUIContainer.Controls list determines the rendering order. }
    property RenderStyle: TRenderStyle read FRenderStyle write FRenderStyle default rs2D;
      deprecated 'do not use this to control front-back UI controls order, better to use controls order and TUIControl.KeepInFront';

    { Render a tooltip of this control. If you want to have tooltip for
      this control detected, you have to override TooltipExists.
      Then the TCastleWindowCustom.TooltipVisible will be detected,
      and your TooltipRender will be called.

      The values of rs2D and rs3D are interpreted in the same way
      as RenderStyle. And TooltipRender is called in the same way as @link(Render),
      so e.g. you can safely assume that modelview matrix is identity
      and (for 2D) WindowPos is zero.
      TooltipRender is always called as a last (front-most) 2D or 3D control.

      @groupBegin }
    function TooltipStyle: TRenderStyle; virtual;
      deprecated 'do not use this to control front-back UI controls order, better to use controls order and TUIControl.KeepInFront';
    function TooltipExists: boolean; virtual;
    procedure TooltipRender; virtual;
    { @groupEnd }

    { Initialize your OpenGL resources.

      This is called when OpenGL context of the container is created,
      or when the control is added to the already existing context.
      In other words, this is the moment when you can initialize
      OpenGL resources, like display lists, VBOs, OpenGL texture names, etc.

      As an exception, this is called regardless of the GetExists value.
      This way a control can prepare it's resources, regardless if it exists now. }
    procedure GLContextOpen; virtual;

    { Destroy your OpenGL resources.

      Called when OpenGL context of the container is destroyed.
      Also called when controls is removed from the container
      @code(Controls) list. Also called from the destructor.

      You should release here any resources that are tied to the
      OpenGL context. In particular, the ones created in GLContextOpen.

      As an exception, this is called regardless of the GetExists value.
      This way a control can release it's resources, regardless if it exists now. }
    procedure GLContextClose; virtual;

    property GLInitialized: boolean read FGLInitialized default false;

    { When non-zero, control will not receive GLContextOpen and
      GLContextClose events when it is added/removed from the
      @link(TUIContainer.Controls) list.

      This can be useful as an optimization, to keep the OpenGL resources
      created even for controls that are not present on the
      @link(TUIContainer.Controls) list. @italic(This must used
      very, very carefully), as bad things will happen if the actual OpenGL
      context will be destroyed while the control keeps the OpenGL resources
      (because it had DisableContextOpenClose > 0). The control will then
      remain having incorrect OpenGL resource handles, and will try to use them,
      causing OpenGL errors or at least weird display artifacts.

      Most of the time, when you think of using this, you should instead
      use the @link(TUIControl.Exists) property. This allows you to keep the control
      of the @link(TUIContainer.Controls) list, and it will be receive
      GLContextOpen and GLContextClose events as usual, but will not exist
      for all other purposes.

      Using this mechanism is only sensible if you want to reliably hide a control,
      but also allow readding it to the @link(TUIContainer.Controls) list,
      and then you want to show it again. This is useful for CastleWindowModes,
      that must push (and then pop) the controls, but then allows the caller
      to modify the controls list. And some games, e.g. castle1, add back
      some (but not all) of the just-hidden controls. For example the TCastleNotifications
      instance is added back, to be visible even in the menu mode.
      This means that CastleWindowModes cannot just modify the TUIContainer.Exists
      value, leaving the control on the @link(TUIContainer.Controls) list:
      it would leave the TUIControl existing many times on the @link(TUIContainer.Controls)
      list, with the undefined TUIContainer.Exists value. }
    property DisableContextOpenClose: Cardinal
      read FDisableContextOpenClose write FDisableContextOpenClose;

   { Called when this control becomes or stops being focused,
     that is: under the mouse cursor and will receive events.
     In this class, they simply update Focused property.
     You can override this to react to mouse enter / mouse exit events. }
    procedure SetFocused(const Value: boolean); virtual;

    property Focused: boolean read FFocused write SetFocused;

    property Parent: TUIControl read FParent;

    { Position and size of this control, assuming it exists,
      in local coordinates (relative to parent 2D control).

      @unorderedList(
        @item(@bold(This must ignore)
          the current value of the @link(GetExists) method
          and @link(Exists) property, that is: the result of this function
          assumes that control does exist.)

        @item(@bold(This must ignore) the anchors. Their effect is applied
          outside of this method.)

        @item(@bold(This must take into account) UI scaling.
          This method must calculate a result already multiplied by @link(UIScale).
          In simple cases, this can be done easily, like this:

          @longCode(#
            function TMyControl.Rect: TRectangle;
            begin
              Result := Rectangle(Left, Bottom, Width, Height).ScaleAround0(UIScale);
            end;
          #)

          In fact, TUIControlSizeable already provides such implementation
          for you.)
      )

      In this class, returns empty rectangle (zero width and height) with
      Left and Bottom correctly set (scaled by @link(UIScale)).

      @seealso CalculatedRect
    }
    function Rect: TRectangle; virtual;

    { Final position and size of this control, assuming it exists,
      in local coordinates (relative to parent 2D control),
      @italic(without UI scaling).
      Useful if you want to base other controls size/position on this control
      calculated size/position.

      This is similar to @link(Rect), but:

      @unorderedList(
        @item(@bold(This takes into account) the anchors.)
        @item(@bold(This ignores) the UI scaling.)
      )

      @bold(If you implement descendants of this class): Note that you
      cannot override this method. It is implemented by simply taking
      @code(RectWithAnchors) result (which in turn is derived from @link(Rect) result)
      and dividing it by UIScale. This should always be correct.

      Maybe in the future overriding this can be possible, but only for the sake
      of more optimal implementation.

      If you implement descendants, you should rather think about overriding
      the @link(Rect) method, if your control has special sizing mechanism.
      The reason why we prefer overriding @link(Rect) (and CalculatedRect is just
      derived from it), not the other way around:
      it is because font measurements are already done in scaled coordinates
      (because UI scaling changes font size for TUIControlFont).
      So things like TCastleLabel have to calculate size in scaled coordinates
      anyway, and the unscaled size can only be derived from it by division.

      @seealso Rect }
    function CalculatedRect: TRectangle;

    { Calculated width of the control, without UI scaling.
      Useful if you want to base other controls size/position on this control
      calculated size.

      Unlike various other width properties of descendants (like
      @link(TUIControlSizeable.Width) or @link(TCastleImageControl.Width)),
      this is the @italic(calculated) size, not the desired size.
      So this is already processed by any auto-sizing mechanism
      (e.g. TCastleImageControl may adjust it's own size to the underlying image,
      depending on settings).

      Unlike @code(Rect.Width), this does not have UI scaling applied.

      It is always equal to just @code(CalculatedRect.Width).

      @seealso CalculatedRect }
    function CalculatedWidth: Cardinal;

    { Calculated height of the control, without UI scaling.
      Useful if you want to base other controls size/position on this control
      calculated size.

      Unlike various other height properties of descendants (like
      @link(TUIControlSizeable.Height) or @link(TCastleImageControl.Height)),
      this is the @italic(calculated) size, not the desired size.
      So this is already processed by any auto-sizing mechanism
      (e.g. TCastleImageControl may adjust it's own size to the underlying image,
      depending on settings).

      Unlike @code(Rect.Height), this does not have UI scaling applied.

      It is always equal to just @code(CalculatedRect.Height).

      @seealso CalculatedRect }
    function CalculatedHeight: Cardinal;

    { Position and size of this control, assuming it exists, in screen (container)
      coordinates. }
    function ScreenRect: TRectangle;

    { How to translate local coords to screen.
      If you use UI scaling, this works in final coordinates
      (after scaling, real pixels on screen). }
    function LocalToScreenTranslation: TVector2Integer;

    { Rectangle filling the parent control (or coordinates), in local coordinates.
      Since this is in local coordinates, the returned rectangle Left and Bottom
      are always zero.
      This is already scaled by UI scaling, since it's derived from @link(Rect)
      size that should also be already scaled. }
    function ParentRect: TRectangle;

    { Quick way to enable horizontal anchor, to automatically keep this
      control aligned to parent. Sets @link(HasHorizontalAnchor),
      @link(HorizontalAnchorSelf), @link(HorizontalAnchorParent),
      @link(HorizontalAnchorDelta). }
    procedure Anchor(const AHorizontalAnchor: THorizontalPosition;
      const AHorizontalAnchorDelta: Integer = 0); overload;

    { Quick way to enable horizontal anchor, to automatically keep this
      control aligned to parent. Sets @link(HasHorizontalAnchor),
      @link(HorizontalAnchorSelf), @link(HorizontalAnchorParent),
      @link(HorizontalAnchorDelta). }
    procedure Anchor(
      const AHorizontalAnchorSelf, AHorizontalAnchorParent: THorizontalPosition;
      const AHorizontalAnchorDelta: Integer = 0); overload;

    { Quick way to enable vertical anchor, to automatically keep this
      control aligned to parent. Sets @link(HasVerticalAnchor),
      @link(VerticalAnchorSelf), @link(VerticalAnchorParent),
      @link(VerticalAnchorDelta). }
    procedure Anchor(const AVerticalAnchor: TVerticalPosition;
      const AVerticalAnchorDelta: Integer = 0); overload;

    { Quick way to enable vertical anchor, to automatically keep this
      control aligned to parent. Sets @link(HasVerticalAnchor),
      @link(VerticalAnchorSelf), @link(VerticalAnchorParent),
      @link(VerticalAnchorDelta). }
    procedure Anchor(
      const AVerticalAnchorSelf, AVerticalAnchorParent: TVerticalPosition;
      const AVerticalAnchorDelta: Integer = 0); overload;

    { Immediately position the control with respect to the parent
      by adjusting @link(Left).
      Deprecated, use @link(Align) with THorizontalPosition. }
    procedure AlignHorizontal(
      const ControlPosition: TPositionRelative = prMiddle;
      const ContainerPosition: TPositionRelative = prMiddle;
      const X: Integer = 0); deprecated 'use Align or Anchor';

    { Immediately position the control with respect to the parent
      by adjusting @link(Left).

      Note that using @link(Anchor) is often more comfortable than this method,
      since you only need to set anchor once (for example, right after creating
      the control). In contract, adjusting position using this method
      will typically need to be repeated at each window on resize,
      like in @link(TCastleWindowCustom.OnResize). }
    procedure Align(
      const ControlPosition: THorizontalPosition;
      const ContainerPosition: THorizontalPosition;
      const X: Integer = 0); overload;

    { Immediately position the control with respect to the parent
      by adjusting @link(Bottom).
      Deprecated, use @link(Align) with TVerticalPosition. }
    procedure AlignVertical(
      const ControlPosition: TPositionRelative = prMiddle;
      const ContainerPosition: TPositionRelative = prMiddle;
      const Y: Integer = 0); deprecated 'use Align or Anchor';

    { Immediately position the control with respect to the parent
      by adjusting @link(Bottom).

      Note that using @link(Anchor) is often more comfortable than this method,
      since you only need to set anchor once (for example, right after creating
      the control). In contract, adjusting position using this method
      will typically need to be repeated at each window on resize,
      like in @link(TCastleWindowCustom.OnResize). }
    procedure Align(
      const ControlPosition: TVerticalPosition;
      const ContainerPosition: TVerticalPosition;
      const Y: Integer = 0); overload;

    { Immediately center the control within the parent,
      both horizontally and vertically.

      Note that using @link(Anchor) is often more comfortable than this method,
      since you only need to set anchor once. For example, right after creating
      the control call @code(Anchor(hpMiddle); Anchor(vpMiddle);).
      In contrast, adjusting position using this method
      will typically need to be repeated at each window on resize,
      like in @link(TCastleWindowCustom.OnResize). }
    procedure Center;

    { UI scale of this control, derived from container
      (see @link(TUIContainer.UIScaling).

      All the drawing and measuring inside your control must take this into
      account. The final @link(Rect) result must already take this scaling
      into account, so that parent controls may depend on it.
      All descendants, like TUIControlSizeable, provide a @link(Rect) implementation
      that does what is necessary. }
    function UIScale: Single;
  published
    { Not existing control is not visible, it doesn't receive input
      and generally doesn't exist from the point of view of user.
      You can also remove this from controls list (like
      @link(TCastleWindowCustom.Controls)), but often it's more comfortable
      to set this property to false. }
    property Exists: boolean read FExists write SetExists default true;

    property Left: Integer read FLeft write SetLeft stored false default 0;
    property Bottom: Integer read FBottom write SetBottom default 0;

    { Automatically adjust horizontal position to align us to
      the parent horizontally. Note that the value of @link(Left) remains
      unchanged (it is just ignored), using the anchors only modifies the output
      of the @link(ScreenRect) value that should be used for rendering/physics.

      @italic(Anchor distance is automatically affected by @link(TUIContainer.UIScaling).) }
    property HasHorizontalAnchor: boolean
      read FHasHorizontalAnchor write SetHasHorizontalAnchor default false;
    { Which @bold(our) border to align (it's aligned
      to parent @link(HorizontalAnchorParent) border),
      only used if @link(HasHorizontalAnchor). }
    property HorizontalAnchorSelf: THorizontalPosition
      read FHorizontalAnchorSelf write SetHorizontalAnchorSelf default hpLeft;
    { Which @bold(parent) border is aligned to our @link(HorizontalAnchorSelf) border,
      only used if @link(HasHorizontalAnchor). }
    property HorizontalAnchorParent: THorizontalPosition
      read FHorizontalAnchorParent write SetHorizontalAnchorParent default hpLeft;
    { Delta between our border and parent,
      only used if @link(HasHorizontalAnchor). }
    property HorizontalAnchorDelta: Integer
      read FHorizontalAnchorDelta write SetHorizontalAnchorDelta default 0;

    { Automatically adjust vertical position to align us to
      the parent vertically. Note that the value of @link(Bottom) remains
      unchanged (it is tjust ignored), using the anchors only modifies the output
      of the @link(ScreenRect) value that should be used for rendering/physics.

      @italic(Anchor distance is automatically affected by @link(TUIContainer.UIScaling).) }
    property HasVerticalAnchor: boolean
      read FHasVerticalAnchor write SetHasVerticalAnchor default false;
    { Which @bold(our) border to align (it's aligned
      to parent @link(VerticalAnchorParent) border),
      only used if @link(HasVerticalAnchor). }
    property VerticalAnchorSelf: TVerticalPosition
      read FVerticalAnchorSelf write SetVerticalAnchorSelf default vpBottom;
    { Which @bold(parent) border is aligned to our @link(VerticalAnchorSelf) border,
      only used if @link(HasVerticalAnchor). }
    property VerticalAnchorParent: TVerticalPosition
      read FVerticalAnchorParent write SetVerticalAnchorParent default vpBottom;
    { Delta between our border and parent,
      only used if @link(HasVerticalAnchor). }
    property VerticalAnchorDelta: Integer
      read FVerticalAnchorDelta write SetVerticalAnchorDelta default 0;

    { Enable or disable UI scaling for this particular control.
      See more about UI scaling on @link(TUIContainer.UIScaling) and
      @link(TUIControl.UIScale). Setting this to @false forces
      @link(TUIControl.UIScale) to always return 1.0.

      Note that this does not work recursively, i.e. it does not affect
      the children of this control. Setting this to @false does not prevent
      UI scaling on children (you have to turn it off explicitly for children too,
      if you need to disable UI scaling recursively). }
    property EnableUIScaling: boolean
      read FEnableUIScaling write SetEnableUIScaling default true;

    { Keep the control in front of other controls (with KeepInFront=@false)
      when inserting.

      TODO: Do not change this propertyu while the control is already
      a children of something. }
    property KeepInFront: boolean read FKeepInFront write FKeepInFront
      default false;

    property CapturesEvents: boolean read FCapturesEvents write FCapturesEvents
      default true;
  end;

  { UI control with configurable size.
    By itself, this does not show anything. But it's useful as an ancestor
    class for new UI classes that want their size to be fully configurable,
    or as a container for UI children. }
  TUIControlSizeable = class(TUIControl)
  strict private
    FWidth, FHeight: Cardinal;
    FFullSize: boolean;
    procedure SetWidth(const Value: Cardinal);
    procedure SetHeight(const Value: Cardinal);
    procedure SetFullSize(const Value: boolean);
  public
    constructor Create(AOwner: TComponent); override;

    { Position and size of the control, assuming it exists.

      Looks at @link(FullSize) value, and the parent size
      (when @link(FullSize) is @true), or at the properties
      @link(Left), @link(Bottom), @link(Width), @link(Height)
      (when @link(FullSize) is @false). }
    function Rect: TRectangle; override;
  published
    { Control size.

      When FullSize is @true, the control always fills
      the whole parent (like TCastleWindow or TCastleControl,
      if you just placed the control on TCastleWindowCustom.Controls
      or TCastleControlCustom.Controls),
      and the values of @link(TUIControl.Left Left),
      @link(TUIControl.Bottom Bottom), @link(Width), @link(Height) are ignored.

      @seealso TUIControl.Rect

      @groupBegin }
    property FullSize: boolean read FFullSize write SetFullSize default false;
    property Width: Cardinal read FWidth write SetWidth default 0;
    property Height: Cardinal read FHeight write SetHeight default 0;
    { @groupEnd }
  end;

  { Simple list of TUIControl instances. }
  TUIControlList = class({$ifdef CASTLE_OBJFPC}specialize{$endif} TObjectList<TUIControl>)
  public
    { Add child control, at the front of other children. }
    procedure InsertFront(const NewItem: TUIControl); overload;
    procedure InsertFrontIfNotExists(const NewItem: TUIControl);
    procedure InsertFront(const NewItems: TUIControlList); overload;

    { Add child control, at the back of other children. }
    procedure InsertBack(const NewItem: TUIControl); overload;
    procedure InsertBackIfNotExists(const NewItem: TUIControl);
    procedure InsertBack(const NewItems: TUIControlList); overload;

    { Insert, honoring @link(TUIControl.KeepInFront). }
    procedure InsertWithZOrder(Index: Integer; const Item: TUIControl);
  end;

  TUIControlClass = class of TUIControl;

  TUIControlPos = TUIControl deprecated 'use TUIControl class';
  TUIRectangularControl = TUIControl deprecated 'use TUIControl class';

  { List of UI controls, with a parent control and container.
    Ordered from back to front.
    Used for @link(TUIContainer.Controls). }
  TChildrenControls = class
  private
    FParent: TUIControl;
    FContainer: TUIContainer;

    procedure RegisterContainer(const C: TUIControl; const AContainer: TUIContainer);
    procedure UnregisterContainer(const C: TUIControl; const AContainer: TUIContainer);
    procedure SetContainer(const AContainer: TUIContainer);
    property Container: TUIContainer read FContainer write SetContainer;

    type
      TMyObjectList = class(TCastleObjectList)
        Parent: TChildrenControls;
        { Pass notifications to Parent. }
        procedure Notify(Ptr: Pointer; Action: TListNotification); override;
      end;
      TCaptureFreeNotifications = class(TComponent)
      protected
        Parent: TChildrenControls;
        { Pass notifications to Parent. }
        procedure Notification(AComponent: TComponent; Operation: TOperation); override;
      end;
    var
      FList: TMyObjectList;
      FCaptureFreeNotifications: TCaptureFreeNotifications;

    {$ifndef VER2_6}
    { Using this causes random crashes in -dRELEASE with FPC 2.6.x. }
    type
      TEnumerator = class
      private
        FList: TChildrenControls;
        FPosition: Integer;
        function GetCurrent: TUIControl;
      public
        constructor Create(AList: TChildrenControls);
        function MoveNext: Boolean;
        property Current: TUIControl read GetCurrent;
      end;
    {$endif}

    function GetItem(const I: Integer): TUIControl;
    procedure SetItem(const I: Integer; const Item: TUIControl);
    { React to add/remove notifications. }
    procedure Notify(Ptr: Pointer; Action: TListNotification);
  public
    constructor Create(AParent: TUIControl);
    destructor Destroy; override;

    {$ifndef VER2_6}
    function GetEnumerator: TEnumerator;
    {$endif}

    property Items[I: Integer]: TUIControl read GetItem write SetItem; default;
    function Count: Integer;
    procedure Assign(const Source: TChildrenControls);
    { Remove the Item from this list.
      Note that the given Item should always exist only once on a list
      (it is not allowed to add it multiple times), so there's no @code(RemoveAll)
      method. }
    procedure Remove(const Item: TUIControl);
    procedure Clear;
    procedure Add(const Item: TUIControl); deprecated 'use InsertFront or InsertBack';
    procedure Insert(Index: Integer; const Item: TUIControl);
    function IndexOf(const Item: TUIControl): Integer;

    { Make sure that NewItem is the only instance of given ReplaceClass
      on the list, replacing old item if necesssary.
      See TCastleObjectList.MakeSingle for precise description. }
    function MakeSingle(ReplaceClass: TUIControlClass; NewItem: TUIControl;
      AddFront: boolean = true): TUIControl;

    { Add at the end of the list. }
    procedure InsertFront(const NewItem: TUIControl); overload;
    procedure InsertFrontIfNotExists(const NewItem: TUIControl);
    procedure InsertFront(const NewItems: TUIControlList); overload;

    { Add at the beginning of the list. }
    procedure InsertBack(const NewItem: TUIControl); overload;
    procedure InsertBackIfNotExists(const NewItem: TUIControl);
    procedure InsertBack(const NewItems: TUIControlList); overload;

    procedure InsertIfNotExists(const Index: Integer; const NewItem: TUIControl); deprecated 'use InsertFrontIfNotExists or InsertBackIfNotExists';
    procedure AddIfNotExists(const NewItem: TUIControl); deprecated 'use InsertFrontIfNotExists or InsertBackIfNotExists';

    { BeginDisableContextOpenClose disables sending
      TUIControl.GLContextOpen and TUIControl.GLContextClose to all the controls
      on the list. EndDisableContextOpenClose ends this.
      They work by increasing / decreasing the TUIControl.DisableContextOpenClose
      for all the items on the list.

      @groupBegin }
    procedure BeginDisableContextOpenClose;
    procedure EndDisableContextOpenClose;
    { @groupEnd }
  end;

function OnGLContextOpen: TGLContextEventList; deprecated 'use ApplicationProperties.OnGLContextOpen';
function OnGLContextClose: TGLContextEventList; deprecated 'use ApplicationProperties.OnGLContextClose';
function IsGLContextOpen: boolean; deprecated 'use ApplicationProperties.IsGLContextOpen';

const
  { Deprecated name for rs2D. }
  ds2D = rs2D deprecated;
  { Deprecated name for rs3D. }
  ds3D = rs3D deprecated;

  prLeft = prLow deprecated;
  prRight = prHigh deprecated;
  prBottom = prLow deprecated;
  prTop = prHigh deprecated;

  hpLeft   = CastleRectangles.hpLeft  ;
  hpMiddle = CastleRectangles.hpMiddle;
  hpRight  = CastleRectangles.hpRight ;
  vpBottom = CastleRectangles.vpBottom;
  vpMiddle = CastleRectangles.vpMiddle;
  vpTop    = CastleRectangles.vpTop   ;

implementation

uses CastleLog;

{ TTouchList ----------------------------------------------------------------- }

function TTouchList.FindFingerIndex(const FingerIndex: TFingerIndex): Integer;
begin
  for Result := 0 to Count - 1 do
    if List^[Result].FingerIndex = FingerIndex then
      Exit;
  Result := -1;
end;

function TTouchList.GetFingerIndexPosition(const FingerIndex: TFingerIndex): TVector2;
var
  Index: Integer;
begin
  Index := FindFingerIndex(FingerIndex);
  if Index <> -1 then
    Result := List^[Index].Position
  else
    Result := TVector2.Zero;
end;

procedure TTouchList.SetFingerIndexPosition(const FingerIndex: TFingerIndex;
  const Value: TVector2);
var
  Index: Integer;
  NewTouch: PTouch;
begin
  Index := FindFingerIndex(FingerIndex);
  if Index <> -1 then
    List^[Index].Position := Value else
  begin
    NewTouch := Add;
    NewTouch^.FingerIndex := FingerIndex;
    NewTouch^.Position := Value;
  end;
end;

procedure TTouchList.RemoveFingerIndex(const FingerIndex: TFingerIndex);
var
  Index: Integer;
begin
  Index := FindFingerIndex(FingerIndex);
  if Index <> -1 then
    Delete(Index);
end;

{ TUIContainer --------------------------------------------------------------- }

constructor TUIContainer.Create(AOwner: TComponent);
begin
  inherited;
  FControls := TChildrenControls.Create(nil);
  TChildrenControls(FControls).Container := Self;
  FRenderStyle := rs2D;
  FTooltipDelay := DefaultTooltipDelay;
  FTooltipDistance := DefaultTooltipDistance;
  FCaptureInput := TFingerIndexCaptureMap.Create;
  FUIScaling := usNone;
  FUIExplicitScale := 1.0;
  FCalculatedUIScale := 1.0; // default safe value, in case some TUIControl will look here
  FFocus := TUIControlList.Create(false);
  FNewFocus := TUIControlList.Create(false);
  FFps := TFramesPerSecond.Create;
  FPressed := TKeysPressed.Create;

  { connect 3D device - 3Dconnexion device }
  Mouse3dPollTimer := 0;
  try
    Mouse3d := T3DConnexionDevice.Create('Castle Control');
  except
    on E: Exception do
      if Log then WritelnLog('3D Mouse', 'Exception %s when initializing T3DConnexionDevice: %s',
        [E.ClassName, E.Message]);
  end;
end;

destructor TUIContainer.Destroy;
begin
  FreeAndNil(FPressed);
  FreeAndNil(FFps);
  FreeAndNil(FControls);
  FreeAndNil(Mouse3d);
  FreeAndNil(FCaptureInput);
  FreeAndNil(FFocus);
  FreeAndNil(FNewFocus);
  { set to nil by SetForceCaptureInput, to detach free notification }
  ForceCaptureInput := nil;
  inherited;
end;

procedure TUIContainer.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;

  { Note: do not move niling FForceCaptureInput to DetachNotification,
    as we don't want to nil the public property too eagerly, the value
    of ForceCaptureInput should remain stable. }
  if (Operation = opRemove) and (AComponent = FForceCaptureInput) then
    { set to nil by SetForceCaptureInput to clean nicely }
    ForceCaptureInput := nil;

  if (Operation = opRemove) and (AComponent is TUIControl) then
    DetachNotification(TUIControl(AComponent));
end;

procedure TUIContainer.SetForceCaptureInput(const Value: TUIControl);
begin
  if FForceCaptureInput <> Value then
  begin
    if FForceCaptureInput <> nil then
      FForceCaptureInput.RemoveFreeNotification(Self);
    FForceCaptureInput := Value;
    if FForceCaptureInput <> nil then
      FForceCaptureInput.FreeNotification(Self);
  end;
end;

procedure TUIContainer.DetachNotification(const C: TUIControl);
var
  Index: Integer;
  FingerIndex: TFingerIndex;
begin
  if FFocus <> nil then
  begin
    Index := FFocus.IndexOf(C);
    if Index <> -1 then
    begin
      C.Focused := false;
      FFocus.Delete(Index);
    end;
  end;

  if FCaptureInput <> nil then
  begin
    while TryGetFingerOfControl(C, FingerIndex) do
      FCaptureInput.Remove(FingerIndex);
  end;
end;

function TUIContainer.TryGetFingerOfControl(const C: TUIControl; out Finger: TFingerIndex): boolean;
var
  FingerControlPair: TFingerIndexCaptureMap.TDictionaryPair;
begin
  { search for control C among the FCaptureInput values, and return corresponding key }
  for FingerControlPair in FCaptureInput do
    if FingerControlPair.Value = C then
    begin
      Finger := FingerControlPair.Key;
      Result := true;
      Exit;
    end;
  Result := false;
end;

function TUIContainer.UseForceCaptureInput: boolean;
begin
  Result :=
    (ForceCaptureInput <> nil) and
    (ForceCaptureInput.Container = Self) { currently added to our Controls tree } and
    ForceCaptureInput.GetExists;
end;

procedure TUIContainer.UpdateFocusAndMouseCursor;
var
  AnythingForcesNoneCursor: boolean;

  { Scan all Controls, recursively.
    Update (add) to FNewFocus, update (set to true) AnythingForcesNoneCursor. }
  procedure CalculateNewFocus;

    { AllowAddingToFocus is used to keep track whether we should
      do FNewFocus.Add on new controls. This way when one control obscures
      another, the obscured control does not land on the FNewFocus list.
      However, the obscured control can still affect the AnythingForcesNoneCursor
      value. }
    procedure RecursiveCalculateNewFocus(const C: TUIControl; var AllowAddingToFocus: boolean);
    var
      I: Integer;
      ChildAllowAddingToFocus: boolean;
    begin
      if (not (csDestroying in C.ComponentState)) and
         C.GetExists and
         C.CapturesEventsAtPosition(MousePosition) then
      begin
        if C.Cursor = mcForceNone then
          AnythingForcesNoneCursor := true;

        if AllowAddingToFocus then
        begin
          FNewFocus.Add(C);
          // siblings to C, obscured by C, will not be added to FNewFocus
          AllowAddingToFocus := false;
        end;

        // our children can be added to FNewFocus
        ChildAllowAddingToFocus := true;
        for I := C.ControlsCount - 1 downto 0 do
          RecursiveCalculateNewFocus(C.Controls[I], ChildAllowAddingToFocus);
      end;
    end;

  var
    I: Integer;
    AllowAddingToFocus: boolean;
  begin
    AllowAddingToFocus := true;
    for I := Controls.Count - 1 downto 0 do
      RecursiveCalculateNewFocus(Controls[I], AllowAddingToFocus);
  end;

  { Possibly adds the control to FNewFocus and
    updates the AnythingForcesNoneCursor if needed. }
  procedure AddInFrontOfNewFocus(const C: TUIControl);
  begin
    if (not (csDestroying in C.ComponentState)) and
       (FNewFocus.IndexOf(C) = -1) then
    begin
      FNewFocus.Add(C);
      if C.Cursor = mcForceNone then
        AnythingForcesNoneCursor := true;
    end;
  end;

  function CalculateMouseCursor: TMouseCursor;
  begin
    Result := mcDefault;

    if Focus.Count <> 0 then
      Result := Focus.Last.Cursor;

    if AnythingForcesNoneCursor then
      Result := mcForceNone;

    { do not hide when container is not focused (mouse look doesn't work
      then too, so better to not hide mouse) }
    if (not Focused) and (Result in [mcNone, mcForceNone]) then
      Result := mcDefault;
  end;

var
  I: Integer;
  Tmp: TUIControlList;
  ControlUnderFinger0: TUIControl;
begin
  { since this is called at the end of TChildrenControls.Notify after
    some control is removed, we're paranoid here about checking csDestroying. }

  { FNewFocus is only used by this method. It is only managed by TUIControl
    to avoid constructing/destructing it in every TUIContainer.UpdateFocusAndMouseCursor
    call. }
  FNewFocus.Clear;
  AnythingForcesNoneCursor := false;

  { Do not scan Controls for focus when csDestroying (in which case Controls
    list may be invalid). Testcase: exit with Alt + F4 from zombie_fighter
    StateAskDialog. }
  if not (csDestroying in ComponentState) then
  begin
    { calculate new FNewFocus value, update AnythingForcesNoneCursor }
    CalculateNewFocus;
    { add controls capturing the input (since they should have Focused = true to
      show them as receiving input) on top of other controls
      (so that e.g. TCastleOnScreenMenu underneath pressed-down button is
      also still focused) }
    if UseForceCaptureInput then
      AddInFrontOfNewFocus(ForceCaptureInput) else
    if FCaptureInput.TryGetValue(0, ControlUnderFinger0) then
      AddInFrontOfNewFocus(ControlUnderFinger0);

    { update TUIControl.Focused values, based on differences between FFocus and FNewFocus }
    for I := 0 to FNewFocus.Count - 1 do
      if FFocus.IndexOf(FNewFocus[I]) = -1 then
        FNewFocus[I].Focused := true;
    for I := 0 to FFocus.Count - 1 do
      if FNewFocus.IndexOf(FFocus[I]) = -1 then
        FFocus[I].Focused := false;
  end;

  { swap FFocus and FNewFocus, so that FFocus changes to new value,
    and the next UpdateFocusAndMouseCursor has ready FNewFocus value. }
  Tmp := FFocus;
  FFocus := FNewFocus;
  FNewFocus := Tmp;

  InternalCursor := CalculateMouseCursor;
end;

function TUIContainer.EventSensorRotation(const X, Y, Z, Angle: Double; const SecondsPassed: Single): boolean;

  function RecursiveSensorRotation(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(MousePosition) then
    begin
      for I := C.ControlsCount - 1 downto 0 do
        if RecursiveSensorRotation(C.Controls[I]) then
          Exit(true);

      if C.SensorRotation(X, Y, Z, Angle, SecondsPassed) then
        Exit(true);
    end;

    Result := false;
  end;

var
  I: Integer;
begin
  { exit as soon as something returns "true", meaning the event is handled }
  for I := Controls.Count - 1 downto 0 do
    if RecursiveSensorRotation(Controls[I]) then
      Exit(true);
  Result := false;
end;

function TUIContainer.EventSensorTranslation(const X, Y, Z, Length: Double; const SecondsPassed: Single): boolean;

  function RecursiveSensorTranslation(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(MousePosition) then
    begin
      for I := C.ControlsCount - 1 downto 0 do
        if RecursiveSensorTranslation(C.Controls[I]) then
          Exit(true);

      if C.SensorTranslation(X, Y, Z, Length, SecondsPassed) then
        Exit(true);
    end;

    Result := false;
  end;

var
  I: Integer;
begin
  { exit as soon as something returns "true", meaning the event is handled }
  for I := Controls.Count - 1 downto 0 do
    if RecursiveSensorTranslation(Controls[I]) then
      Exit(true);
  Result := false;
end;

function TUIContainer.EventJoyAxisMove(const JoyID, Axis: Byte): boolean;

  function RecursiveJoyAxisMove(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(MousePosition) then
    begin
      for I := C.ControlsCount - 1 downto 0 do
        if RecursiveJoyAxisMove(C.Controls[I]) then
          Exit(true);

      if C.JoyAxisMove(JoyID, Axis) then
        Exit(true);
    end;

    Result := false;
  end;

var
  I: Integer;
begin
  { exit as soon as something returns "true", meaning the event is handled }
  for I := Controls.Count - 1 downto 0 do
    if RecursiveJoyAxisMove(Controls[I]) then
      Exit(true);
  Result := false;
end;

function TUIContainer.EventJoyButtonPress(const JoyID, Button: Byte): boolean;

  function RecursiveJoyButtonPress(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(MousePosition) then
    begin
      for I := C.ControlsCount - 1 downto 0 do
        if RecursiveJoyButtonPress(C.Controls[I]) then
          Exit(true);

      if C.JoyButtonPress(JoyID, Button) then
        Exit(true);
    end;

    Result := false;
  end;

var
  I: Integer;
begin
  { exit as soon as something returns "true", meaning the event is handled }
  for I := Controls.Count - 1 downto 0 do
    if RecursiveJoyButtonPress(Controls[I]) then
      Exit(true);
  Result := false;
end;

procedure TUIContainer.EventUpdate;

  procedure UpdateTooltip;
  var
    T: TTimerResult;
    NewTooltipVisible: boolean;
  begin
    { Update TooltipVisible and LastPositionForTooltip*.
      Idea is that user must move the mouse very slowly to activate tooltip. }

    T := Fps.UpdateStartTime;
    if (not HasLastPositionForTooltip) or
       { reset the time counter to show tooltip, if you moved mouse/finger
         significantly }
       (PointsDistanceSqr(LastPositionForTooltip, MousePosition) >
        Sqr(TooltipDistance)) or
       { on touch devices, the time counter to show tooltip doesn't advance
         if we don't keep the finger pressed down }
       (ApplicationProperties.TouchDevice and (MousePressed = [])) then
    begin
      HasLastPositionForTooltip := true;
      LastPositionForTooltip := MousePosition;
      LastPositionForTooltipTime := T;
      NewTooltipVisible := false;
    end else
      { TODO: allow tooltips on other controls on Focus list,
        if Focus.Last.TooltipExists = false but other control on Focus
        has tooltips.
        Set something like TooltipFocusIndex or just TooltipControl
        to pass correct control to TGLContainer.EventRender then,
        right now we hardcoded there rendering of Focus.Last tooltip. }
      NewTooltipVisible :=
        { make TooltipVisible only when we're over a control that has
          focus. This avoids unnecessary changing of TooltipVisible
          (and related Invalidate) when there's no tooltip possible. }
        (Focus.Count <> 0) and
        Focus.Last.TooltipExists and
        (TimerSeconds(T, LastPositionForTooltipTime) > TooltipDelay);

    if FTooltipVisible <> NewTooltipVisible then
    begin
      FTooltipVisible := NewTooltipVisible;

      if TooltipVisible then
      begin
        { when setting TooltipVisible from false to true,
          update LastPositionForTooltip. We don't want to hide the tooltip
          at the slightest jiggle of the mouse :) On the other hand,
          we don't want to update LastPositionForTooltip more often,
          as it would disable the purpose of TooltipDistance: faster
          mouse movement should hide the tooltip. }
        LastPositionForTooltip := MousePosition;
        { also update TooltipPosition }
        FTooltipPosition := MousePosition;
      end;

      Invalidate;
    end;
  end;

  procedure RecursiveUpdate(const C: TUIControl; var HandleInput: boolean);
  var
    I: Integer;
    Dummy: boolean;
  begin
    if C.GetExists then
    begin
      { go downward, from front to back.
        Important for controls watching/setting HandleInput,
        e.g. for sliders/OnScreenMenu to block the scene manager underneath
        from processing arrow keys. }
      I := C.ControlsCount - 1;
      while I >= 0 do
      begin
        // coded this way in case some Update method changes the Controls list
        if I < C.ControlsCount then
          RecursiveUpdate(C.Controls[I], HandleInput);
        Dec(I);
      end;

      if C <> ForceCaptureInput then
      begin
        { Although we call Update for all the existing controls, we look
          at CapturesEventsAtPosition and track HandleInput values.
          See TUIControl.Update for explanation. }
        if C.CapturesEventsAtPosition(MousePosition) then
        begin
          C.Update(Fps.SecondsPassed, HandleInput);
        end else
        begin
          { controls where CapturesEventsAtPosition = false always get
            HandleInput parameter set to false. }
          Dummy := false;
          C.Update(Fps.SecondsPassed, Dummy);
        end;
      end;
    end;
  end;

var
  I, J: Integer;
  HandleInput: boolean;
  Tx, Ty, Tz, TLength, Rx, Ry, Rz, RAngle: Double;
  Mouse3dPollSpeed: Single;
const
  Mouse3dPollDelay = 0.05;
begin
  Fps._UpdateBegin;

  UpdateTooltip;

  { 3D Mouse }
  if Assigned(Mouse3D) and Mouse3D.Loaded then
  begin
    Mouse3dPollTimer := Mouse3dPollTimer - Fps.SecondsPassed;
    if Mouse3dPollTimer < 0 then
    begin
      { get values from sensor }
      Mouse3dPollSpeed := -Mouse3dPollTimer + Mouse3dPollDelay;
      Tx := 0; { make sure they are initialized }
      Ty := 0;
      Tz := 0;
      TLength := 0;
      Mouse3D.GetSensorTranslation(Tx, Ty, Tz, TLength);
      Rx := 0; { make sure they are initialized }
      Ry := 0;
      Rz := 0;
      RAngle := 0;
      Mouse3D.GetSensorRotation(Rx, Ry, Rz, RAngle);

      { send to all 2D controls, including viewports }
      EventSensorTranslation(Tx, Ty, Tz, TLength, Mouse3dPollSpeed);
      EventSensorRotation(Rx, Ry, Rz, RAngle, Mouse3dPollSpeed);

      { set timer.
        The "repeat ... until" below should not be necessary under normal
        circumstances, as Mouse3dPollDelay should be much larger than typical
        frequency of how often this is checked. But we do it for safety
        (in case something else, like AI or collision detection,
        slows us down *a lot*). }
      repeat
        Mouse3dPollTimer := Mouse3dPollTimer + Mouse3dPollDelay;
      until Mouse3dPollTimer > 0;
    end;
  end;

  { Joysticks }
  if Assigned(Joysticks) then
  begin
    Joysticks.Poll;

    for I := 0 to Joysticks.JoyCount - 1 do
    begin
      for J := 0 to Joysticks.GetJoy(I)^.Info.Count.Buttons -1 do
      begin
        //Joysticks.Down(I, J);
        //Joysticks.Up(I, J);
        if Joysticks.Press(I, J) then
          EventJoyButtonPress(I, J);
      end;
      for J := 0 to Joysticks.GetJoy(I)^.Info.Count.Axes -1 do
      begin
        if Joysticks.AxisPos(I, J) <> 0 then
          EventJoyAxisMove(I, J);
      end;
    end;
  end;

  HandleInput := true;

  { ForceCaptureInput has the 1st chance to process inputs }
  if UseForceCaptureInput then
    ForceCaptureInput.Update(Fps.SecondsPassed, HandleInput);

  I := Controls.Count - 1;
  while I >= 0 do
  begin
    // coded this way in case some Update method changes the Controls list
    if I < Controls.Count then
      RecursiveUpdate(Controls[I], HandleInput);
    Dec(I);
  end;

  if Assigned(OnUpdate) then OnUpdate(Self);
end;

function TUIContainer.EventPress(const Event: TInputPressRelease): boolean;

  function RecursivePress(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(Event.Position)  then
    begin
      { try to pass press to C children }
      for I := C.ControlsCount - 1 downto 0 do
        { checking "I < C.ControlsCount" below is a poor safeguard in case
          some Press handler changes the Controls.Count.
          At least we will not crash. }
        if (I < C.ControlsCount) and RecursivePress(C.Controls[I]) then
          Exit(true);

      { try C.Press itself }
      if (C <> ForceCaptureInput) and C.Press(Event) then
      begin
        { We have to check whether C.Container = Self. That is because
          the implementation of control's Press method could remove itself
          from our Controls list. Consider e.g. TCastleOnScreenMenu.Press
          that may remove itself from the Window.Controls list when clicking
          "close menu" item. We cannot, in such case, save a reference to
          this control in FCaptureInput, because we should not speak with it
          anymore (we don't know when it's destroyed, we cannot call it's
          Release method because it has Container = nil, and so on). }
        if (Event.EventType = itMouseButton) and
           (C.Container = Self) then
          FCaptureInput.AddOrSetValue(Event.FingerIndex, C);
        Exit(true);
      end;
    end;

    Result := false;
  end;

var
  I: Integer;
begin
  Result := false;

  { pass to ForceCaptureInput }
  if UseForceCaptureInput then
  begin
    if ForceCaptureInput.Press(Event) then
      Exit(true);
  end;

  { pass to all Controls with TUIControl.Press event }
  for I := Controls.Count - 1 downto 0 do
    { checking "I < Controls.Count" below is a poor safeguard in case
      some Press handler changes the Controls.Count.
      At least we will not crash. }
    if (I < Controls.Count) and RecursivePress(Controls[I]) then
      Exit(true);

  { pass to container event }
  if Assigned(OnPress) then
  begin
    OnPress(Self, Event);
    Result := true;
  end;
end;

function TUIContainer.EventRelease(const Event: TInputPressRelease): boolean;

  function RecursiveRelease(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(Event.Position) then
    begin
      { try to pass release to C children }
      for I := C.ControlsCount - 1 downto 0 do
        if RecursiveRelease(C.Controls[I]) then
          Exit(true);

      { try C.Release itself }
      if (C <> ForceCaptureInput) and C.Release(Event) then
        Exit(true);
    end;

    Result := false;
  end;

var
  I: Integer;
  Capture: TUIControl;
begin
  Result := false;

  { pass to ForceCaptureInput }
  if UseForceCaptureInput then
  begin
    if ForceCaptureInput.Release(Event) then
      Exit(true);
  end;

  { pass to control holding capture }

  if not FCaptureInput.TryGetValue(Event.FingerIndex, Capture) then
    Capture := nil;

  if (Capture <> nil) and not Capture.GetExists then
  begin
    { No longer capturing, since the GetExists returns false now.
      We do not send any events to non-existing controls. }
    FCaptureInput.Remove(Event.FingerIndex);
    Capture := nil;
  end;

  if (Capture <> nil) and (MousePressed = []) then
  begin
    { No longer capturing, but do not set Capture to nil (it should receive the Release event). }
    FCaptureInput.Remove(Event.FingerIndex);
  end;

  if (Capture <> nil) and (Capture <> ForceCaptureInput) then
  begin
    Result := Capture.Release(Event);
    Exit; // if something is capturing the input, prevent other controls from getting the events
  end;

  { pass to all Controls with TUIControl.Release event }
  for I := Controls.Count - 1 downto 0 do
    if RecursiveRelease(Controls[I]) then
      Exit(true);

  { pass to container event }
  if Assigned(OnRelease) then
  begin
    OnRelease(Self, Event);
    Result := true;
  end;
end;

procedure TUIContainer.ReleaseCapture(const C: TUIControl);
var
  FingerIndex: TFingerIndex;
begin
  while TryGetFingerOfControl(C, FingerIndex) do
    FCaptureInput.Remove(FingerIndex);
end;

procedure TUIContainer.EventOpen(const OpenWindowsCount: Cardinal);

  procedure RecursiveGLContextOpen(const C: TUIControl);
  var
    I: Integer;
  begin
    for I := C.ControlsCount - 1 downto 0 do
      RecursiveGLContextOpen(C.Controls[I]);

    { Check here C.GLInitialized to not call C.GLContextOpen twice.
      Control may have GL resources already initialized if it was added
      e.g. from Application.OnInitialize before EventOpen. }
    if not C.GLInitialized then
      C.GLContextOpen;
  end;

var
  I: Integer;
begin
  if OpenWindowsCount = 1 then
    ApplicationProperties._GLContextOpen;

  { Call GLContextOpen on controls before OnOpen,
    this way OnOpen has controls with GLInitialized = true,
    so using SaveScreen etc. makes more sense there. }
  for I := Controls.Count - 1 downto 0 do
    RecursiveGLContextOpen(Controls[I]);

  if Assigned(OnOpen) then OnOpen(Self);
  if Assigned(OnOpenObject) then OnOpenObject(Self);
end;

procedure TUIContainer.EventClose(const OpenWindowsCount: Cardinal);

  procedure RecursiveGLContextClose(const C: TUIControl);
  var
    I: Integer;
  begin
    for I := C.ControlsCount - 1 downto 0 do
      RecursiveGLContextClose(C.Controls[I]);

    if C.GLInitialized then
      C.GLContextClose;
  end;

var
  I: Integer;
begin
  { Call GLContextClose on controls after OnClose,
    consistent with inverse order in OnOpen. }
  if Assigned(OnCloseObject) then OnCloseObject(Self);
  if Assigned(OnClose) then OnClose(Self);

  { call GLContextClose on controls before OnClose.
    This may be called from Close, which may be called from TCastleWindowCustom destructor,
    so prepare for Controls being possibly nil now. }
  if Controls <> nil then
    for I := Controls.Count - 1 downto 0 do
      RecursiveGLContextClose(Controls[I]);

  if OpenWindowsCount = 1 then
    ApplicationProperties._GLContextClose;
end;

function TUIContainer.AllowSuspendForInput: boolean;

  function RecursiveAllowSuspendForInput(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists then
    begin
      for I := C.ControlsCount - 1 downto 0 do
        if not RecursiveAllowSuspendForInput(C.Controls[I]) then
          Exit(false);

      if not C.AllowSuspendForInput then
        Exit(false);
    end;

    Result := true;
  end;

var
  I: Integer;
begin
  { Do not suspend when you're over a control that may have a tooltip,
    as EventUpdate must track and eventually show tooltip. }
  if (Focus.Count <> 0) and Focus.Last.TooltipExists then
    Exit(false);

  for I := Controls.Count - 1 downto 0 do
    if not RecursiveAllowSuspendForInput(Controls[I]) then
      Exit(false);

  Result := true;
end;

procedure TUIContainer.EventMotion(const Event: TInputMotion);

  function RecursiveMotion(const C: TUIControl): boolean;
  var
    I: Integer;
  begin
    if C.GetExists and C.CapturesEventsAtPosition(Event.Position) then
    begin
      { try to pass release to C children }
      for I := C.ControlsCount - 1 downto 0 do
        if RecursiveMotion(C.Controls[I]) then
          Exit(true);

      { try C.Motion itself }
      if (C <> ForceCaptureInput) and C.Motion(Event) then
        Exit(true);
    end;

    Result := false;
  end;

var
  I: Integer;
  Capture: TUIControl;
begin
  UpdateFocusAndMouseCursor;

  { pass to ForceCaptureInput }
  if UseForceCaptureInput then
  begin
    if ForceCaptureInput.Motion(Event) then
      Exit;
  end;

  { pass to control holding capture }

  if not FCaptureInput.TryGetValue(Event.FingerIndex, Capture) then
    Capture := nil;

  if (Capture <> nil) and not Capture.GetExists then
  begin
    { No longer capturing, since the GetExists returns false now.
      We do not send any events to non-existing controls. }
    FCaptureInput.Remove(Event.FingerIndex);
    Capture := nil;
  end;

  if (Capture <> nil) and (Capture <> ForceCaptureInput) then
  begin
    Capture.Motion(Event);
    Exit; // if something is capturing the input, prevent other controls from getting the events
  end;

  { pass to all Controls }
  for I := Controls.Count - 1 downto 0 do
    if RecursiveMotion(Controls[I]) then
      Exit;

  { pass to container event }
  if Assigned(OnMotion) then
    OnMotion(Self, Event);
end;

procedure TUIContainer.ControlsVisibleChange(Sender: TObject);
begin
  Invalidate;
end;

procedure TUIContainer.EventBeforeRender;

  procedure RecursiveBeforeRender(const C: TUIControl);
  var
    I: Integer;
  begin
    if C.GetExists then
    begin
      for I := C.ControlsCount - 1 downto 0 do
        RecursiveBeforeRender(C.Controls[I]);

      if C.GLInitialized then
        C.BeforeRender;
    end;
  end;

var
  I: Integer;
begin
  for I := Controls.Count - 1 downto 0 do
    RecursiveBeforeRender(Controls[I]);

  if Assigned(OnBeforeRender) then OnBeforeRender(Self);
end;

procedure TUIContainer.EventResize;

  procedure RecursiveResize(const C: TUIControl);
  var
    I: Integer;
  begin
    for I := C.ControlsCount - 1 downto 0 do
      RecursiveResize(C.Controls[I]);
    C.Resize;
  end;

var
  I: Integer;
begin
  if UIScaling in [usEncloseReferenceSize, usFitReferenceSize] then
    { usXxxReferenceSize adjust current Width/Height to reference,
      so the FCalculatedUIScale must be adjusted on each resize. }
    UpdateUIScale;

  for I := Controls.Count - 1 downto 0 do
    RecursiveResize(Controls[I]);

  { This way control's get Resize before our OnResize,
    useful to process them all reliably in OnResize. }
  if Assigned(OnResize) then OnResize(Self);
end;

function TUIContainer.Controls: TChildrenControls;
begin
  Result := TChildrenControls(FControls);
end;

function TUIContainer.IsMousePositionForMouseLook: boolean;
var
  P: TVector2;
begin
  P := MousePosition;
  Result := (P[0] = Width div 2) and (P[1] = Height div 2);
end;

procedure TUIContainer.MakeMousePositionForMouseLook;
begin
  { Paranoidally check is position different, to avoid setting
    MousePosition in every Update. Setting MousePosition should be optimized
    for this case (when position is already set), but let's check anyway.

    This also avoids infinite loop, when setting MousePosition,
    getting Motion event, setting MousePosition, getting Motion event...
    in a loop.
    Not really likely (as messages will be queued, and some
    MousePosition setting will finally just not generate event Motion),
    but I want to safeguard anyway. }

{
  WritelnLog('ml', Format('Mouse Position is %f,%f. Good for mouse look? %s. Setting pos to %f,%f if needed',
    [MousePosition[0],
     MousePosition[1],
     BoolToStr(IsMousePositionForMouseLook, true),
     Single(Width div 2),
     Single(Height div 2)]));
}

  if (not IsMousePositionForMouseLook) and Focused then
    { Note: setting to float position (ContainerWidth/2, ContainerHeight/2)
      seems simpler, but is risky: we if the backend doesn't support sub-pixel accuracy,
      we will never be able to position mouse exactly at half pixel. }
    MousePosition := Vector2(Width div 2, Height div 2);
end;

procedure TUIContainer.SetUIScaling(const Value: TUIScaling);
begin
  if FUIScaling <> Value then
  begin
    FUIScaling := Value;
    UpdateUIScale;
  end;
end;

procedure TUIContainer.SetUIReferenceWidth(const Value: Integer);
begin
  if FUIReferenceWidth <> Value then
  begin
    FUIReferenceWidth := Value;
    UpdateUIScale;
  end;
end;

procedure TUIContainer.SetUIReferenceHeight(const Value: Integer);
begin
  if FUIReferenceHeight <> Value then
  begin
    FUIReferenceHeight := Value;
    UpdateUIScale;
  end;
end;

procedure TUIContainer.SetUIExplicitScale(const Value: Single);
begin
  if FUIExplicitScale <> Value then
  begin
    FUIExplicitScale := Value;
    UpdateUIScale;
  end;
end;

function TUIContainer.DefaultUIScale: Single;
begin
  case UIScaling of
    usNone         : Result := 1;
    usExplicitScale: Result := UIExplicitScale;
    usEncloseReferenceSize, usFitReferenceSize:
      begin
        Result := 1;

        { don't do adjustment before our Width/Height are sensible }
        if not GLInitialized then Exit;

        if (UIReferenceWidth <> 0) and (Width > 0) then
        begin
          Result := Width / UIReferenceWidth;
          if (UIReferenceHeight <> 0) and (Height > 0) then
            if UIScaling = usEncloseReferenceSize then
              MinVar(Result, Height / UIReferenceHeight) else
              MaxVar(Result, Height / UIReferenceHeight);
        end else
        if (UIReferenceHeight <> 0) and (Height > 0) then
          Result := Height / UIReferenceHeight;
        WritelnLog('Scaling', 'Automatic scaling to reference sizes %dx%d in effect. Actual window size is %dx%d. Calculated scale is %f, which simulates surface of size %dx%d.',
          [UIReferenceWidth, UIReferenceHeight,
           Width, Height,
           Result, Round(Width / Result), Round(Height / Result)]);
      end;
    else raise EInternalError.Create('UIScaling unknown');
  end;
end;

procedure TUIContainer.UpdateUIScale;

  procedure RecursiveUIScaleChanged(const C: TUIControl);
  var
    I: Integer;
  begin
    for I := 0 to C.ControlsCount - 1 do
      RecursiveUIScaleChanged(C.Controls[I]);
    C.UIScaleChanged;
  end;

var
  I: Integer;
begin
  FCalculatedUIScale := DefaultUIScale;
  for I := 0 to Controls.Count - 1 do
    RecursiveUIScaleChanged(Controls[I]);
end;

function TUIContainer.UnscaledWidth: Cardinal;
begin
  Result := Round(Width / FCalculatedUIScale);
end;

function TUIContainer.UnscaledHeight: Cardinal;
begin
  Result := Round(Height / FCalculatedUIScale);
end;

function TUIContainer.UnscaledRect: TRectangle;
begin
  Result := Rect;
  if not Result.IsEmpty then
  begin
    Result.Width  := Round(Result.Width  / FCalculatedUIScale);
    Result.Height := Round(Result.Height / FCalculatedUIScale);
  end;
end;

procedure TUIContainer.SaveScreen(const URL: string);
var
  Image: TRGBImage;
begin
  Image := SaveScreen;
  try
    WritelnLog('SaveScreen', 'Screen saved to ' + URL);
    SaveImage(Image, URL);
  finally FreeAndNil(Image) end;
end;

function TUIContainer.SaveScreen: TRGBImage;
begin
  Result := SaveScreen(Rect);
end;

function TUIContainer.Dpi: Integer;
begin
  { Default implementation, if you cannot query real dpi value of the screen. }
  Result := DefaultDpi;
end;

function TUIContainer.Rect: TRectangle;
begin
  Result := Rectangle(0, 0, Width, Height);
end;

procedure TUIContainer.Invalidate;
begin
  { Default implementation, does nothing, assuming the main program redraws in a loop. }
end;

function TUIContainer.Focused: boolean;
begin
  { Default implementation, assuming that the context is always focused. }
  Result := true;
end;

procedure TUIContainer.SetInternalCursor(const Value: TMouseCursor);
begin
  { Default implementation, ignores new cursor value. }
end;

function TUIContainer.GetMousePosition: TVector2;
begin
  { Default implementation, assuming mouse is glued to the middle of the screen.
    Some methods, like TUIContainer.UpdateFocusAndMouseCursor,
    use this to calculate "focused" CGE control.

    This returns the same value as TUIContainer.MakeMousePositionForMouseLook sets,
    so the "mouse look" will report "no movement", which seems reasonable if we don't
    know mouse position.
  }
  Result := Vector2(Width div 2, Height div 2);
end;

procedure TUIContainer.SetMousePosition(const Value: TVector2);
begin
  { Default implementation, ignores new mouse position. }
end;

function TUIContainer.GetTouches(const Index: Integer): TTouch;
begin
  Assert(Index = 0, 'Base TUIContainer implementation does not support multi-touch, so you can only access Touches[0]');
  Result.FingerIndex := 0;
  Result.Position := MousePosition;
end;

function TUIContainer.TouchesCount: Integer;
begin
  Result := 1;
end;

function TUIContainer.GLInitialized: boolean;
begin
  { Default implementation, assuming the OpenGL context is always initialized. }
  Result := true;
end;

{ TInputListener ------------------------------------------------------------- }

constructor TInputListener.Create(AOwner: TComponent);
begin
  inherited;
  FExclusiveEvents := true;
  FCursor := mcDefault;
end;

function TInputListener.Press(const Event: TInputPressRelease): boolean;
begin
  Result := false;
end;

function TInputListener.Release(const Event: TInputPressRelease): boolean;
begin
  Result := false;
end;

function TInputListener.Motion(const Event: TInputMotion): boolean;
begin
  Result := false;
end;

function TInputListener.SensorRotation(const X, Y, Z, Angle: Double; const SecondsPassed: Single): boolean;
begin
  Result := false;
end;

function TInputListener.SensorTranslation(const X, Y, Z, Length: Double; const SecondsPassed: Single): boolean;
begin
  Result := false;
end;

function TInputListener.JoyAxisMove(const JoyID, Axis: Byte): boolean;
begin
  Result := False;
end;

function TInputListener.JoyButtonPress(const JoyID, Button: Byte): boolean;
begin
  Result := False;
end;

procedure TInputListener.Update(const SecondsPassed: Single;
  var HandleInput: boolean);
begin
end;

procedure TInputListener.VisibleChange(const RectOrCursorChanged: boolean = false);
begin
  if Assigned(OnVisibleChange) then
    OnVisibleChange(Self);
  if RectOrCursorChanged and (Container <> nil) then
    Container.UpdateFocusAndMouseCursor;
end;

function TInputListener.AllowSuspendForInput: boolean;
begin
  Result := true;
end;

procedure TInputListener.Resize;
begin
  {$warnings off}
  ContainerResize(ContainerWidth, ContainerHeight); // call deprecated, to keep it working
  {$warnings on}
end;

procedure TInputListener.ContainerResize(const AContainerWidth, AContainerHeight: Cardinal);
begin
end;

function TInputListener.ContainerWidth: Cardinal;
begin
  if ContainerSizeKnown then
    Result := Container.Width else
    Result := 0;
end;

function TInputListener.ContainerHeight: Cardinal;
begin
  if ContainerSizeKnown then
    Result := Container.Height else
    Result := 0;
end;

function TInputListener.ContainerRect: TRectangle;
begin
  if ContainerSizeKnown then
    Result := Container.Rect else
    Result := TRectangle.Empty;
end;

function TInputListener.ContainerSizeKnown: boolean;
begin
  { Note that ContainerSizeKnown is calculated looking at current Container,
    without waiting for Resize. This way it works even before
    we receive Resize method, which may happen to be useful:
    if you insert a SceneManager to a window before it's open (like it happens
    with standard scene manager in TCastleWindow and TCastleControl),
    and then you do something inside OnOpen that wants to render
    this viewport (which may happen if you simply initialize a progress bar
    without any predefined loading_image). Scene manager did not receive
    a Resize in this case yet (it will receive it from OnResize,
    which happens after OnOpen).

    See castle_game_engine/tests/testcontainer.pas for cases
    when this is really needed. }

  Result := (Container <> nil) and
    (not (csDestroying in Container.ComponentState)) and
    Container.GLInitialized;
end;

procedure TInputListener.SetCursor(const Value: TMouseCursor);
begin
  if Value <> FCursor then
  begin
    FCursor := Value;
    if Container <> nil then Container.UpdateFocusAndMouseCursor;
    DoCursorChange;
  end;
end;

procedure TInputListener.DoCursorChange;
begin
  if Assigned(OnCursorChange) then OnCursorChange(Self);
end;

procedure TInputListener.SetContainer(const Value: TUIContainer);
begin
  FContainer := Value;
end;

{ TUIControl ----------------------------------------------------------------- }

constructor TUIControl.Create(AOwner: TComponent);
begin
  inherited;
  FExists := true;
  FEnableUIScaling := true;
  FCapturesEvents := true;
end;

destructor TUIControl.Destroy;
begin
  GLContextClose;
  FreeAndNil(FControls);
  inherited;
end;

procedure TUIControl.CreateControls;
begin
  if FControls = nil then
  begin
    FControls := TChildrenControls.Create(Self);
    TChildrenControls(FControls).Container := Container;
  end;
end;

procedure TUIControl.InsertFront(const NewItem: TUIControl);
begin
  CreateControls;
  FControls.InsertFront(NewItem);
end;

procedure TUIControl.InsertFrontIfNotExists(const NewItem: TUIControl);
begin
  CreateControls;
  FControls.InsertFrontIfNotExists(NewItem);
end;

procedure TUIControl.InsertFront(const NewItems: TUIControlList);
begin
  CreateControls;
  FControls.InsertFront(NewItems);
end;

procedure TUIControl.InsertBack(const NewItem: TUIControl);
begin
  CreateControls;
  FControls.InsertBack(NewItem);
end;

procedure TUIControl.InsertBackIfNotExists(const NewItem: TUIControl);
begin
  CreateControls;
  FControls.InsertBackIfNotExists(NewItem);
end;

procedure TUIControl.InsertBack(const NewItems: TUIControlList);
begin
  CreateControls;
  FControls.InsertBack(NewItems);
end;

procedure TUIControl.RemoveControl(Item: TUIControl);
begin
  if FControls <> nil then
    FControls.Remove(Item);
end;

procedure TUIControl.ClearControls;
begin
  if FControls <> nil then
    FControls.Clear;
end;

function TUIControl.GetControls(const I: Integer): TUIControl;
begin
  Result := FControls[I];
end;

procedure TUIControl.SetControls(const I: Integer; const Item: TUIControl);
begin
  FControls[I] := Item;
end;

function TUIControl.ControlsCount: Integer;
begin
  if FControls <> nil then
    Result := FControls.Count else
    Result := 0;
end;

procedure TUIControl.SetContainer(const Value: TUIContainer);
var
  I: Integer;
begin
  inherited;
  if FControls <> nil then
  begin
    TChildrenControls(FControls).Container := Value;
    for I := 0 to FControls.Count - 1 do
      FControls[I].SetContainer(Value);
  end;
end;

procedure TUIControl.SetEnableUIScaling(const Value: boolean);
begin
  if FEnableUIScaling <> Value then
  begin
    FEnableUIScaling := Value;
    UIScaleChanged;
  end;
end;

function TUIControl.UIScale: Single;
begin
  if ContainerSizeKnown and EnableUIScaling then
    Result := Container.FCalculatedUIScale else
    Result := 1.0;
end;

function TUIControl.LeftBottomScaled: TVector2Integer;
begin
  Result := Vector2Integer(
    Round(UIScale * Left), Round(UIScale * Bottom));
end;

procedure TUIControl.UIScaleChanged;
begin
end;

{ No point in doing anything? We should propagate it to to parent like T3D?
procedure TUIControl.DoCursorChange;
begin
  inherited;
  if FControls <> nil then
    for I := 0 to FControls.Count - 1 do
      FControls[I].DoCursorChange;
end;
}

function TUIControl.CapturesEventsAtPosition(const Position: TVector2): boolean;
var
  SR: TRectangle;
begin
  if not CapturesEvents then
    Exit(false);

  SR := ScreenRect;
  Result := SR.Contains(Position) or
    { if the control covers the whole Container, it *always* captures events,
      even when mouse position is unknown yet, or outside the window. }
    (ContainerSizeKnown and
     (SR.Left <= 0) and
     (SR.Bottom <= 0) and
     (SR.Width >= ContainerWidth) and
     (SR.Height >= ContainerHeight));
end;

function TUIControl.TooltipExists: boolean;
begin
  Result := false;
end;

procedure TUIControl.BeforeRender;
begin
end;

procedure TUIControl.Render;
begin
end;

procedure TUIControl.RenderOverChildren;
begin
end;

function TUIControl.TooltipStyle: TRenderStyle;
begin
  Result := rs2D;
end;

procedure TUIControl.TooltipRender;
begin
end;

procedure TUIControl.GLContextOpen;
begin
  FGLInitialized := true;
end;

procedure TUIControl.GLContextClose;
begin
  FGLInitialized := false;
end;

function TUIControl.GetExists: boolean;
begin
  Result := FExists;
end;

procedure TUIControl.SetFocused(const Value: boolean);
begin
  FFocused := Value;
end;

procedure TUIControl.SetExists(const Value: boolean);
begin
  if FExists <> Value then
  begin
    FExists := Value;
    VisibleChange(true);
  end;
end;

{ We store Left property value in file under "tuicontrolpos_real_left" name,
  to avoid clashing with TComponent magic "left" property name.
  The idea how to do this is taken from TComponent's own implementation
  of it's "left" magic property (rtl/objpas/classes/compon.inc). }

procedure TUIControl.ReadRealLeft(Reader: TReader);
begin
  FLeft := Reader.ReadInteger;
end;

procedure TUIControl.WriteRealLeft(Writer: TWriter);
begin
  Writer.WriteInteger(FLeft);
end;

procedure TUIControl.ReadLeft(Reader: TReader);
var
  D: LongInt;
begin
  D := DesignInfo;
  LongRec(D).Lo:=Reader.ReadInteger;
  DesignInfo := D;
end;

procedure TUIControl.ReadTop(Reader: TReader);
var
  D: LongInt;
begin
  D := DesignInfo;
  LongRec(D).Hi:=Reader.ReadInteger;
  DesignInfo := D;
end;

procedure TUIControl.WriteLeft(Writer: TWriter);
begin
  Writer.WriteInteger(LongRec(DesignInfo).Lo);
end;

procedure TUIControl.WriteTop(Writer: TWriter);
begin
  Writer.WriteInteger(LongRec(DesignInfo).Hi);
end;

procedure TUIControl.DefineProperties(Filer: TFiler);
Var Ancestor : TComponent;
    Temp : longint;
begin
  { Don't call inherited that defines magic left/top.
    This would make reading design-time "left" broken, it seems that our
    declaration of Left with "stored false" would then prevent the design-time
    Left from ever loading.

    Instead, we'll save design-time "Left" below, under a special name. }

  Filer.DefineProperty('TUIControlPos_RealLeft',
    {$ifdef CASTLE_OBJFPC}@{$endif} ReadRealLeft,
    {$ifdef CASTLE_OBJFPC}@{$endif} WriteRealLeft,
    FLeft <> 0);

  { Code from fpc/trunk/rtl/objpas/classes/compon.inc }
  Temp:=0;
  Ancestor:=TComponent(Filer.Ancestor);
  If Assigned(Ancestor) then Temp:=Ancestor.DesignInfo;
  Filer.Defineproperty('TUIControlPos_Design_Left',
    {$ifdef CASTLE_OBJFPC}@{$endif} readleft,
    {$ifdef CASTLE_OBJFPC}@{$endif} writeleft,
    (longrec(DesignInfo).Lo<>Longrec(temp).Lo));
  Filer.Defineproperty('TUIControlPos_Design_Top',
    {$ifdef CASTLE_OBJFPC}@{$endif} readtop,
    {$ifdef CASTLE_OBJFPC}@{$endif} writetop,
    (longrec(DesignInfo).Hi<>Longrec(temp).Hi));
end;

procedure TUIControl.SetLeft(const Value: Integer);
begin
  if FLeft <> Value then
  begin
    FLeft := Value;
    VisibleChange(true);
  end;
end;

procedure TUIControl.SetBottom(const Value: Integer);
begin
  if FBottom <> Value then
  begin
    FBottom := Value;
    VisibleChange(true);
  end;
end;

procedure TUIControl.Align(
  const ControlPosition: THorizontalPosition;
  const ContainerPosition: THorizontalPosition;
  const X: Integer = 0);
begin
  Left := Rect.AlignCore(ControlPosition, ParentRect, ContainerPosition, X);
end;

procedure TUIControl.Align(
  const ControlPosition: TVerticalPosition;
  const ContainerPosition: TVerticalPosition;
  const Y: Integer = 0);
begin
  Bottom := Rect.AlignCore(ControlPosition, ParentRect, ContainerPosition, Y);
end;

procedure TUIControl.AlignHorizontal(
  const ControlPosition: TPositionRelative;
  const ContainerPosition: TPositionRelative;
  const X: Integer);
begin
  Align(
    THorizontalPosition(ControlPosition),
    THorizontalPosition(ContainerPosition), X);
end;

procedure TUIControl.AlignVertical(
  const ControlPosition: TPositionRelative;
  const ContainerPosition: TPositionRelative;
  const Y: Integer);
begin
  Align(
    TVerticalPosition(ControlPosition),
    TVerticalPosition(ContainerPosition), Y);
end;

procedure TUIControl.Center;
begin
  Align(hpMiddle, hpMiddle);
  Align(vpMiddle, vpMiddle);
end;

function TUIControl.Rect: TRectangle;
begin
  Result := Rectangle(LeftBottomScaled, 0, 0);
end;

function TUIControl.CalculatedRect: TRectangle;
begin
  Result := RectWithAnchors(true).ScaleAround0(1 / UIScale);
end;

function TUIControl.CalculatedWidth: Cardinal;
begin
  { Naive implementation:
  Result := CalculatedRect.Width; }

  { Optimized implementation, knowing that RectWithAnchors(true) does not
    change Rect.Width:
  Result := Rect.ScaleAround0(1 / UIScale).Width; }

  { Optimized implementation using ScaleWidthAround0: }
  Result := Rect.ScaleWidthAround0(1 / UIScale);
  //Assert(Result = CalculatedRect.Width);
end;

function TUIControl.CalculatedHeight: Cardinal;
begin
  Result := Rect.ScaleHeightAround0(1 / UIScale);
  //Assert(Result = CalculatedRect.Height);
end;

(*
function TUIControl.LocalRect: TRectangle;
begin
  {$warnings off}
  Result := Rect; // make deprecated Rect work by calling it here
  {$warnings off}
end;
*)

function TUIControl.RectWithAnchors(const CalculateEvenWithoutContainer: boolean): TRectangle;
var
  PR: TRectangle;
begin
  if (not ContainerSizeKnown) and
     (not CalculateEvenWithoutContainer) then
    { Don't call virtual Rect in this state, Rect implementations
      typically assume that ParentRect is sensible.
      This is crucial, various programs will crash without it. }
    Exit(TRectangle.Empty);

  Result := Rect;

  { apply anchors }
  if HasHorizontalAnchor or HasVerticalAnchor then
    PR := ParentRect;
  if HasHorizontalAnchor then
    Result.Left := Result.AlignCore(HorizontalAnchorSelf, PR, HorizontalAnchorParent,
      Round(UIScale * HorizontalAnchorDelta));
  if HasVerticalAnchor then
    Result.Bottom := Result.AlignCore(VerticalAnchorSelf, PR, VerticalAnchorParent,
      Round(UIScale * VerticalAnchorDelta));
end;

function TUIControl.ScreenRect: TRectangle;
var
  T: TVector2Integer;
begin
  Result := RectWithAnchors;
  { transform local to screen space }
  T := LocalToScreenTranslation;
  Result.Left := Result.Left + T[0];
  Result.Bottom := Result.Bottom + T[1];
end;

function TUIControl.LocalToScreenTranslation: TVector2Integer;
var
  RA: TRectangle;
begin
  if Parent <> nil then
  begin
    Result := Parent.LocalToScreenTranslation;
    RA := Parent.RectWithAnchors;
    Result.Data[0] := Result.Data[0] + RA.Left;
    Result.Data[1] := Result.Data[1] + RA.Bottom;
  end else
    Result := TVector2Integer.Zero;
end;

function TUIControl.ParentRect: TRectangle;
begin
  if Parent <> nil then
  begin
    Result := Parent.Rect;
    Result.Left := 0;
    Result.Bottom := 0;
  end else
    Result := ContainerRect;
end;

procedure TUIControl.SetHasHorizontalAnchor(const Value: boolean);
begin
  if FHasHorizontalAnchor <> Value then
  begin
    FHasHorizontalAnchor := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetHorizontalAnchorSelf(const Value: THorizontalPosition);
begin
  if FHorizontalAnchorSelf <> Value then
  begin
    FHorizontalAnchorSelf := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetHorizontalAnchorParent(const Value: THorizontalPosition);
begin
  if FHorizontalAnchorParent <> Value then
  begin
    FHorizontalAnchorParent := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetHorizontalAnchorDelta(const Value: Integer);
begin
  if FHorizontalAnchorDelta <> Value then
  begin
    FHorizontalAnchorDelta := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetHasVerticalAnchor(const Value: boolean);
begin
  if FHasVerticalAnchor <> Value then
  begin
    FHasVerticalAnchor := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetVerticalAnchorSelf(const Value: TVerticalPosition);
begin
  if FVerticalAnchorSelf <> Value then
  begin
    FVerticalAnchorSelf := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetVerticalAnchorParent(const Value: TVerticalPosition);
begin
  if FVerticalAnchorParent <> Value then
  begin
    FVerticalAnchorParent := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.SetVerticalAnchorDelta(const Value: Integer);
begin
  if FVerticalAnchorDelta <> Value then
  begin
    FVerticalAnchorDelta := Value;
    VisibleChange;
  end;
end;

procedure TUIControl.Anchor(const AHorizontalAnchor: THorizontalPosition;
  const AHorizontalAnchorDelta: Integer);
begin
  HasHorizontalAnchor := true;
  HorizontalAnchorSelf := AHorizontalAnchor;
  HorizontalAnchorParent := AHorizontalAnchor;
  HorizontalAnchorDelta := AHorizontalAnchorDelta;
end;

procedure TUIControl.Anchor(
  const AHorizontalAnchorSelf, AHorizontalAnchorParent: THorizontalPosition;
  const AHorizontalAnchorDelta: Integer);
begin
  HasHorizontalAnchor := true;
  HorizontalAnchorSelf := AHorizontalAnchorSelf;
  HorizontalAnchorParent := AHorizontalAnchorParent;
  HorizontalAnchorDelta := AHorizontalAnchorDelta;
end;

procedure TUIControl.Anchor(const AVerticalAnchor: TVerticalPosition;
  const AVerticalAnchorDelta: Integer);
begin
  HasVerticalAnchor := true;
  VerticalAnchorSelf := AVerticalAnchor;
  VerticalAnchorParent := AVerticalAnchor;
  VerticalAnchorDelta := AVerticalAnchorDelta;
end;

procedure TUIControl.Anchor(
  const AVerticalAnchorSelf, AVerticalAnchorParent: TVerticalPosition;
  const AVerticalAnchorDelta: Integer);
begin
  HasVerticalAnchor := true;
  VerticalAnchorSelf := AVerticalAnchorSelf;
  VerticalAnchorParent := AVerticalAnchorParent;
  VerticalAnchorDelta := AVerticalAnchorDelta;
end;

{ TUIControlSizeable --------------------------------------------------------- }

constructor TUIControlSizeable.Create(AOwner: TComponent);
begin
  inherited;
  FFullSize := false;
end;

function TUIControlSizeable.Rect: TRectangle;
begin
  if FullSize then
    Result := ParentRect else
  begin
    Result := Rectangle(Left, Bottom, Width, Height);
    // applying UIScale on this is easy...
    Result := Result.ScaleAround0(UIScale);
  end;
end;

procedure TUIControlSizeable.SetWidth(const Value: Cardinal);
begin
  if FWidth <> Value then
  begin
    FWidth := Value;
    VisibleChange(true);
  end;
end;

procedure TUIControlSizeable.SetHeight(const Value: Cardinal);
begin
  if FHeight <> Value then
  begin
    FHeight := Value;
    VisibleChange(true);
  end;
end;

procedure TUIControlSizeable.SetFullSize(const Value: boolean);
begin
  if FFullSize <> Value then
  begin
    FFullSize := Value;
    VisibleChange(true);
  end;
end;

{ TChildrenControls ------------------------------------------------------------- }

constructor TChildrenControls.Create(AParent: TUIControl);
begin
  inherited Create;
  FParent := AParent;
  FList := TMyObjectList.Create;
  FList.Parent := Self;
  FCaptureFreeNotifications := TCaptureFreeNotifications.Create(nil);
  FCaptureFreeNotifications.Parent := Self;
end;

destructor TChildrenControls.Destroy;
begin
  FreeAndNil(FList);
  FreeAndNil(FCaptureFreeNotifications);
  inherited;
end;

function TChildrenControls.GetItem(const I: Integer): TUIControl;
begin
  Result := TUIControl(FList.Items[I]);
end;

procedure TChildrenControls.SetItem(const I: Integer; const Item: TUIControl);
begin
  FList.Items[I] := Item;
end;

function TChildrenControls.Count: Integer;
begin
  Result := FList.Count;
end;

procedure TChildrenControls.BeginDisableContextOpenClose;
var
  I: Integer;
begin
  for I := 0 to FList.Count - 1 do
    with TUIControl(FList.Items[I]) do
      DisableContextOpenClose := DisableContextOpenClose + 1;
end;

procedure TChildrenControls.EndDisableContextOpenClose;
var
  I: Integer;
begin
  for I := 0 to FList.Count - 1 do
    with TUIControl(FList.Items[I]) do
      DisableContextOpenClose := DisableContextOpenClose - 1;
end;

procedure TChildrenControls.InsertFront(const NewItem: TUIControl);
begin
  Insert(Count, NewItem);
end;

procedure TChildrenControls.InsertFrontIfNotExists(const NewItem: TUIControl);
begin
  if FList.IndexOf(NewItem) = -1 then
    InsertFront(NewItem);
end;

procedure TChildrenControls.InsertFront(const NewItems: TUIControlList);
var
  I: Integer;
begin
  for I := 0 to NewItems.Count - 1 do
    InsertFront(NewItems[I]);
end;

procedure TChildrenControls.InsertBack(const NewItem: TUIControl);
begin
  FList.Insert(0, NewItem);
end;

procedure TChildrenControls.InsertBackIfNotExists(const NewItem: TUIControl);
begin
  if FList.IndexOf(NewItem) = -1 then
    InsertBack(NewItem);
end;

procedure TChildrenControls.Add(const Item: TUIControl);
begin
  InsertFront(Item);
end;

procedure TChildrenControls.Insert(Index: Integer; const Item: TUIControl);
var
  I: Integer;
begin
  { TODO: code duplicated with TUIControlList.InsertWithZOrder }
  Index := Clamped(Index, 0, Count);
  if Item.KeepInFront or
     (Count = 0) or
     (Index = 0) or
     (not Items[Index - 1].KeepInFront) then
    FList.Insert(Index, Item) else
  begin
    for I := Index - 1 downto 0 do
      if not Items[I].KeepInFront then
      begin
        FList.Insert(I + 1, Item);
        Exit;
      end;
    { everything has KeepInFront = true }
    FList.Insert(0, Item);
  end;
end;

procedure TChildrenControls.InsertIfNotExists(const Index: Integer; const NewItem: TUIControl);
begin
  Insert(Index, NewItem);
end;

procedure TChildrenControls.AddIfNotExists(const NewItem: TUIControl);
begin
  Insert(Count, NewItem);
end;

function TChildrenControls.IndexOf(const Item: TUIControl): Integer;
begin
  Result := FList.IndexOf(Item);
end;

procedure TChildrenControls.InsertBack(const NewItems: TUIControlList);
var
  I: Integer;
begin
  for I := NewItems.Count - 1 downto 0 do
    InsertBack(NewItems[I]);
end;

{$ifndef VER2_6}
function TChildrenControls.GetEnumerator: TEnumerator;
begin
  Result := TEnumerator.Create(Self);
end;
{$endif}

procedure TChildrenControls.Notify(Ptr: Pointer; Action: TListNotification);
var
  C: TUIControl;
begin
  { TODO: while this updating works cool,
    if the Parent or Container is destroyed
    before children --- the children will keep invalid reference. }

  C := TUIControl(Ptr);
  case Action of
    lnAdded:
      begin
        if ((C.FContainer <> nil) or (C.FParent <> nil)) and
           ((Container <> nil) or (FParent <> nil)) then
          WritelnWarning('UI', 'Inserting to the UI list (InsertFront, InsertBack) an item that is already a part of other UI list: ' + C.Name + ' (' + C.ClassName + '). The result is undefined, you cannot insert the same TUIControl instance multiple times.');
        C.FreeNotification(FCaptureFreeNotifications);
        if Container <> nil then RegisterContainer(C, FContainer);
        C.FParent := FParent;
      end;
    lnExtracted, lnDeleted:
      begin
        C.FParent := nil;
        if Container <> nil then UnregisterContainer(C, FContainer);
        C.RemoveFreeNotification(FCaptureFreeNotifications);
      end;
    else raise EInternalError.Create('TChildrenControls.Notify action?');
  end;

  { This notification may get called during FreeAndNil(FControls)
    in TUIContainer.Destroy. Then FControls is already nil, and we're
    getting remove notification for all items (as FreeAndNil first sets
    object to nil). Testcase: lets_take_a_walk exit. }
  if (FContainer <> nil) and
     (FContainer.FControls <> nil) then
  begin
    FContainer.UpdateFocusAndMouseCursor;
    FContainer.Invalidate;
  end;
end;

procedure TChildrenControls.TCaptureFreeNotifications.Notification(AComponent: TComponent; Operation: TOperation);
begin
  inherited;

  { We have to remove a reference to the object from list.
    This is crucial, various methods assume that all objects on
    the list are always valid objects (no invalid references,
    even for a short time). }

  if (Operation = opRemove) and (AComponent is TUIControl) then
    Parent.FList.Remove(AComponent);
end;

procedure TChildrenControls.Assign(const Source: TChildrenControls);
begin
  FList.Assign(Source.FList);
end;

procedure TChildrenControls.Remove(const Item: TUIControl);
begin
  FList.Remove(Item);
end;

procedure TChildrenControls.Clear;
begin
  FList.Clear;
end;

function TChildrenControls.MakeSingle(ReplaceClass: TUIControlClass; NewItem: TUIControl;
  AddFront: boolean): TUIControl;
begin
  Result := FList.MakeSingle(ReplaceClass, NewItem, AddFront) as TUIControl;
end;

procedure TChildrenControls.RegisterContainer(
  const C: TUIControl; const AContainer: TUIContainer);
begin
  { Make sure AContainer.ControlsVisibleChange (which in turn calls Invalidate)
    will be called when a control calls OnVisibleChange.

    We only change OnVisibleChange from @nil to it's own internal callback
    (when adding a control), and from it's own internal callback to @nil
    (when removing a control).
    This means that if user code will assign OnVisibleChange callback to some
    custom method --- we will not touch it anymore. That's safer.
    Athough in general user code should not change OnVisibleChange for controls
    on this list, to keep automatic Invalidate working. }
  if not Assigned(C.OnVisibleChange) then
    C.OnVisibleChange :=
      {$ifdef CASTLE_OBJFPC}@{$endif} AContainer.ControlsVisibleChange;

  { Register AContainer to be notified of control destruction. }
  C.FreeNotification(AContainer);

  C.Container := AContainer;
  C.UIScaleChanged;

  if AContainer.GLInitialized then
  begin
    if C.DisableContextOpenClose = 0 then
      C.GLContextOpen;
    AContainer.Invalidate;
    { Call initial Resize for control.
      If window OpenGL context is not yet initialized, defer it to
      the Open time, then our initial EventResize will be called
      that will do Resize on every control. }
    C.Resize;
  end;
end;

procedure TChildrenControls.UnregisterContainer(
  const C: TUIControl; const AContainer: TUIContainer);
var
  MyMethod: TNotifyEvent;
begin
  if AContainer.GLInitialized and
     (C.DisableContextOpenClose = 0) then
    C.GLContextClose;

  MyMethod := {$ifdef CASTLE_OBJFPC}@{$endif} AContainer.ControlsVisibleChange;
  if CompareMethods(TMethod(C.OnVisibleChange), TMethod(MyMethod)) then
    C.OnVisibleChange := nil;

  C.RemoveFreeNotification(AContainer);
  AContainer.DetachNotification(C);

  C.Container := nil;
end;

procedure TChildrenControls.SetContainer(const AContainer: TUIContainer);
var
  I: Integer;
begin
  if FContainer <> AContainer then
  begin
    if FContainer <> nil then
      for I := 0 to Count - 1 do
        UnregisterContainer(Items[I], FContainer);
    FContainer := AContainer;
    if FContainer <> nil then
      for I := 0 to Count - 1 do
        RegisterContainer(Items[I], FContainer);
  end;
end;

{ TChildrenControls.TMyObjectList ----------------------------------------------- }

procedure TChildrenControls.TMyObjectList.Notify(Ptr: Pointer; Action: TListNotification);
begin
  Parent.Notify(Ptr, Action);
end;

{ TChildrenControls.TEnumerator ------------------------------------------------- }

{$ifndef VER2_6}
function TChildrenControls.TEnumerator.GetCurrent: TUIControl;
begin
  Result := FList.Items[FPosition];
end;

constructor TChildrenControls.TEnumerator.Create(AList: TChildrenControls);
begin
  inherited Create;
  FList := AList;
  FPosition := -1;
end;

function TChildrenControls.TEnumerator.MoveNext: Boolean;
begin
  Inc(FPosition);
  Result := FPosition < FList.Count;
end;
{$endif}

{ TUIControlList ------------------------------------------------------------- }

procedure TUIControlList.InsertFront(const NewItem: TUIControl);
begin
  InsertWithZOrder(Count, NewItem);
end;

procedure TUIControlList.InsertFrontIfNotExists(const NewItem: TUIControl);
begin
  if IndexOf(NewItem) = -1 then
    InsertFront(NewItem);
end;

procedure TUIControlList.InsertFront(const NewItems: TUIControlList);
var
  I: Integer;
begin
  for I := 0 to NewItems.Count - 1 do
    InsertFront(NewItems[I]);
end;

procedure TUIControlList.InsertBack(const NewItem: TUIControl);
begin
  InsertWithZOrder(0, NewItem);
end;

procedure TUIControlList.InsertBackIfNotExists(const NewItem: TUIControl);
begin
  if IndexOf(NewItem) = -1 then
    InsertBack(NewItem);
end;

procedure TUIControlList.InsertBack(const NewItems: TUIControlList);
var
  I: Integer;
begin
  for I := NewItems.Count - 1 downto 0 do
    InsertBack(NewItems[I]);
end;

procedure TUIControlList.InsertWithZOrder(Index: Integer; const Item: TUIControl);
var
  I: Integer;
begin
  Index := Clamped(Index, 0, Count);
  if Item.KeepInFront or
     (Count = 0) or
     (Index = 0) or
     (not Items[Index - 1].KeepInFront) then
    Insert(Index, Item) else
  begin
    for I := Index - 1 downto 0 do
      if not Items[I].KeepInFront then
      begin
        Insert(I + 1, Item);
        Exit;
      end;
    { everything has KeepInFront = true }
    Insert(0, Item);
  end;
end;

{ globals -------------------------------------------------------------------- }

function OnGLContextOpen: TGLContextEventList;
begin
  Result := ApplicationProperties.OnGLContextOpen;
end;

function OnGLContextClose: TGLContextEventList;
begin
  Result := ApplicationProperties.OnGLContextClose;
end;

function IsGLContextOpen: boolean;
begin
  Result := ApplicationProperties.IsGLContextOpen;
end;

end.