This file is indexed.

/usr/lib/lazarus/0.9.30.4/ide/codebrowser.pas is in lazarus-src-0.9.30.4 0.9.30.4-6.

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

The actual contents of the file can be viewed below.

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

  Author: Mattias Gaertner

  Abstract:
    Browser for packages, classes, methods, functions.
    Scope:
      Browse units of IDE, or a project or a package.
      Browse with required packages or without.
    Sort:
      Owner, unit, class, visibility, type (procedure, var, const, ...), identifier

  Notes:
    The codetools provides TCodeTree of every unit.

  ToDo:
    - pause
    - scan recently used packages
    - scan packages in global links
}
unit CodeBrowser;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, types, LCLProc, LResources, Forms, Controls, Graphics,
  Dialogs, Clipbrd, LCLIntf, AVL_Tree, StdCtrls, ExtCtrls, ComCtrls, Buttons,
  Menus, HelpIntfs,
  // codetools
  CodeAtom, BasicCodeTools, DefineTemplates, CodeTree, CodeCache,
  CodeToolsStructs, CodeToolManager, PascalParserTool, LinkScanner, FileProcs,
  CodeIndex, StdCodeTools, SourceLog, CustomCodeTool,
  // IDEIntf
  IDEWindowIntf, SrcEditorIntf, IDEMsgIntf, IDEDialogs, LazConfigStorage,
  IDEHelpIntf, PackageIntf, TextTools, IDECommands, LazIDEIntf,
  // IDE
  Project, DialogProcs, PackageSystem, PackageDefs, LazarusIDEStrConsts,
  IDEOptionDefs, MsgQuickFixes, BasePkgManager, AddToProjectDlg,
  EnvironmentOpts;


type
  TCodeBrowserLevel = (
    cblPackages,
    cblUnits,
    cblIdentifiers
    );
    
  TCodeBrowserTextFilter = (
    cbtfBegins,
    cbtfContains
    );
    
const
  CodeBrowserLevelNames: array[TCodeBrowserLevel] of string = (
    'Packages',
    'Units',
    'Identifiers'
    );
    
  CodeBrowserTextFilterNames: array[TCodeBrowserTextFilter] of string = (
    'Begins',
    'Contains'
    );

  CodeBrowserIDEName     = ' '+'Lazarus IDE';// Note: space is needed to avoid name clashing
  CodeBrowserProjectName = ' '+'Project';
  CodeBrowserHidden = ' ';

type

  { TCodeBrowserViewOptions }

  TCodeBrowserViewOptions = class
  private
    FChangeStamp: integer;
    FModified: boolean;
    FScope: string;
    FLevels: TStrings;
    FShowEmptyNodes: boolean;
    FShowPrivate: boolean;
    FShowProtected: boolean;
    FStoreWithRequiredPackages: boolean;
    FWithRequiredPackages: boolean;
    FLevelFilterText: array[TCodeBrowserLevel] of string;
    FLevelFilterType: array[TCodeBrowserLevel] of TCodeBrowserTextFilter;
    function GetLevelFilterText(Level: TCodeBrowserLevel): string;
    function GetLevelFilterType(Level: TCodeBrowserLevel
      ): TCodeBrowserTextFilter;
    procedure SetLevelFilterText(Level: TCodeBrowserLevel; const AValue: string
      );
    procedure SetLevelFilterType(Level: TCodeBrowserLevel;
      const AValue: TCodeBrowserTextFilter);
    procedure SetModified(const AValue: boolean);
    procedure SetScope(const AValue: string);
    procedure SetLevels(const AValue: TStrings);
    procedure SetShowEmptyNodes(const AValue: boolean);
    procedure SetShowPrivate(const AValue: boolean);
    procedure SetShowProtected(const AValue: boolean);
    procedure SetStoreWithRequiredPackages(const AValue: boolean);
    procedure SetWithRequiredPackages(const AValue: boolean);
    procedure IncreaseChangeStamp;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    procedure LoadFromConfig(ConfigStore: TConfigStorage; const Path: string);
    procedure SaveToConfig(ConfigStore: TConfigStorage; const Path: string);
    function HasLevel(Level: TCodeBrowserLevel): boolean;
  public
    property Scope: string read FScope write SetScope;
    property WithRequiredPackages: boolean read FWithRequiredPackages write SetWithRequiredPackages;
    property StoreWithRequiredPackages: boolean read FStoreWithRequiredPackages write SetStoreWithRequiredPackages;
    property Levels: TStrings read FLevels write SetLevels;
    property ShowPrivate: boolean read FShowPrivate write SetShowPrivate;
    property ShowProtected: boolean read FShowProtected write SetShowProtected;
    property ShowEmptyNodes: boolean read FShowEmptyNodes write SetShowEmptyNodes;
    property LevelFilterText[Level: TCodeBrowserLevel]: string read GetLevelFilterText write SetLevelFilterText;
    property LevelFilterType[Level: TCodeBrowserLevel]: TCodeBrowserTextFilter read GetLevelFilterType write SetLevelFilterType;
    property Modified: boolean read FModified write SetModified;
    property ChangeStamp: integer read FChangeStamp;
  end;


  TCodeBrowserWorkStage = (
    cbwsGetScopeOptions,
    cbwsGatherPackages,
    cbwsFreeUnusedPackages,
    cbwsAddNewPackages,
    cbwsGatherFiles,
    cbwsGatherOutdatedFiles,
    cbwsUpdateUnits,
    cbwsGetViewOptions,
    cbwsUpdateTreeView,
    cbwsFinished
    );
    
  TExpandableNodeType = (
    entPackage,
    entUnit,
    entClass
    );
    
  TCopyNodeType = (
    cntIdentifier,
    cntDescription
    );

  { TCodeBrowserView }

  TCodeBrowserView = class(TForm)
    AllClassesSeparatorMenuItem: TMenuItem;
    AllPackagesSeparatorMenuItem: TMenuItem;
    AllUnitsSeparatorMenuItem: TMenuItem;
    BrowseTreeView: TTreeView;
    UseIdentifierInCurUnitMenuItem: TMenuItem;
    UseUnitInCurUnitMenuItem: TMenuItem;
    RescanButton: TButton;
    IdleTimer1: TIdleTimer;
    UsePkgInProjectMenuItem: TMenuItem;
    UsePkgInCurUnitMenuItem: TMenuItem;
    UseSeparatorMenuItem: TMenuItem;
    ShowEmptyNodesCheckBox: TCheckBox;
    CollapseAllClassesMenuItem: TMenuItem;
    CollapseAllPackagesMenuItem: TMenuItem;
    CollapseAllUnitsMenuItem: TMenuItem;
    CopyDescriptionMenuItem: TMenuItem;
    CopyIdentifierMenuItem: TMenuItem;
    CopySeparatorMenuItem: TMenuItem;
    ExpandAllClassesMenuItem: TMenuItem;
    ExpandAllPackagesMenuItem: TMenuItem;
    ExpandAllUnitsMenuItem: TMenuItem;
    ExportMenuItem: TMenuItem;
    IdentifierFilterBeginsSpeedButton: TSpeedButton;
    IdentifierFilterContainsSpeedButton: TSpeedButton;
    IdentifierFilterEdit: TEdit;
    ImageList1: TImageList;
    LevelsGroupBox: TGroupBox;
    OpenMenuItem: TMenuItem;
    OptionsGroupBox: TGroupBox;
    PackageFilterBeginsSpeedButton: TSpeedButton;
    PackageFilterContainsSpeedButton: TSpeedButton;
    PackageFilterEdit: TEdit;
    PopupMenu1: TPopupMenu;
    ProgressBar1: TProgressBar;
    ScopeComboBox: TComboBox;
    ScopeGroupBox: TGroupBox;
    ScopeWithRequiredPackagesCheckBox: TCheckBox;
    ShowIdentifiersCheckBox: TCheckBox;
    ShowPackagesCheckBox: TCheckBox;
    ShowPrivateCheckBox: TCheckBox;
    ShowProtectedCheckBox: TCheckBox;
    ShowUnitsCheckBox: TCheckBox;
    StatusBar1: TStatusBar;
    UnitFilterBeginsSpeedButton: TSpeedButton;
    UnitFilterContainsSpeedButton: TSpeedButton;
    UnitFilterEdit: TEdit;
    procedure BrowseTreeViewMouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    procedure FormDeactivate(Sender: TObject);
    procedure UseIdentifierInCurUnitMenuItemClick(Sender: TObject);
    procedure UsePkgInCurUnitMenuItemClick(Sender: TObject);
    procedure UsePkgInProjectMenuItemClick(Sender: TObject);
    procedure UseUnitInCurUnitMenuItemClick(Sender: TObject);
    procedure BrowseTreeViewMouseDown(Sender: TOBject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure BrowseTreeViewShowHint(Sender: TObject; HintInfo: PHintInfo);
    procedure CollapseAllPackagesMenuItemClick(Sender: TObject);
    procedure CollapseAllUnitsMenuItemClick(Sender: TObject);
    procedure CollapseAllClassesMenuItemClick(Sender: TObject);
    procedure CopyDescriptionMenuItemClick(Sender: TObject);
    procedure CopyIdentifierMenuItemClick(Sender: TObject);
    procedure ExpandAllClassesMenuItemClick(Sender: TObject);
    procedure ExpandAllPackagesMenuItemClick(Sender: TObject);
    procedure ExpandAllUnitsMenuItemClick(Sender: TObject);
    procedure ExportMenuItemClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure IdleTimer1Timer(Sender: TObject);
    procedure PackageFilterEditChange(Sender: TObject);
    procedure PackageFilterEditEditingDone(Sender: TObject);
    procedure PopupMenu1Popup(Sender: TObject);
    procedure RescanButtonClick(Sender: TObject);
    procedure ScopeComboBoxGetItems(Sender: TObject);
    procedure ScopeComboBoxEditingDone(Sender: TObject);
    procedure ScopeWithRequiredPackagesCheckBoxChange(Sender: TObject);
    procedure OnIdle(Sender: TObject; var Done: Boolean);
    procedure OpenMenuItemClick(Sender: TObject);
    procedure ShowIdentifiersCheckBoxChange(Sender: TObject);
    procedure ShowPackagesCheckBoxChange(Sender: TObject);
    procedure ShowPrivateCheckBoxChange(Sender: TObject);
    procedure ShowUnitsCheckBoxChange(Sender: TObject);
  private
    FHintWindow: THintWindow;
    FIDEDescription: string;
    FOptions: TCodeBrowserViewOptions;
    FOptionsChangeStamp: integer;
    FProjectDescription: string;
    FParserRoot: TCodeBrowserUnitList;
    FScannedBytes: PtrInt;
    FScannedIdentifiers: PtrInt;
    FScannedLines: PtrInt;
    FScannedPackages: integer;
    FScannedUnits: integer;
    FUpdateNeeded: boolean;
    FViewRoot: TCodeBrowserUnitList;
    FVisibleIdentifiers: PtrInt;
    FVisiblePackages: integer;
    FVisibleUnits: integer;
    FWorkingParserRoot: TCodeBrowserUnitList;
    fUpdateCount: integer;
    fStage: TCodeBrowserWorkStage;
    fOutdatedFiles: TAVLTree;// tree of TCodeBrowserUnit
    fLastStatusBarUpdate: TDateTime;
    ImgIDDefault: integer;
    ImgIDProgramCode: Integer;
    ImgIDUnitCode: Integer;
    ImgIDInterfaceSection: Integer;
    ImgIDImplementation: Integer;
    ImgIDInitialization: Integer;
    ImgIDFinalization: Integer;
    ImgIDTypeSection: Integer;
    ImgIDType: Integer;
    ImgIDVarSection: Integer;
    ImgIDVariable: Integer;
    ImgIDConstSection: Integer;
    ImgIDConst: Integer;
    ImgIDClass: Integer;
    ImgIDProc: Integer;
    ImgIDProperty: Integer;
    ImgIDPackage: Integer;
    ImgIDProject: Integer;
    procedure LoadOptions;
    procedure LoadLevelsGroupBox;
    procedure LoadFilterGroupbox;
    procedure FillScopeComboBox;
    procedure SetScannedBytes(const AValue: PtrInt);
    procedure SetScannedIdentifiers(const AValue: PtrInt);
    procedure SetScannedLines(const AValue: PtrInt);
    procedure SetScannedPackages(const AValue: integer);
    procedure SetScannedUnits(const AValue: integer);
    procedure SetUpdateNeeded(const AValue: boolean);
    procedure SetVisibleIdentifiers(const AValue: PtrInt);
    procedure SetVisiblePackages(const AValue: integer);
    procedure SetVisibleUnits(const AValue: integer);
    procedure Work(var Done: Boolean);
    procedure WorkGetScopeOptions;
    procedure WorkGatherPackages;
    procedure WorkFreeUnusedPackages;
    procedure WorkAddNewUnitLists;
    procedure WorkGatherFileLists;
    procedure WorkUpdateFileList(List: TCodeBrowserUnitList);
    procedure WorkGatherOutdatedFiles;
    procedure WorkUpdateUnits;
    procedure WorkUpdateUnit(AnUnit: TCodeBrowserUnit);
    procedure WorkGetViewOptions;
    procedure WorkUpdateTreeView;
    procedure FreeUnitList(List: TCodeBrowserUnitList);
    procedure UpdateStatusBar(Lazy: boolean);
    procedure RemoveUnit(AnUnit: TCodeBrowserUnit);
    function CountIdentifiers(Tool: TCodeTool): integer;
    procedure UpdateTreeView;
    procedure ClearTreeView;
    procedure InitTreeView;
    function ListOwnerToText(const ListOwner: string): string;
    procedure InitImageList;
    function GetNodeImage(CodeNode: TObject): integer;
    function GetTVNodeHint(TVNode: TTreeNode): string;
    function GetCodeHelp(TVNode: TTreeNode; out BaseURL, HTMLHint: string): boolean;
    procedure ExpandCollapseAllNodesInTreeView(NodeType: TExpandableNodeType;
                                               Expand: boolean);
    procedure CopyNode(TVNode: TTreeNode; NodeType: TCopyNodeType);
    function GetSelectedUnit: TCodeBrowserUnit;
    function GetSelectedPackage: TLazPackage;
    function GetCurUnitInSrcEditor(out FileOwner: TObject;
                                   out UnitCode: TCodeBuffer): boolean;
    function GetCurPackageInSrcEditor: TLazPackage;
    procedure OpenTVNode(TVNode: TTreeNode);
    procedure UseUnitInSrcEditor(InsertIdentifier: boolean);
    procedure CloseHintWindow;
  public
    procedure BeginUpdate;
    procedure EndUpdate;
    function ExportTree: TModalResult;
    function ExportTreeAsText(Filename: string): TModalResult;
    function GetScopeToCurUnitOwner(UseFCLAsDefault: boolean): string;
    function SetScopeToCurUnitOwner(UseFCLAsDefault,
                                    WithRequiredPackages: boolean): boolean;
    procedure SetFilterToSimpleIdentifier(Identifier: string);
    procedure InvalidateStage(AStage: TCodeBrowserWorkStage);
  public
    property ParserRoot: TCodeBrowserUnitList read FParserRoot;
    property WorkingParserRoot: TCodeBrowserUnitList read FWorkingParserRoot;
    property ViewRoot: TCodeBrowserUnitList read FViewRoot;
    property Options: TCodeBrowserViewOptions read FOptions;
    property IDEDescription: string read FIDEDescription;
    property ProjectDescription: string read FProjectDescription;
    property ScannedPackages: integer read FScannedPackages write SetScannedPackages;
    property ScannedUnits: integer read FScannedUnits write SetScannedUnits;
    property ScannedLines: PtrInt read FScannedLines write SetScannedLines;
    property ScannedBytes: PtrInt read FScannedBytes write SetScannedBytes;
    property ScannedIdentifiers: PtrInt read FScannedIdentifiers write SetScannedIdentifiers;
    property VisiblePackages: integer read FVisiblePackages write SetVisiblePackages;
    property VisibleUnits: integer read FVisibleUnits write SetVisibleUnits;
    property VisibleIdentifiers: PtrInt read FVisibleIdentifiers write SetVisibleIdentifiers;
    property UpdateNeeded: boolean read FUpdateNeeded write SetUpdateNeeded;
  end;
  
  { TQuickFixIdentifierNotFound_Search }

  TQuickFixIdentifierNotFound_Search = class(TIDEMsgQuickFixItem)
  public
    constructor Create;
    function IsApplicable(Line: TIDEMessageLine): boolean; override;
    procedure Execute(const Msg: TIDEMessageLine; Step: TIMQuickFixStep); override;
  end;

var
  CodeBrowserView: TCodeBrowserView = nil;
  
function StringToCodeBrowserTextFilter(const s: string): TCodeBrowserTextFilter;

procedure InitCodeBrowserQuickFixItems;
procedure CreateCodeBrowser;

implementation

{$R *.lfm}

const
  ProgressGetScopeStart=0;
  ProgressGetScopeSize=10;
  ProgressGatherPackagesStart=ProgressGetScopeStart+ProgressGetScopeSize;
  ProgressGatherPackagesSize=30;
  ProgressFreeUnusedPkgStart=ProgressGatherPackagesStart+ProgressGatherPackagesSize;
  ProgressFreeUnusedPkgSize=100;
  ProgressAddNewUnitListsStart=ProgressFreeUnusedPkgStart+ProgressFreeUnusedPkgSize;
  ProgressAddNewUnitListsSize=300;
  ProgressGatherFileListsStart=ProgressAddNewUnitListsStart+ProgressAddNewUnitListsSize;
  ProgressGatherFileListsSize=300;
  ProgressGatherOutdatedFilesStart=ProgressGatherFileListsStart+ProgressGatherFileListsSize;
  ProgressGatherOutdatedFilesSize=300;
  ProgressUpdateUnitsStart=ProgressGatherOutdatedFilesStart+ProgressGatherOutdatedFilesSize;
  ProgressUpdateUnitsSize=3000;
  ProgressGetViewOptionsStart=ProgressUpdateUnitsStart+ProgressUpdateUnitsSize;
  ProgressGetViewOptionsSize=10;
  ProgressUpdateTreeViewStart=ProgressGetViewOptionsStart+ProgressGetViewOptionsSize;
  ProgressUpdateTreeViewSize=1000;
  ProgressTotal=ProgressUpdateTreeViewStart+ProgressUpdateTreeViewSize;
const
  ProcDescFlags = [phpWithStart,phpWithParameterNames,
                   phpWithVarModifiers,phpWithResultType,phpWithoutSemicolon];
  ProcIdentifierFlags = [phpWithoutClassKeyword,phpWithParameterNames,
                   phpWithoutSemicolon];
  PropDescFlags = [phpWithoutClassKeyword,phpWithParameterNames,
                   phpWithVarModifiers,phpWithResultType];

function StringToCodeBrowserTextFilter(const s: string): TCodeBrowserTextFilter;
begin
  for Result:=Low(TCodeBrowserTextFilter) to High(TCodeBrowserTextFilter) do
    if SysUtils.CompareText(CodeBrowserTextFilterNames[Result],s)=0 then exit;
  Result:=cbtfBegins;
end;

procedure InitCodeBrowserQuickFixItems;
begin
  RegisterIDEMsgQuickFix(TQuickFixIdentifierNotFound_Search.Create);
end;

procedure CreateCodeBrowser;
begin
  if CodeBrowserView=nil then
    CodeBrowserView:=TCodeBrowserView.Create(LazarusIDE.OwningComponent);
end;


{ TCodeBrowserView }

procedure TCodeBrowserView.FormCreate(Sender: TObject);
begin
  FHintWindow := nil;
  FOptions:=TCodeBrowserViewOptions.Create;
  
  FIDEDescription:=lisLazarusIDE;
  FProjectDescription:=dlgEnvProject;

  Name:=NonModalIDEWindowNames[nmiwCodeBrowser];
  Caption := lisCodeBrowser;

  ScopeGroupBox.Caption:=dlgScope;
  ScopeWithRequiredPackagesCheckBox.Caption:=lisWithRequiredPackages;
  RescanButton.Caption:=lisRescan;
  LevelsGroupBox.Caption:=lisLevels;
  ShowPackagesCheckBox.Caption:=lisShowPackages;
  ShowUnitsCheckBox.Caption:=lisShowUnits;
  ShowIdentifiersCheckBox.Caption:=lisShowIdentifiers;

  OptionsGroupBox.Caption:=lisFilter;
  ShowPrivateCheckBox.Caption:=lisPrivate;
  ShowProtectedCheckBox.Caption:=lisProtected;
  ShowEmptyNodesCheckBox.Caption:=lisShowEmptyUnitsPackages;

  ExpandAllPackagesMenuItem.Caption:=lisExpandAllPackages;
  CollapseAllPackagesMenuItem.Caption:=lisCollapseAllPackages;
  ExpandAllUnitsMenuItem.Caption:=lisExpandAllUnits;
  CollapseAllUnitsMenuItem.Caption:=lisCollapseAllUnits;
  ExpandAllClassesMenuItem.Caption:=lisExpandAllClasses;
  CollapseAllClassesMenuItem.Caption:=lisCollapseAllClasses;
  ExportMenuItem.Caption:=lisExport;
  OpenMenuItem.Caption:=lisHintOpen;
  // UsePkgInProjectMenuItem.Caption: see PopupMenu1Popup
  // UsePkgInCurUnitMenuItem.Caption: see PopupMenu1Popup
  // UseUnitInCurUnitMenuItem.Caption: see PopupMenu1Popup

  PackageFilterBeginsSpeedButton.Caption:=lisBegins;
  PackageFilterBeginsSpeedButton.Hint:=lisPackageNameBeginsWith;
  PackageFilterContainsSpeedButton.Caption:=lisContains;
  PackageFilterContainsSpeedButton.Hint:=lisPackageNameContains;
  UnitFilterBeginsSpeedButton.Caption:=lisBegins;
  UnitFilterBeginsSpeedButton.Hint:=lisUnitNameBeginsWith;
  UnitFilterContainsSpeedButton.Caption:=lisContains;
  UnitFilterContainsSpeedButton.Hint:=lisUnitNameContains;
  IdentifierFilterBeginsSpeedButton.Caption:=lisBegins;
  IdentifierFilterBeginsSpeedButton.Hint:=lisIdentifierBeginsWith;
  IdentifierFilterContainsSpeedButton.Caption:=lisContains;
  IdentifierFilterContainsSpeedButton.Hint:=lisIdentifierContains;
  
  ProgressBar1.Max:=ProgressTotal;

  InitImageList;
  LoadOptions;
  
  UpdateNeeded:=true;
  Application.AddOnIdleHandler(@OnIdle);
end;

procedure TCodeBrowserView.FormDestroy(Sender: TObject);
begin
  ClearTreeView;
  FreeAndNil(fOutdatedFiles);
  FreeAndNil(FViewRoot);
  FreeAndNil(FParserRoot);
  FreeAndNil(FWorkingParserRoot);
  FreeAndNil(FOptions);
end;

procedure TCodeBrowserView.IdleTimer1Timer(Sender: TObject);
begin
  InvalidateStage(cbwsGetViewOptions);
  IdleTimer1.Enabled:=false;
end;

procedure TCodeBrowserView.PackageFilterEditChange(Sender: TObject);
begin
  IdleTimer1.Enabled:=true;
end;

procedure TCodeBrowserView.PackageFilterEditEditingDone(Sender: TObject);
begin
  InvalidateStage(cbwsGetViewOptions);
end;

procedure TCodeBrowserView.PopupMenu1Popup(Sender: TObject);
var
  TVNode: TTreeNode;
  Node: TObject;
  Identifier: String;
  UnitList: TCodeBrowserUnitList;
  EnableUsePkgInProject: Boolean;
  APackage: TLazPackage;
  EnableUsePkgInCurUnit: Boolean;
  TargetPackage: TLazPackage;
  EnableUseUnitInCurUnit: Boolean;
  CurUnit: TCodeBrowserUnit;
  SrcEditUnitOwner: TObject;
  SrcEditUnitCode: TCodeBuffer;
  CurUnitName: String;
  SrcEditUnitName: String;
  CBNode: TCodeBrowserNode;
  EnableUseIdentifierInCurUnit: Boolean;
  SrcEdit: TSourceEditorInterface;
begin
  ExpandAllPackagesMenuItem.Visible:=Options.HasLevel(cblPackages);
  CollapseAllPackagesMenuItem.Visible:=ExpandAllPackagesMenuItem.Visible;
  AllPackagesSeparatorMenuItem.Visible:=ExpandAllPackagesMenuItem.Visible;
  
  ExpandAllUnitsMenuItem.Visible:=Options.HasLevel(cblUnits);
  CollapseAllUnitsMenuItem.Visible:=ExpandAllUnitsMenuItem.Visible;
  AllUnitsSeparatorMenuItem.Visible:=ExpandAllUnitsMenuItem.Visible;

  ExpandAllClassesMenuItem.Visible:=Options.HasLevel(cblIdentifiers);
  CollapseAllClassesMenuItem.Visible:=ExpandAllClassesMenuItem.Visible;
  AllClassesSeparatorMenuItem.Visible:=ExpandAllClassesMenuItem.Visible;

  TVNode:=BrowseTreeView.Selected;
  Node:=nil;
  if TVNode<>nil then
    Node:=TObject(TVNode.Data);
  EnableUsePkgInProject:=false;
  EnableUsePkgInCurUnit:=false;
  EnableUseUnitInCurUnit:=false;
  EnableUseIdentifierInCurUnit:=false;
  if Node<>nil then begin
    Identifier:='';
    APackage:=nil;
    UnitList:=nil;
    CurUnit:=nil;
    TargetPackage:=nil;
    if Node is TCodeBrowserNode then begin
      Identifier:=TCodeBrowserNode(Node).Identifier;
      CBNode:=TCodeBrowserNode(Node);
      CurUnit:=CBNode.CBUnit;
      if CurUnit<>nil then
        UnitList:=CurUnit.UnitList;
    end else if Node is TCodeBrowserUnit then begin
      CurUnit:=TCodeBrowserUnit(Node);
      UnitList:=CurUnit.UnitList;
    end else if Node is TCodeBrowserUnitList then begin
      UnitList:=TCodeBrowserUnitList(Node);
    end;
    if UnitList<>nil then begin
      if UnitList.Owner=CodeBrowserProjectName then begin
        // project
      end else if UnitList.Owner=CodeBrowserIDEName then begin
        // IDE
      end else if UnitList.Owner=CodeBrowserHidden then begin
        // nothing
      end else begin
        // package
        APackage:=PackageGraph.FindAPackageWithName(UnitList.Owner,nil);
        if APackage<>nil then begin
          // check if package can be added to project
          if Project1.FindDependencyByName(APackage.Name)=nil then begin
            EnableUsePkgInProject:=true;
            UsePkgInProjectMenuItem.Caption:=Format(lisUsePackageInProject, [
              APackage.Name]);
          end;
          // check if package can be added to package of src editor unit
          TargetPackage:=GetCurPackageInSrcEditor;
          if (TargetPackage<>nil)
          and (SysUtils.CompareText(TargetPackage.Name,APackage.Name)<>0)
          and (TargetPackage.FindDependencyByName(APackage.Name)=nil) then begin
            EnableUsePkgInCurUnit:=true;
            UsePkgInCurUnitMenuItem.Caption:=Format(
              lisUsePackageInPackage, [APackage.Name,
              TargetPackage.Name]);
          end;
          // check if unit can be added to project/package
          GetCurUnitInSrcEditor(SrcEditUnitOwner,SrcEditUnitCode);
          if (CurUnit<>nil) and (SrcEditUnitOwner<>nil) then begin
            CurUnitName:=ExtractFileNameOnly(CurUnit.Filename);
            SrcEditUnitName:=ExtractFileNameOnly(SrcEditUnitCode.Filename);
            if SysUtils.CompareText(CurUnitName,SrcEditUnitName)<>0 then begin
              EnableUseUnitInCurUnit:=true;
              UseUnitInCurUnitMenuItem.Caption:=
                Format(lisUseUnitInUnit, [CurUnitName, SrcEditUnitName]);
              if (Node is TCodeBrowserNode) and (Identifier<>'') then begin
                EnableUseIdentifierInCurUnit:=true;
                SrcEdit:=SourceEditorManagerIntf.ActiveEditor;
                UseIdentifierInCurUnitMenuItem.Caption:=
                  Format(lisUseIdentifierInAt, [Identifier, ExtractFilename(
                    SrcEdit.FileName), dbgs(SrcEdit.CursorScreenXY)]);
              end;
            end;
          end;
        end;
      end;
    end;
    OpenMenuItem.Visible:=true;
    CopyDescriptionMenuItem.Caption:=lisCopyDescription;
    CopyIdentifierMenuItem.Caption:=Format(lisCopyIdentifier, ['"', Identifier,
     '"']);
    CopyDescriptionMenuItem.Visible:=true;
    CopyIdentifierMenuItem.Visible:=Identifier<>'';
    CopySeparatorMenuItem.Visible:=true;

    UseUnitInCurUnitMenuItem.Enabled:=EnableUseUnitInCurUnit;
    UseUnitInCurUnitMenuItem.Visible:=true;
    if not EnableUseUnitInCurUnit then
      UseUnitInCurUnitMenuItem.Caption:=lisPkgMangUseUnit;

    UseIdentifierInCurUnitMenuItem.Enabled:=EnableUseIdentifierInCurUnit;
    UseIdentifierInCurUnitMenuItem.Visible:=true;
    if not EnableUseIdentifierInCurUnit then
      UseIdentifierInCurUnitMenuItem.Caption:=lisUseIdentifier;

    UsePkgInProjectMenuItem.Enabled:=EnableUsePkgInProject;
    UsePkgInProjectMenuItem.Visible:=true;
    if not EnableUsePkgInProject then
      UsePkgInProjectMenuItem.Caption:=lisUsePackageInProject2;

    UsePkgInCurUnitMenuItem.Enabled:=EnableUsePkgInCurUnit;
    UsePkgInCurUnitMenuItem.Visible:=true;
    if not EnableUsePkgInCurUnit then
      UsePkgInCurUnitMenuItem.Caption:=lisUsePackageInPackage2;
  end else begin
    OpenMenuItem.Visible:=false;
    CopyDescriptionMenuItem.Visible:=false;
    CopyIdentifierMenuItem.Visible:=false;
    CopySeparatorMenuItem.Visible:=false;
    UseUnitInCurUnitMenuItem.Visible:=false;
    UseIdentifierInCurUnitMenuItem.Visible:=false;
    UsePkgInProjectMenuItem.Visible:=false;
    UsePkgInCurUnitMenuItem.Visible:=false;
    UseSeparatorMenuItem.Visible:=false;
  end;
end;

procedure TCodeBrowserView.RescanButtonClick(Sender: TObject);
begin
  UpdateNeeded:=true;
  InvalidateStage(cbwsGetScopeOptions);
end;

procedure TCodeBrowserView.ScopeComboBoxGetItems(Sender: TObject);
begin
  FillScopeComboBox;
end;

procedure TCodeBrowserView.ScopeComboBoxEditingDone(Sender: TObject);
begin
  InvalidateStage(cbwsGetScopeOptions);
end;

procedure TCodeBrowserView.ScopeWithRequiredPackagesCheckBoxChange(
  Sender: TObject);
begin
  InvalidateStage(cbwsGetScopeOptions);
end;

procedure TCodeBrowserView.OnIdle(Sender: TObject; var Done: Boolean);
begin
  if (Screen.GetCurrentModalForm<>nil) then exit;
  Work(Done);
end;

procedure TCodeBrowserView.OpenMenuItemClick(Sender: TObject);
begin
  OpenTVNode(BrowseTreeView.Selected);
end;

procedure TCodeBrowserView.ShowIdentifiersCheckBoxChange(Sender: TObject);
begin
  InvalidateStage(cbwsGetViewOptions);
end;

procedure TCodeBrowserView.ShowPackagesCheckBoxChange(Sender: TObject);
begin
  //DebugLn(['TCodeBrowserView.ShowPackagesCheckBoxChange ']);
  InvalidateStage(cbwsGetViewOptions);
end;

procedure TCodeBrowserView.ShowPrivateCheckBoxChange(Sender: TObject);
begin
  InvalidateStage(cbwsGetViewOptions);
end;

procedure TCodeBrowserView.ShowUnitsCheckBoxChange(Sender: TObject);
begin
  InvalidateStage(cbwsGetViewOptions);
end;

procedure TCodeBrowserView.LoadOptions;
begin
  BeginUpdate;
  ScopeWithRequiredPackagesCheckBox.Checked:=Options.WithRequiredPackages;
  ScopeComboBox.Text:=Options.Scope;
  LoadLevelsGroupBox;
  LoadFilterGroupbox;
  EndUpdate;
end;

procedure TCodeBrowserView.LoadLevelsGroupBox;
begin
  ShowPackagesCheckBox.Checked:=Options.HasLevel(cblPackages);
  ShowUnitsCheckBox.Checked:=Options.HasLevel(cblUnits);
  ShowIdentifiersCheckBox.Checked:=Options.HasLevel(cblIdentifiers);
end;

procedure TCodeBrowserView.LoadFilterGroupbox;
begin
  ShowPrivateCheckBox.Checked:=Options.ShowPrivate;
  ShowProtectedCheckBox.Checked:=Options.ShowProtected;
  ShowEmptyNodesCheckBox.Checked:=Options.ShowEmptyNodes;

  PackageFilterEdit.Text:=Options.LevelFilterText[cblPackages];
  case Options.LevelFilterType[cblPackages] of
  cbtfBegins:   PackageFilterBeginsSpeedButton.Down:=true;
  cbtfContains: PackageFilterContainsSpeedButton.Down:=true;
  end;

  UnitFilterEdit.Text:=Options.LevelFilterText[cblUnits];
  case Options.LevelFilterType[cblUnits] of
  cbtfBegins:   UnitFilterBeginsSpeedButton.Down:=true;
  cbtfContains: UnitFilterContainsSpeedButton.Down:=true;
  end;

  IdentifierFilterEdit.Text:=Options.LevelFilterText[cblIdentifiers];
  case Options.LevelFilterType[cblIdentifiers] of
  cbtfBegins:   IdentifierFilterBeginsSpeedButton.Down:=true;
  cbtfContains: IdentifierFilterContainsSpeedButton.Down:=true;
  end;
end;

procedure TCodeBrowserView.FillScopeComboBox;
var
  sl: TStringList;
  i: Integer;
begin
  if ScopeComboBox.Items.Count=0 then begin
    sl:=TStringList.Create;
    try
      if PackageGraph<>nil then begin
        for i:=0 to PackageGraph.Count-1 do
          sl.Add(PackageGraph.Packages[i].Name);
      end;
      sl.Sort;
      sl.Insert(0,IDEDescription);
      sl.Insert(1,ProjectDescription);
      ScopeComboBox.Items.Assign(sl);
    finally
      sl.Free;
    end;
  end;
end;

procedure TCodeBrowserView.InitImageList;

  procedure AddResImg(ImgList: TImageList; const ResName: string;
    out ImgID: integer);
  var
    Bitmap: TCustomBitmap;
    Resource: TLResource;
  begin
    //TODO: use ImgList.AddLazarusResource
    Resource:=LazarusResources.Find(ResName);
    if Resource=nil then
      DebugLn('TCodeExplorerView.CodeExplorerViewCREATE: ',
        ' WARNING: icon not found: "',ResName,'"');
    if SysUtils.CompareText(Resource.ValueType,'xpm')=0 then begin
      Bitmap:=TPixmap.Create;
    end else if SysUtils.CompareText(Resource.ValueType,'png')=0 then begin
      Bitmap:=TPortableNetworkGraphic.Create;
    end else
      DebugLn('TCodeExplorerView.CodeExplorerViewCREATE: ',
        ' WARNING: wrong icon format: "',ResName,'"="',Resource.ValueType,'"');
    Bitmap.LoadFromLazarusResource(ResName);
    //DebugLn(['AddResImg ',ResName,' ',Bitmap.Width,' ',Bitmap.Height]);
    ImgID:=ImgList.Add(Bitmap,nil);
    Bitmap.Free;
  end;

begin
  ImgIDDefault := Imagelist1.AddLazarusResource('ce_default');
  ImgIDProgramCode := Imagelist1.AddLazarusResource('ce_program');
  ImgIDUnitCode := Imagelist1.AddLazarusResource('ce_unit');
  ImgIDInterfaceSection := Imagelist1.AddLazarusResource('ce_interface');
  ImgIDImplementation := Imagelist1.AddLazarusResource('ce_implementation');
  ImgIDInitialization := Imagelist1.AddLazarusResource('ce_initialization');
  ImgIDFinalization := Imagelist1.AddLazarusResource('ce_finalization');
  ImgIDTypeSection := Imagelist1.AddLazarusResource('ce_type');
  ImgIDType := Imagelist1.AddLazarusResource('ce_type');
  ImgIDVarSection := Imagelist1.AddLazarusResource('ce_variable');
  ImgIDVariable := Imagelist1.AddLazarusResource('ce_variable');
  ImgIDConstSection := Imagelist1.AddLazarusResource('ce_const');
  ImgIDConst := Imagelist1.AddLazarusResource('ce_const');
  ImgIDClass := Imagelist1.AddLazarusResource('ce_class');
  ImgIDProc := Imagelist1.AddLazarusResource('ce_procedure');
  ImgIDProperty := Imagelist1.AddLazarusResource('ce_property');
  ImgIDPackage := Imagelist1.AddLazarusResource('item_package');
  ImgIDProject := Imagelist1.AddLazarusResource('item_project');
end;

procedure TCodeBrowserView.SetScannedBytes(const AValue: PtrInt);
begin
  if FScannedBytes=AValue then exit;
  FScannedBytes:=AValue;
end;

procedure TCodeBrowserView.SetScannedIdentifiers(const AValue: PtrInt);
begin
  if FScannedIdentifiers=AValue then exit;
  FScannedIdentifiers:=AValue;
end;

procedure TCodeBrowserView.SetScannedLines(const AValue: PtrInt);
begin
  if FScannedLines=AValue then exit;
  FScannedLines:=AValue;
end;

procedure TCodeBrowserView.SetScannedPackages(const AValue: integer);
begin
  if FScannedPackages=AValue then exit;
  FScannedPackages:=AValue;
end;

procedure TCodeBrowserView.SetScannedUnits(const AValue: integer);
begin
  if FScannedUnits=AValue then exit;
  FScannedUnits:=AValue;
end;

procedure TCodeBrowserView.SetUpdateNeeded(const AValue: boolean);
begin
  if FUpdateNeeded=AValue then exit;
  FUpdateNeeded:=AValue;
  if FUpdateNeeded then
    InvalidateStage(cbwsGetScopeOptions);
end;

procedure TCodeBrowserView.SetVisibleIdentifiers(const AValue: PtrInt);
begin
  if FVisibleIdentifiers=AValue then exit;
  FVisibleIdentifiers:=AValue;
end;

procedure TCodeBrowserView.SetVisiblePackages(const AValue: integer);
begin
  if FVisiblePackages=AValue then exit;
  FVisiblePackages:=AValue;
end;

procedure TCodeBrowserView.SetVisibleUnits(const AValue: integer);
begin
  if FVisibleUnits=AValue then exit;
  FVisibleUnits:=AValue;
end;

procedure TCodeBrowserView.UseUnitInSrcEditor(InsertIdentifier: boolean);
var
  // temporary data, that can be freed on next idle
  SelectedUnit: TCodeBrowserUnit;
  TVNode: TTreeNode;
  Node: TObject;
  IdentifierNode: TCodeBrowserNode;
  // normal vars
  SelectedUnitName: String;
  SelectedCode: TCodeBuffer;
  List: TFPList;
  SelectedOwner: TObject;
  APackage: TLazPackage;
  TargetCode: TCodeBuffer;
  TargetOwner: TObject;
  SrcEdit: TSourceEditorInterface;
  Code: TCodeBuffer;
  CodeMarker: TSourceLogMarker;
  Identifier: String;
  SelectedUnitFilename: String;
  IdentStart: integer;
  IdentEnd: integer;
  InsertStartPos: TPoint;
  InsertEndPos: TPoint;
begin
  TVNode:=BrowseTreeView.Selected;
  if TVNode=nil then exit;
  Node:=TObject(TVNode.Data);
  IdentifierNode:=nil;
  SelectedUnit:=nil;
  if Node is TCodeBrowserNode then begin
    IdentifierNode:=TCodeBrowserNode(Node);
    Identifier:=IdentifierNode.Identifier;
    SelectedUnit:=IdentifierNode.CBUnit;
  end else if Node is TCodeBrowserUnit then begin
    SelectedUnit:=TCodeBrowserUnit(Node);
  end else
    exit;
  if (SelectedUnit=nil) then exit;
  SelectedUnitFilename:=SelectedUnit.Filename;

  if InsertIdentifier then begin
    if (IdentifierNode=nil) or (Identifier='') then exit;
  end;
  if SelectedUnit.UnitList=nil then begin
    DebugLn(['TCodeBrowserView.UseUnitInSrcEditor not implemented: '
      +'SelectedUnit.UnitList=nil']);
    MessageDlg('Implement me',
      'TCodeBrowserView.UseUnitInSrcEditor not implemented: '
        +'SelectedUnit.UnitList=nil',
      mtInformation, [mbOk], 0);
    exit;
  end;
  SelectedOwner:=nil;
  if SelectedUnit.UnitList.Owner=CodeBrowserProjectName then begin
    // project
    SelectedOwner:=Project1;
  end else if SelectedUnit.UnitList.Owner=CodeBrowserIDEName then begin
    // IDE can not be added as dependency
    DebugLn(['TCodeBrowserView.UseUnitInSrcEditor IDE can not be '
      +'added as dependency']);
    exit;
  end else if SelectedUnit.UnitList.Owner=CodeBrowserHidden then begin
    // nothing
    DebugLn(['TCodeBrowserView.UseUnitInSrcEditor hidden unitlist']
      );
    exit;
  end else begin
    // package
    APackage:=PackageGraph.FindAPackageWithName(SelectedUnit.UnitList.Owner,nil);
    if APackage=nil then begin
      DebugLn(['TCodeBrowserView.UseUnitInSrcEditor package not '
        +'found: ', SelectedUnit.UnitList.Owner]);
      exit;
    end;
    SelectedOwner:=APackage;
  end;

  // get target unit
  if not GetCurUnitInSrcEditor(TargetOwner, TargetCode) then exit;
  if (not (TargetOwner is TProject))
  and (not (TargetOwner is TLazPackage)) then begin
    DebugLn(['TCodeBrowserView.UseUnitInSrcEditor not implemented: '
      +'TargetOwner=', DbgSName(TargetOwner)]);
    MessageDlg('Implement me',
      'TCodeBrowserView.UseUnitInSrcEditor not implemented: '
        +'TargetOwner='+DbgSName(TargetOwner),
      mtInformation, [mbOk], 0);
    exit;
  end;

  if (SelectedOwner is TProject) and (TargetOwner<>SelectedOwner) then begin
    // unit of project can not be used by other packages/projects
    MessageDlg(lisImpossible,
      lisAProjectUnitCanNotBeUsedByOtherPackagesProjects,
      mtError, [mbCancel], 0);
    exit;
  end;

  // safety first: clear the references, they will become invalid on next idle
  SelectedUnit:=nil;
  IdentifierNode:=nil;
  Node:=nil;
  TVNode:=nil;


  List:=TFPList.Create;
  CodeMarker:=nil;
  try
    SrcEdit:=SourceEditorManagerIntf.ActiveEditor;
    if SrcEdit=nil then exit;
    InsertStartPos:=SrcEdit.CursorTextXY;
    Code:=TCodeBuffer(SrcEdit.CodeToolsBuffer);
    CodeMarker:=Code.AddMarkerXY(InsertStartPos.Y,InsertStartPos.X,Self);

    List.Add(TargetOwner);
    if (SelectedOwner is TLazPackage) then begin
      // add package to TargetOwner
      APackage:=TLazPackage(SelectedOwner);
      if PkgBoss.AddDependencyToOwners(List, APackage)<>mrOk then begin
        DebugLn(['TCodeBrowserView.UseUnitInSrcEditor PkgBoss.'
          +'AddDependencyToOwners failed']);
        exit;
      end;
    end;

    // get nice unit name
    if not LazarusIDE.SaveSourceEditorChangesToCodeCache(nil) then begin
      DebugLn(['TCodeBrowserView.UseUnitInSrcEditor LazarusIDE.'
        +'SaveSourceEditorChangesToCodeCache failed']);
      exit;
    end;
    SelectedCode:=CodeToolBoss.LoadFile(SelectedUnitFilename, true, false);
    if SelectedCode=nil then begin
      debugln(['TCodeBrowserView.UseUnitInSrcEditor failed to load SelectedUnitFilename=',SelectedUnitFilename]);
      exit;
    end;
    SelectedUnitName:=CodeToolBoss.GetSourceName(SelectedCode, false);

    // add unit to uses section
    if not CodeToolBoss.AddUnitToMainUsesSection(TargetCode, SelectedUnitName,
      '') then
    begin
      DebugLn(['TCodeBrowserView.UseUnitInSrcEditor CodeToolBoss.'
        +'AddUnitToMainUsesSection failed: TargetCode=', TargetCode.Filename, ' '
          +'SelectedUnitName=', SelectedUnitName]);
      LazarusIDE.DoJumpToCodeToolBossError;
    end;

    // insert identifier
    if InsertIdentifier then begin
      if CodeMarker.Deleted then begin
        DebugLn(['TCodeBrowserView.UseUnitInSrcEditor insert place was deleted']);
        exit;
      end;
      GetIdentStartEndAtPosition(Code.Source,CodeMarker.NewPosition,
                                 IdentStart,IdentEnd);
      Code.AbsoluteToLineCol(IdentStart,InsertStartPos.Y,InsertStartPos.X);
      InsertEndPos:=InsertStartPos;
      inc(InsertEndPos.X,IdentEnd-IdentStart);
      SrcEdit.ReplaceText(InsertStartPos,InsertEndPos,Identifier);
    end;
  finally
    List.Free;
    CodeMarker.Free;
  end;
end;

procedure TCodeBrowserView.Work(var Done: Boolean);
// do some work
// This is called during OnIdle, so progress in small steps
var
  OldStage: TCodeBrowserWorkStage;
begin
  OldStage:=fStage;
  case fStage of
  cbwsGetScopeOptions:     WorkGetScopeOptions;
  cbwsGatherPackages:      WorkGatherPackages;
  cbwsFreeUnusedPackages:  WorkFreeUnusedPackages;
  cbwsAddNewPackages:      WorkAddNewUnitLists;
  cbwsGatherFiles:         WorkGatherFileLists;
  cbwsGatherOutdatedFiles: WorkGatherOutdatedFiles;
  cbwsUpdateUnits:         WorkUpdateUnits;
  cbwsGetViewOptions:      WorkGetViewOptions;
  cbwsUpdateTreeView:      WorkUpdateTreeView;
  else
    FOptionsChangeStamp:=Options.ChangeStamp;
    UpdateNeeded:=false;
    Done:=true;
    ProgressBar1.Position:=ProgressTotal;
    exit;
  end;
  if ord(OldStage)<ord(cbwsFinished) then begin
    Done:=false;
    UpdateStatusBar(fStage<cbwsFinished);
  end;
  //if fStage=cbwsFinished then CodeToolBoss.WriteMemoryStats;
end;

procedure TCodeBrowserView.WorkGetScopeOptions;
var
  CurChangStamp: LongInt;
begin
  DebugLn(['TCodeBrowserView.WorkGetScopeOptions START']);
  IdleTimer1.Enabled:=false;

  ProgressBar1.Position:=ProgressGetScopeStart;
  CurChangStamp:=Options.ChangeStamp;
  Options.WithRequiredPackages:=ScopeWithRequiredPackagesCheckBox.Checked;
  Options.Scope:=ScopeComboBox.Text;

  // this stage finished -> next stage
  if UpdateNeeded or (Options.ChangeStamp<>CurChangStamp) then
    fStage:=cbwsGatherPackages
  else
    fStage:=cbwsGetViewOptions;
  ProgressBar1.Position:=ProgressGetScopeStart+ProgressGetScopeSize;
end;

procedure TCodeBrowserView.WorkGatherPackages;

  procedure AddPackage(APackage: TLazPackage);
  begin
    TCodeBrowserUnitList.Create(APackage.Name,FWorkingParserRoot);
  end;
  
  procedure AddPackages(FirstDependency: TPkgDependency);
  var
    List: TFPList;
    i: Integer;
  begin
    List:=nil;
    try
      PackageGraph.GetAllRequiredPackages(FirstDependency,List);
      if (List=nil) then exit;
      for i:=0 to List.Count-1 do begin
        if TObject(List[i]) is TLazPackage then
          AddPackage(TLazPackage(List[i]));
      end;
    finally
      List.Free;
    end;
  end;

var
  APackage: TLazPackage;
  RootOwner: string;
  i: Integer;
begin
  // clean up
  if fOutdatedFiles<>nil then fOutdatedFiles.Clear;

  // find ParserRoot
  RootOwner:='';
  if Options.Scope=IDEDescription then begin
    RootOwner:=CodeBrowserIDEName;
  end else if Options.Scope=ProjectDescription then begin
    RootOwner:=CodeBrowserProjectName;
  end else begin
    APackage:=PackageGraph.FindAPackageWithName(Options.Scope,nil);
    if APackage<>nil then
      RootOwner:=APackage.Name;
  end;
  DebugLn(['TCodeBrowserView.WorkGatherPackages RootOwner="',RootOwner,'"']);
  FreeAndNil(FWorkingParserRoot);
  FWorkingParserRoot:=TCodeBrowserUnitList.Create(RootOwner,nil);
  
  // find required packages
  if Options.WithRequiredPackages then begin
    if SysUtils.CompareText(FWorkingParserRoot.Owner,CodeBrowserIDEName)=0 then begin
      for i:=0 to PackageGraph.Count-1 do
        AddPackage(PackageGraph[i]);
    end else if SysUtils.CompareText(FWorkingParserRoot.Owner,CodeBrowserProjectName)=0
    then begin
      AddPackages(Project1.FirstRequiredDependency);
    end else if FWorkingParserRoot.Owner<>'' then begin
      APackage:=PackageGraph.FindAPackageWithName(FWorkingParserRoot.Owner,nil);
      if APackage<>nil then
        AddPackages(APackage.FirstRequiredDependency);
    end;
  end;
  
  // update ParserRoot item (children will be updated on next Idle)
  if FParserRoot=nil then begin
    FParserRoot:=TCodeBrowserUnitList.Create(FWorkingParserRoot.Owner,nil);
    inc(FScannedPackages);
  end else begin
    FParserRoot.Owner:=FWorkingParserRoot.Owner;
  end;
  
  // this stage finished -> next stage
  fStage:=cbwsFreeUnusedPackages;
  ProgressBar1.Position:=ProgressGatherPackagesStart+ProgressGatherPackagesSize;
end;

procedure TCodeBrowserView.WorkFreeUnusedPackages;

  function FindUnusedUnitList: TCodeBrowserUnitList;
  var
    Node: TAVLTreeNode;
    UnusedPackage: TCodeBrowserUnitList;
    PackageName: String;
  begin
    // find an unused package (a package in ParserRoot but not in WorkingParserRoot)
    Result:=nil;
    if (FParserRoot=nil) or (FParserRoot.UnitLists=nil) then exit;
    Node:=FParserRoot.UnitLists.FindLowest;
    while Node<>nil do begin
      UnusedPackage:=TCodeBrowserUnitList(Node.Data);
      PackageName:=UnusedPackage.Owner;
      if (FWorkingParserRoot=nil)
      or (FWorkingParserRoot.UnitLists=nil)
      or (FWorkingParserRoot.UnitLists.FindKey(@PackageName,
         @ComparePAnsiStringWithUnitListOwner)=nil)
      then begin
        Result:=UnusedPackage;
        exit;
      end;
      Node:=FParserRoot.UnitLists.FindSuccessor(Node);
    end;
  end;
  
var
  UnusedPackage: TCodeBrowserUnitList;
begin
  DebugLn(['TCodeBrowserView.WorkFreeUnusedPackages START']);

  // find an unused package
  UnusedPackage:=FindUnusedUnitList;
  if UnusedPackage=nil then begin
    // this stage finished -> next stage
    fStage:=cbwsAddNewPackages;
    ProgressBar1.Position:=ProgressFreeUnusedPkgStart+ProgressFreeUnusedPkgSize;
    exit;
  end;

  // free the unused package
  FreeUnitList(UnusedPackage);
end;

procedure TCodeBrowserView.WorkAddNewUnitLists;
var
  Node: TAVLTreeNode;
  List: TCodeBrowserUnitList;
begin
  ProgressBar1.Position:=ProgressAddNewUnitListsStart;
  if (FWorkingParserRoot<>nil) and (FWorkingParserRoot.UnitLists<>nil)
  and (FParserRoot<>nil) then begin
    Node:=FWorkingParserRoot.UnitLists.FindLowest;
    while Node<>nil do begin
      List:=TCodeBrowserUnitList(Node.Data);
      if FParserRoot.FindUnitList(List.Owner)=nil then begin
        // new unit list
        TCodeBrowserUnitList.Create(List.Owner,FParserRoot);
        inc(FScannedPackages);
      end;
      Node:=FWorkingParserRoot.UnitLists.FindSuccessor(Node);
    end;
  end;
  
  // this stage finished -> next stage
  fStage:=cbwsGatherFiles;
  ProgressBar1.Position:=ProgressAddNewUnitListsStart+ProgressAddNewUnitListsSize;
end;

procedure TCodeBrowserView.WorkGatherFileLists;

  function ListFilesAreValid(List: TCodeBrowserUnitList): boolean;
  begin
    Result:=List.UnitsValid;
  end;

  function FindListWithInvalidFileList(StartList: TCodeBrowserUnitList
    ): TCodeBrowserUnitList;
  var
    APackage: TCodeBrowserUnitList;
    Node: TAVLTreeNode;
  begin
    Result:=nil;
    if StartList=nil then exit;
    if not ListFilesAreValid(StartList) then begin
      Result:=StartList;
      exit;
    end;
    if (StartList.UnitLists=nil) then exit;
    Node:=StartList.UnitLists.FindLowest;
    while Node<>nil do begin
      APackage:=TCodeBrowserUnitList(Node.Data);
      Result:=FindListWithInvalidFileList(APackage);
      if Result<>nil then exit;
      Node:=StartList.UnitLists.FindSuccessor(Node);
    end;
  end;

var
  List: TCodeBrowserUnitList;
begin
  DebugLn(['TCodeBrowserView.WorkGatherFiles START']);
  // find a unit list which needs update
  List:=FindListWithInvalidFileList(FParserRoot);
  if List=nil then begin
    // this stage finished -> next stage
    fStage:=cbwsGatherOutdatedFiles;
    ProgressBar1.Position:=ProgressGatherFileListsStart+ProgressGatherFileListsSize;
    exit;
  end;
  
  WorkUpdateFileList(List);
end;

procedure TCodeBrowserView.WorkUpdateFileList(List: TCodeBrowserUnitList);
var
  NewFileList: TAVLTree;

  procedure AddFile(const Filename: string; ClearIncludedByInfo: boolean);
  begin
    //DebugLn(['AddFile Filename="',Filename,'"']);
    if Filename='' then exit;
    if System.Pos('$',Filename)>0 then begin
      DebugLn(['WARNING: TCodeBrowserView.WorkUpdateFiles Macros in filename ',Filename]);
      exit;
    end;
    if NewFileList.FindKey(@Filename,@ComparePAnsiStringWithUnitFilename)<>nil
    then exit;
    //DebugLn(['TCodeBrowserView.WorkUpdateFiles AddFile ',Filename]);
    NewFileList.Add(TCodeBrowserUnit.Create(Filename));
    if ClearIncludedByInfo then begin
      CodeToolBoss.SourceCache.ClearIncludedByEntry(Filename);
    end;
  end;
  
  procedure AddFilesOfProject(AProject: TProject);
  var
    AnUnitInfo: TUnitInfo;
  begin
    if AProject=nil then exit;
    AnUnitInfo:=AProject.FirstPartOfProject;
    //DebugLn(['AddFilesOfProject ',AnUnitInfo<>nil]);
    while AnUnitInfo<>nil do begin
      //DebugLn(['AddFilesOfProject ',AnUnitInfo.Filename]);
      if FilenameIsPascalUnit(AnUnitInfo.Filename)
      or (AnUnitInfo=aProject.MainUnitInfo) then
        AddFile(AnUnitInfo.Filename,false);
      AnUnitInfo:=AnUnitInfo.NextPartOfProject;
    end;
  end;
  
  procedure AddFilesOfPackageFCL;
  var
    LazDir: String;
    UnitSetID: string;
    UnitSetChanged: Boolean;
    UnitSet: TFPCUnitSetCache;
    Filename: String;
    ConfigCache: TFPCTargetConfigCache;
    Node: TAVLTreeNode;
    Item: PStringToStringTreeItem;
  begin
    // use unitset of the lazarus source directory
    LazDir:=AppendPathDelim(EnvironmentOptions.LazarusDirectory);
    if (LazDir='') or (not FilenameIsAbsolute(LazDir)) then exit;
    UnitSetID:=CodeToolBoss.GetUnitSetIDForDirectory(LazDir);
    if UnitSetID='' then exit;
    UnitSetChanged:=false;
    UnitSet:=CodeToolBoss.FPCDefinesCache.FindUnitSetWithID(UnitSetID,
                                                          UnitSetChanged,false);
    if UnitSet=nil then exit;
    ConfigCache:=UnitSet.GetConfigCache(false);
    if (ConfigCache=nil) or (ConfigCache.Units=nil) then exit;
    Node:=ConfigCache.Units.Tree.FindLowest;
    while Node<>nil do begin
      Item:=PStringToStringTreeItem(Node.Data);
      Filename:=Item^.Value;
      if (CompareFileExt(Filename,'ppu',false)=0) then begin
        // search source in fpc sources
        Filename:=UnitSet.GetUnitSrcFile(ExtractFileNameOnly(Filename));
      end;
      if FilenameIsPascalUnit(Filename) then
        AddFile(Filename,false);
      Node:=ConfigCache.Units.Tree.FindSuccessor(Node);
    end;
  end;
  
  procedure AddFilesOfPackage(APackage: TLazPackage);
  var
    i: Integer;
    PkgFile: TPkgFile;
  begin
    if APackage=nil then exit;
    for i:=0 to APackage.FileCount-1 do begin
      PkgFile:=APackage.Files[i];
      if (PkgFile.FileType in PkgFileUnitTypes) then
        AddFile(PkgFile.GetFullFilename,true);
    end;
    if APackage.Name='FCL' then begin
      AddFilesOfPackageFCL;
    end;
  end;
  
  procedure AddFilesOfDirectory(const Directory: string;
    ClearIncludedByInfo: boolean);
  // ! needs ending PathDelim !
  var
    FileInfo: TSearchRec;
  begin
    //DebugLn(['AddFilesOfDirectory Directory="',Directory,'"']);
    if (not FilenameIsAbsolute(Directory))
    or (not DirectoryExistsUTF8(Directory)) then begin
      DebugLn(['AddFilesOfDirectory WARNING: does not exist: "',Directory,'"']);
      exit;
    end;
    if FindFirstUTF8(Directory+FileMask,faAnyFile,FileInfo)=0 then begin
      repeat
        // check if special file
        if (FileInfo.Name='.') or (FileInfo.Name='..') or (FileInfo.Name='')
        then
          continue;
        if FilenameIsPascalUnit(FileInfo.Name) then
          AddFile(Directory+FileInfo.Name,ClearIncludedByInfo);
      until FindNextUTF8(FileInfo)<>0;
    end;
    FindCloseUTF8(FileInfo);
  end;
  
  procedure AddFilesOfSearchPath(const SrcPath, BaseDir: string;
    ClearIncludedByInfo: boolean);
  var
    Dir: String;
    p: Integer;
  begin
    //DebugLn(['AddFilesOfSearchPath SrcPath="',SrcPath,'" BaseDir="',BaseDir,'"']);
    p:=1;
    while (p<=length(SrcPath)) do begin
      Dir:=GetNextDelimitedItem(SrcPath,';',p);
      if Dir<>'' then begin
        if not FilenameIsAbsolute(Dir) then
          Dir:=BaseDir+PathDelim+Dir;
        Dir:=CleanAndExpandDirectory(Dir);
        AddFilesOfDirectory(Dir,ClearIncludedByInfo);
      end;
    end;
  end;
  
  procedure AddFilesOfIDE;
  var
    LazDefines: TDefineTemplate;
    LazSrcDir: TDefineTemplate;
    LazIDEDir: TDefineTemplate;
    LazIDESrcPath: TDefineTemplate;
    SrcPath: String;
    LazDir: String;
  begin
    LazDir:=AppendPathDelim(EnvironmentOptions.LazarusDirectory);
    if not DirectoryExistsUTF8(LazDir) then begin
      DebugLn(['AddFilesOfIDE WARNING: lazarus directory not found: "',LazDir,'"']);
      exit;
    end;
    // get the SrcPath template of the lazarus/ide directory
    LazDefines:=CodeToolBoss.DefineTree
                      .FindDefineTemplateByName(StdDefTemplLazarusSources,true);
    if LazDefines=nil then begin
      DebugLn(['AddFilesOfIDE WARNING: codetools define templates for lazarus not found']);
      exit;
    end;
    LazSrcDir:=LazDefines.FindChildByName(StdDefTemplLazarusSrcDir);
    if LazSrcDir=nil then begin
      DebugLn(['AddFilesOfIDE WARNING: codetools define templates for lazarus directory not found']);
      exit;
    end;
    LazIDEDir:=LazSrcDir.FindChildByName('ide');
    if LazIDEDir=nil then begin
      DebugLn(['AddFilesOfIDE WARNING: codetools define templates for lazarus ide directory not found']);
      exit;
    end;
    LazIDESrcPath:=LazIDEDir.FindChildByName('IDE path addition');
    if LazIDESrcPath=nil then begin
      DebugLn(['AddFilesOfIDE WARNING: codetools define templates for src path of lazarus ide directory not found']);
      exit;
    end;
    SrcPath:=StringReplace(LazIDESrcPath.Value,'$(#LazarusDir)',LazDir,
                           [rfReplaceAll, rfIgnoreCase]);
    AddFilesOfSearchPath(SrcPath+';.',LazDir+'ide'+PathDelim,true);
  end;

  procedure DeleteUnusedFiles;
  var
    Node: TAVLTreeNode;
    CurUnit: TCodeBrowserUnit;
    NextNode: TAVLTreeNode;
  begin
    if List.Units=nil then exit;
    Node:=List.Units.FindLowest;
    while Node<>nil do begin
      NextNode:=List.Units.FindSuccessor(Node);
      CurUnit:=TCodeBrowserUnit(Node.Data);
      if NewFileList.FindKey(@CurUnit.Filename,
        @ComparePAnsiStringWithUnitFilename)=nil
      then begin
        // this unit is not part of List anymore -> delete
        RemoveUnit(CurUnit);
        List.DeleteUnit(CurUnit);
      end;
      Node:=NextNode;
    end;
  end;
  
  procedure AddNewFiles;
  var
    Node: TAVLTreeNode;
    AnUnit: TCodeBrowserUnit;
  begin
    Node:=NewFileList.FindLowest;
    while Node<>nil do begin
      AnUnit:=TCodeBrowserUnit(Node.Data);
      //DebugLn(['AddNewFiles ',AnUnit.Filename,' exists=',List.FindUnit(AnUnit.Filename)<>nil]);
      if List.FindUnit(AnUnit.Filename)=nil then begin
        // this unit was not part of List -> add
        //DebugLn(['AddNewFiles "',List.Owner,'" "',AnUnit.Filename,'"']);
        List.AddUnit(AnUnit.Filename);
      end;
      Node:=NewFileList.FindSuccessor(Node);
    end;
  end;

var
  APackage: TLazPackage;
begin
  DebugLn(['TCodeBrowserView.WorkUpdateFiles ',List.Owner]);
  NewFileList:=TAVLTree.Create(@CompareUnitFilenames);
  try
    // get new list of files
    if List.Owner=CodeBrowserIDEName then begin
      AddFilesOfIDE;
    end else if List.Owner=CodeBrowserProjectName then begin
      AddFilesOfProject(Project1);
    end else begin
      APackage:=PackageGraph.FindAPackageWithName(List.Owner,nil);
      AddFilesOfPackage(APackage);
    end;
    
    // update file list
    DeleteUnusedFiles;
    AddNewFiles;
    
    List.UnitsValid:=true;
  finally
    NewFileList.FreeAndClear;
    NewFileList.Free;
  end;
end;

procedure TCodeBrowserView.WorkGatherOutdatedFiles;
// add all files to fOutdatedFiles

  procedure AddFile(AnUnit: TCodeBrowserUnit);
  begin
    if fOutdatedFiles=nil then
      fOutdatedFiles:=TAVLTree.Create(@CompareUnitFilenames);
    if fOutdatedFiles.Find(AnUnit)<>nil then exit;
    fOutdatedFiles.Add(AnUnit);
  end;

  procedure AddFiles(List: TCodeBrowserUnitList);
  var
    Node: TAVLTreeNode;
  begin
    if List.Units<>nil then begin
      Node:=List.Units.FindLowest;
      while Node<>nil do begin
        AddFile(TCodeBrowserUnit(Node.Data));
        Node:=List.Units.FindSuccessor(Node);
      end;
    end;
    if List.UnitLists<>nil then begin
      Node:=List.UnitLists.FindLowest;
      while Node<>nil do begin
        AddFiles(TCodeBrowserUnitList(Node.Data));
        Node:=List.UnitLists.FindSuccessor(Node);
      end;
    end;
  end;

begin
  if fOutdatedFiles<>nil then
    fOutdatedFiles.Clear;
  AddFiles(ParserRoot);
  
  // this stage finished -> next stage
  fStage:=cbwsUpdateUnits;
  ProgressBar1.Position:=ProgressGatherOutdatedFilesStart+ProgressGatherOutdatedFilesSize;
end;

procedure TCodeBrowserView.WorkUpdateUnits;

  function FindOutdatedUnit: TCodeBrowserUnit;
  var
    Node: TAVLTreeNode;
  begin
    Result:=nil;
    if fOutdatedFiles=nil then exit;
    Node:=fOutdatedFiles.FindLowest;
    if Node=nil then exit;
    Result:=TCodeBrowserUnit(Node.Data);
  end;

const
  SmallTimeStep = (1/86400)/5;
var
  AnUnit: TCodeBrowserUnit;
  StartTime: TDateTime;
begin
  //DebugLn(['TCodeBrowserView.WorkUpdateUnits START']);
  CodeToolBoss.ActivateWriteLock;
  try
    // parse units
    StartTime:=Now;
    repeat
      AnUnit:=FindOutdatedUnit;
      if AnUnit=nil then begin
        // this stage finished -> next stage
        fStage:=cbwsGetViewOptions;
        ProgressBar1.Position:=ProgressUpdateUnitsStart+ProgressUpdateUnitsSize;
        exit;
      end;

      WorkUpdateUnit(AnUnit);
    until Abs(Now-StartTime)>SmallTimeStep;
  finally
    CodeToolBoss.DeactivateWriteLock;
  end;
end;

procedure TCodeBrowserView.WorkUpdateUnit(AnUnit: TCodeBrowserUnit);

  procedure UpdateScannedCounters(Tool: TCodeTool);
  var
    LineCnt: Integer;
    ByteCnt: Integer;
    i: Integer;
    Link: TSourceLink;
    CodeBuf: TCodeBuffer;
    LastCode: TCodeBuffer;
  begin
    if (Tool=nil) or (Tool.Scanner=nil) then exit;
    LineCnt:=0;
    ByteCnt:=0;
    LastCode:=nil;
    for i:=0 to Tool.Scanner.LinkCount-1 do begin
      Link:=Tool.Scanner.Links[i];
      CodeBuf:=TCodeBuffer(Link.Code);
      if CodeBuf<>LastCode then begin
        inc(LineCnt,LineEndCount(CodeBuf.Source));
        inc(ByteCnt,length(CodeBuf.Source));
        LastCode:=CodeBuf;
      end;
    end;
    AnUnit.ScannedBytes:=ByteCnt;
    AnUnit.ScannedLines:=LineCnt;
    AnUnit.ScannedIdentifiers:=CountIdentifiers(Tool);
    AnUnit.CodeTool:=Tool;
    inc(FScannedBytes,AnUnit.ScannedBytes);
    inc(FScannedLines,AnUnit.ScannedLines);
    inc(FScannedIdentifiers,AnUnit.ScannedIdentifiers);
    //DebugLn(['UpdateScannedCounters ',ExtractFileName(AnUnit.Filename),' LineCnt=',LineCnt,' ByteCnt=',ByteCnt,' ',DbgSName(AnUnit.CodeTool)]);
  end;

var
  MainCodeBuf: TCodeBuffer;
  Tool: TCodeTool;
begin
  //DebugLn(['TCodeBrowserView.WorkUpdateUnit START ',AnUnit.Filename]);
  // mark as updated
  fOutdatedFiles.Remove(AnUnit);
  // reset scanning counters
  if AnUnit.Scanned then begin
    dec(FScannedBytes,AnUnit.ScannedBytes);
    dec(FScannedLines,AnUnit.ScannedLines);
    dec(FScannedIdentifiers,AnUnit.ScannedIdentifiers);
    AnUnit.ScannedBytes:=0;
    AnUnit.ScannedLines:=0;
    AnUnit.ScannedIdentifiers:=0;
    dec(FScannedUnits);
  end;
  AnUnit.Scanned:=true;
  inc(FScannedUnits);
  // load the file
  AnUnit.CodeBuffer:=CodeToolBoss.LoadFile(AnUnit.Filename,false,false);
  if AnUnit.CodeBuffer=nil then exit;
  // check if this is a unit
  MainCodeBuf:=CodeToolBoss.GetMainCode(AnUnit.CodeBuffer);
  if MainCodeBuf<>AnUnit.CodeBuffer then begin
    // this file was used as an include file
    DebugLn(['TCodeBrowserView.WorkUpdateUnit HINT: this is not a unit: ',AnUnit.Filename,
      ' (it was included by ',MainCodeBuf.Filename,')']);
    exit;
  end;
  // scan
  CodeToolBoss.Explore(AnUnit.CodeBuffer,Tool,false,true);
  UpdateScannedCounters(Tool);
  //DebugLn(['TCodeBrowserView.WorkUpdateUnit END ',AnUnit.Filename]);
end;

procedure TCodeBrowserView.WorkGetViewOptions;
var
  NewLevels: TStringList;
begin
  //DebugLn(['TCodeBrowserView.WorkGetViewOptions START']);
  Options.ShowPrivate:=ShowPrivateCheckBox.Checked;
  Options.ShowProtected:=ShowProtectedCheckBox.Checked;
  Options.ShowEmptyNodes:=ShowEmptyNodesCheckBox.Checked;

  // levels
  NewLevels:=TStringList.Create;
  if ShowPackagesCheckBox.Checked then
    NewLevels.Add(CodeBrowserLevelNames[cblPackages]);
  if ShowUnitsCheckBox.Checked then
    NewLevels.Add(CodeBrowserLevelNames[cblUnits]);
  if ShowIdentifiersCheckBox.Checked then
    NewLevels.Add(CodeBrowserLevelNames[cblIdentifiers]);
  Options.Levels:=NewLevels;
  NewLevels.Free;

  // level filter
  Options.LevelFilterText[cblPackages]:=PackageFilterEdit.Text;
  if PackageFilterBeginsSpeedButton.Down then
    Options.LevelFilterType[cblPackages]:=cbtfBegins;
  if PackageFilterContainsSpeedButton.Down then
    Options.LevelFilterType[cblPackages]:=cbtfContains;

  Options.LevelFilterText[cblUnits]:=UnitFilterEdit.Text;
  //DebugLn(['TCodeBrowserView.WorkGetOptions UnitFIlter=',Options.LevelFilterText[cblUnits],' Edit=',UnitFilterEdit.Text]);
  if UnitFilterBeginsSpeedButton.Down then
    Options.LevelFilterType[cblUnits]:=cbtfBegins;
  if UnitFilterContainsSpeedButton.Down then
    Options.LevelFilterType[cblUnits]:=cbtfContains;

  Options.LevelFilterText[cblIdentifiers]:=IdentifierFilterEdit.Text;
  if IdentifierFilterBeginsSpeedButton.Down then
    Options.LevelFilterType[cblIdentifiers]:=cbtfBegins;
  if IdentifierFilterContainsSpeedButton.Down then
    Options.LevelFilterType[cblIdentifiers]:=cbtfContains;

  DebugLn(['TCodeBrowserView.WorkGetViewOptions UpdateNeeded=',UpdateNeeded,' ChangeStamp=',Options.ChangeStamp<>FOptionsChangeStamp]);

  // this stage finished -> next stage
  if UpdateNeeded or (Options.ChangeStamp<>FOptionsChangeStamp) then
    fStage:=cbwsUpdateTreeView
  else
    fStage:=cbwsFinished;
  ProgressBar1.Position:=ProgressGetViewOptionsStart+ProgressGetViewOptionsSize;
end;

procedure TCodeBrowserView.WorkUpdateTreeView;
begin
  ProgressBar1.Position:=ProgressUpdateTreeViewStart;
  UpdateTreeView;
  // this stage finished -> next stage
  fStage:=cbwsFinished;
  ProgressBar1.Position:=ProgressUpdateTreeViewStart+ProgressUpdateTreeViewSize;
end;

procedure TCodeBrowserView.FreeUnitList(List: TCodeBrowserUnitList);
var
  Node: TAVLTreeNode;
  AnUnit: TCodeBrowserUnit;
begin
  //DebugLn(['TCodeBrowserView.FreeUnitList ',List.Owner]);
  dec(FScannedPackages);
  if List.Units<>nil then begin
    Node:=List.Units.FindLowest;
    while Node<>nil do begin
      AnUnit:=TCodeBrowserUnit(Node.Data);
      RemoveUnit(AnUnit);
      Node:=List.Units.FindSuccessor(Node);
    end;
  end;
  List.Free;
end;

procedure TCodeBrowserView.UpdateStatusBar(Lazy: boolean);
const
  SmallTimeStep = 1/86400;

  function BigIntToStr(i: integer): string;
  var
    p: Integer;
  begin
    if i=0 then begin
      Result:='0';
      exit;
    end;
    Result:='';
    if i>=100000 then begin
      i:=i div 1000;
      Result:='k';
      if i>=100000 then begin
        i:=i div 1000;
        Result:='m';
        if i>=100000 then begin
          i:=i div 1000;
          Result:='g';
          if i>=100000 then begin
            i:=i div 1000;
            Result:='t';
          end;
        end;
      end;
    end;

    p:=0;
    while i>0 do begin
      if p=3 then begin
        Result:=DefaultFormatSettings.ThousandSeparator+Result;
        p:=0;
      end;
      Result:=chr((i mod 10)+ord('0'))+Result;
      i:=i div 10;
      inc(p);
    end;
  end;
var
  s: String;
begin
  if Lazy and (Abs(Now-fLastStatusBarUpdate)<SmallTimeStep) then begin
    // the last update is not long ago
    // => skip update
    exit;
  end;
  fLastStatusBarUpdate:=Now;
  s:='packages='+BigIntToStr(VisiblePackages)+'/'+BigIntToStr(ScannedPackages)
    +' units='+BigIntToStr(VisibleUnits)+'/'+BigIntToStr(ScannedUnits)
    +' identifiers='+BigIntToStr(VisibleIdentifiers)+'/'+BigIntToStr(ScannedIdentifiers)
    +' lines='+BigIntToStr(ScannedLines)
    +' bytes='+BigIntToStr(ScannedBytes);
  if fStage<>cbwsFinished then
    s:=s+'. Scanning ...';
  StatusBar1.SimpleText:=s;
end;

procedure TCodeBrowserView.UpdateTreeView;
var
  ShowPackages: boolean;
  ShowUnits: boolean;
  ShowIdentifiers: boolean;
  ShowPrivate: boolean;
  ShowProtected: boolean;
  ShowEmptyNodes: boolean;
  NewPackageCount: integer;
  NewUnitCount: integer;
  NewIdentifierCount: PtrInt;
  
  LevelFilterText: array[TCodeBrowserLevel] of string;
  LevelFilterType: array[TCodeBrowserLevel] of TCodeBrowserTextFilter;

  function GetCodeTool(AnUnit: TCodeBrowserUnit): TStandardCodeTool;
  begin
    //DebugLn(['GetCodeTool ',AnUnit.CodeTool<>nil,' ',AnUnit.CodeBuffer<>nil]);
    Result:=AnUnit.CodeTool;
    if Result<>nil then exit;
    if AnUnit.CodeBuffer=nil then exit;
    Result:=CodeToolBoss.GetCodeToolForSource(AnUnit.CodeBuffer,true,false)
                as TCodeTool;
    //DebugLn(['GetCodeTool END ',Result<>nil]);
  end;
  
  function IdentifierFitsFilter(LvlType: TCodeBrowserLevel;
    const Identifier: string): boolean;
  begin
    //DebugLn(['IdentifierFitsFilter Identifier=',Identifier,' Filter=',LevelFilterText[LvlType]]);
    if (LevelFilterText[LvlType]='') then exit(true);
    if Identifier='' then exit(false);

    case LevelFilterType[LvlType] of
    cbtfBegins:
      Result:=ComparePrefixIdent(PChar(Pointer(LevelFilterText[LvlType])),
                                 PChar(Pointer(Identifier)));
    cbtfContains:
      Result:=IdentifierPos(PChar(Pointer(LevelFilterText[LvlType])),
                            PChar(Pointer(Identifier)))>=0;
    else
      Result:=true;
    end;
  end;

  procedure AddUnitNodes(SrcUnit: TCodeBrowserUnit; var DestUnit: TObject);
  var
    Tool: TStandardCodeTool;
    
    procedure AddUnit;
    begin
      if DestUnit=nil then
        DestUnit:=TCodeBrowserUnit.Create('');
    end;
    
    function Shorten(const s: string): string;
    const
      MAX_LEN=100;
    begin
      Result:=DbgStr(s);
      if Length(Result)>MAX_LEN then
        Result:=LeftStr(Result, MAX_LEN)+'...';
    end;

    procedure GetNodeDescription(CTNode: TCodeTreeNode;
      out Description, Identifier: string);
    const
      NodeFlags = [];
    var
      Inheritance: String;
    begin
      case CTNode.Desc of
      ctnProcedure:
        begin
          Identifier:=Tool.ExtractProcHead(CTNode,ProcIdentifierFlags);
          Description:=Tool.ExtractProcHead(CTNode,ProcDescFlags);
        end;
      ctnVarDefinition:
        begin
          Identifier:=Tool.ExtractDefinitionName(CTNode);
          Description:='var '+Identifier
                     +' : '+Shorten(Tool.ExtractDefinitionNodeType(CTNode));
        end;
      ctnConstDefinition:
        begin
          Identifier:=Tool.ExtractDefinitionName(CTNode);
          Description:='const '+Shorten(Tool.ExtractNode(CTNode,NodeFlags));
        end;
      ctnTypeDefinition,ctnGenericType:
        begin
          Identifier:=Tool.ExtractDefinitionName(CTNode);
          Description:='type '+Identifier;
          if CTNode.FirstChild<>nil then begin
            case CTNode.FirstChild.Desc of
            ctnClass,ctnClassInterface,ctnObject,
            ctnObjCClass,ctnObjCCategory,ctnObjCProtocol,
            ctnCPPClass:
              begin
                case CTNode.FirstChild.Desc of
                ctnClassInterface:
                  Description:=Description+' = interface';
                ctnObject:
                  Description:=Description+' = object';
                ctnObjCClass:
                  Description:=Description+' = objcclass';
                ctnObjCCategory:
                  Description:=Description+' = objccategory';
                ctnObjCProtocol:
                  Description:=Description+' = objcprotocol';
                ctnCPPClass:
                  Description:=Description+' = cppclass';
                else
                  Description:=Description+' = class';
                end;
                Inheritance:=Tool.ExtractClassInheritance(CTNode.FirstChild,[]);
                if Inheritance<>'' then
                  Description:=Description+'('+Inheritance+')';
              end;
            ctnRecordType:
              Description:=Description+' = record';
            end;
          end;
        end;
      ctnProperty:
        begin
          Identifier:=Tool.ExtractPropName(CTNode,false);
          Description:='property '+Shorten(Tool.ExtractProperty(CTNode,PropDescFlags));
        end;
      ctnEnumIdentifier:
        begin
          Identifier:=Tool.ExtractIdentifier(CTNode.StartPos);
          Description:='enum '+Identifier;
        end;
      end;
    end;
    
    procedure AddIdentifierNode(CTNode: TCodeTreeNode);
    var
      NewNode: TCodeBrowserNode;
      ChildCTNode: TCodeTreeNode;

      procedure AddChildNode;
      var
        NewChildNode: TCodeBrowserNode;
        ChildDescription, ChildIdentifier: string;
        NewCodePos: TCodePosition;
      begin
        //DebugLn(['AddChildNode ',ChildCTNode.DescAsString,' ',ChildDescription]);
        if (ChildCTNode.Parent.Desc=ctnClassPrivate) and (not ShowPrivate) then
          exit;
        if (ChildCTNode.Parent.Desc=ctnClassProtected) and (not ShowProtected)
        then
          exit;
        GetNodeDescription(ChildCTNode,ChildDescription,ChildIdentifier);
        
        if IdentifierFitsFilter(cblIdentifiers,ChildIdentifier) then begin
          NewChildNode:=NewNode.AddNode(ChildDescription,ChildIdentifier);
          if NewChildNode<>nil then begin
            NewChildNode.Desc:=ChildCTNode.Desc;
            Tool.CleanPosToCodePos(ChildCTNode.StartPos,NewCodePos);
            NewChildNode.CodePos:=NewCodePos;
          end;
        end;
      end;
      
    var
      Description, Identifier: string;
      CurUnit: TCodeBrowserUnit;
      NewCodePos: TCodePosition;
    begin
      if not ShowIdentifiers then exit;
      AddUnit;
      CurUnit:=TCodeBrowserUnit(DestUnit);
      //DebugLn(['AddIdentifierNode ',CTNode.DescAsString,' Description="',Description,'"']);
      GetNodeDescription(CTNode,Description,Identifier);
      NewNode:=CurUnit.AddNode(Description,Identifier);
      NewNode.Desc:=CTNode.Desc;
      Tool.CleanPosToCodePos(CTNode.StartPos,NewCodePos);
      NewNode.CodePos:=NewCodePos;
      //DebugLn(['AddIdentifierNode Code=',NewNode.FCodePos.Code<>nil,' P=',NewNode.FCodePos.P]);
      
      if (CTNode.Desc in [ctnTypeDefinition,ctnGenericType])
      and (CTNode.FirstChild<>nil)
      and (CTNode.FirstChild.Desc in AllClasses+[ctnRecordType,ctnEnumerationType])
      then begin
        // add child nodes
        ChildCTNode:=CTNode.FirstChild;
        while (ChildCTNode<>nil) and (ChildCTNode.StartPos<CTNode.EndPos) do
        begin
          if ChildCTNode.Desc in
          [ctnProcedure,ctnVarDefinition,ctnProperty,ctnEnumIdentifier]
          then begin
            AddChildNode;
          end;
          if ChildCTNode.Desc=ctnProcedureHead then
            ChildCTNode:=ChildCTNode.NextSkipChilds
          else
            ChildCTNode:=ChildCTNode.Next;
        end;
      end;
      
      if (NewNode.ChildNodes=nil)
      and (not IdentifierFitsFilter(cblIdentifiers,Identifier)) then begin
        // identifier is not needed -> remove
        CurUnit.DeleteNode(NewNode);
      end;
    end;
    
  var
    CTNode: TCodeTreeNode;
  begin
    if SrcUnit=nil then exit;
    //DebugLn(['AddUnitNodes SrcUnit.Filename="',SrcUnit.Filename,'"']);
    Tool:=GetCodeTool(SrcUnit);
    if Tool=nil then exit;
    if Tool.Tree=nil then exit;
    
    CTNode:=Tool.Tree.Root;
    while CTNode<>nil do begin
      //DebugLn(['AddUnitNodes ',CTNode.DescAsString]);
      case CTNode.Desc of
      ctnProcedure:
        if not Tool.NodeIsMethodBody(CTNode) then
          AddIdentifierNode(CTNode);
      ctnVarDefinition,ctnConstDefinition,ctnTypeDefinition,ctnGenericType:
        if not Tool.NodeIsForwardDeclaration(CTNode) then
          AddIdentifierNode(CTNode);
      end;

      // go to next node
      case CTNode.Desc of
      ctnProgram,ctnLibrary,ctnPackage,ctnUnit,ctnInterface,
      ctnTypeSection,ctnConstSection,ctnVarSection,ctnResStrSection:
        // go into child nodes
        CTNode:=CTNode.Next;
      ctnImplementation, ctnBeginBlock, ctnAsmBlock: break;
      else
        // skip children and go to next sibling or parent
        CTNode:=CTNode.NextSkipChilds;
      end;
    end;
  end;
  
  procedure AddUnits(SrcList: TCodeBrowserUnitList;
    var DestParentList: TCodeBrowserUnitList);
    
    procedure RaiseParentNotUnitList;
    begin
      raise Exception.Create('TCodeBrowserView.UpdateTreeView.AddUnits.RaiseParentNotUnitList');
    end;
    
  var
    Node: TAVLTreeNode;
    CurUnit: TCodeBrowserUnit;
    NewUnit: TCodeBrowserUnit;
    List: TCodeBrowserUnitList;
    OldDestParentList: TObject;
  begin
    if SrcList=nil then exit;
    //DebugLn(['AddUnits SrcList.Owner="',SrcList.Owner,'" HasUnits=',SrcList.Units<>nil]);
    if SrcList.Units=nil then exit;
    OldDestParentList:=DestParentList;
    Node:=SrcList.Units.FindLowest;
    NewUnit:=nil;
    while Node<>nil do begin
      CurUnit:=TCodeBrowserUnit(Node.Data);
      if (CurUnit.Filename='')
      or IdentifierFitsFilter(cblUnits,ExtractFileNameOnly(CurUnit.Filename))
      then begin
        if DestParentList=nil then begin
          DestParentList:=TCodeBrowserUnitList.Create(CodeBrowserHidden,nil);
        end else if not (DestParentList is TCodeBrowserUnitList) then
          RaiseParentNotUnitList;
        List:=TCodeBrowserUnitList(DestParentList);
        if ShowUnits then begin
          // create a unit node
          NewUnit:=List.AddUnit(CurUnit.Filename);
          NewUnit.CodeBuffer:=CurUnit.CodeBuffer;
          NewUnit.CodeTool:=CurUnit.CodeTool;
        end else if NewUnit=nil then begin
          // create a dummy unit node to add all identifiers
          NewUnit:=List.FindUnit('');
          if NewUnit=nil then
            NewUnit:=List.AddUnit('');
        end;
        //DebugLn(['AddUnits AddUnitNodes ',CurUnit.Filename]);
        AddUnitNodes(CurUnit,TObject(NewUnit));
        if (not ShowEmptyNodes) and (NewUnit.ChildNodeCount=0) then begin
          // remove empty unit
          List.DeleteUnit(NewUnit);
          NewUnit:=nil;
          if OldDestParentList=nil then begin
            FreeAndNil(DestParentList);
          end;
        end;
        if (NewUnit<>nil) and (NewUnit.UnitList=nil) and (List<>nil) then
          List.AddUnit(NewUnit);
      end;
      Node:=SrcList.Units.FindSuccessor(Node);
    end;
  end;

  procedure AddUnitLists(SrcList: TCodeBrowserUnitList;
    var DestParentList: TCodeBrowserUnitList);
  var
    Node: TAVLTreeNode;
    SubList: TCodeBrowserUnitList;
    NewList: TCodeBrowserUnitList;
    OldDestParentList: TCodeBrowserUnitList;
    NewListCreated: Boolean;
    CreateNode: Boolean;
  begin
    if SrcList=nil then exit;
    //DebugLn(['AddUnitLists SrcList.Owner="',SrcList.Owner,'"']);

    OldDestParentList:=DestParentList;
    
    // check filter
    CreateNode:=IdentifierFitsFilter(cblPackages,SrcList.Owner);
    
    // create node
    NewListCreated:=false;
    if CreateNode then begin
      if ShowPackages then begin
        if DestParentList=nil then begin
          DestParentList:=TCodeBrowserUnitList.Create(CodeBrowserHidden,nil);
        end;
        NewList:=TCodeBrowserUnitList.Create(SrcList.Owner,DestParentList);
        NewListCreated:=true;
      end else begin
        NewList:=DestParentList;
      end;
    end;
    // create nodes for unitlists
    if SrcList.UnitLists<>nil then begin
      Node:=SrcList.UnitLists.FindLowest;
      while Node<>nil do begin
        SubList:=TCodeBrowserUnitList(Node.Data);
        AddUnitLists(SubList,DestParentList);// DestParentList because: as sibling not child!
        Node:=SrcList.UnitLists.FindSuccessor(Node);
      end;
    end;
    if CreateNode then begin
      // create nodes for units
      AddUnits(SrcList,NewList);
      // remove empty unit lists
      if (not ShowEmptyNodes) and NewListCreated and (NewList.IsEmpty) then begin
        //DebugLn(['AddUnitLists EMPTY ',NewList.Owner,' ',NewList.UnitListCount,' ',NewList.UnitCount]);
        if DestParentList=NewList then
          DestParentList:=nil;
        NewList.Free;
        NewList:=nil;
        if (OldDestParentList=nil) and (DestParentList<>nil)
        and DestParentList.IsEmpty then begin
          FreeAndNil(DestParentList);
        end;
      end;
      // update DestParentList
      if (DestParentList=nil) then
        DestParentList:=NewList;
    end;
  end;

  procedure AddTreeNodes(CodeNode: TObject; ParentViewNode: TTreeNode);
  var
    TVNode: TTreeNode;

    procedure RecursiveAdd(Tree: TAVLTree);
    var
      Node: TAVLTreeNode;
    begin
      if Tree<>nil then begin
        Node:=Tree.FindLowest;
        while Node<>nil do begin
          AddTreeNodes(TObject(Node.Data), TVNode);
          Node:=Tree.FindSuccessor(Node);
        end;
      end;
    end;

    {off $DEFINE DisableTreeViewNodes}
    procedure AddToTreeView(Name: String);
    begin
      {$IFNDEF DisableTreeViewNodes}
      TVNode:=BrowseTreeView.Items.AddChildObject(
        ParentViewNode, Name, CodeNode);
      TVNode.ImageIndex:=GetNodeImage(CodeNode);
      TVNode.SelectedIndex:=TVNode.ImageIndex;
      {$ENDIF}
    end;

  // create visual nodes (TTreeNode)
  var
    CurList: TCodeBrowserUnitList;
    CurListName: String;
    CurUnit: TCodeBrowserUnit;
    CurUnitName: String;
    CurTool: TStandardCodeTool;
    CurNode: TCodeBrowserNode;
    ExpandParent: Boolean;
  begin
    if CodeNode=nil then exit;
    ExpandParent:=true;
    //DebugLn(['AddTreeNodes ',DbgSName(CodeNode)]);
    TVNode:=ParentViewNode;

    if CodeNode is TCodeBrowserUnitList then begin
      CurList:=TCodeBrowserUnitList(CodeNode);
      //DebugLn(['AddTreeNodes ',CurList.Owner]);
      if CurList.Owner=CodeBrowserHidden then begin
        TVNode:=ParentViewNode;
      end else begin
        CurListName:=ListOwnerToText(CurList.Owner);
        inc(NewPackageCount);
        AddToTreeView(CurListName);
      end;
      RecursiveAdd(CurList.UnitLists);
      RecursiveAdd(CurList.Units);
    end
    else if CodeNode is TCodeBrowserUnit then begin
      CurUnit:=TCodeBrowserUnit(CodeNode);
      CurTool:=nil;
      if CurUnit.Filename<>'' then
        CurTool:=GetCodeTool(CurUnit);
      if CurTool<>nil then begin
        // add a tree node for this unit
        CurUnitName:=TCodeTool(CurTool).GetCachedSourceName;
        if CurUnitName='' then
          CurUnitName:=ExtractFileNameOnly(CurTool.MainFilename);
        inc(NewUnitCount);
        AddToTreeView(CurUnitName);
      end else begin
        // do not add a tree node for this unit
        TVNode:=ParentViewNode;
      end;
      // create tree nodes for code nodes
      RecursiveAdd(CurUnit.ChildNodes);
    end
    else if CodeNode is TCodeBrowserNode then begin
      CurNode:=TCodeBrowserNode(CodeNode);
      if CurNode.Description<>'' then begin
        inc(NewIdentifierCount);
        //if (NewIdentifierCount mod 100)=0 then
        //  DebugLn(['AddTreeNodes ',NewIdentifierCount,' ',CurNode.Description]);
        AddToTreeView(CurNode.Description);
        // create tree nodes for child code nodes
        RecursiveAdd(CurNode.ChildNodes);
        // do not expand unit nodes
        if (ParentViewNode<>nil)
        and (TObject(ParentViewNode.Data) is TCodeBrowserUnit) then
          ExpandParent:=false;
      end;
    end;
    if ParentViewNode<>nil then
      ParentViewNode.Expanded:=ExpandParent;
  end;

var
  lvl: TCodeBrowserLevel;
begin
  ShowPackages:=Options.HasLevel(cblPackages);
  ShowUnits:=Options.HasLevel(cblUnits);
  ShowIdentifiers:=Options.HasLevel(cblIdentifiers);
  ShowPrivate:=Options.ShowPrivate;
  ShowProtected:=Options.ShowProtected;
  ShowEmptyNodes:=Options.ShowEmptyNodes;
  NewPackageCount:=0;
  NewUnitCount:=0;
  NewIdentifierCount:=0;

  for lvl:=Low(TCodeBrowserLevel) to High(TCodeBrowserLevel) do begin
    LevelFilterText[lvl]:=Options.LevelFilterText[lvl];
    LevelFilterType[lvl]:=Options.LevelFilterType[lvl];
  end;
  DebugLn(['TCodeBrowserView.UpdateTreeView UnitFilter=',LevelFilterText[cblUnits]]);
  
  //DebugLn(['TCodeBrowserView.UpdateTreeView ShowPackages=',ShowPackages,' ShowUnits=',ShowUnits,' ShowIdentifiers=',ShowIdentifiers]);

  BrowseTreeView.Cursor:=crHourGlass;
  BrowseTreeView.BeginUpdate;
  CodeToolBoss.ActivateWriteLock;
  try
    InitTreeView;

    // create internal nodes
    AddUnitLists(ParserRoot,fViewRoot);

    // create treeview nodes
    AddTreeNodes(ViewRoot,nil);
  finally
    CodeToolBoss.DeactivateWriteLock;
    //DebugLn(['TCodeBrowserView.UpdateTreeView EndUpdate']);
    BrowseTreeView.EndUpdate;
    //DebugLn(['TCodeBrowserView.UpdateTreeView AFER ENDUPDATE']);
    BrowseTreeView.Cursor:=crDefault;
  end;
  VisiblePackages:=NewPackageCount;
  VisibleUnits:=NewUnitCount;
  VisibleIdentifiers:=NewIdentifierCount;
  UpdateStatusBar(false);
end;

procedure TCodeBrowserView.RemoveUnit(AnUnit: TCodeBrowserUnit);
begin
  if AnUnit.Scanned then begin
    dec(FScannedUnits);
    dec(FScannedLines,AnUnit.ScannedLines);
    dec(FScannedBytes,AnUnit.ScannedBytes);
    dec(FScannedIdentifiers,AnUnit.ScannedIdentifiers);
    AnUnit.Scanned:=false;
    if fOutdatedFiles<>nil then
      fOutdatedFiles.Remove(AnUnit);
  end;
end;

function TCodeBrowserView.CountIdentifiers(Tool: TCodeTool): integer;
var
  Node: TCodeTreeNode;
begin
  Result:=0;
  if (Tool=nil) or (Tool.Tree=nil) then exit;
  Node:=Tool.Tree.Root;
  while Node<>nil do begin
    if Node.Desc=ctnImplementation then break;
    if (Node.Desc in (AllIdentifierDefinitions+[ctnProcedure,ctnProperty]))
    and (not Tool.NodeIsForwardDeclaration(Node)) then
      inc(Result);
    if not (Node.Desc in [ctnProcedure,ctnBeginBlock,ctnAsmBlock]) then
      Node:=Node.Next
    else
      Node:=Node.NextSkipChilds;
  end;
end;

procedure TCodeBrowserView.ClearTreeView;
begin
  BrowseTreeView.Items.Clear;
  FreeAndNil(FViewRoot);
end;

procedure TCodeBrowserView.InitTreeView;
begin
  ClearTreeView;
end;

function TCodeBrowserView.ListOwnerToText(const ListOwner: string): string;
begin
  if ListOwner=CodeBrowserIDEName then
    Result:=IDEDescription
  else if ListOwner=CodeBrowserProjectName then
    Result:=ProjectDescription
  else
    Result:=ListOwner;
end;

function TCodeBrowserView.GetNodeImage(CodeNode: TObject): integer;
var
  List: TCodeBrowserUnitList;
  Node: TCodeBrowserNode;
begin
  Result:=ImgIDDefault;
  
  if CodeNode is TCodeBrowserUnit then begin
    Result:=ImgIDUnitCode;
  end else if CodeNode is TCodeBrowserUnitList then begin
    List:=TCodeBrowserUnitList(CodeNode);
    if List.Owner=IDEDescription then
      Result:=ImgIDProject
    else if List.Owner=ProjectDescription then
      Result:=ImgIDProject
    else
      Result:=ImgIDPackage;
  end else if CodeNode is TCodeBrowserNode then begin
    Node:=TCodeBrowserNode(CodeNode);
    case Node.Desc of
    ctnProgram,ctnLibrary,ctnPackage:
      Result:=ImgIDProgramCode;
    ctnUnit:
      Result:=ImgIDUnitCode;
    ctnInterface:
      Result:=ImgIDInterfaceSection;
    ctnImplementation:
      Result:=ImgIDImplementation;
    ctnInitialization:
      Result:=ImgIDInitialization;
    ctnFinalization:
      Result:=ImgIDFinalization;
    ctnTypeSection:
      Result:=ImgIDTypeSection;
    ctnTypeDefinition,ctnGenericType:
      Result:=ImgIDType;
    ctnVarSection:
      Result:=ImgIDVarSection;
    ctnVarDefinition:
      Result:=ImgIDVariable;
    ctnConstSection,ctnResStrSection:
      Result:=ImgIDConstSection;
    ctnConstDefinition:
      Result:=ImgIDConst;
    ctnClass,ctnObject,ctnObjCClass,ctnObjCCategory,ctnObjCProtocol,ctnCPPClass:
      Result:=ImgIDClass;
    ctnProcedure:
      Result:=ImgIDProc;
    ctnProperty:
      Result:=ImgIDProperty;
    end;
  end;
end;

function TCodeBrowserView.GetTVNodeHint(TVNode: TTreeNode): string;
var
  NodeData: TObject;
  CurUnit: TCodeBrowserUnit;
  Node: TCodeBrowserNode;
  Line, Column: integer;
  BaseURL, HTMLHint: String;
begin
  Result:='';
  if (TVNode=nil) or (TVNode.Data=nil) then exit;
  NodeData:=TObject(TVNode.Data);
  //DebugLn(['TCodeBrowserView.GetTVNodeHint ',DbgSName(NodeData)]);
  if NodeData is TCodeBrowserUnitList then begin

  end else if NodeData is TCodeBrowserUnit then begin
    CurUnit:=TCodeBrowserUnit(NodeData);
    if CurUnit.Filename<>'' then
      Result:=TVNode.Text+#13+CurUnit.Filename;
  end else if NodeData is TCodeBrowserNode then begin
    Node:=TCodeBrowserNode(NodeData);
    if Node.CodePos.Code<>nil then begin
      Result:=TVNode.Text+#13+Node.CodePos.Code.Filename;
      Node.CodePos.Code.AbsoluteToLineCol(Node.CodePos.P,Line,Column);
      if Line>0 then
        Result:=Result+' ('+IntToStr(Line)+','+IntToStr(Column)+')';
        if GetCodeHelp(TVNode, BaseURL, HTMLHint) then
           Result := HTMLHint;
    end;
  end;
end;

function TCodeBrowserView.GetCodeHelp(TVNode: TTreeNode; out BaseURL,
  HTMLHint: string): boolean;
var
  NodeData: TObject;
  Node: TCodeBrowserNode;
  Tool: TCodeTool;
  CleanPos: integer;
  CTNode: TCodeTreeNode;
  NewCodePos: TCodeXYPosition;
begin
  Result:=false;
  BaseURL:='';
  HTMLHint:='';
  if (TVNode=nil) or (TVNode.Data=nil) then exit;
  NodeData:=TObject(TVNode.Data);
  if NodeData is TCodeBrowserNode then begin
    Node:=TCodeBrowserNode(NodeData);
    if Node.CodePos.Code=nil then exit;
    if not LazarusIDE.BeginCodeTools then // commit source editor changes to codetools
      exit;
    // parse unit
    CodeToolBoss.Explore(Node.CodePos.Code,Tool,false,false);
    if Tool=nil then exit;
    // find source position in parsed code
    if Tool.CodePosToCleanPos(Node.CodePos,CleanPos)<>0 then exit;
    // find node
    CTNode:=Tool.FindDeepestNodeAtPos(CleanPos,false);
    if (CTNode=nil) or (CTNode.Desc<>Node.Desc) then
      exit; // source has changed

    // find cleanpos of identifier
    case CTNode.Desc of
    ctnProcedure:
      begin
        if SysUtils.CompareText(Tool.ExtractProcHead(CTNode,ProcIdentifierFlags),
          Node.Identifier)<>0
        then
          exit; // source has changed
        Tool.MoveCursorToProcName(CTNode,true);
        CleanPos:=Tool.CurPos.StartPos;
      end;
    ctnProperty:
      begin
        if SysUtils.CompareText(Tool.ExtractPropName(CTNode,false),Node.Identifier)<>0
        then
          exit; // source has changed
        Tool.MoveCursorToPropName(CTNode);
        CleanPos:=Tool.CurPos.StartPos;
      end;
    ctnGenericType:
      begin
        Tool.ExtractDefinitionName(CTNode);
        if CTNode.FirstChild<>nil then
          CleanPos:=CTNode.FirstChild.StartPos;
        if SysUtils.CompareText(Tool.ExtractIdentifier(CleanPos),Node.Identifier)<>0
        then
          exit; // source has changed
      end;
    ctnVarDefinition,ctnTypeDefinition,ctnConstDefinition,
    ctnEnumIdentifier:
      if SysUtils.CompareText(Tool.ExtractIdentifier(CleanPos),Node.Identifier)<>0
      then
        exit; // source has changed
    else
      exit;
    end;

    // get source position
    if not Tool.CleanPosToCaret(CleanPos,NewCodePos) then exit;

    // ask the help system about the identifier
    if LazarusHelp.GetHintForSourcePosition(NewCodePos.Code.Filename,
      Point(NewCodePos.X,NewCodePos.Y),BaseURL,HTMLHint)<>shrSuccess then exit;

    if HTMLHint <> '' then
       Result:=true;
  end;
end;

procedure TCodeBrowserView.ExpandCollapseAllNodesInTreeView(
  NodeType: TExpandableNodeType; Expand: boolean);
var
  Node: TTreeNode;
begin
  BrowseTreeView.BeginUpdate;
  Node:=BrowseTreeView.Items.GetFirstNode;
  while Node<>nil do begin
    if (Node.Data<>nil) then begin
      case NodeType of
      entPackage:
        if  TObject(Node.Data) is TCodeBrowserUnitList then
          Node.Expanded:=Expand;
      entUnit:
        if  TObject(Node.Data) is TCodeBrowserUnit then
          Node.Expanded:=Expand;
      entClass:
        if  (TObject(Node.Data) is TCodeBrowserNode) then
          Node.Expanded:=Expand;
      end;
    end;
    Node:=Node.GetNext;
  end;
  BrowseTreeView.EndUpdate;
end;

procedure TCodeBrowserView.CopyNode(TVNode: TTreeNode; NodeType: TCopyNodeType
  );
var
  Node: TCodeBrowserNode;
  s: string;
begin
  if (TVNode=nil) or (TVNode.Data=nil) then exit;
  s:='';
  if  TObject(TVNode.Data) is TCodeBrowserUnitList then begin
    s:=TVNode.Text;
  end;
  if  TObject(TVNode.Data) is TCodeBrowserUnit then begin
    s:=TVNode.Text;
  end;
  if  (TObject(TVNode.Data) is TCodeBrowserNode) then begin
    Node:=TCodeBrowserNode(TVNode.Data);
    if NodeType=cntIdentifier then
      s:=Node.Identifier
    else
      s:=Node.Description;
  end;
  Clipboard.AsText:=s;
end;

procedure TCodeBrowserView.InvalidateStage(AStage: TCodeBrowserWorkStage);
begin
  if ord(fStage)>ord(AStage) then
    fStage:=AStage;
end;

function TCodeBrowserView.GetSelectedUnit: TCodeBrowserUnit;
var
  TVNode: TTreeNode;
  Node: TObject;
begin
  Result:=nil;
  TVNode:=BrowseTreeView.Selected;
  if TVNode=nil then exit;
  Node:=TObject(TVNode.Data);
  if Node=nil then exit;
  if not (Node is TCodeBrowserUnit) then exit;
  Result:=TCodeBrowserUnit(Node);
end;

function TCodeBrowserView.GetSelectedPackage: TLazPackage;
var
  TVNode: TTreeNode;
  Node: TObject;
  UnitList: TCodeBrowserUnitList;
begin
  Result:=nil;
  TVNode:=BrowseTreeView.Selected;
  if TVNode=nil then exit;
  Node:=TObject(TVNode.Data);
  if Node=nil then exit;
  if not (Node is TCodeBrowserUnitList) then exit;
  UnitList:=TCodeBrowserUnitList(Node);
  Result:=PackageGraph.FindAPackageWithName(UnitList.Owner,nil);
end;

function TCodeBrowserView.GetCurUnitInSrcEditor(out FileOwner: TObject; out
  UnitCode: TCodeBuffer): boolean;
var
  SrcEdit: TSourceEditorInterface;
  Code: TCodeBuffer;
  Owners: TFPList;
begin
  FileOwner:=nil;
  UnitCode:=nil;
  Result:=false;
  SrcEdit:=SourceEditorManagerIntf.ActiveEditor;
  if SrcEdit=nil then exit;
  Code:=CodeToolBoss.GetMainCode(TCodeBuffer(SrcEdit.CodeToolsBuffer));
  if Code=nil then exit;
  Owners:=PkgBoss.GetOwnersOfUnit(Code.FileName);
  try
    if (Owners=nil) or (Owners.Count=0) then exit;
    FileOwner:=TObject(Owners[0]);
    UnitCode:=Code;
    Result:=true;
  finally
    Owners.Free;
  end;
end;

function TCodeBrowserView.GetCurPackageInSrcEditor: TLazPackage;
var
  SrcEdit: TSourceEditorInterface;
  Owners: TFPList;
  i: Integer;
begin
  Result:=nil;
  SrcEdit:=SourceEditorManagerIntf.ActiveEditor;
  if SrcEdit=nil then exit;
  Owners:=PkgBoss.GetOwnersOfUnit(SrcEdit.FileName);
  try
    if (Owners=nil) then exit;
    for i:=0 to Owners.Count-1 do begin
      if TObject(Owners[i]) is TLazPackage then begin
        Result:=TLazPackage(Owners[i]);
        exit;
      end;
    end;
  finally
    Owners.Free;
  end;
end;

procedure TCodeBrowserView.OpenTVNode(TVNode: TTreeNode);
var
  NodeData: TObject;
  List: TCodeBrowserUnitList;
  APackage: TLazPackage;
  CurUnit: TCodeBrowserUnit;
  Node: TCodeBrowserNode;
  Line,Column: integer;
begin
  if (TVNode=nil) or (TVNode.Data=nil) then exit;
  NodeData:=TObject(TVNode.Data);
  if NodeData is TCodeBrowserUnitList then begin
    List:=TCodeBrowserUnitList(NodeData);
    DebugLn(['TCodeBrowserView.OpenSelected "',List.Owner,'=',CodeBrowserProjectName,'"']);
    if List.Owner=CodeBrowserProjectName then begin
      // open project inspector
      DebugLn(['TCodeBrowserView.OpenSelected open project inspector']);
      ExecuteIDECommand(Self,ecProjectInspector);
    end else if List.Owner=CodeBrowserIDEName then begin
      // open the IDE -> already open
    end else if List.Owner=CodeBrowserHidden then begin
      // nothing
    end else begin
      // open package
      APackage:=PackageGraph.FindAPackageWithName(List.Owner,nil);
      if APackage<>nil then begin
        PackageEditingInterface.DoOpenPackageWithName(List.Owner,[],false);
      end;
    end;
  end else if NodeData is TCodeBrowserUnit then begin
    CurUnit:=TCodeBrowserUnit(NodeData);
    if CurUnit.Filename<>'' then begin
      LazarusIDE.DoOpenEditorFile(CurUnit.Filename,-1,-1,[ofOnlyIfExists]);
    end;
  end else if NodeData is TCodeBrowserNode then begin
    Node:=TCodeBrowserNode(NodeData);
    if (Node.CodePos.Code<>nil)
    and (Node.CodePos.Code.Filename<>'') then begin
      Node.CodePos.Code.AbsoluteToLineCol(Node.CodePos.P,Line,Column);
      LazarusIDE.DoOpenFileAndJumpToPos(Node.CodePos.Code.Filename,
        Point(Column,Line),-1,-1,-1,[ofOnlyIfExists]);
    end;
  end;
end;

procedure TCodeBrowserView.BeginUpdate;
begin
  inc(fUpdateCount);
  BrowseTreeView.BeginUpdate;
end;

procedure TCodeBrowserView.EndUpdate;
begin
  dec(fUpdateCount);
  BrowseTreeView.EndUpdate;
end;

function TCodeBrowserView.ExportTree: TModalResult;
var
  SaveDialog: TSaveDialog;
begin
  SaveDialog:=TSaveDialog.Create(nil);
  try
    InitIDEFileDialog(SaveDialog);
    SaveDialog.Title:='Save tree as text (*.txt) ...';
    SaveDialog.FileName:='identifiers.txt';
    SaveDialog.DefaultExt:='txt';
    if not SaveDialog.Execute then exit(mrCancel);
    Result:=ExportTreeAsText(SaveDialog.FileName);
  finally
    StoreIDEFileDialog(SaveDialog);
    SaveDialog.Free;
  end;
end;

function TCodeBrowserView.ExportTreeAsText(Filename: String): TModalResult;

  procedure WriteNode(var List: TStrings; Node: TTreeNode; Prefix: String='');
  const
    CodeBrowserTypes: array[1..3] of TClass =
      (TCodeBrowserUnitList, TCodeBrowserUnit, TCodeBrowserNode);
    NodeIndent = '  ';
  var
    Child: TTreeNode;
    i: Integer;
  begin
    if Node=nil then exit;
    for i:=Low(CodeBrowserTypes) to High(CodeBrowserTypes) do begin
      if TObject(Node.Data) is CodeBrowserTypes[i] then begin
        List.Add(prefix+Node.Text);
        Prefix:=Prefix+NodeIndent;
        break;
      end;
    end;
    Child:=Node.GetFirstChild;
    while Child<>nil do begin
      WriteNode(List,Child,Prefix);
      Child:=Child.GetNextSibling;
    end;
  end;

var
  List: TStrings;
begin
  Filename:=CleanAndExpandFilename(Filename);
  Result:=CheckCreatingFile(Filename,true,true,true);
  if Result<>mrOk then exit;
  List:=TStringList.Create;
  try
    WriteNode(List,BrowseTreeView.Items.GetFirstNode);
    Result:=SaveStringToFile(Filename,List.Text,[],
      'exporting identifiers as text');
  finally
    List.Free;
  end;
end;

function TCodeBrowserView.GetScopeToCurUnitOwner(UseFCLAsDefault: boolean
  ): string;
var
  SrcEdit: TSourceEditorInterface;
  Code: TCodeBuffer;
  MainCode: TCodeBuffer;
  Owners: TFPList;
begin
  Result:='';
  if UseFCLAsDefault then
    Result:=PackageGraph.FCLPackage.Name;
  SrcEdit:=SourceEditorManagerIntf.ActiveEditor;
  if SrcEdit=nil then exit;
  Code:=TCodeBuffer(SrcEdit.CodeToolsBuffer);
  if Code=nil then exit;
  MainCode:=CodeToolBoss.GetMainCode(Code);
  if MainCode<>nil then
    Code:=MainCode;

  Owners:=PkgBoss.GetPossibleOwnersOfUnit(Code.FileName,[]);
  try
    if (Owners=nil) or (Owners.Count=0) then exit;
    if TObject(Owners[0])=Project1 then begin
      Result:=ProjectDescription;
      exit;
    end;
    if TObject(Owners[0]) is TLazPackage then begin
      Result:=TLazPackage(Owners[0]).Name;
      exit;
    end;
  finally
    Owners.Free;
  end;
end;

function TCodeBrowserView.SetScopeToCurUnitOwner(UseFCLAsDefault,
  WithRequiredPackages: boolean): boolean;
var
  NewScope: String;
  i: LongInt;
begin
  Result:=false;
  NewScope:=GetScopeToCurUnitOwner(UseFCLAsDefault);
  if NewScope='' then exit;
  FillScopeComboBox;
  ScopeComboBox.Text:=NewScope;
  i:=ScopeComboBox.Items.IndexOf(NewScope);
  if i>=0 then
    ScopeComboBox.ItemIndex:=i;
  ScopeWithRequiredPackagesCheckBox.Checked:=WithRequiredPackages;
  InvalidateStage(cbwsGetScopeOptions);
end;

procedure TCodeBrowserView.SetFilterToSimpleIdentifier(Identifier: string);
begin
  ShowPackagesCheckBox.Checked:=true;
  PackageFilterEdit.Text:='';
  PackageFilterContainsSpeedButton.Down:=true;

  ShowUnitsCheckBox.Checked:=true;
  UnitFilterEdit.Text:='';
  UnitFilterContainsSpeedButton.Down:=true;

  ShowIdentifiersCheckBox.Checked:=true;
  IdentifierFilterEdit.Text:=Identifier;
  IdentifierFilterBeginsSpeedButton.Down:=true;

  ShowEmptyNodesCheckBox.Checked:=false;

  InvalidateStage(cbwsGetViewOptions);
end;

procedure TCodeBrowserView.BrowseTreeViewShowHint(Sender: TObject;
  HintInfo: PHintInfo);
var
  TVNode: TTreeNode;
  HintStr: String;
  MousePos: TPoint;
  HintWinRect : TRect;
begin
  //DebugLn(['TCodeBrowserView.BrowseTreeViewShowHint ',dbgs(HintInfo^.CursorPos)]);
  HintStr:='';
  MousePos:=HintInfo^.CursorPos;
  TVNode:=BrowseTreeView.GetNodeAt(MousePos.X,MousePos.Y);
  if TVNode<>nil then begin
    HintStr:=GetTVNodeHint(TVNode);
    //DebugLn(['TCodeBrowserView.BrowseTreeViewShowHint HintStr="',HintStr,'"']);
  end;

  HintInfo^.HintStr:=''; // do not use the normal mechanism

  // open a THintWindow with LazarusHelp instead
  if hintstr = '' then
     exit;
  if csDestroying in ComponentState then exit;
  if FHintWindow <> nil then
    FHintWindow.Visible := false;
  if FHintWindow = nil then
    FHintWindow := THintWindow.Create(Self);
  if LazarusHelp.CreateHint(FHintWindow, HintInfo^.HintPos, '', HintStr, HintWinRect) then
      FHintWindow.ActivateHint(HintWinRect, HintStr);
end;

procedure TCodeBrowserView.CloseHintWindow;
begin
  if FHintWindow <> nil then begin
    FHintWindow.Close;
    FHintWindow := nil;
  end;
end;

procedure TCodeBrowserView.CollapseAllPackagesMenuItemClick(Sender: TObject);
begin
  ExpandCollapseAllNodesInTreeView(entPackage,false);
end;

procedure TCodeBrowserView.CollapseAllUnitsMenuItemClick(Sender: TObject);
begin
  ExpandCollapseAllNodesInTreeView(entUnit,false);
end;

procedure TCodeBrowserView.CollapseAllClassesMenuItemClick(Sender: TObject);
begin
  ExpandCollapseAllNodesInTreeView(entClass,false);
end;

procedure TCodeBrowserView.CopyDescriptionMenuItemClick(Sender: TObject);
begin
  CopyNode(BrowseTreeView.Selected,cntDescription);
end;

procedure TCodeBrowserView.CopyIdentifierMenuItemClick(Sender: TObject);
begin
  CopyNode(BrowseTreeView.Selected,cntIdentifier);
end;

procedure TCodeBrowserView.ExpandAllClassesMenuItemClick(Sender: TObject);
begin
  ExpandCollapseAllNodesInTreeView(entClass,true);
end;

procedure TCodeBrowserView.ExpandAllPackagesMenuItemClick(Sender: TObject);
begin
  ExpandCollapseAllNodesInTreeView(entPackage,true);
end;

procedure TCodeBrowserView.ExpandAllUnitsMenuItemClick(Sender: TObject);
begin
  ExpandCollapseAllNodesInTreeView(entUnit,true);
end;

procedure TCodeBrowserView.ExportMenuItemClick(Sender: TObject);
begin
  ExportTree;
end;

procedure TCodeBrowserView.BrowseTreeViewMouseDown(Sender: TOBject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  if ssDouble in Shift then
    OpenTVNode(BrowseTreeView.GetNodeAt(X,Y));
end;

procedure TCodeBrowserView.UsePkgInProjectMenuItemClick(Sender: TObject);
var
  APackage: TLazPackage;
begin
  APackage:=GetSelectedPackage;
  if APackage=nil then exit;
  PkgBoss.AddProjectDependency(Project1,APackage);
end;

procedure TCodeBrowserView.UseUnitInCurUnitMenuItemClick(Sender: TObject);
begin
  UseUnitInSrcEditor(false);
end;

procedure TCodeBrowserView.UsePkgInCurUnitMenuItemClick(Sender: TObject);
var
  APackage: TLazPackage;
  TargetPackage: TLazPackage;
  List: TFPList;
begin
  APackage:=GetSelectedPackage;
  if APackage=nil then exit;
  TargetPackage:=GetCurPackageInSrcEditor;
  if TargetPackage=nil then exit;
  List:=TFPList.Create;
  try
    List.Add(TargetPackage);
    if PkgBoss.AddDependencyToOwners(List,APackage)=mrOk then begin
      PackageEditingInterface.DoOpenPackageWithName(TargetPackage.Name,[],false);
    end;
  finally
    List.Free;
  end;
end;

procedure TCodeBrowserView.UseIdentifierInCurUnitMenuItemClick(Sender: TObject);
begin
  UseUnitInSrcEditor(true);
end;

procedure TCodeBrowserView.BrowseTreeViewMouseMove(Sender: TObject;
  Shift: TShiftState; X, Y: Integer);
begin
  CloseHintWindow;
end;

procedure TCodeBrowserView.FormDeactivate(Sender: TObject);
begin
  CloseHintWindow;
end;

{ TCodeBrowserViewOptions }

procedure TCodeBrowserViewOptions.SetModified(const AValue: boolean);
begin
  if AValue then
    IncreaseChangeStamp;
  if FModified=AValue then exit;
  FModified:=AValue;
end;

function TCodeBrowserViewOptions.GetLevelFilterText(Level: TCodeBrowserLevel
  ): string;
begin
  Result:=FLevelFilterText[Level];
end;

function TCodeBrowserViewOptions.GetLevelFilterType(Level: TCodeBrowserLevel
  ): TCodeBrowserTextFilter;
begin
  Result:=FLevelFilterType[Level];
end;

procedure TCodeBrowserViewOptions.SetLevelFilterText(Level: TCodeBrowserLevel;
  const AValue: string);
begin
  if FLevelFilterText[Level]=AValue then exit;
  FLevelFilterText[Level]:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetLevelFilterType(Level: TCodeBrowserLevel;
  const AValue: TCodeBrowserTextFilter);
begin
  if FLevelFilterType[Level]=AValue then exit;
  FLevelFilterType[Level]:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetScope(const AValue: string);
begin
  if FScope=AValue then exit;
  FScope:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetLevels(const AValue: TStrings);
begin
  if FLevels=AValue then exit;
  if FLevels.Text=AValue.Text then exit;
  FLevels.Assign(AValue);
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetShowEmptyNodes(const AValue: boolean);
begin
  if FShowEmptyNodes=AValue then exit;
  FShowEmptyNodes:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetShowPrivate(const AValue: boolean);
begin
  if FShowPrivate=AValue then exit;
  FShowPrivate:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetShowProtected(const AValue: boolean);
begin
  if FShowProtected=AValue then exit;
  FShowProtected:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.SetStoreWithRequiredPackages(
  const AValue: boolean);
begin
  if FStoreWithRequiredPackages=AValue then exit;
  FStoreWithRequiredPackages:=AValue;
end;

procedure TCodeBrowserViewOptions.SetWithRequiredPackages(const AValue: boolean
  );
begin
  if FWithRequiredPackages=AValue then exit;
  FWithRequiredPackages:=AValue;
  Modified:=true;
end;

procedure TCodeBrowserViewOptions.IncreaseChangeStamp;
begin
  CTIncreaseChangeStamp(FChangeStamp);
end;

constructor TCodeBrowserViewOptions.Create;
begin
  FLevels:=TStringList.Create;
  FChangeStamp:=CTInvalidChangeStamp;
  Clear;
end;

destructor TCodeBrowserViewOptions.Destroy;
begin
  FreeAndNil(FLevels);
  inherited Destroy;
end;

procedure TCodeBrowserViewOptions.Clear;
var
  l: TCodeBrowserLevel;
begin
  FLevels.Clear;
  FLevels.Text:=CodeBrowserLevelNames[cblPackages]+#13
               +CodeBrowserLevelNames[cblUnits]+#13
               +CodeBrowserLevelNames[cblIdentifiers];
  WithRequiredPackages:=false;
  ShowPrivate:=false;
  ShowProtected:=true;
  Scope:='Project';
  for l:=Low(TCodeBrowserLevel) to High(TCodeBrowserLevel) do begin
    FLevelFilterType[l]:=cbtfContains;
    FLevelFilterText[l]:='';
  end;
  IncreaseChangeStamp;
  Modified:=false;
end;

procedure TCodeBrowserViewOptions.LoadFromConfig(ConfigStore: TConfigStorage;
  const Path: string);
var
  l: TCodeBrowserLevel;
  SubPath: String;
begin
  Clear;
  WithRequiredPackages:=
                  ConfigStore.GetValue(Path+'WithRequiredPackages/Value',false);
  Scope:=ConfigStore.GetValue(Path+'Scope/Value','Project');
  ShowPrivate:=ConfigStore.GetValue(Path+'ShowPrivate/Value',false);
  ShowProtected:=ConfigStore.GetValue(Path+'ShowProtected/Value',true);
  ShowEmptyNodes:=ConfigStore.GetValue(Path+'ShowEmptyNodes/Value',true);
  ConfigStore.GetValue(Path+'Levels/',FLevels);
  for l:=Low(TCodeBrowserLevel) to High(TCodeBrowserLevel) do begin
    SubPath:=Path+'LevelFilter/'+CodeBrowserLevelNames[l];
    FLevelFilterType[l]:=StringToCodeBrowserTextFilter(
      ConfigStore.GetValue(SubPath+'/Type',''));
    FLevelFilterText[l]:=ConfigStore.GetValue(SubPath+'/Text','');
  end;
  Modified:=false;
end;

procedure TCodeBrowserViewOptions.SaveToConfig(ConfigStore: TConfigStorage;
  const Path: string);
var
  l: TCodeBrowserLevel;
  SubPath: String;
  b: Boolean;
begin
  b:=WithRequiredPackages;
  if not StoreWithRequiredPackages then
    b:=false;
  ConfigStore.SetDeleteValue(Path+'WithRequiredPackages/Value',b,false);
  ConfigStore.SetDeleteValue(Path+'Scope/Value',Scope,'Project');
  ConfigStore.SetDeleteValue(Path+'ShowPrivate/Value',ShowPrivate,false);
  ConfigStore.SetDeleteValue(Path+'ShowProtected/Value',ShowProtected,true);
  ConfigStore.SetDeleteValue(Path+'ShowEmptyNodes/Value',ShowEmptyNodes,true);
  ConfigStore.SetValue(Path+'Levels/',FLevels);
  for l:=Low(TCodeBrowserLevel) to High(TCodeBrowserLevel) do begin
    SubPath:=Path+'LevelFilter/'+CodeBrowserLevelNames[l];
    ConfigStore.SetDeleteValue(SubPath+'/Type',
      CodeBrowserTextFilterNames[FLevelFilterType[l]],
      CodeBrowserTextFilterNames[cbtfBegins]);
    ConfigStore.SetDeleteValue(SubPath+'/Text',FLevelFilterText[l],'');
  end;
  Modified:=false;
end;

function TCodeBrowserViewOptions.HasLevel(Level: TCodeBrowserLevel): boolean;
begin
  Result:=Levels.IndexOf(CodeBrowserLevelNames[Level])>=0;
end;

{ TQuickFixIdentifierNotFound_Search }

constructor TQuickFixIdentifierNotFound_Search.Create;
begin
  Name:='Search identifier: Error: Identifier not found "identifier"';
  Caption:=lisQuickFixSearchIdentifier;
  Steps:=[imqfoMenuItem];
end;

function TQuickFixIdentifierNotFound_Search.IsApplicable(Line: TIDEMessageLine
  ): boolean;
const
  SearchStr = ') Error: Identifier not found "';
var
  Msg: String;
  p: integer;
  Code: TCodeBuffer;
  Filename: string;
  Caret: TPoint;
begin
  Result:=false;
  if (Line.Parts=nil) then exit;
  Msg:=Line.Msg;
  p:=System.Pos(SearchStr,Msg);
  if p<1 then exit;
  inc(p,length(SearchStr));
  Line.GetSourcePosition(Filename,Caret.Y,Caret.X);
  if (Filename='') or (Caret.X<1) or (Caret.Y<1) then exit;
  Code:=CodeToolBoss.LoadFile(Filename,true,false);
  if Code=nil then exit;
  Result:=true;
end;

procedure TQuickFixIdentifierNotFound_Search.Execute(
  const Msg: TIDEMessageLine; Step: TIMQuickFixStep);
var
  Identifier: String;
  CodeBuf: TCodeBuffer;
  Filename: string;
  Caret: TPoint;
begin
  if Step=imqfoMenuItem then begin
    DebugLn(['TQuickFixIdentifierNotFound_Search.Execute Dir=',Msg.Directory,' Msg=',Msg.Msg,' Filename=',Msg.Parts.Values['Filename']]);
    // get source position
    // (FPC reports position right after the unknown identifier
    //  for example right after FilenameIsAbsolute)
    if not GetMsgLineFilename(Msg,CodeBuf,false) then exit;
    Msg.GetSourcePosition(Filename,Caret.Y,Caret.X);
    if not LazarusIDE.BeginCodeTools then begin
      DebugLn(['TQuickFixIdentifierNotFound_Search.Execute failed because IDE busy']);
      exit;
    end;

    // get identifier
    if not REMatches(Msg.Msg,'Error: Identifier not found "([a-z_0-9]+)"','I') then begin
      DebugLn('TQuickFixIdentifierNotFound_Search invalid message ',Msg.Msg);
      exit;
    end;
    Identifier:=REVar(1);
    DebugLn(['TQuickFixIdentifierNotFound_Search.Execute Identifier=',Identifier]);

    if (Identifier='') or (not IsValidIdent(Identifier)) then begin
      DebugLn(['TQuickFixIdentifierNotFound_Search.Execute not an identifier "',dbgstr(Identifier),'"']);
      exit;
    end;

    if LazarusIDE.DoOpenFileAndJumpToPos(Filename,Caret,-1,-1,-1,OpnFlagsPlainFile
      )<>mrOk
    then exit;

    // start code browser
    CreateCodeBrowser;
    CodeBrowserView.SetScopeToCurUnitOwner(true,true);
    CodeBrowserView.SetFilterToSimpleIdentifier(Identifier);
    IDEWindowCreators.ShowForm(CodeBrowserView,true);
  end;
end;

end.