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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>

#include <o3tl/safeint.hxx>
#include <vcl/svapp.hxx>
#include <vcl/salnativewidgets.hxx>
#include <vcl/help.hxx>
#include <vcl/settings.hxx>
#include <vcl/commandevent.hxx>

#include <cstdlib>
#include <memory>
#include <stack>

#include <vcl/treelistbox.hxx>
#include <vcl/svlbitm.hxx>
#include <tools/wintypes.hxx>
#include <bitmaps.hlst>
#include <svimpbox.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <tools/debug.hxx>

#include <vcl/treelistentry.hxx>
#include <vcl/viewdataentry.hxx>

// #i27063# (pl), #i32300# (pb) never access VCL after DeInitVCL - also no destructors
Image*  SvImpLBox::s_pDefCollapsed      = nullptr;
Image*  SvImpLBox::s_pDefExpanded       = nullptr;
oslInterlockedCount SvImpLBox::s_nImageRefCount   = 0;

SvImpLBox::SvImpLBox( SvTreeListBox* pLBView, SvTreeList* pLBTree, WinBits nWinStyle)
    : m_aHorSBar(VclPtr<ScrollBar>::Create(pLBView, WB_DRAG | WB_HSCROLL))
    , m_aScrBarBox(VclPtr<ScrollBarBox>::Create(pLBView))
    , m_aFctSet(this, pLBView)
    , mbForceMakeVisible (false)
    , m_aVerSBar(VclPtr<ScrollBar>::Create(pLBView, WB_DRAG | WB_VSCROLL))
    , m_aOutputSize(0, 0)
    , mbNoAutoCurEntry(false)
    , m_aSelEng(pLBView, nullptr)
    , m_nNextVerVisSize(0)
{
    osl_atomic_increment(&s_nImageRefCount);
    m_pView = pLBView;
    m_pTree = pLBTree;
    m_aSelEng.SetFunctionSet( static_cast<FunctionSet*>(&m_aFctSet) );
    m_aSelEng.ExpandSelectionOnMouseMove( false );
    SetStyle( nWinStyle );
    SetSelectionMode( SelectionMode::Single );
    SetDragDropMode( DragDropMode::NONE );

    m_aVerSBar->SetScrollHdl( LINK( this, SvImpLBox, ScrollUpDownHdl ) );
    m_aHorSBar->SetScrollHdl( LINK( this, SvImpLBox, ScrollLeftRightHdl ) );
    m_aHorSBar->SetEndScrollHdl( LINK( this, SvImpLBox, EndScrollHdl ) );
    m_aVerSBar->SetEndScrollHdl( LINK( this, SvImpLBox, EndScrollHdl ) );
    m_aVerSBar->SetRange( Range(0,0) );
    m_aVerSBar->Hide();
    m_aHorSBar->SetRange( Range(0,0) );
    m_aHorSBar->SetPageSize( 24 ); // pixels
    m_aHorSBar->SetLineSize( 8 ); // pixels

    m_nHorSBarHeight = static_cast<short>(m_aHorSBar->GetSizePixel().Height());
    m_nVerSBarWidth = static_cast<short>(m_aVerSBar->GetSizePixel().Width());

    m_pStartEntry = nullptr;
    m_pCursor             = nullptr;
    m_pAnchor             = nullptr;
    m_nVisibleCount       = 0;    // number of rows of data in control
    m_nNodeBmpTabDistance = NODE_BMP_TABDIST_NOTVALID;
    m_nNodeBmpWidth       = 0;

    // button animation in listbox
    m_pActiveButton = nullptr;
    m_pActiveEntry = nullptr;
    m_pActiveTab = nullptr;

    m_nFlags = LBoxFlags::NONE;

    m_aEditIdle.SetPriority( TaskPriority::LOWEST );
    m_aEditIdle.SetInvokeHandler( LINK(this,SvImpLBox,EditTimerCall) );

    m_nMostRight = -1;
    m_pMostRightEntry = nullptr;
    m_nCurUserEvent = nullptr;

    m_bUpdateMode = true;
    m_bInVScrollHdl = false;
    m_nFlags |= LBoxFlags::Filling;

    m_bSubLstOpLR = m_bContextMenuHandling = false;
}

SvImpLBox::~SvImpLBox()
{
    m_aEditIdle.Stop();
    StopUserEvent();

    if ( osl_atomic_decrement(&s_nImageRefCount) == 0 )
    {
        DELETEZ(s_pDefCollapsed);
        DELETEZ(s_pDefExpanded);
    }
    m_aVerSBar.disposeAndClear();
    m_aHorSBar.disposeAndClear();
    m_aScrBarBox.disposeAndClear();
}

void SvImpLBox::UpdateStringSorter()
{
    const css::lang::Locale& rNewLocale = Application::GetSettings().GetLanguageTag().getLocale();

    if( m_pStringSorter )
    {
        // different Locale from the older one, drop it and force recreate
        const css::lang::Locale &aLocale = m_pStringSorter->getLocale();
        if( aLocale.Language != rNewLocale.Language ||
            aLocale.Country != rNewLocale.Country ||
            aLocale.Variant != rNewLocale.Variant )
            m_pStringSorter.reset();
    }

    if( !m_pStringSorter )
    {
        m_pStringSorter.reset(new comphelper::string::NaturalStringSorter(
                              ::comphelper::getProcessComponentContext(),
                              rNewLocale));
    }
}

short SvImpLBox::UpdateContextBmpWidthVector( SvTreeListEntry const * pEntry, short nWidth )
{
    DBG_ASSERT( m_pView->pModel, "View and Model aren't valid!" );

    sal_uInt16 nDepth = m_pView->pModel->GetDepth( pEntry );
    // initialize vector if necessary
    std::vector< short >::size_type nSize = m_aContextBmpWidthVector.size();
    while ( nDepth > nSize )
    {
        m_aContextBmpWidthVector.resize( nSize + 1 );
        m_aContextBmpWidthVector.at( nSize ) = nWidth;
        ++nSize;
    }
    if( m_aContextBmpWidthVector.size() == nDepth )
    {
        m_aContextBmpWidthVector.resize( nDepth + 1 );
        m_aContextBmpWidthVector.at( nDepth ) = 0;
    }
    short nContextBmpWidth = m_aContextBmpWidthVector[ nDepth ];
    if( nContextBmpWidth < nWidth )
    {
        m_aContextBmpWidthVector.at( nDepth ) = nWidth;
        return nWidth;
    }
    else
        return nContextBmpWidth;
}

void SvImpLBox::UpdateContextBmpWidthVectorFromMovedEntry( SvTreeListEntry* pEntry )
{
    DBG_ASSERT( pEntry, "Moved Entry is invalid!" );

    SvLBoxContextBmp* pBmpItem = static_cast< SvLBoxContextBmp* >( pEntry->GetFirstItem(SvLBoxItemType::ContextBmp) );
    short nExpWidth = static_cast<short>(pBmpItem->GetBitmap1().GetSizePixel().Width());
    short nColWidth = static_cast<short>(pBmpItem->GetBitmap2().GetSizePixel().Width());
    short nMax = std::max(nExpWidth, nColWidth);
    UpdateContextBmpWidthVector( pEntry, nMax );

    if( pEntry->HasChildren() ) // recursive call, whether expanded or not
    {
        SvTreeListEntry* pChild = m_pView->FirstChild( pEntry );
        DBG_ASSERT( pChild, "The first child is invalid!" );
        do
        {
            UpdateContextBmpWidthVectorFromMovedEntry( pChild );
            pChild = m_pView->Next( pChild );
        } while ( pChild );
    }
}

void SvImpLBox::UpdateContextBmpWidthMax( SvTreeListEntry const * pEntry )
{
    sal_uInt16 nDepth = m_pView->pModel->GetDepth( pEntry );
    if( m_aContextBmpWidthVector.empty() )
        return;
    short nWidth = m_aContextBmpWidthVector[ nDepth ];
    if( nWidth != m_pView->nContextBmpWidthMax ) {
        m_pView->nContextBmpWidthMax = nWidth;
        m_nFlags |= LBoxFlags::IgnoreChangedTabs;
        m_pView->SetTabs();
        m_nFlags &= ~LBoxFlags::IgnoreChangedTabs;
    }
}

void SvImpLBox::SetStyle( WinBits i_nWinStyle )
{
    m_nStyle = i_nWinStyle;
    if ( ( m_nStyle & WB_SIMPLEMODE) && ( m_aSelEng.GetSelectionMode() == SelectionMode::Multiple ) )
        m_aSelEng.AddAlways( true );
}

void SvImpLBox::SetNoAutoCurEntry( bool b )
{
    mbNoAutoCurEntry = b;
}

// don't touch the model any more
void SvImpLBox::Clear()
{
    StopUserEvent();
    m_pStartEntry = nullptr;
    m_pAnchor = nullptr;

    m_pActiveButton = nullptr;
    m_pActiveEntry = nullptr;
    m_pActiveTab = nullptr;

    m_nMostRight = -1;
    m_pMostRightEntry = nullptr;

    // don't touch the cursor any more
    if( m_pCursor )
    {
        if( m_pView->HasFocus() )
            m_pView->HideFocus();
        m_pCursor = nullptr;
    }
    m_aVerSBar->Hide();
    m_aVerSBar->SetThumbPos( 0 );
    Range aRange( 0, 0 );
    m_aVerSBar->SetRange( aRange );
    m_aOutputSize = m_pView->Control::GetOutputSizePixel();
    m_aHorSBar->Hide();
    m_aHorSBar->SetThumbPos( 0 );
    MapMode aMapMode( m_pView->GetMapMode());
    aMapMode.SetOrigin( Point(0,0) );
    m_pView->Control::SetMapMode( aMapMode );
    m_aHorSBar->SetRange( aRange );
    m_aHorSBar->SetSizePixel(Size(m_aOutputSize.Width(),m_nHorSBarHeight));
    m_pView->SetClipRegion();
    if( GetUpdateMode() )
        m_pView->Invalidate( GetVisibleArea() );
    m_nFlags |= LBoxFlags::Filling;
    if( !m_aHorSBar->IsVisible() && !m_aVerSBar->IsVisible() )
        m_aScrBarBox->Hide();

    m_aContextBmpWidthVector.clear();

    CallEventListeners( VclEventId::ListboxItemRemoved );
}

// *********************************************************************
// Paint, navigate, scroll
// *********************************************************************

IMPL_LINK_NOARG(SvImpLBox, EndScrollHdl, ScrollBar*, void)
{
    if( m_nFlags & LBoxFlags::EndScrollSetVisSize )
    {
        m_aVerSBar->SetVisibleSize( m_nNextVerVisSize );
        m_nFlags &= ~LBoxFlags::EndScrollSetVisSize;
    }
    EndScroll();
}

// handler for vertical scrollbar

IMPL_LINK( SvImpLBox, ScrollUpDownHdl, ScrollBar *, pScrollBar, void )
{
    DBG_ASSERT(!m_bInVScrollHdl,"Scroll handler out-paces itself!");
    long nDelta = pScrollBar->GetDelta();
    if( !nDelta )
        return;

    m_nFlags &= ~LBoxFlags::Filling;

    m_bInVScrollHdl = true;

    if( m_pView->IsEditingActive() )
    {
        m_pView->EndEditing( true ); // Cancel
        m_pView->PaintImmediately();
    }
    BeginScroll();

    if( nDelta > 0 )<--- Assuming that condition 'nDelta>0' is not redundant
    {
        if( nDelta == 1 )
            CursorDown();
        else
            PageDown( static_cast<sal_uInt16>(nDelta) );
    }
    else
    {
        nDelta *= -1;<--- Compound assignment '*=', assigned value is -1
        if( nDelta == 1 )<--- Condition 'nDelta==1' is always false
            CursorUp();
        else
            PageUp( static_cast<sal_uInt16>(nDelta) );
    }
    m_bInVScrollHdl = false;
}


void SvImpLBox::CursorDown()
{
    if (!m_pStartEntry)
        return;

    SvTreeListEntry* pNextFirstToDraw = m_pView->NextVisible(m_pStartEntry);
    if( pNextFirstToDraw )
    {
        m_nFlags &= ~LBoxFlags::Filling;
        ShowCursor( false );
        m_pView->PaintImmediately();
        m_pStartEntry = pNextFirstToDraw;
        tools::Rectangle aArea( GetVisibleArea() );
        m_pView->Scroll( 0, -(m_pView->GetEntryHeight()), aArea, ScrollFlags::NoChildren );
        m_pView->PaintImmediately();
        ShowCursor( true );
        m_pView->NotifyScrolled();
    }
}

void SvImpLBox::CursorUp()
{
    if (!m_pStartEntry)
        return;

    SvTreeListEntry* pPrevFirstToDraw = m_pView->PrevVisible(m_pStartEntry);
    if( !pPrevFirstToDraw )
        return;

    m_nFlags &= ~LBoxFlags::Filling;
    long nEntryHeight = m_pView->GetEntryHeight();
    ShowCursor( false );
    m_pView->PaintImmediately();
    m_pStartEntry = pPrevFirstToDraw;
    tools::Rectangle aArea( GetVisibleArea() );
    aArea.AdjustBottom( -nEntryHeight );
    m_pView->Scroll( 0, nEntryHeight, aArea, ScrollFlags::NoChildren );
    m_pView->PaintImmediately();
    ShowCursor( true );
    m_pView->NotifyScrolled();
}

void SvImpLBox::PageDown( sal_uInt16 nDelta )
{
    sal_uInt16 nRealDelta = nDelta;

    if( !nDelta )
        return;

    if (!m_pStartEntry)
        return;

    SvTreeListEntry* pNext = m_pView->NextVisible(m_pStartEntry, nRealDelta);
    if( pNext == m_pStartEntry )
        return;

    ShowCursor( false );

    m_nFlags &= ~LBoxFlags::Filling;
    m_pStartEntry = pNext;

    if( nRealDelta >= m_nVisibleCount )
    {
        m_pView->Invalidate( GetVisibleArea() );
        m_pView->PaintImmediately();
    }
    else
    {
        tools::Rectangle aArea( GetVisibleArea() );
        long nScroll = m_pView->GetEntryHeight() * static_cast<long>(nRealDelta);
        nScroll = -nScroll;
        m_pView->PaintImmediately();
        m_pView->Scroll( 0, nScroll, aArea, ScrollFlags::NoChildren );
        m_pView->PaintImmediately();
        m_pView->NotifyScrolled();
    }

    ShowCursor( true );
}

void SvImpLBox::PageUp( sal_uInt16 nDelta )
{
    sal_uInt16 nRealDelta = nDelta;
    if( !nDelta )
        return;

    if (!m_pStartEntry)
        return;

    SvTreeListEntry* pPrev = m_pView->PrevVisible(m_pStartEntry, nRealDelta);
    if( pPrev == m_pStartEntry )
        return;

    m_nFlags &= ~LBoxFlags::Filling;
    ShowCursor( false );

    m_pStartEntry = pPrev;
    if( nRealDelta >= m_nVisibleCount )
    {
        m_pView->Invalidate( GetVisibleArea() );
        m_pView->PaintImmediately();
    }
    else
    {
        long nEntryHeight = m_pView->GetEntryHeight();
        tools::Rectangle aArea( GetVisibleArea() );
        m_pView->PaintImmediately();
        m_pView->Scroll( 0, nEntryHeight*nRealDelta, aArea, ScrollFlags::NoChildren );
        m_pView->PaintImmediately();
        m_pView->NotifyScrolled();
    }

    ShowCursor( true );
}

void SvImpLBox::KeyUp( bool bPageUp )
{
    if( !m_aVerSBar->IsVisible() )
        return;

    long nDelta;
    if( bPageUp )
        nDelta = m_aVerSBar->GetPageSize();
    else
        nDelta = 1;

    long nThumbPos = m_aVerSBar->GetThumbPos();

    if( nThumbPos < nDelta )
        nDelta = nThumbPos;

    if( nDelta <= 0 )
        return;

    m_nFlags &= ~LBoxFlags::Filling;
    BeginScroll();

    m_aVerSBar->SetThumbPos( nThumbPos - nDelta );
    if( bPageUp )
        PageUp( static_cast<short>(nDelta) );
    else
        CursorUp();

    EndScroll();
}


void SvImpLBox::KeyDown( bool bPageDown )
{
    if( !m_aVerSBar->IsVisible() )
        return;

    long nDelta;
    if( bPageDown )
        nDelta = m_aVerSBar->GetPageSize();
    else
        nDelta = 1;

    long nThumbPos = m_aVerSBar->GetThumbPos();
    long nVisibleSize = m_aVerSBar->GetVisibleSize();
    long nRange = m_aVerSBar->GetRange().Len();

    long nTmp = nThumbPos+nVisibleSize;
    while( (nDelta > 0) && (nTmp+nDelta) >= nRange )
        nDelta--;

    if( nDelta <= 0 )
        return;

    m_nFlags &= ~LBoxFlags::Filling;
    BeginScroll();

    m_aVerSBar->SetThumbPos( nThumbPos+nDelta );
    if( bPageDown )
        PageDown( static_cast<short>(nDelta) );
    else
        CursorDown();

    EndScroll();
}


void SvImpLBox::InvalidateEntriesFrom( long nY ) const
{
    if( !(m_nFlags & LBoxFlags::InPaint ))
    {
        tools::Rectangle aRect( GetVisibleArea() );
        aRect.SetTop( nY );
        m_pView->Invalidate( aRect );
    }
}

void SvImpLBox::InvalidateEntry( long nY ) const
{
    if( !(m_nFlags & LBoxFlags::InPaint ))
    {
        tools::Rectangle aRect( GetVisibleArea() );
        long nMaxBottom = aRect.Bottom();
        aRect.SetTop( nY );
        aRect.SetBottom( nY ); aRect.AdjustBottom(m_pView->GetEntryHeight() );
        if( aRect.Top() > nMaxBottom )
            return;
        if( aRect.Bottom() > nMaxBottom )
            aRect.SetBottom( nMaxBottom );
        if (m_pView->SupportsDoubleBuffering())
            // Perform full paint when flicker is to be avoided explicitly.
            m_pView->Invalidate();
        else
            m_pView->Invalidate(aRect);
    }
}

void SvImpLBox::InvalidateEntry( SvTreeListEntry* pEntry )
{
    if( GetUpdateMode() )
    {
        long nPrev = m_nMostRight;
        SetMostRight( pEntry );
        if( nPrev < m_nMostRight )
            ShowVerSBar();
    }
    if( !(m_nFlags & LBoxFlags::InPaint ))
    {
        bool bHasFocusRect = false;
        if( pEntry==m_pCursor && m_pView->HasFocus() )
        {
            bHasFocusRect = true;
            ShowCursor( false );
        }
        InvalidateEntry( GetEntryLine( pEntry ) );
        if( bHasFocusRect )
            ShowCursor( true );
    }
}


void SvImpLBox::RecalcFocusRect()
{
    if( m_pView->HasFocus() && m_pCursor )
    {
        m_pView->HideFocus();
        long nY = GetEntryLine( m_pCursor );
        tools::Rectangle aRect = m_pView->GetFocusRect( m_pCursor, nY );
        vcl::Region aOldClip( m_pView->GetClipRegion());
        vcl::Region aClipRegion( GetClipRegionRect() );
        m_pView->SetClipRegion( aClipRegion );
        m_pView->ShowFocus( aRect );
        m_pView->SetClipRegion( aOldClip );
    }
}


//  Sets cursor. When using SingleSelection, the selection is adjusted.
void SvImpLBox::SetCursor( SvTreeListEntry* pEntry, bool bForceNoSelect )
{
    SvViewDataEntry* pViewDataNewCur = nullptr;
    if( pEntry )
        pViewDataNewCur= m_pView->GetViewDataEntry(pEntry);
    if( pEntry &&
        pEntry == m_pCursor &&
        pViewDataNewCur &&
        pViewDataNewCur->HasFocus() &&
        pViewDataNewCur->IsSelected())
    {
        return;
    }

    // if this cursor is not selectable, find first visible that is and use it
    while( pEntry && pViewDataNewCur && !pViewDataNewCur->IsSelectable() )
    {
        pEntry = m_pView->NextVisible(pEntry);
        pViewDataNewCur = pEntry ? m_pView->GetViewDataEntry(pEntry) : nullptr;
    }

    SvTreeListEntry* pOldCursor = m_pCursor;
    if( m_pCursor && pEntry != m_pCursor )
    {
        m_pView->SetEntryFocus( m_pCursor, false );
        if( m_bSimpleTravel )
            m_pView->Select( m_pCursor, false );
        m_pView->HideFocus();
    }
    m_pCursor = pEntry;
    if( m_pCursor )
    {
        if (pViewDataNewCur)
            pViewDataNewCur->SetFocus( true );
        if(!bForceNoSelect && m_bSimpleTravel && !(m_nFlags & LBoxFlags::DeselectAll) && GetUpdateMode())
        {
            m_pView->Select( m_pCursor );
            CallEventListeners( VclEventId::ListboxTreeFocus, m_pCursor );
        }
        // multiple selection: select in cursor move if we're not in
        // Add mode (Ctrl-F8)
        else if( GetUpdateMode() &&
                 m_pView->GetSelectionMode() == SelectionMode::Multiple &&
                 !(m_nFlags & LBoxFlags::DeselectAll) && !m_aSelEng.IsAddMode() &&
                 !bForceNoSelect )
        {
            m_pView->Select( m_pCursor );
            CallEventListeners( VclEventId::ListboxTreeFocus, m_pCursor );
        }
        else
        {
            ShowCursor( true );
            if (bForceNoSelect && GetUpdateMode())
            {
                CallEventListeners( VclEventId::ListboxTreeFocus, m_pCursor);
            }
        }

        if( m_pAnchor )
        {
            DBG_ASSERT(m_aSelEng.GetSelectionMode() != SelectionMode::Single,"Mode?");
            SetAnchorSelection( pOldCursor, m_pCursor );
        }
    }
    m_nFlags &= ~LBoxFlags::DeselectAll;

    m_pView->OnCurrentEntryChanged();
}

void SvImpLBox::ShowCursor( bool bShow )
{
    if( !bShow || !m_pCursor || !m_pView->HasFocus() )
    {
        vcl::Region aOldClip( m_pView->GetClipRegion());
        vcl::Region aClipRegion( GetClipRegionRect() );
        m_pView->SetClipRegion( aClipRegion );
        m_pView->HideFocus();
        m_pView->SetClipRegion( aOldClip );
    }
    else
    {
        long nY = GetEntryLine( m_pCursor );
        tools::Rectangle aRect = m_pView->GetFocusRect( m_pCursor, nY );
        vcl::Region aOldClip( m_pView->GetClipRegion());
        vcl::Region aClipRegion( GetClipRegionRect() );
        m_pView->SetClipRegion( aClipRegion );
        m_pView->ShowFocus( aRect );
        m_pView->SetClipRegion( aOldClip );
    }
}


void SvImpLBox::UpdateAll( bool bInvalidateCompleteView )
{
    FindMostRight();
    m_aVerSBar->SetRange( Range(0, m_pView->GetVisibleCount()-1 ) );
    SyncVerThumb();
    FillView();
    ShowVerSBar();
    if( m_bSimpleTravel && m_pCursor && m_pView->HasFocus() )
        m_pView->Select( m_pCursor );
    ShowCursor( true );
    if( bInvalidateCompleteView )
        m_pView->Invalidate();
    else
        m_pView->Invalidate( GetVisibleArea() );
}

IMPL_LINK( SvImpLBox, ScrollLeftRightHdl, ScrollBar *, pScrollBar, void )
{
    long nDelta = pScrollBar->GetDelta();
    if( nDelta )
    {
        if( m_pView->IsEditingActive() )
        {
            m_pView->EndEditing( true ); // Cancel
            m_pView->PaintImmediately();
        }
        m_pView->nFocusWidth = -1;
        KeyLeftRight( nDelta );
    }
}

void SvImpLBox::KeyLeftRight( long nDelta )
{
    if( !(m_nFlags & LBoxFlags::InResize) )
        m_pView->PaintImmediately();
    BeginScroll();
    m_nFlags &= ~LBoxFlags::Filling;
    ShowCursor( false );

    // calculate new origin
    long nPos = m_aHorSBar->GetThumbPos();
    Point aOrigin( -nPos, 0 );

    MapMode aMapMode( m_pView->GetMapMode() );
    aMapMode.SetOrigin( aOrigin );
    m_pView->SetMapMode( aMapMode );

    if( !(m_nFlags & LBoxFlags::InResize) )
    {
        tools::Rectangle aRect( GetVisibleArea() );
        m_pView->Scroll( -nDelta, 0, aRect, ScrollFlags::NoChildren );
    }
    else
        m_pView->Invalidate();
    RecalcFocusRect();
    ShowCursor( true );
    m_pView->NotifyScrolled();
}


// returns the last entry if position is just past the last entry
SvTreeListEntry* SvImpLBox::GetClickedEntry( const Point& rPoint ) const
{
    DBG_ASSERT( m_pView->GetModel(), "SvImpLBox::GetClickedEntry: how can this ever happen? Please tell me (frank.schoenheit@sun.com) how to reproduce!" );
    if ( !m_pView->GetModel() )
        // this is quite impossible. Nevertheless, stack traces from the crash reporter
        // suggest it isn't. Okay, make it safe, and wait for somebody to reproduce it
        // reliably :-\ ...
        // #122359# / 2005-05-23 / frank.schoenheit@sun.com
        return nullptr;
    if( m_pView->GetEntryCount() == 0 || !m_pStartEntry || !m_pView->GetEntryHeight())
        return nullptr;

    sal_uInt16 nClickedEntry = static_cast<sal_uInt16>(rPoint.Y() / m_pView->GetEntryHeight() );
    sal_uInt16 nTemp = nClickedEntry;
    SvTreeListEntry* pEntry = m_pView->NextVisible(m_pStartEntry, nTemp);
    return pEntry;
}


//  checks if the entry was hit "the right way"
//  (Focusrect+ ContextBitmap at TreeListBox)

bool SvImpLBox::EntryReallyHit(SvTreeListEntry* pEntry, const Point& rPosPixel, long nLine)
{
    bool bRet;
    // we are not too exact when it comes to "special" entries
    // (with CheckButtons etc.)
    if( pEntry->ItemCount() >= 3 )
        return true;

    tools::Rectangle aRect( m_pView->GetFocusRect( pEntry, nLine ));
    aRect.SetRight( GetOutputSize().Width() - m_pView->GetMapMode().GetOrigin().X() );

    SvLBoxContextBmp* pBmp = static_cast<SvLBoxContextBmp*>(pEntry->GetFirstItem(SvLBoxItemType::ContextBmp));
    aRect.AdjustLeft( -pBmp->GetWidth(m_pView,pEntry) );
    aRect.AdjustLeft( -4 ); // a little tolerance

    Point aPos( rPosPixel );
    aPos -= m_pView->GetMapMode().GetOrigin();
    bRet = aRect.IsInside( aPos );
    return bRet;
}


// returns 0 if position is just past the last entry
SvTreeListEntry* SvImpLBox::GetEntry( const Point& rPoint ) const
{
    if( (m_pView->GetEntryCount() == 0) || !m_pStartEntry ||
        (rPoint.Y() > m_aOutputSize.Height())
        || !m_pView->GetEntryHeight())
        return nullptr;

    sal_uInt16 nClickedEntry = static_cast<sal_uInt16>(rPoint.Y() / m_pView->GetEntryHeight() );
    sal_uInt16 nTemp = nClickedEntry;
    SvTreeListEntry* pEntry = m_pView->NextVisible(m_pStartEntry, nTemp);
    if( nTemp != nClickedEntry )
        pEntry = nullptr;
    return pEntry;
}


SvTreeListEntry* SvImpLBox::MakePointVisible(const Point& rPoint)
{
    if( !m_pCursor )
        return nullptr;
    long nY = rPoint.Y();
    SvTreeListEntry* pEntry = nullptr;
    long nMax = m_aOutputSize.Height();
    if( nY < 0 || nY >= nMax ) // aOutputSize.Height() )
    {
        if( nY < 0 )
            pEntry = m_pView->PrevVisible(m_pCursor);
        else
            pEntry = m_pView->NextVisible(m_pCursor);

        if( pEntry && pEntry != m_pCursor )
            m_pView->SetEntryFocus( m_pCursor, false );

        if( nY < 0 )
            KeyUp( false );
        else
            KeyDown( false );
    }
    else
    {
        pEntry = GetClickedEntry( rPoint );
        if( !pEntry )
        {
            sal_uInt16 nSteps = 0xFFFF;
            // TODO: LastVisible is not yet implemented!
            pEntry = m_pView->NextVisible(m_pStartEntry, nSteps);
        }
        if( pEntry )
        {
            if( pEntry != m_pCursor &&
                 m_aSelEng.GetSelectionMode() == SelectionMode::Single
            )
                m_pView->Select( m_pCursor, false );
        }
    }
    return pEntry;
}

tools::Rectangle SvImpLBox::GetClipRegionRect() const
{
    Point aOrigin( m_pView->GetMapMode().GetOrigin() );
    aOrigin.setX( aOrigin.X() * -1 ); // conversion document coordinates
    tools::Rectangle aClipRect( aOrigin, m_aOutputSize );
    aClipRect.AdjustBottom( 1 );
    return aClipRect;
}


void SvImpLBox::Paint(vcl::RenderContext& rRenderContext, const tools::Rectangle& rRect)
{
    if (!m_pView->GetVisibleCount())
        return;

    m_nFlags |= LBoxFlags::InPaint;

    if (m_nFlags & LBoxFlags::Filling)
    {
        SvTreeListEntry* pFirst = m_pView->First();
        if (pFirst != m_pStartEntry)
        {
            ShowCursor(false);
            m_pStartEntry = m_pView->First();
            m_aVerSBar->SetThumbPos( 0 );
            StopUserEvent();
            ShowCursor(true);
            m_nCurUserEvent = Application::PostUserEvent(LINK(this, SvImpLBox, MyUserEvent),
                                                       reinterpret_cast<void*>(1));
            return;
        }
    }

    if (!m_pStartEntry)
    {
        m_pStartEntry = m_pView->First();
    }

    if (m_nNodeBmpTabDistance == NODE_BMP_TABDIST_NOTVALID)
        SetNodeBmpTabDistance();

    long nRectHeight = rRect.GetHeight();
    long nEntryHeight = m_pView->GetEntryHeight();

    // calculate area for the entries we want to draw
    sal_uInt16 nStartLine = static_cast<sal_uInt16>(rRect.Top() / nEntryHeight);
    sal_uInt16 nCount = static_cast<sal_uInt16>(nRectHeight / nEntryHeight);
    nCount += 2; // don't miss a row

    long nY = nStartLine * nEntryHeight;
    SvTreeListEntry* pEntry = m_pStartEntry;
    while (nStartLine && pEntry)
    {
        pEntry = m_pView->NextVisible(pEntry);
        nStartLine--;
    }

    vcl::Region aClipRegion(GetClipRegionRect());

    // first draw the lines, then clip them!
    rRenderContext.SetClipRegion();
    if (m_nStyle & (WB_HASLINES | WB_HASLINESATROOT))
        DrawNet(rRenderContext);

    rRenderContext.SetClipRegion(aClipRegion);

    if (!m_pCursor && !mbNoAutoCurEntry)
    {
        // do not select if multiselection or explicit set
        bool bNotSelect = (m_aSelEng.GetSelectionMode() == SelectionMode::Multiple ) || ((m_nStyle & WB_NOINITIALSELECTION) == WB_NOINITIALSELECTION);
        SetCursor(m_pStartEntry, bNotSelect);
    }

    for(sal_uInt16 n=0; n< nCount && pEntry; n++)
    {
        /*long nMaxRight=*/
        m_pView->PaintEntry1(*pEntry, nY, rRenderContext );
        nY += nEntryHeight;
        pEntry = m_pView->NextVisible(pEntry);
    }

    m_nFlags &= ~LBoxFlags::DeselectAll;
    rRenderContext.SetClipRegion();
    m_nFlags &= ~LBoxFlags::InPaint;
}

void SvImpLBox::MakeVisible( SvTreeListEntry* pEntry, bool bMoveToTop )
{
    if( !pEntry )
        return;

    bool bInView = IsEntryInView( pEntry );

    if( bInView && (!bMoveToTop || m_pStartEntry == pEntry) )
        return;  // is already visible

    if( m_pStartEntry || mbForceMakeVisible )
        m_nFlags &= ~LBoxFlags::Filling;
    if( !bInView )
    {
        if( !m_pView->IsEntryVisible(pEntry) )  // Parent(s) collapsed?
        {
            SvTreeListEntry* pParent = m_pView->GetParent( pEntry );
            while( pParent )
            {
                if( !m_pView->IsExpanded( pParent ) )
                {
                    bool bRet = m_pView->Expand( pParent );
                    DBG_ASSERT(bRet,"Not expanded!");
                }
                pParent = m_pView->GetParent( pParent );
            }
            // do the parent's children fit into the view or do we have to scroll?
            if( IsEntryInView( pEntry ) && !bMoveToTop )
                return;  // no need to scroll
        }
    }

    m_pStartEntry = pEntry;
    ShowCursor( false );
    FillView();
    m_aVerSBar->SetThumbPos( static_cast<long>(m_pView->GetVisiblePos( m_pStartEntry )) );
    ShowCursor( true );
    m_pView->Invalidate();
}

void SvImpLBox::ScrollToAbsPos( long nPos )
{
    if( m_pView->GetVisibleCount() == 0 )
        return;
    long nLastEntryPos = m_pView->GetAbsPos( m_pView->Last() );

    if( nPos < 0 )
        nPos = 0;
    else if( nPos > nLastEntryPos )
        nPos = nLastEntryPos;

    SvTreeListEntry* pEntry = m_pView->GetEntryAtAbsPos( nPos );
    if( !pEntry || pEntry == m_pStartEntry )
        return;

    if( m_pStartEntry || mbForceMakeVisible )
        m_nFlags &= ~LBoxFlags::Filling;

    if( m_pView->IsEntryVisible(pEntry) )
    {
        m_pStartEntry = pEntry;
        ShowCursor( false );
        m_aVerSBar->SetThumbPos( nPos );
        ShowCursor( true );
        if (GetUpdateMode())
            m_pView->Invalidate();
    }
}

void SvImpLBox::DrawNet(vcl::RenderContext& rRenderContext)
{
    if (m_pView->GetVisibleCount() < 2 && !m_pStartEntry->HasChildrenOnDemand() &&
        !m_pStartEntry->HasChildren())
    {
        return;
    }

    // for platforms that don't have nets, DrawNativeControl does nothing and returns true
    // so that SvImpLBox::DrawNet() doesn't draw anything either
    if (rRenderContext.IsNativeControlSupported(ControlType::ListNet, ControlPart::Entire))
    {
        ImplControlValue aControlValue;
        if (rRenderContext.DrawNativeControl(ControlType::ListNet, ControlPart::Entire,
                                             tools::Rectangle(), ControlState::ENABLED, aControlValue, OUString()))
        {
            return;
        }
    }

    long nEntryHeight = m_pView->GetEntryHeight();
    long nEntryHeightDIV2 = nEntryHeight / 2;
    if( nEntryHeightDIV2 && !(nEntryHeight & 0x0001))
        nEntryHeightDIV2--;

    SvTreeListEntry* pChild;
    SvTreeListEntry* pEntry = m_pStartEntry;

    SvLBoxTab* pFirstDynamicTab = m_pView->GetFirstDynamicTab();
    while (m_pTree->GetDepth( pEntry ) > 0)
    {
        pEntry = m_pView->GetParent(pEntry);
    }
    sal_uInt16 nOffs = static_cast<sal_uInt16>(m_pView->GetVisiblePos(m_pStartEntry) - m_pView->GetVisiblePos(pEntry));
    long nY = 0;
    nY -= (nOffs * nEntryHeight);

    DBG_ASSERT(pFirstDynamicTab,"No Tree!");

    rRenderContext.Push(PushFlags::LINECOLOR);

    const StyleSettings& rStyleSettings = rRenderContext.GetSettings().GetStyleSettings();
    Color aCol = rStyleSettings.GetFaceColor();

    if (aCol.IsRGBEqual(rRenderContext.GetBackground().GetColor()))
        aCol = rStyleSettings.GetShadowColor();
    rRenderContext.SetLineColor(aCol);
    Point aPos1, aPos2;
    sal_uInt16 nDistance;
    sal_uLong nMax = m_nVisibleCount + nOffs + 1;

    const Image& rExpandedNodeBitmap = GetExpandedNodeBmp();

    for (sal_uLong n=0; n< nMax && pEntry; n++)
    {
        if (m_pView->IsExpanded(pEntry))
        {
            aPos1.setX( m_pView->GetTabPos(pEntry, pFirstDynamicTab) );
            // if it is not a context bitmap, go a little to the right below the
            // first text (node bitmap, too)
            if (!m_pView->nContextBmpWidthMax)
                aPos1.AdjustX(rExpandedNodeBitmap.GetSizePixel().Width() / 2 );

            aPos1.setY( nY );
            aPos1.AdjustY(nEntryHeightDIV2 );

            pChild = m_pView->FirstChild( pEntry );
            assert(pChild && "Child?");
            pChild = pChild->LastSibling();
            nDistance = static_cast<sal_uInt16>(m_pView->GetVisiblePos(pChild) - m_pView->GetVisiblePos(pEntry));
            aPos2 = aPos1;
            aPos2.AdjustY(nDistance * nEntryHeight );
            rRenderContext.DrawLine(aPos1, aPos2);
        }
        // visible in control?
        if (n >= nOffs && ((m_nStyle & WB_HASLINESATROOT) || !m_pTree->IsAtRootDepth(pEntry)))
        {
            // can we recycle aPos1?
            if (!m_pView->IsExpanded(pEntry))
            {
                // nope
                aPos1.setX( m_pView->GetTabPos(pEntry, pFirstDynamicTab) );
                // if it is not a context bitmap, go a little to the right below
                // the first text (node bitmap, too)
                if (!m_pView->nContextBmpWidthMax)
                    aPos1.AdjustX(rExpandedNodeBitmap.GetSizePixel().Width() / 2 );
                aPos1.setY( nY );
                aPos1.AdjustY(nEntryHeightDIV2 );
                aPos2.setX( aPos1.X() );
            }
            aPos2.setY( aPos1.Y() );
            aPos2.AdjustX( -(m_pView->GetIndent()) );
            rRenderContext.DrawLine(aPos1, aPos2);
        }
        nY += nEntryHeight;
        pEntry = m_pView->NextVisible(pEntry);
    }
    if (m_nStyle & WB_HASLINESATROOT)
    {
        pEntry = m_pView->First();
        aPos1.setX( m_pView->GetTabPos(pEntry, pFirstDynamicTab) );
        // if it is not a context bitmap, go a little to the right below the
        // first text (node bitmap, too)
        if (!m_pView->nContextBmpWidthMax)
            aPos1.AdjustX(rExpandedNodeBitmap.GetSizePixel().Width() / 2 );
        aPos1.AdjustX( -(m_pView->GetIndent()) );
        aPos1.setY( GetEntryLine( pEntry ) );
        aPos1.AdjustY(nEntryHeightDIV2 );
        pChild = pEntry->LastSibling();
        aPos2.setX( aPos1.X() );
        aPos2.setY( GetEntryLine( pChild ) );
        aPos2.AdjustY(nEntryHeightDIV2 );
        rRenderContext.DrawLine(aPos1, aPos2);
    }
    rRenderContext.Pop();
}

void SvImpLBox::PositionScrollBars( Size& rSize, sal_uInt16 nMask )
{
    long nOverlap = 0;

    Size aVerSize( m_nVerSBarWidth, rSize.Height() );
    Size aHorSize( rSize.Width(), m_nHorSBarHeight );

    if( nMask & 0x0001 )
        aHorSize.AdjustWidth( -m_nVerSBarWidth );
    if( nMask & 0x0002 )
        aVerSize.AdjustHeight( -m_nHorSBarHeight );

    aVerSize.AdjustHeight(2 * nOverlap );
    Point aVerPos( rSize.Width() - aVerSize.Width() + nOverlap, -nOverlap );
    m_aVerSBar->SetPosSizePixel( aVerPos, aVerSize );

    aHorSize.AdjustWidth(2 * nOverlap );
    Point aHorPos( -nOverlap, rSize.Height() - aHorSize.Height() + nOverlap );

    m_aHorSBar->SetPosSizePixel( aHorPos, aHorSize );

    if( nMask & 0x0001 )
        rSize.setWidth( aVerPos.X() );
    if( nMask & 0x0002 )
        rSize.setHeight( aHorPos.Y() );

    if( (nMask & (0x0001|0x0002)) == (0x0001|0x0002) )
        m_aScrBarBox->Show();
    else
        m_aScrBarBox->Hide();
}

void SvImpLBox::AdjustScrollBars( Size& rSize )
{
    long nEntryHeight = m_pView->GetEntryHeight();
    if( !nEntryHeight )
        return;

    sal_uInt16 nResult = 0;

    Size aOSize( m_pView->Control::GetOutputSizePixel() );

    const WinBits nWindowStyle = m_pView->GetStyle();
    bool bVerSBar = ( nWindowStyle & WB_VSCROLL ) != 0;
    bool bHorBar = false;
    long nMaxRight = aOSize.Width(); //GetOutputSize().Width();
    Point aOrigin( m_pView->GetMapMode().GetOrigin() );
    aOrigin.setX( aOrigin.X() * -1 );
    nMaxRight += aOrigin.X() - 1;
    long nVis = m_nMostRight - aOrigin.X();
    if( (nWindowStyle & (WB_AUTOHSCROLL|WB_HSCROLL)) &&
        (nVis < m_nMostRight || nMaxRight < m_nMostRight) )
    {
        bHorBar = true;
    }

    // number of entries that are not collapsed
    sal_uLong nTotalCount = m_pView->GetVisibleCount();

    // number of entries visible within the view
    m_nVisibleCount = aOSize.Height() / nEntryHeight;

    // do we need a vertical scrollbar?
    if( bVerSBar || nTotalCount > m_nVisibleCount )
    {
        nResult = 1;
        nMaxRight -= m_nVerSBarWidth;
        if( !bHorBar )
        {
            if( (nWindowStyle & (WB_AUTOHSCROLL|WB_HSCROLL)) &&
                (nVis < m_nMostRight || nMaxRight < m_nMostRight) )
                bHorBar = true;
        }
    }

    // do we need a horizontal scrollbar?
    if( bHorBar )
    {
        nResult |= 0x0002;
        // the number of entries visible within the view has to be recalculated
        // because the horizontal scrollbar is now visible.
        m_nVisibleCount =  (aOSize.Height() - m_nHorSBarHeight) / nEntryHeight;
        // we might actually need a vertical scrollbar now
        if( !(nResult & 0x0001) &&
            ((nTotalCount > m_nVisibleCount) || bVerSBar) )
        {
            nResult = 3;
        }
    }

    PositionScrollBars( aOSize, nResult );

    // adapt Range, VisibleRange etc.

    // refresh output size, in case we have to scroll
    tools::Rectangle aRect;
    aRect.SetSize( aOSize );
    m_aSelEng.SetVisibleArea( aRect );

    // vertical scrollbar
    long nTemp = static_cast<long>(m_nVisibleCount);
    nTemp--;
    if( nTemp != m_aVerSBar->GetVisibleSize() )
    {
        if( !m_bInVScrollHdl )
        {
            m_aVerSBar->SetPageSize( nTemp - 1 );
            m_aVerSBar->SetVisibleSize( nTemp );
        }
        else
        {
            m_nFlags |= LBoxFlags::EndScrollSetVisSize;
            m_nNextVerVisSize = nTemp;
        }
    }

    // horizontal scrollbar
    nTemp = m_aHorSBar->GetThumbPos();
    m_aHorSBar->SetVisibleSize( aOSize.Width() );
    long nNewThumbPos = m_aHorSBar->GetThumbPos();
    Range aRange( m_aHorSBar->GetRange() );
    if( aRange.Max() < m_nMostRight+25 )
    {
        aRange.Max() = m_nMostRight+25;
        m_aHorSBar->SetRange( aRange );
    }

    if( nTemp != nNewThumbPos )
    {
        nTemp = nNewThumbPos - nTemp;
        if( m_pView->IsEditingActive() )
        {
            m_pView->EndEditing( true ); // Cancel
            m_pView->PaintImmediately();
        }
        m_pView->nFocusWidth = -1;
        KeyLeftRight( nTemp );
    }

    if( nResult & 0x0001 )
        m_aVerSBar->Show();
    else
        m_aVerSBar->Hide();

    if( nResult & 0x0002 )
        m_aHorSBar->Show();
    else
    {
        m_aHorSBar->Hide();
    }
    rSize = aOSize;
}

void SvImpLBox::InitScrollBarBox()
{
    m_aScrBarBox->SetSizePixel( Size(m_nVerSBarWidth, m_nHorSBarHeight) );
    Size aSize( m_pView->Control::GetOutputSizePixel() );
    m_aScrBarBox->SetPosPixel( Point(aSize.Width()-m_nVerSBarWidth, aSize.Height()-m_nHorSBarHeight));
}

void SvImpLBox::Resize()
{
    m_aOutputSize = m_pView->Control::GetOutputSizePixel();
    if( m_aOutputSize.IsEmpty() )
        return;
    m_nFlags |= LBoxFlags::InResize;
    InitScrollBarBox();

    if( m_pView->GetEntryHeight())
    {
        AdjustScrollBars( m_aOutputSize );
        UpdateAll(false);
    }
    // HACK, as in floating and docked windows the scrollbars might not be drawn
    // correctly/not be drawn at all after resizing!
    if( m_aHorSBar->IsVisible())
        m_aHorSBar->Invalidate();
    if( m_aVerSBar->IsVisible())
        m_aVerSBar->Invalidate();
    m_nFlags &= ~LBoxFlags::InResize;
}

void SvImpLBox::FillView()
{
    if( !m_pStartEntry )<--- First condition
    {
        sal_uLong nVisibleViewCount = m_pView->GetVisibleCount();
        long nTempThumb = m_aVerSBar->GetThumbPos();
        if( nTempThumb < 0 )
            nTempThumb = 0;
        else if( o3tl::make_unsigned(nTempThumb) >= nVisibleViewCount )
            nTempThumb = nVisibleViewCount == 0 ? 0 : nVisibleViewCount - 1;
        m_pStartEntry = m_pView->GetEntryAtVisPos(nTempThumb);
    }
    if( !m_pStartEntry )<--- Second condition
        return;

    sal_uInt16 nLast = static_cast<sal_uInt16>(m_pView->GetVisiblePos(m_pView->LastVisible()));
    sal_uInt16 nThumb = static_cast<sal_uInt16>(m_pView->GetVisiblePos( m_pStartEntry ));
    sal_uLong nCurDispEntries = nLast-nThumb+1;
    if( nCurDispEntries >=  m_nVisibleCount )
        return;

    ShowCursor( false );
    // fill window by moving the thumb up incrementally
    bool bFound = false;
    SvTreeListEntry* pTemp = m_pStartEntry;
    while( nCurDispEntries < m_nVisibleCount && pTemp )
    {
        pTemp = m_pView->PrevVisible(m_pStartEntry);
        if( pTemp )
        {
            nThumb--;
            m_pStartEntry = pTemp;
            nCurDispEntries++;
            bFound = true;
        }
    }
    if( bFound )
    {
        m_aVerSBar->SetThumbPos( nThumb );
        ShowCursor( true ); // recalculate focus rectangle
        m_pView->Invalidate();
    }
}


void SvImpLBox::ShowVerSBar()
{
    bool bVerBar = ( m_pView->GetStyle() & WB_VSCROLL ) != 0;
    sal_uLong nVis = 0;
    if( !bVerBar )
        nVis = m_pView->GetVisibleCount();
    if( bVerBar || (m_nVisibleCount && nVis > static_cast<sal_uLong>(m_nVisibleCount-1)) )
    {
        if( !m_aVerSBar->IsVisible() )
        {
            m_pView->nFocusWidth = -1;
            AdjustScrollBars( m_aOutputSize );
            if( GetUpdateMode() )
                m_aVerSBar->Invalidate();
        }
    }
    else
    {
        if( m_aVerSBar->IsVisible() )
        {
            m_pView->nFocusWidth = -1;
            AdjustScrollBars( m_aOutputSize );
        }
    }

    long nMaxRight = GetOutputSize().Width();
    Point aPos( m_pView->GetMapMode().GetOrigin() );
    aPos.setX( aPos.X() * -1 ); // convert document coordinates
    nMaxRight = nMaxRight + aPos.X() - 1;
    if( nMaxRight < m_nMostRight  )
    {
        if( !m_aHorSBar->IsVisible() )
        {
            m_pView->nFocusWidth = -1;
            AdjustScrollBars( m_aOutputSize );
            if( GetUpdateMode() )
                m_aHorSBar->Invalidate();
        }
        else
        {
            Range aRange( m_aHorSBar->GetRange() );
            if( aRange.Max() < m_nMostRight+25 )
            {
                aRange.Max() = m_nMostRight+25;
                m_aHorSBar->SetRange( aRange );
            }
            else
            {
                m_pView->nFocusWidth = -1;
                AdjustScrollBars( m_aOutputSize );
            }
        }
    }
    else
    {
        if( m_aHorSBar->IsVisible() )
        {
            m_pView->nFocusWidth = -1;
            AdjustScrollBars( m_aOutputSize );
        }
    }
}


void SvImpLBox::SyncVerThumb()
{
    if( m_pStartEntry )
    {
        long nEntryPos = m_pView->GetVisiblePos( m_pStartEntry );
        m_aVerSBar->SetThumbPos( nEntryPos );
    }
    else
        m_aVerSBar->SetThumbPos( 0 );
}

bool SvImpLBox::IsEntryInView( SvTreeListEntry* pEntry ) const
{
    // parent collapsed
    if( !m_pView->IsEntryVisible(pEntry) )
        return false;
    long nY = GetEntryLine( pEntry );
    if( nY < 0 )
        return false;
    long nMax = m_nVisibleCount * m_pView->GetEntryHeight();
    return nY < nMax;
}


long SvImpLBox::GetEntryLine(const SvTreeListEntry* pEntry) const
{
    if(!m_pStartEntry )
        return -1; // invisible position

    long nFirstVisPos = m_pView->GetVisiblePos( m_pStartEntry );
    long nEntryVisPos = m_pView->GetVisiblePos( pEntry );
    nFirstVisPos = nEntryVisPos - nFirstVisPos;
    nFirstVisPos *= m_pView->GetEntryHeight();
    return nFirstVisPos;
}

void SvImpLBox::SetEntryHeight()
{
    SetNodeBmpWidth( GetExpandedNodeBmp() );
    SetNodeBmpWidth( GetCollapsedNodeBmp() );
    if(!m_pView->HasViewData()) // are we within the Clear?
    {
        Size aSize = m_pView->Control::GetOutputSizePixel();
        AdjustScrollBars( aSize );
    }
    else
    {
        Resize();
        if( GetUpdateMode() )
            m_pView->Invalidate();
    }
}


// ***********************************************************************
// Callback Functions
// ***********************************************************************

void SvImpLBox::EntryExpanded( SvTreeListEntry* pEntry )
{
    // SelAllDestrAnch( false, true ); //DeselectAll();
    if( !GetUpdateMode() )
        return;

    ShowCursor( false );
    long nY = GetEntryLine( pEntry );
    if( IsLineVisible(nY) )
    {
        InvalidateEntriesFrom( nY );
        FindMostRight( pEntry );
    }
    m_aVerSBar->SetRange( Range(0, m_pView->GetVisibleCount()-1 ) );
    // if we expanded before the thumb, the thumb's position has to be
    // corrected
    SyncVerThumb();
    ShowVerSBar();
    ShowCursor( true );
}

void SvImpLBox::EntryCollapsed( SvTreeListEntry* pEntry )
{
    if( !m_pView->IsEntryVisible( pEntry ) )
        return;

    ShowCursor( false );

    if( !m_pMostRightEntry || m_pTree->IsChild( pEntry,m_pMostRightEntry ) )
    {
        FindMostRight();
    }

    if( m_pStartEntry )
    {
        long nOldThumbPos   = m_aVerSBar->GetThumbPos();
        sal_uLong nVisList      = m_pView->GetVisibleCount();
        m_aVerSBar->SetRange( Range(0, nVisList-1) );
        long nNewThumbPos   = m_aVerSBar->GetThumbPos();
        if( nNewThumbPos != nOldThumbPos  )
        {
            m_pStartEntry = m_pView->First();
            sal_uInt16 nDistance = static_cast<sal_uInt16>(nNewThumbPos);
            if( nDistance )
                m_pStartEntry = m_pView->NextVisible(m_pStartEntry, nDistance);
            if( GetUpdateMode() )
                m_pView->Invalidate();
        }
        else
            SyncVerThumb();
        ShowVerSBar();
    }
    // has the cursor been collapsed?
    if( m_pTree->IsChild( pEntry, m_pCursor ) )
        SetCursor( pEntry );
    if( GetUpdateMode() )
        ShowVerSBar();
    ShowCursor( true );
    if( GetUpdateMode() && m_pCursor )
        m_pView->Select( m_pCursor );
}

void SvImpLBox::CollapsingEntry( SvTreeListEntry* pEntry )
{
    if( !m_pView->IsEntryVisible( pEntry ) || !m_pStartEntry )
        return;

    SelAllDestrAnch( false ); // deselect all

    // is the collapsed cursor visible?
    long nY = GetEntryLine( pEntry );
    if( IsLineVisible(nY) )
    {
        if( GetUpdateMode() )
            InvalidateEntriesFrom( nY );
    }
    else
    {
        if( m_pTree->IsChild(pEntry, m_pStartEntry) )
        {
            m_pStartEntry = pEntry;
            if( GetUpdateMode() )
                m_pView->Invalidate();
        }
    }
}


void SvImpLBox::SetNodeBmpWidth( const Image& rBmp )
{
    const Size aSize( rBmp.GetSizePixel() );
    m_nNodeBmpWidth = aSize.Width();
}

void SvImpLBox::SetNodeBmpTabDistance()
{
    m_nNodeBmpTabDistance = -m_pView->GetIndent();
    if( m_pView->nContextBmpWidthMax )
    {
        // only if the first dynamic tab is centered (we currently assume that)
        Size aSize = GetExpandedNodeBmp().GetSizePixel();
        m_nNodeBmpTabDistance -= aSize.Width() / 2;
    }
}


// corrects the cursor when using SingleSelection

void SvImpLBox::EntrySelected( SvTreeListEntry* pEntry, bool bSelect )
{
    if( m_nFlags & LBoxFlags::IgnoreSelect )
        return;

    m_nFlags &= ~LBoxFlags::DeselectAll;
    if( bSelect &&
        m_aSelEng.GetSelectionMode() == SelectionMode::Single &&
        pEntry != m_pCursor )
    {
        SetCursor( pEntry );
        DBG_ASSERT(m_pView->GetSelectionCount()==1,"selection count?");
    }

    if( GetUpdateMode() && m_pView->IsEntryVisible(pEntry) )
    {
        long nY = GetEntryLine( pEntry );
        if( IsLineVisible( nY ) )
        {
            ShowCursor(false);
            InvalidateEntry(pEntry);
            ShowCursor(true);
        }
    }
}


void SvImpLBox::RemovingEntry( SvTreeListEntry* pEntry )
{
    CallEventListeners( VclEventId::ListboxItemRemoved , pEntry );

    DestroyAnchor();

    if( !m_pView->IsEntryVisible( pEntry ) )
    {
        // if parent is collapsed => bye!
        m_nFlags |= LBoxFlags::RemovedEntryInvisible;
        return;
    }

    if( pEntry == m_pMostRightEntry || (
        pEntry->HasChildren() && m_pView->IsExpanded(pEntry) &&
        m_pTree->IsChild(pEntry, m_pMostRightEntry)))
    {
        m_nFlags |= LBoxFlags::RemovedRecalcMostRight;
    }

    SvTreeListEntry* pOldStartEntry = m_pStartEntry;

    SvTreeListEntry* pParent = m_pView->GetModel()->GetParent(pEntry);

    if (pParent && m_pView->GetModel()->GetChildList(pParent).size() == 1)
    {
        DBG_ASSERT( m_pView->IsExpanded( pParent ), "Parent not expanded");
        pParent->SetFlags( pParent->GetFlags() | SvTLEntryFlags::NO_NODEBMP);
        InvalidateEntry( pParent );
    }

    if( m_pCursor && m_pTree->IsChild( pEntry, m_pCursor) )
        m_pCursor = pEntry;
    if( m_pStartEntry && m_pTree->IsChild(pEntry,m_pStartEntry) )
        m_pStartEntry = pEntry;

    SvTreeListEntry* pTemp;
    if( m_pCursor && m_pCursor == pEntry )
    {
        if( m_bSimpleTravel )
            m_pView->Select( m_pCursor, false );
        ShowCursor( false );    // focus rectangle gone
        // NextSibling, because we also delete the children of the cursor
        pTemp = m_pCursor->NextSibling();
        if( !pTemp )
            pTemp = m_pView->PrevVisible(m_pCursor);

        SetCursor( pTemp, true );
    }
    if( m_pStartEntry && m_pStartEntry == pEntry )
    {
        pTemp = m_pStartEntry->NextSibling();
        if( !pTemp )
            pTemp = m_pView->PrevVisible(m_pStartEntry);
        m_pStartEntry = pTemp;
    }
    if( GetUpdateMode())
    {
        // if it is the last one, we have to invalidate it, so the lines are
        // drawn correctly (in this case they're deleted)
        if( m_pStartEntry && (m_pStartEntry != pOldStartEntry || pEntry == m_pView->GetModel()->Last()) )
        {
            m_aVerSBar->SetThumbPos( m_pView->GetVisiblePos( m_pStartEntry ));
            m_pView->Invalidate( GetVisibleArea() );
        }
        else
            InvalidateEntriesFrom( GetEntryLine( pEntry ) );
    }
}

void SvImpLBox::EntryRemoved()
{
    if( m_nFlags & LBoxFlags::RemovedEntryInvisible )
    {
        m_nFlags &= ~LBoxFlags::RemovedEntryInvisible;
        return;
    }
    if( !m_pStartEntry )
        m_pStartEntry = m_pTree->First();
    if( !m_pCursor )
        SetCursor( m_pStartEntry, true );

    if( m_pCursor && (m_bSimpleTravel || !m_pView->GetSelectionCount() ))
        m_pView->Select( m_pCursor );

    if( GetUpdateMode())
    {
        if( m_nFlags & LBoxFlags::RemovedRecalcMostRight )
            FindMostRight();
        m_aVerSBar->SetRange( Range(0, m_pView->GetVisibleCount()-1 ) );
        FillView();
        if( m_pStartEntry )
            // if something above the thumb was deleted
            m_aVerSBar->SetThumbPos( m_pView->GetVisiblePos( m_pStartEntry) );

        ShowVerSBar();
        if( m_pCursor && m_pView->HasFocus() && !m_pView->IsSelected(m_pCursor) )
        {
            if( m_pView->GetSelectionCount() )
            {
                // is a neighboring entry selected?
                SvTreeListEntry* pNextCursor = m_pView->PrevVisible( m_pCursor );
                if( !pNextCursor || !m_pView->IsSelected( pNextCursor ))
                    pNextCursor = m_pView->NextVisible( m_pCursor );
                if( !pNextCursor || !m_pView->IsSelected( pNextCursor ))
                    // no neighbor selected: use first selected
                    pNextCursor = m_pView->FirstSelected();
                SetCursor( pNextCursor );
                MakeVisible( m_pCursor );
            }
            else
                m_pView->Select( m_pCursor );
        }
        ShowCursor( true );
    }
    m_nFlags &= ~LBoxFlags::RemovedRecalcMostRight;
}


void SvImpLBox::MovingEntry( SvTreeListEntry* pEntry )
{
    bool bDeselAll(m_nFlags & LBoxFlags::DeselectAll);
    SelAllDestrAnch( false );  // DeselectAll();
    if( !bDeselAll )
        m_nFlags &= ~LBoxFlags::DeselectAll;

    if( pEntry == m_pCursor )
        ShowCursor( false );
    if( IsEntryInView( pEntry ) )
        m_pView->Invalidate();
    if( pEntry != m_pStartEntry )
        return;

    SvTreeListEntry* pNew = nullptr;
    if( !pEntry->HasChildren() )
    {
        pNew = m_pView->NextVisible(m_pStartEntry);
        if( !pNew )
            pNew = m_pView->PrevVisible(m_pStartEntry);
    }
    else
    {
        pNew = pEntry->NextSibling();
        if( !pNew )
            pNew = pEntry->PrevSibling();
    }
    m_pStartEntry = pNew;
}

void SvImpLBox::EntryMoved( SvTreeListEntry* pEntry )
{
    UpdateContextBmpWidthVectorFromMovedEntry( pEntry );

    if ( !m_pStartEntry )
        // this might happen if the only entry in the view is moved to its very same position
        // #i97346#
        m_pStartEntry = m_pView->First();

    m_aVerSBar->SetRange( Range(0, m_pView->GetVisibleCount()-1));
    sal_uInt16 nFirstPos = static_cast<sal_uInt16>(m_pTree->GetAbsPos( m_pStartEntry ));
    sal_uInt16 nNewPos = static_cast<sal_uInt16>(m_pTree->GetAbsPos( pEntry ));
    FindMostRight();
    if( nNewPos < nFirstPos ) // HACK!
        m_pStartEntry = pEntry;
    SyncVerThumb();
    if( pEntry == m_pCursor )
    {
        if( m_pView->IsEntryVisible( m_pCursor ) )
            ShowCursor( true );
        else
        {
            SvTreeListEntry* pParent = pEntry;
            do {
                pParent = m_pTree->GetParent( pParent );
            }
            while( !m_pView->IsEntryVisible( pParent ) );
            SetCursor( pParent );
        }
    }
    if( IsEntryInView( pEntry ) )
        m_pView->Invalidate();
}


void SvImpLBox::EntryInserted( SvTreeListEntry* pEntry )
{
    if( !GetUpdateMode() )
        return;

    SvTreeListEntry* pParent = m_pTree->GetParent(pEntry);
    if (pParent && m_pTree->GetChildList(pParent).size() == 1)
        // draw plus sign
        m_pTree->InvalidateEntry( pParent );

    if( !m_pView->IsEntryVisible( pEntry ) )
        return;
    bool bDeselAll(m_nFlags & LBoxFlags::DeselectAll);
    if( bDeselAll )
        SelAllDestrAnch( false );
    else
        DestroyAnchor();
    //  nFlags &= (~LBoxFlags::DeselectAll);
//      ShowCursor( false ); // if cursor is moved lower
    long nY = GetEntryLine( pEntry );
    bool bEntryVisible = IsLineVisible( nY );
    if( bEntryVisible )
    {
        ShowCursor( false ); // if cursor is moved lower
        nY -= m_pView->GetEntryHeight(); // because of lines
        InvalidateEntriesFrom( nY );
    }
    else if( m_pStartEntry && nY < GetEntryLine(m_pStartEntry) )
    {
        // Check if the view is filled completely. If not, then adjust
        // pStartEntry and the Cursor (automatic scrolling).
        sal_uInt16 nLast = static_cast<sal_uInt16>(m_pView->GetVisiblePos(m_pView->LastVisible()));
        sal_uInt16 nThumb = static_cast<sal_uInt16>(m_pView->GetVisiblePos( m_pStartEntry ));
        sal_uInt16 nCurDispEntries = nLast-nThumb+1;
        if( nCurDispEntries < m_nVisibleCount )
        {
            // set at the next paint event
            m_pStartEntry = nullptr;
            SetCursor( nullptr );
            m_pView->Invalidate();
        }
    }
    else if( !m_pStartEntry )
        m_pView->Invalidate();

    SetMostRight( pEntry );
    m_aVerSBar->SetRange( Range(0, m_pView->GetVisibleCount()-1));
    SyncVerThumb(); // if something was inserted before the thumb
    ShowVerSBar();
    ShowCursor( true );
    if( m_pStartEntry != m_pView->First() && (m_nFlags & LBoxFlags::Filling) )
        m_pView->PaintImmediately();
}


// ********************************************************************
// Event handler
// ********************************************************************


// ****** Control the control animation

bool SvImpLBox::ButtonDownCheckCtrl(const MouseEvent& rMEvt, SvTreeListEntry* pEntry)
{
    SvLBoxItem* pItem = m_pView->GetItem(pEntry,rMEvt.GetPosPixel().X(),&m_pActiveTab);
    if (pItem && pItem->GetType() == SvLBoxItemType::Button)
    {
        m_pActiveButton = static_cast<SvLBoxButton*>(pItem);
        m_pActiveEntry = pEntry;
        if( m_pCursor == m_pActiveEntry )
            m_pView->HideFocus();
        m_pView->CaptureMouse();
        m_pActiveButton->SetStateHilighted( true );
        InvalidateEntry(m_pActiveEntry);
        return true;
    }
    else
        m_pActiveButton = nullptr;
    return false;
}

bool SvImpLBox::MouseMoveCheckCtrl(const MouseEvent& rMEvt, SvTreeListEntry const * pEntry)
{
    if( m_pActiveButton )
    {
        long nMouseX = rMEvt.GetPosPixel().X();
        if( pEntry == m_pActiveEntry &&
             m_pView->GetItem(m_pActiveEntry, nMouseX) == m_pActiveButton )
        {
            if( !m_pActiveButton->IsStateHilighted() )
            {
                m_pActiveButton->SetStateHilighted(true );
                InvalidateEntry(m_pActiveEntry);
            }
        }
        else
        {
            if( m_pActiveButton->IsStateHilighted() )
            {
                m_pActiveButton->SetStateHilighted(false );
                InvalidateEntry(m_pActiveEntry);
            }
        }
        return true;
    }
    return false;
}

bool SvImpLBox::ButtonUpCheckCtrl( const MouseEvent& rMEvt )
{
    if( m_pActiveButton )
    {
        m_pView->ReleaseMouse();
        SvTreeListEntry* pEntry = GetClickedEntry( rMEvt.GetPosPixel() );
        m_pActiveButton->SetStateHilighted( false );
        long nMouseX = rMEvt.GetPosPixel().X();
        if (pEntry == m_pActiveEntry && m_pView->GetItem(m_pActiveEntry, nMouseX) == m_pActiveButton)
            m_pActiveButton->ClickHdl(m_pActiveEntry);
        InvalidateEntry(m_pActiveEntry);
        if (m_pCursor == m_pActiveEntry)
            ShowCursor(true);
        m_pActiveButton = nullptr;
        m_pActiveEntry = nullptr;
        m_pActiveTab = nullptr;
        return true;
    }
    return false;
}

// ******* Control plus/minus button for expanding/collapsing

// false == no expand/collapse button hit
bool SvImpLBox::IsNodeButton( const Point& rPosPixel, SvTreeListEntry* pEntry ) const
{
    if( !pEntry->HasChildren() && !pEntry->HasChildrenOnDemand() )
        return false;

    SvLBoxTab* pFirstDynamicTab = m_pView->GetFirstDynamicTab();
    if( !pFirstDynamicTab )
        return false;

    long nMouseX = rPosPixel.X();
    // convert to document coordinates
    Point aOrigin( m_pView->GetMapMode().GetOrigin() );
    nMouseX -= aOrigin.X();

    long nX = m_pView->GetTabPos( pEntry, pFirstDynamicTab);
    nX += m_nNodeBmpTabDistance;
    if( nMouseX < nX )
        return false;
    nX += m_nNodeBmpWidth;
    return nMouseX <= nX;
}

// false == hit no node button
bool SvImpLBox::ButtonDownCheckExpand( const MouseEvent& rMEvt, SvTreeListEntry* pEntry )
{
    bool bRet = false;

    if ( m_pView->IsEditingActive() && pEntry == m_pView->pEdEntry )
        // inplace editing -> nothing to do
        bRet = true;
    else if ( IsNodeButton( rMEvt.GetPosPixel(), pEntry ) )
    {
        if ( m_pView->IsExpanded( pEntry ) )
        {
            m_pView->EndEditing( true );
            m_pView->Collapse( pEntry );
        }
        else
        {
            // you can expand an entry, which is in editing
            m_pView->Expand( pEntry );
        }
        bRet = true;
    }

    return bRet;
}

void SvImpLBox::MouseButtonDown( const MouseEvent& rMEvt )
{
    if ( !rMEvt.IsLeft() && !rMEvt.IsRight())
        return;

    m_aEditIdle.Stop();
    Point aPos( rMEvt.GetPosPixel());

    if( aPos.X() > m_aOutputSize.Width() || aPos.Y() > m_aOutputSize.Height() )
        return;

    if( !m_pCursor )
        m_pCursor = m_pStartEntry;
    m_nFlags &= ~LBoxFlags::Filling;
    m_pView->GrabFocus();
    //fdo#82270 Grabbing focus can invalidate the entries, re-fetch
    SvTreeListEntry* pEntry = GetEntry(aPos);
    // the entry can still be invalid!
    if( !pEntry || !m_pView->GetViewData( pEntry ))
        return;

    long nY = GetEntryLine( pEntry );
    // Node-Button?
    if( ButtonDownCheckExpand( rMEvt, pEntry ) )
        return;

    if( !EntryReallyHit(pEntry,aPos,nY))
        return;

    SvLBoxItem* pXItem = m_pView->GetItem( pEntry, aPos.X() );
    if( pXItem )
    {
        SvLBoxTab* pXTab = m_pView->GetTab( pEntry, pXItem );
        if ( !rMEvt.IsMod1() && !rMEvt.IsMod2() && rMEvt.IsLeft() && pXTab->IsEditable()
            && pEntry == m_pView->FirstSelected() && nullptr == m_pView->NextSelected( pEntry ) )
                // #i8234# FirstSelected() and NextSelected() ensures, that inplace editing is only triggered, when only one entry is selected
            m_nFlags |= LBoxFlags::StartEditTimer;
        if ( !m_pView->IsSelected( pEntry ) )
            m_nFlags &= ~LBoxFlags::StartEditTimer;
    }


    if( (rMEvt.GetClicks() % 2) == 0)
    {
        m_nFlags &= ~LBoxFlags::StartEditTimer;
        m_pView->pHdlEntry = pEntry;
        if( !m_pView->DoubleClickHdl() )
        {
            // Handler signals nothing to be done anymore, bail out, 'this' may
            // even be dead and destroyed.
            return;
        }
        else
        {
            // if the entry was deleted within the handler
            pEntry = GetClickedEntry( aPos );
            if( !pEntry )
                return;
            if( pEntry != m_pView->pHdlEntry )
            {
                // select anew & bye
                if( !m_bSimpleTravel && !m_aSelEng.IsAlwaysAdding())
                    SelAllDestrAnch( false ); // DeselectAll();
                SetCursor( pEntry );

                return;
            }
            if( pEntry->HasChildren() || pEntry->HasChildrenOnDemand() )
            {
                if( m_pView->IsExpanded(pEntry) )
                    m_pView->Collapse( pEntry );
                else
                    m_pView->Expand( pEntry );
                if( pEntry == m_pCursor )  // only if Entryitem was clicked
                                          // (Nodebutton is not an Entryitem!)
                    m_pView->Select( m_pCursor );
                return;
            }
        }
    }
    else
    {
        // CheckButton? (TreeListBox: Check + Info)
        if( ButtonDownCheckCtrl(rMEvt, pEntry) )
            return;
        // Inplace-Editing?
    }
    if ( m_aSelEng.GetSelectionMode() != SelectionMode::NONE
         && !rMEvt.IsRight() ) // tdf#128824
        m_aSelEng.SelMouseButtonDown( rMEvt );
}

void SvImpLBox::MouseButtonUp( const MouseEvent& rMEvt)
{
    if ( !ButtonUpCheckCtrl( rMEvt ) && ( m_aSelEng.GetSelectionMode() != SelectionMode::NONE ) )
        m_aSelEng.SelMouseButtonUp( rMEvt );
    EndScroll();
    if( m_nFlags & LBoxFlags::StartEditTimer )
    {
        m_nFlags &= ~LBoxFlags::StartEditTimer;
        m_aEditClickPos = rMEvt.GetPosPixel();
        m_aEditIdle.Start();
    }

    if (m_pView->mbActivateOnSingleClick)
        m_pView->DoubleClickHdl();
}

void SvImpLBox::MouseMove( const MouseEvent& rMEvt)
{
    Point aPos = rMEvt.GetPosPixel();
    SvTreeListEntry* pEntry = GetClickedEntry(aPos);
    if ( !MouseMoveCheckCtrl( rMEvt, pEntry ) && ( m_aSelEng.GetSelectionMode() != SelectionMode::NONE ) )
    {
        m_aSelEng.SelMouseMove(rMEvt);
        if (m_pView->mbHoverSelection)
        {
            if (aPos.X() < 0 || aPos.Y() < 0 || aPos.X() > m_aOutputSize.Width() || aPos.Y() > m_aOutputSize.Height())
                m_pView->SelectAll(false);
            else if (!m_pView->IsSelected(pEntry) && IsSelectable(pEntry))
                m_pView->Select(pEntry);
        }
    }
}

void SvImpLBox::ExpandAll()
{
    sal_uInt16 nRefDepth = m_pTree->GetDepth(m_pCursor);
    SvTreeListEntry* pCur = m_pTree->Next(m_pCursor);
    while (pCur && m_pTree->GetDepth(pCur) > nRefDepth)
    {
        if (pCur->HasChildren() && !m_pView->IsExpanded(pCur))
            m_pView->Expand(pCur);
        pCur = m_pTree->Next(pCur);
    }
}

void SvImpLBox::CollapseTo(SvTreeListEntry* pParentToCollapse)
{
    // collapse all parents until we get to the given parent to collapse
    if (pParentToCollapse)
    {
        sal_uInt16 nRefDepth;
        // special case explorer: if the root only has a single
        // entry, don't collapse the root entry
        if (m_pTree->GetChildList(nullptr).size() < 2)
        {
            nRefDepth = 1;
            pParentToCollapse = m_pCursor;
            while (m_pTree->GetParent(pParentToCollapse)
                   && m_pTree->GetDepth(m_pTree->GetParent(pParentToCollapse)) > 0)
            {
                pParentToCollapse = m_pTree->GetParent(pParentToCollapse);
            }
        }
        else
            nRefDepth = m_pTree->GetDepth(pParentToCollapse);

        if (m_pView->IsExpanded(pParentToCollapse))
            m_pView->Collapse(pParentToCollapse);
        SvTreeListEntry* pCur = m_pTree->Next(pParentToCollapse);
        while (pCur && m_pTree->GetDepth(pCur) > nRefDepth)
        {
            if (pCur->HasChildren() && m_pView->IsExpanded(pCur))
                m_pView->Collapse(pCur);
            pCur = m_pTree->Next(pCur);
        }
    }
}

bool SvImpLBox::KeyInput( const KeyEvent& rKEvt)
{
    m_aEditIdle.Stop();
    const vcl::KeyCode& rKeyCode = rKEvt.GetKeyCode();

    if( rKeyCode.IsMod2() )
        return false; // don't evaluate Alt key

    m_nFlags &= ~LBoxFlags::Filling;

    if( !m_pCursor )<--- First condition
        m_pCursor = m_pStartEntry;
    if( !m_pCursor )<--- Second condition
        return false;

    bool bKeyUsed = true;

    sal_uInt16  nDelta = static_cast<sal_uInt16>(m_aVerSBar->GetPageSize());
    sal_uInt16  aCode = rKeyCode.GetCode();

    bool    bShift = rKeyCode.IsShift();
    bool    bMod1 = rKeyCode.IsMod1();

    SvTreeListEntry* pNewCursor;

    switch( aCode )
    {
        case KEY_UP:
            if( !IsEntryInView( m_pCursor ) )
                MakeVisible( m_pCursor );

            pNewCursor = m_pCursor;
            do
            {
                pNewCursor = m_pView->PrevVisible(pNewCursor);
            } while( pNewCursor && !IsSelectable(pNewCursor) );

            // if there is no next entry, take the current one
            // this ensures that in case of _one_ entry in the list, this entry is selected when pressing
            // the cursor key
            if (!pNewCursor)
                pNewCursor = m_pCursor;

            m_aSelEng.CursorPosChanging( bShift, bMod1 );
            SetCursor( pNewCursor, bMod1 );     // no selection, when Ctrl is on
            if( !IsEntryInView( pNewCursor ) )
                KeyUp( false );
            break;

        case KEY_DOWN:
            if( !IsEntryInView( m_pCursor ) )
                MakeVisible( m_pCursor );

            pNewCursor = m_pCursor;
            do
            {
                pNewCursor = m_pView->NextVisible(pNewCursor);
            } while( pNewCursor && !IsSelectable(pNewCursor) );

            // if there is no next entry, take the current one
            // this ensures that in case of _one_ entry in the list, this entry is selected when pressing
            // the cursor key
            // 06.09.20001 - 83416 - frank.schoenheit@sun.com
            if ( !pNewCursor && m_pCursor )
                pNewCursor = m_pCursor;

            if( pNewCursor )
            {
                m_aSelEng.CursorPosChanging( bShift, bMod1 );
                if( IsEntryInView( pNewCursor ) )
                    SetCursor( pNewCursor, bMod1 ); // no selection, when Ctrl is on
                else
                {
                    if( m_pCursor )
                        m_pView->Select( m_pCursor, false );
                    KeyDown( false );
                    SetCursor( pNewCursor, bMod1 ); // no selection, when Ctrl is on
                }
            }
            else
                KeyDown( false );   // because scrollbar range might still
                                        // allow scrolling
            break;

        case KEY_RIGHT:
        {
            if( m_bSubLstOpLR )
            {
                // only try to expand if sublist is expandable,
                // otherwise ignore the key press
                if( IsExpandable() && !m_pView->IsExpanded( m_pCursor ) )
                    m_pView->Expand( m_pCursor );
            }
            else if (m_aHorSBar->IsVisible())
            {
                long    nThumb = m_aHorSBar->GetThumbPos();
                nThumb += m_aHorSBar->GetLineSize();
                long    nOldThumb = m_aHorSBar->GetThumbPos();
                m_aHorSBar->SetThumbPos( nThumb );
                nThumb = nOldThumb;
                nThumb -= m_aHorSBar->GetThumbPos();
                nThumb *= -1;
                if( nThumb )
                {
                    KeyLeftRight( nThumb );
                    EndScroll();
                }
            }
            else
                bKeyUsed = false;
            break;
        }

        case KEY_LEFT:
        {
            if (m_aHorSBar->IsVisible())
            {
                long    nThumb = m_aHorSBar->GetThumbPos();
                nThumb -= m_aHorSBar->GetLineSize();
                long    nOldThumb = m_aHorSBar->GetThumbPos();
                m_aHorSBar->SetThumbPos( nThumb );
                nThumb = nOldThumb;
                nThumb -= m_aHorSBar->GetThumbPos();
                if( nThumb )
                {
                    KeyLeftRight( -nThumb );
                    EndScroll();
                }
                else if( m_bSubLstOpLR )
                {
                    if( IsExpandable() && m_pView->IsExpanded( m_pCursor ) )
                        m_pView->Collapse( m_pCursor );
                    else
                    {
                        pNewCursor = m_pView->GetParent( m_pCursor );
                        if( pNewCursor )
                            SetCursor( pNewCursor );
                    }
                }
            }
            else if( m_bSubLstOpLR )
            {
                if( IsExpandable() && m_pView->IsExpanded( m_pCursor ) )
                    m_pView->Collapse( m_pCursor );
                else
                {
                    pNewCursor = m_pView->GetParent( m_pCursor );
                    if( pNewCursor )
                        SetCursor( pNewCursor );
                }
            }
            else
                bKeyUsed = false;
            break;
        }

        case KEY_PAGEUP:
            if( !bMod1 )
            {
                pNewCursor = m_pView->PrevVisible(m_pCursor, nDelta);

                while( nDelta && pNewCursor && !IsSelectable(pNewCursor) )
                {
                    pNewCursor = m_pView->NextVisible(pNewCursor);
                    nDelta--;
                }

                if( nDelta )
                {
                    DBG_ASSERT(pNewCursor && pNewCursor!=m_pCursor, "Cursor?");
                    m_aSelEng.CursorPosChanging( bShift, bMod1 );
                    if( IsEntryInView( pNewCursor ) )
                        SetCursor( pNewCursor );
                    else
                    {
                        SetCursor( pNewCursor );
                        KeyUp( true );
                    }
                }
            }
            else
                bKeyUsed = false;
            break;

        case KEY_PAGEDOWN:
            if( !bMod1 )
            {
                pNewCursor= m_pView->NextVisible(m_pCursor, nDelta);

                while( nDelta && pNewCursor && !IsSelectable(pNewCursor) )
                {
                    pNewCursor = m_pView->PrevVisible(pNewCursor);
                    nDelta--;
                }

                if( nDelta && pNewCursor )
                {
                    DBG_ASSERT(pNewCursor && pNewCursor!=m_pCursor, "Cursor?");
                    m_aSelEng.CursorPosChanging( bShift, bMod1 );
                    if( IsEntryInView( pNewCursor ) )
                        SetCursor( pNewCursor );
                    else
                    {
                        SetCursor( pNewCursor );
                        KeyDown( true );
                    }
                }
                else
                    KeyDown( false ); // see also: KEY_DOWN
            }
            else
                bKeyUsed = false;
            break;

        case KEY_SPACE:
            if ( m_pView->GetSelectionMode() != SelectionMode::NONE )
            {
                if ( bMod1 )
                {
                    if ( m_pView->GetSelectionMode() == SelectionMode::Multiple && !bShift )
                        // toggle selection
                        m_pView->Select( m_pCursor, !m_pView->IsSelected( m_pCursor ) );
                }
                else if ( !bShift /*&& !bMod1*/ )
                {
                    if ( m_aSelEng.IsAddMode() )
                    {
                        // toggle selection
                        m_pView->Select( m_pCursor, !m_pView->IsSelected( m_pCursor ) );
                    }
                    else if ( !m_pView->IsSelected( m_pCursor ) )
                    {
                        SelAllDestrAnch( false );
                        m_pView->Select( m_pCursor );
                    }
                    else
                        bKeyUsed = false;
                }
                else
                    bKeyUsed = false;
            }
            else
                bKeyUsed = false;
            break;

        case KEY_RETURN:
            bKeyUsed = !m_pView->DoubleClickHdl();
            break;

        case KEY_F2:
            if( !bShift && !bMod1 )
            {
                m_aEditClickPos = Point( -1, -1 );
                EditTimerCall( nullptr );
            }
            else
                bKeyUsed = false;
            break;

        case KEY_F8:
            if( bShift && m_pView->GetSelectionMode()==SelectionMode::Multiple &&
                !(m_nStyle & WB_SIMPLEMODE))
            {
                if( m_aSelEng.IsAlwaysAdding() )
                    m_aSelEng.AddAlways( false );
                else
                    m_aSelEng.AddAlways( true );
            }
            else
                bKeyUsed = false;
            break;

        case KEY_ADD:
            if (!m_pView->IsExpanded(m_pCursor))
                m_pView->Expand(m_pCursor);
            if (bMod1)
                ExpandAll();
            break;

        case KEY_A:
            if( bMod1 )
                SelAllDestrAnch( true );
            else
                bKeyUsed = false;
            break;

        case KEY_SUBTRACT:
            if (m_pView->IsExpanded(m_pCursor))
                m_pView->Collapse(m_pCursor);
            if (bMod1)
                CollapseTo(m_pTree->GetRootLevelParent(m_pCursor));
            break;

        case KEY_MULTIPLY:
            if( bMod1 )
            {
                // only try to expand/collapse if sublist is expandable,
                // otherwise ignore the key press
                if( IsExpandable() )
                {
                    if (!m_pView->IsAllExpanded(m_pCursor))
                    {
                        m_pView->Expand(m_pCursor);
                        ExpandAll();
                    }
                    else
                        CollapseTo(m_pCursor);
                }
            }
            else
                bKeyUsed = false;
            break;

        case KEY_DIVIDE :
            if( bMod1 )
                SelAllDestrAnch( true );
            else
                bKeyUsed = false;
            break;

        case KEY_COMMA :
            if( bMod1 )
                SelAllDestrAnch( false );
            else
                bKeyUsed = false;
            break;

        case KEY_HOME :
            pNewCursor = m_pView->GetModel()->First();

            while( pNewCursor && !IsSelectable(pNewCursor) )
            {
                pNewCursor = m_pView->NextVisible(pNewCursor);
            }

            if( pNewCursor && pNewCursor != m_pCursor )
            {
//              SelAllDestrAnch( false );
                m_aSelEng.CursorPosChanging( bShift, bMod1 );
                SetCursor( pNewCursor );
                if( !IsEntryInView( pNewCursor ) )
                    MakeVisible( pNewCursor );
            }
            else
                bKeyUsed = false;
            break;

        case KEY_END :
            pNewCursor = m_pView->GetModel()->Last();

            while( pNewCursor && !IsSelectable(pNewCursor) )
            {
                pNewCursor = m_pView->PrevVisible(pNewCursor);
            }

            if( pNewCursor && pNewCursor != m_pCursor)
            {
//              SelAllDestrAnch( false );
                m_aSelEng.CursorPosChanging( bShift, bMod1 );
                SetCursor( pNewCursor );
                if( !IsEntryInView( pNewCursor ) )
                    MakeVisible( pNewCursor );
            }
            else
                bKeyUsed = false;
            break;

        case KEY_ESCAPE:
        case KEY_TAB:
        case KEY_DELETE:
        case KEY_BACKSPACE:
            // must not be handled because this quits dialogs and does other magic things...
            // if there are other single keys which should not be handled, they can be added here
            bKeyUsed = false;
            break;

        default:
            // is there any reason why we should eat the events here? The only place where this is called
            // is from SvTreeListBox::KeyInput. If we set bKeyUsed to true here, then the key input
            // is just silenced. However, we want SvLBox::KeyInput to get a chance, to do the QuickSelection
            // handling.
            // (The old code here which intentionally set bKeyUsed to sal_True said this was because of "quick search"
            // handling, but actually there was no quick search handling anymore. We just re-implemented it.)
            // #i31275# / 2009-06-16 / frank.schoenheit@sun.com
            bKeyUsed = false;
            break;
    }
    return bKeyUsed;
}

void SvImpLBox::GetFocus()
{
    if( m_pCursor )
    {
        m_pView->SetEntryFocus( m_pCursor, true );
        ShowCursor( true );
// auskommentiert wg. deselectall
//      if( bSimpleTravel && !pView->IsSelected(pCursor) )
//          pView->Select( pCursor, true );
    }
    if( m_nStyle & WB_HIDESELECTION )
    {
        SvTreeListEntry* pEntry = m_pView->FirstSelected();
        while( pEntry )
        {
            InvalidateEntry( pEntry );
            pEntry = m_pView->NextSelected( pEntry );
        }
    }
}

void SvImpLBox::LoseFocus()
{
    m_aEditIdle.Stop();
    if( m_pCursor )
        m_pView->SetEntryFocus( m_pCursor,false );
    ShowCursor( false );

    if( m_nStyle & WB_HIDESELECTION )
    {
        SvTreeListEntry* pEntry = m_pView ?  m_pView->FirstSelected() : nullptr;
        while( pEntry )
        {
            InvalidateEntry( pEntry );
            pEntry = m_pView->NextSelected( pEntry );
        }
    }
}


// ********************************************************************
// SelectionEngine
// ********************************************************************

void SvImpLBox::SelectEntry( SvTreeListEntry* pEntry, bool bSelect )
{
    m_pView->Select( pEntry, bSelect );
}

ImpLBSelEng::ImpLBSelEng( SvImpLBox* pImpl, SvTreeListBox* pV )
{
    pImp = pImpl;
    pView = pV;
}

ImpLBSelEng::~ImpLBSelEng()
{
}

void ImpLBSelEng::BeginDrag()
{
    pImp->BeginDrag();
}

void ImpLBSelEng::CreateAnchor()
{
    pImp->m_pAnchor = pImp->m_pCursor;
}

void ImpLBSelEng::DestroyAnchor()
{
    pImp->m_pAnchor = nullptr;
}

void ImpLBSelEng::SetCursorAtPoint(const Point& rPoint, bool bDontSelectAtCursor)
{
    SvTreeListEntry* pNewCursor = pImp->MakePointVisible( rPoint );
    if( pNewCursor != pImp->m_pCursor  )
        pImp->BeginScroll();

    if( pNewCursor )
    {
        // at SimpleTravel, the SetCursor is selected and the select handler is
        // called
        //if( !bDontSelectAtCursor && !pImp->bSimpleTravel )
        //  pImp->SelectEntry( pNewCursor, true );
        pImp->SetCursor( pNewCursor, bDontSelectAtCursor );
    }
}

bool ImpLBSelEng::IsSelectionAtPoint( const Point& rPoint )
{
    SvTreeListEntry* pEntry = pImp->MakePointVisible( rPoint );
    if( pEntry )
        return pView->IsSelected(pEntry);
    return false;
}

void ImpLBSelEng::DeselectAtPoint( const Point& rPoint )
{
    SvTreeListEntry* pEntry = pImp->MakePointVisible( rPoint );
    if( !pEntry )
        return;
    pImp->SelectEntry( pEntry, false );
}

void ImpLBSelEng::DeselectAll()
{
    pImp->SelAllDestrAnch( false, false ); // don't reset SelectionEngine!
    pImp->m_nFlags &= ~LBoxFlags::DeselectAll;
}

// ***********************************************************************
// Selection
// ***********************************************************************

void SvImpLBox::SetAnchorSelection(SvTreeListEntry* pOldCursor,SvTreeListEntry* pNewCursor)
{
    SvTreeListEntry* pEntry;
    sal_uLong nAnchorVisPos = m_pView->GetVisiblePos( m_pAnchor );
    sal_uLong nOldVisPos = m_pView->GetVisiblePos( pOldCursor );
    sal_uLong nNewVisPos = m_pView->GetVisiblePos( pNewCursor );

    if( nOldVisPos > nAnchorVisPos ||
        ( nAnchorVisPos==nOldVisPos && nNewVisPos > nAnchorVisPos) )
    {
        if( nNewVisPos > nOldVisPos )
        {
            pEntry = pOldCursor;
            while( pEntry && pEntry != pNewCursor )
            {
                m_pView->Select( pEntry );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry );
            return;
        }

        if( nNewVisPos < nAnchorVisPos )
        {
            pEntry = m_pAnchor;
            while( pEntry && pEntry != pOldCursor )
            {
                m_pView->Select( pEntry, false );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry, false );

            pEntry = pNewCursor;
            while( pEntry && pEntry != m_pAnchor )
            {
                m_pView->Select( pEntry );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry );
            return;
        }

        if( nNewVisPos < nOldVisPos )
        {
            pEntry = m_pView->NextVisible(pNewCursor);
            while( pEntry && pEntry != pOldCursor )
            {
                m_pView->Select( pEntry, false );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry, false );
            return;
        }
    }
    else
    {
        if( nNewVisPos < nOldVisPos )  // enlarge selection
        {
            pEntry = pNewCursor;
            while( pEntry && pEntry != pOldCursor )
            {
                m_pView->Select( pEntry );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry );
            return;
        }

        if( nNewVisPos > nAnchorVisPos )
        {
            pEntry = pOldCursor;
            while( pEntry && pEntry != m_pAnchor )
            {
                m_pView->Select( pEntry, false );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry, false );
            pEntry = m_pAnchor;
            while( pEntry && pEntry != pNewCursor )
            {
                m_pView->Select( pEntry );
                pEntry = m_pView->NextVisible(pEntry);
            }
            if( pEntry )
                m_pView->Select( pEntry );
            return;
        }

        if( nNewVisPos > nOldVisPos )
        {
            pEntry = pOldCursor;
            while( pEntry && pEntry != pNewCursor )
            {
                m_pView->Select( pEntry, false );
                pEntry = m_pView->NextVisible(pEntry);
            }
            return;
        }
    }
}

void SvImpLBox::SelAllDestrAnch(
    bool bSelect, bool bDestroyAnchor, bool bSingleSelToo )
{
    SvTreeListEntry* pEntry;
    m_nFlags &= ~LBoxFlags::DeselectAll;
    if( bSelect && m_bSimpleTravel )
    {
        if( m_pCursor && !m_pView->IsSelected( m_pCursor ))
        {
            m_pView->Select( m_pCursor );
        }
        return;
    }
    if( !bSelect && m_pView->GetSelectionCount() == 0 )
    {
        if( m_bSimpleTravel && ( !GetUpdateMode() || !m_pCursor) )
            m_nFlags |= LBoxFlags::DeselectAll;
        return;
    }
    if( bSelect && m_pView->GetSelectionCount() == m_pView->GetEntryCount())
        return;
    if( !bSingleSelToo && m_bSimpleTravel )
        return;

    if( !bSelect && m_pView->GetSelectionCount()==1 && m_pCursor &&
        m_pView->IsSelected( m_pCursor ))
    {
        m_pView->Select( m_pCursor, false );
        if( bDestroyAnchor )
            DestroyAnchor(); // delete anchor & reset SelectionEngine
        else
            m_pAnchor = nullptr; // always delete internal anchor
        return;
    }

    if( m_bSimpleTravel && !m_pCursor && !GetUpdateMode() )
        m_nFlags |= LBoxFlags::DeselectAll;

    ShowCursor( false );
    bool bUpdate = GetUpdateMode();

    m_nFlags |= LBoxFlags::IgnoreSelect; // EntryInserted should not do anything
    pEntry = m_pTree->First();
    while( pEntry )
    {
        if( m_pView->Select( pEntry, bSelect ) )
        {
            if( bUpdate && m_pView->IsEntryVisible(pEntry) )
            {
                long nY = GetEntryLine( pEntry );
                if( IsLineVisible( nY ) )
                    InvalidateEntry(pEntry);
            }
        }
        pEntry = m_pTree->Next( pEntry );
    }
    m_nFlags &= ~LBoxFlags::IgnoreSelect;

    if( bDestroyAnchor )
        DestroyAnchor(); // delete anchor & reset SelectionEngine
    else
        m_pAnchor = nullptr; // always delete internal anchor
    ShowCursor( true );
}

void SvImpLBox::SetSelectionMode( SelectionMode eSelMode  )
{
    m_aSelEng.SetSelectionMode( eSelMode);
    if( eSelMode == SelectionMode::Single )
        m_bSimpleTravel = true;
    else
        m_bSimpleTravel = false;
    if( (m_nStyle & WB_SIMPLEMODE) && (eSelMode == SelectionMode::Multiple) )
        m_aSelEng.AddAlways( true );
}

// ***********************************************************************
// Drag & Drop
// ***********************************************************************

void SvImpLBox::SetDragDropMode( DragDropMode eDDMode )
{
    if( eDDMode != DragDropMode::NONE )
    {
        m_aSelEng.ExpandSelectionOnMouseMove( false );
        m_aSelEng.EnableDrag( true );
    }
    else
    {
        m_aSelEng.ExpandSelectionOnMouseMove();
        m_aSelEng.EnableDrag( false );
    }
}

void SvImpLBox::BeginDrag()
{
    m_nFlags &= ~LBoxFlags::Filling;
    BeginScroll();
    m_pView->StartDrag( 0, m_aSelEng.GetMousePosPixel() );
    EndScroll();
}

void SvImpLBox::PaintDDCursor(SvTreeListEntry* pEntry, bool bShow)
{
    if (pEntry)
    {

        SvViewDataEntry* pViewData = m_pView->GetViewData(pEntry);
        pViewData->SetDragTarget(bShow);
#ifdef MACOSX
        // in MacOS we need to draw directly (as we are synchronous) or no invalidation happens
        m_pView->PaintEntry1(*pEntry, GetEntryLine(pEntry), *m_pView);
#else
        InvalidateEntry(pEntry);
#endif
    }
}

void SvImpLBox::Command( const CommandEvent& rCEvt )
{
    CommandEventId nCommand = rCEvt.GetCommand();

    if( nCommand == CommandEventId::ContextMenu )
        m_aEditIdle.Stop();

    // scroll mouse event?
    if (nCommand == CommandEventId::Wheel ||
        nCommand == CommandEventId::StartAutoScroll ||
        nCommand == CommandEventId::AutoScroll ||
        nCommand == CommandEventId::Gesture)
    {
        if (m_pView->HandleScrollCommand(rCEvt, m_aHorSBar.get(), m_aVerSBar.get()))
            return;
    }

    if( m_bContextMenuHandling && nCommand == CommandEventId::ContextMenu )
    {
        Point   aPopupPos;
        bool    bClickedIsFreePlace = false;
        std::stack<SvTreeListEntry*> aSelRestore;

        if( rCEvt.IsMouseEvent() )
        {   // change selection, if mouse position doesn't fit to selection

            aPopupPos = rCEvt.GetMousePosPixel();

            SvTreeListEntry*    pClickedEntry = GetEntry( aPopupPos );
            if( pClickedEntry )
            {   // mouse in non empty area
                bool                bClickedIsSelected = false;

                // collect the currently selected entries
                SvTreeListEntry*        pSelected = m_pView->FirstSelected();
                while( pSelected )
                {
                    bClickedIsSelected |= ( pClickedEntry == pSelected );
                    pSelected = m_pView->NextSelected( pSelected );
                }

                // if the entry which the user clicked at is not selected
                if( !bClickedIsSelected )
                {   // deselect all other and select the clicked one
                    m_pView->SelectAll( false );
                    m_pView->SetCursor( pClickedEntry );
                }
            }
            else if( m_aSelEng.GetSelectionMode() == SelectionMode::Single )
            {
                bClickedIsFreePlace = true;
                sal_Int32               nSelectedEntries = m_pView->GetSelectionCount();
                SvTreeListEntry*        pSelected = m_pView->FirstSelected();
                for(sal_Int32 nSel = 0; nSel < nSelectedEntries; nSel++ )
                {
                    aSelRestore.push(pSelected);
                    pSelected = m_pView->NextSelected( pSelected );
                }
                m_pView->SelectAll( false );
            }
            else
            {   // deselect all
                m_pView->SelectAll( false );
            }


        }
        else
        {   // key event (or at least no mouse event)
            sal_Int32   nSelectionCount = m_pView->GetSelectionCount();

            if( nSelectionCount )
            {   // now always take first visible as base for positioning the menu
                SvTreeListEntry*    pSelected = m_pView->FirstSelected();
                while( pSelected )
                {
                    if( IsEntryInView( pSelected ) )
                        break;

                    pSelected = m_pView->NextSelected( pSelected );
                }

                if( !pSelected )
                {
                    // no one was visible
                    pSelected = m_pView->FirstSelected();
                    m_pView->MakeVisible( pSelected );
                }

                aPopupPos = m_pView->GetFocusRect( pSelected, m_pView->GetEntryPosition( pSelected ).Y() ).Center();
            }
            else
                aPopupPos = Point( 0, 0 );
        }

        {
            VclPtr<PopupMenu> pPopup = m_pView->CreateContextMenu();
            if (pPopup)
            {
                // do action for selected entry in popup menu
                sal_uInt16 nMenuAction = pPopup->Execute( m_pView, aPopupPos );
                if ( nMenuAction )
                    m_pView->ExecuteContextMenuAction( nMenuAction );
                pPopup.disposeAndClear();
            }
        }

        if( bClickedIsFreePlace )
        {
            while(!aSelRestore.empty())
            {
                SvTreeListEntry* pEntry = aSelRestore.top();
                //#i19717# the entry is maybe already deleted
                bool bFound = false;
                for(sal_uLong nEntry = 0; nEntry < m_pView->GetEntryCount(); nEntry++)
                    if(pEntry == m_pView->GetEntry(nEntry))
                    {
                        bFound = true;
                        break;
                    }
                if(bFound)
                    SetCurEntry( pEntry );
                aSelRestore.pop();
            }
        }
    }
    else
    {
        const Point& rPos = rCEvt.GetMousePosPixel();
        if( rPos.X() < m_aOutputSize.Width() && rPos.Y() < m_aOutputSize.Height() )
            m_aSelEng.Command( rCEvt );
    }
}

void SvImpLBox::BeginScroll()
{
    if( !(m_nFlags & LBoxFlags::InScrolling))
    {
        m_nFlags |= LBoxFlags::InScrolling;
    }
}

void SvImpLBox::EndScroll()
{
    if( m_nFlags & LBoxFlags::InScrolling)
    {
        m_pView->NotifyEndScroll();
        m_nFlags &= ~LBoxFlags::InScrolling;
    }
}


tools::Rectangle SvImpLBox::GetVisibleArea() const
{
    Point aPos( m_pView->GetMapMode().GetOrigin() );
    aPos.setX( aPos.X() * -1 );
    tools::Rectangle aRect( aPos, m_aOutputSize );
    return aRect;
}

void SvImpLBox::Invalidate()
{
    m_pView->SetClipRegion();
}

void SvImpLBox::SetCurEntry( SvTreeListEntry* pEntry )
{
    if  (  ( m_aSelEng.GetSelectionMode() != SelectionMode::Single )
        && ( m_aSelEng.GetSelectionMode() != SelectionMode::NONE )
        )
        SelAllDestrAnch( false );
    if ( pEntry )
        MakeVisible( pEntry );
    SetCursor( pEntry );
    if ( pEntry && ( m_aSelEng.GetSelectionMode() != SelectionMode::NONE ) )
        m_pView->Select( pEntry );
}

IMPL_LINK_NOARG(SvImpLBox, EditTimerCall, Timer *, void)
{
    if( !m_pView->IsInplaceEditingEnabled() )
        return;

    bool bIsMouseTriggered = m_aEditClickPos.X() >= 0;
    if ( bIsMouseTriggered )
    {
        Point aCurrentMousePos = m_pView->GetPointerPosPixel();
        if  (   ( std::abs( aCurrentMousePos.X() - m_aEditClickPos.X() ) > 5 )
            ||  ( std::abs( aCurrentMousePos.Y() - m_aEditClickPos.Y() ) > 5 )
            )
        {
            return;
        }
    }

    SvTreeListEntry* pEntry = GetCurEntry();
    if( pEntry )
    {
        ShowCursor( false );
        m_pView->ImplEditEntry( pEntry );
        ShowCursor( true );
    }
}

bool SvImpLBox::RequestHelp( const HelpEvent& rHEvt )
{
    if( rHEvt.GetMode() & HelpEventMode::QUICK )
    {
        Point aPos( m_pView->ScreenToOutputPixel( rHEvt.GetMousePosPixel() ));
        if( !GetVisibleArea().IsInside( aPos ))
            return false;

        SvTreeListEntry* pEntry = GetEntry( aPos );
        if( pEntry )
        {
            // recalculate text rectangle
            SvLBoxTab* pTab;
            SvLBoxItem* pItem = m_pView->GetItem( pEntry, aPos.X(), &pTab );
            if (!pItem || pItem->GetType() != SvLBoxItemType::String)
                return false;

            aPos = GetEntryPosition( pEntry );
            aPos.setX( m_pView->GetTabPos( pEntry, pTab ) ); //pTab->GetPos();
            Size aSize(pItem->GetWidth(m_pView, pEntry), pItem->GetHeight(m_pView, pEntry));
            SvLBoxTab* pNextTab = NextTab( pTab );
            bool bItemClipped = false;
            // is the item cut off by its right neighbor?
            if( pNextTab && m_pView->GetTabPos(pEntry,pNextTab) < aPos.X()+aSize.Width() )
            {
                aSize.setWidth( pNextTab->GetPos() - pTab->GetPos() );
                bItemClipped = true;
            }
            tools::Rectangle aItemRect( aPos, aSize );

            tools::Rectangle aViewRect( GetVisibleArea() );

            if( bItemClipped || !aViewRect.IsInside( aItemRect ) )
            {
                // clip the right edge of the item at the edge of the view
                //if( aItemRect.Right() > aViewRect.Right() )
                //  aItemRect.Right() = aViewRect.Right();

                Point aPt = m_pView->OutputToScreenPixel( aItemRect.TopLeft() );
                aItemRect.SetLeft( aPt.X() );
                aItemRect.SetTop( aPt.Y() );
                aPt = m_pView->OutputToScreenPixel( aItemRect.BottomRight() );
                aItemRect.SetRight( aPt.X() );
                aItemRect.SetBottom( aPt.Y() );

                Help::ShowQuickHelp( m_pView, aItemRect,
                                     static_cast<SvLBoxString*>(pItem)->GetText(), QuickHelpFlags::Left | QuickHelpFlags::VCenter );
                return true;
            }
        }
    }
    return false;
}

SvLBoxTab* SvImpLBox::NextTab( SvLBoxTab const * pTab )
{
    sal_uInt16 nTabCount = m_pView->TabCount();
    if( nTabCount <= 1 )
        return nullptr;
    for( int nTab=0; nTab < (nTabCount-1); nTab++)
    {
        if( m_pView->aTabs[nTab].get() == pTab )
            return m_pView->aTabs[nTab+1].get();
    }
    return nullptr;
}

void SvImpLBox::EndSelection()
{
    DestroyAnchor();
    m_nFlags &=  ~LBoxFlags::StartEditTimer;
}

void SvImpLBox::SetUpdateMode( bool bMode )
{
    if( m_bUpdateMode != bMode )
    {
        m_bUpdateMode = bMode;
        if( m_bUpdateMode )
            UpdateAll( false );
    }
}

bool SvImpLBox::SetMostRight( SvTreeListEntry* pEntry )
{
    if( m_pView->nTreeFlags & SvTreeFlags::RECALCTABS )
    {
        m_nFlags |= LBoxFlags::IgnoreChangedTabs;
        m_pView->SetTabs();
        m_nFlags &= ~LBoxFlags::IgnoreChangedTabs;
    }

    sal_uInt16 nLastTab = m_pView->aTabs.size() - 1;
    sal_uInt16 nLastItem = pEntry->ItemCount() - 1;
    if( !m_pView->aTabs.empty() && nLastItem != USHRT_MAX )
    {
        if( nLastItem < nLastTab )
            nLastTab = nLastItem;

        SvLBoxTab* pTab = m_pView->aTabs[ nLastTab ].get();
        SvLBoxItem& rItem = pEntry->GetItem( nLastTab );

        long nTabPos = m_pView->GetTabPos( pEntry, pTab );

        long nMaxRight = GetOutputSize().Width();
        Point aPos( m_pView->GetMapMode().GetOrigin() );
        aPos.setX( aPos.X() * -1 ); // conversion document coordinates
        nMaxRight = nMaxRight + aPos.X() - 1;

        long nNextTab = nTabPos < nMaxRight ? nMaxRight : nMaxRight + 50;
        long nTabWidth = nNextTab - nTabPos + 1;
        auto nItemSize = rItem.GetWidth(m_pView,pEntry);
        long nOffset = pTab->CalcOffset( nItemSize, nTabWidth );

        long nRight = nTabPos + nOffset + nItemSize;
        if( nRight > m_nMostRight )
        {
            m_nMostRight = nRight;
            m_pMostRightEntry = pEntry;
            return true;
        }
    }
    return false;
}

void SvImpLBox::FindMostRight()
{
    m_nMostRight = -1;
    m_pMostRightEntry = nullptr;
    if( !m_pView->GetModel() )
        return;

    SvTreeListEntry* pEntry = m_pView->FirstVisible();
    while( pEntry )
    {
        SetMostRight( pEntry );
        pEntry = m_pView->NextVisible( pEntry );
    }
}

void SvImpLBox::FindMostRight( SvTreeListEntry* pParent )
{
    if( !pParent )
        FindMostRight();
    else
        FindMostRight_Impl( pParent );
}

void SvImpLBox::FindMostRight_Impl( SvTreeListEntry* pParent )
{
    SvTreeListEntries& rList = m_pTree->GetChildList( pParent );

    size_t nCount = rList.size();
    for( size_t nCur = 0; nCur < nCount; nCur++ )
    {
        SvTreeListEntry* pChild = rList[nCur].get();
        SetMostRight( pChild );
        if( pChild->HasChildren() && m_pView->IsExpanded( pChild ))
            FindMostRight_Impl( pChild );
    }
}

void SvImpLBox::NotifyTabsChanged()
{
    if( GetUpdateMode() && !(m_nFlags & LBoxFlags::IgnoreChangedTabs ) &&
        m_nCurUserEvent == nullptr )
    {
        m_nCurUserEvent = Application::PostUserEvent(LINK(this,SvImpLBox,MyUserEvent));
    }
}

bool SvImpLBox::IsExpandable() const
{
    return m_pCursor->HasChildren() || m_pCursor->HasChildrenOnDemand();
}

IMPL_LINK(SvImpLBox, MyUserEvent, void*, pArg, void )
{
    m_nCurUserEvent = nullptr;
    if( !pArg )
    {
        m_pView->Invalidate();
        m_pView->PaintImmediately();
    }
    else
    {
        FindMostRight();
        ShowVerSBar();
        m_pView->Invalidate( GetVisibleArea() );
    }
}


void SvImpLBox::StopUserEvent()
{
    if( m_nCurUserEvent != nullptr )
    {
        Application::RemoveUserEvent( m_nCurUserEvent );
        m_nCurUserEvent = nullptr;
    }
}

void SvImpLBox::ShowFocusRect( const SvTreeListEntry* pEntry )
{
    if( pEntry )
    {
        long nY = GetEntryLine(pEntry);
        tools::Rectangle aRect = m_pView->GetFocusRect(pEntry, nY);
        vcl::Region aOldClip( m_pView->GetClipRegion());
        vcl::Region aClipRegion( GetClipRegionRect() );
        m_pView->SetClipRegion( aClipRegion );
        m_pView->ShowFocus( aRect );
        m_pView->SetClipRegion( aOldClip );

    }
    else
    {
        m_pView->HideFocus();
    }
}


void SvImpLBox::implInitDefaultNodeImages()
{
    if ( s_pDefCollapsed )
        // assume that all or nothing is initialized
        return;

    s_pDefCollapsed = new Image(StockImage::Yes, RID_BMP_TREENODE_COLLAPSED);
    s_pDefExpanded = new Image(StockImage::Yes, RID_BMP_TREENODE_EXPANDED);
}


const Image& SvImpLBox::GetDefaultExpandedNodeImage( )
{
    implInitDefaultNodeImages();
    return *s_pDefExpanded;
}


const Image& SvImpLBox::GetDefaultCollapsedNodeImage( )
{
    implInitDefaultNodeImages();
    return *s_pDefCollapsed;
}


void SvImpLBox::CallEventListeners( VclEventId nEvent, void* pData )
{
    if ( m_pView )
        m_pView->CallImplEventListeners( nEvent, pData);
}


bool SvImpLBox::IsSelectable( const SvTreeListEntry* pEntry )
{
    if( pEntry )
    {
        SvViewDataEntry* pViewDataNewCur = m_pView->GetViewDataEntry(pEntry);
        return (pViewDataNewCur == nullptr) || pViewDataNewCur->IsSelectable();
    }
    else
    {
        return false;
    }
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */