File: unitdependencies.pas

package info (click to toggle)
lazarus 2.0.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 214,460 kB
  • sloc: pascal: 1,862,622; xml: 265,709; cpp: 56,595; sh: 3,008; java: 609; makefile: 535; perl: 297; sql: 222; ansic: 137
file content (2299 lines) | stat: -rw-r--r-- 71,068 bytes parent folder | download | duplicates (2)
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
{
***************************************************************************
*                                                                         *
*   This source is free software; you can redistribute it and/or modify   *
*   it under the terms of the GNU General Public License as published by  *
*   the Free Software Foundation; either version 2 of the License, or     *
*   (at your option) any later version.                                   *
*                                                                         *
*   This code is distributed in the hope that it will be useful, but      *
*   WITHOUT ANY WARRANTY; without even the implied warranty of            *
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
*   General Public License for more details.                              *
*                                                                         *
*   A copy of the GNU General Public License is available on the World    *
*   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
*   obtain it by writing to the Free Software Foundation,                 *
*   Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.   *
*                                                                         *
***************************************************************************

  Author: Mattias Gaertner

  Abstract:
    IDE Window showing dependencies of units and packages.

  ToDo:
    - show unit selected in TV on units graph
}
unit UnitDependencies;

{$mode objfpc}{$H+}

{$I ide.inc}

interface

uses
  // RTL + FCL
  Classes, SysUtils, types, math, Laz_AVL_Tree,
  // LCL
  Forms, Controls, ExtCtrls, ComCtrls, StdCtrls, Buttons, Dialogs, Menus, Clipbrd,
  // CodeTools
  CodeToolManager, DefineTemplates, CTUnitGraph, CTUnitGroupGraph,
  FileProcs, CodeCache, AvgLvlTree,
  // LazUtils
  LazLoggerBase, LazFileUtils, LazFileCache, LazStringUtils, LazUTF8, LvlGraphCtrl,
  // IDE interface
  LazIDEIntf, ProjectIntf, IDEWindowIntf, PackageIntf, SrcEditorIntf, IDEImagesIntf,
  IDEMsgIntf, IDEExternToolIntf, IDECommands, IDEDialogs,
  // IDE
  IDEOptionDefs, LazarusIDEStrConsts, UnusedUnitsDlg;

const
  GroupPrefixProject = '-Project-';
  GroupPrefixFPCSrc = 'FPC:';
  GroupNone = '-None-';
type

  { TUDSCCNode }

  TUDSCCNode = class
  public
    UDItem: TObject; // a TUDUnit or TUDUses
    InIntfCycle: boolean;
    InImplCycle: boolean;
    TarjanIndex: integer;
    TarjanLowLink: integer;
    TarjanVisiting: boolean; // currently on stack
    function AsString: string;
    constructor Create(Item: TObject);
  end;

  { TUDUnit }

  TUDUnit = class(TUGGroupUnit)
  public
    SCCNode: TUDSCCNode;
    function GetSCCNode: TUDSCCNode;
    function HasImplementationUses: boolean;
    destructor Destroy; override;
  end;

  { TUDUses }

  TUDUses = class(TUGUses)
  public
    SCCNode: TUDSCCNode;
    function GetSCCNode: TUDSCCNode;
    destructor Destroy; override;
  end;

  TUDNodeType = (
    udnNone,
    udnGroup,
    udnDirectory,
    udnInterface,
    udnImplementation,
    udnUsedByInterface,
    udnUsedByImplementation,
    udnUnit
    );
  TUDNodeTypes = set of TUDNodeType;

  { TUDBaseNode }

  TUDBaseNode = class
  public
    TVNode: TTreeNode;
    NodeText: string;
    Typ: TUDNodeType;
    Identifier: string; // GroupName, Directory, Filename
    Group: string;
    HasChildren: boolean;
    IntfCycle: boolean;
    ImplCycle: boolean;
    HasImplementationUses: boolean;
  end;

  { TUDNode }

  TUDNode = class(TUDBaseNode)
  public
    Parent: TUDNode;
    ChildNodes: TAVLTree; // tree of TUDNode sorted for Typ and NodeText
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    function GetNode(aTyp: TUDNodeType; const ANodeText: string;
      CreateIfNotExists: boolean = false): TUDNode;
    function FindFirst(aTyp: TUDNodeType): TUDNode;
    function FindUnit(const aUnitName: string): TUDNode;
    function Count: integer;
  end;

  TUDWFlag = (
    udwParsing,
    udwNeedUpdateGroupsLvlGraph, // rebuild GroupsLvlGraph
    udwNeedUpdateUnitsLvlGraph, // rebuild UnitsLvlGraph
    udwNeedUpdateAllUnitsTreeView, // rebuild AllUnitsTreeView
    udwNeedUpdateAllUnitsTVSearch, // update search in AllUnitsTreeView
    udwNeedUpdateSelUnitsTreeView, // rebuild SelUnitsTreeView
    udwNeedUpdateSelUnitsTVSearch // update search in SelUnitsTreeView
    );
  TUDWFlags = set of TUDWFlag;

  { TUnitDependenciesWindow }

  TUnitDependenciesWindow = class(TForm)
    AllUnitsFilterEdit: TEdit;
    AllUnitsSearchEdit: TEdit;
    AllUnitsSearchNextSpeedButton: TSpeedButton;
    AllUnitsSearchPrevSpeedButton: TSpeedButton;
    AllUnitsGroupBox: TGroupBox;
    AllUnitsShowDirsSpeedButton: TSpeedButton;
    AllUnitsShowGroupNodesSpeedButton: TSpeedButton;
    AllUnitsTreeView: TTreeView; // Node.Data is TUDNode
    MainPageControl: TPageControl;
    UnitsTVOpenFileMenuItem: TMenuItem;
    RefreshButton: TButton;
    StatsLabel: TLabel;
    StatusPanel: TPanel;
    Timer1: TTimer;
    UnitsTVUnusedUnitsMenuItem: TMenuItem;
    UnitsTVCopyFilenameMenuItem: TMenuItem;
    UnitsTVCollapseAllMenuItem: TMenuItem;
    UnitsTVExpandAllMenuItem: TMenuItem;
    ProgressBar1: TProgressBar;
    GroupsTabSheet: TTabSheet;
    GroupsSplitter: TSplitter;
    SearchPkgsCheckBox: TCheckBox;
    SearchSrcEditCheckBox: TCheckBox;
    SelectedUnitsGroupBox: TGroupBox;
    SelUnitsSearchEdit: TEdit;
    SelUnitsSearchNextSpeedButton: TSpeedButton;
    SelUnitsSearchPrevSpeedButton: TSpeedButton;
    SelUnitsTreeView: TTreeView;
    SearchCustomFilesBrowseButton: TButton;
    SearchCustomFilesCheckBox: TCheckBox;
    ScopePanel: TPanel;
    SearchCustomFilesComboBox: TComboBox;
    UnitsSplitter: TSplitter;
    UnitsTabSheet: TTabSheet;
    UnitsTVPopupMenu: TPopupMenu;
    procedure AllUnitsFilterEditChange(Sender: TObject);
    procedure AllUnitsSearchEditChange(Sender: TObject);
    procedure AllUnitsSearchNextSpeedButtonClick(Sender: TObject);
    procedure AllUnitsSearchPrevSpeedButtonClick(Sender: TObject);
    procedure AllUnitsShowDirsSpeedButtonClick(Sender: TObject);
    procedure AllUnitsShowGroupNodesSpeedButtonClick(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure RefreshButtonClick(Sender: TObject);
    procedure SelUnitsTreeViewExpanding(Sender: TObject; Node: TTreeNode;
      var AllowExpansion: Boolean);
    procedure Timer1Timer(Sender: TObject);
    procedure UnitsLvlGraphMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure UnitsLvlGraphSelectionChanged(Sender: TObject);
    procedure UnitsTreeViewShowHint(Sender: TObject; HintInfo: PHintInfo);
    procedure UnitsTreeViewMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure AllUnitsTreeViewSelectionChanged(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure GroupsLvlGraphSelectionChanged(Sender: TObject);
    procedure OnIdle(Sender: TObject; var {%H-}Done: Boolean);
    procedure SearchPkgsCheckBoxChange(Sender: TObject);
    procedure SearchSrcEditCheckBoxChange(Sender: TObject);
    procedure SelUnitsSearchEditChange(Sender: TObject);
    procedure SelUnitsSearchNextSpeedButtonClick(Sender: TObject);
    procedure SelUnitsSearchPrevSpeedButtonClick(Sender: TObject);
    procedure SearchCustomFilesBrowseButtonClick(Sender: TObject);
    procedure SearchCustomFilesCheckBoxChange(Sender: TObject);
    procedure SearchCustomFilesComboBoxChange(Sender: TObject);
    procedure UnitsTVCollapseAllMenuItemClick(Sender: TObject);
    procedure UnitsTVCopyFilenameMenuItemClick(Sender: TObject);
    procedure UnitsTVExpandAllMenuItemClick(Sender: TObject);
    procedure UnitsTVOpenFileMenuItemClick(Sender: TObject);
    procedure UnitsTVPopupMenuPopup(Sender: TObject);
    procedure UnitsTVUnusedUnitsMenuItemClick(Sender: TObject);
  private
    FCurrentUnit: TUGUnit;
    FIdleConnected: boolean;
    FPendingUnitDependencyRoute: TStrings;
    FUsesGraph: TUsesGraph;
    FGroups: TUGGroups; // referenced by Nodes.Data of GroupsLvlGraph
    FNewUsesGraph: TUsesGraph; // on idle the units are scanned and this graph
      // is filled up, when parsing is complete it becomes the new UsesGraph
    FNewGroups: TUGGroups;
    FAllUnitsRootUDNode: TUDNode;
    FSelUnitsRootUDNode: TUDNode;
    FFlags: TUDWFlags;
    fImgIndexProject: integer;
    fImgIndexUnit: integer;
    fImgIndexPackage: integer;
    fImgIndexDirectory: integer;
    fImgIndexOverlayImplUses: integer;
    fImgIndexOverlayIntfCycle: integer;
    fImgIndexOverlayImplCycle: integer;
    fAllUnitsTVSearchStartNode: TTreeNode;
    fSelUnitsTVSearchStartNode: TTreeNode;
    function CreateAllUnitsTree: TUDNode;
    function CreateSelUnitsTree: TUDNode;
    procedure ExpandPendingUnitDependencyRoute(RootNode: TUDNode);
    procedure ConvertUnitNameRouteToPath(Route: TStrings); // inserts missing links
    procedure AddUsesSubNodes(UDNode: TUDNode);
    procedure CreateTVNodes(TV: TTreeView;
      ParentTVNode: TTreeNode; ParentUDNode: TUDNode; Expand: boolean);
    procedure FreeUsesGraph;
    function GetPopupTV_UDNode(out UDNode: TUDNode): boolean;
    procedure SelectNextSearchTV(TV: TTreeView; StartTVNode: TTreeNode;
      SearchNext, SkipStart: boolean);
    function FindNextTVNode(StartNode: TTreeNode;
      LowerSearch: string; SearchNext, SkipStart: boolean): TTreeNode;
    function FindUnitTVNodeWithFilename(TV: TTreeView; aFilename: string): TTreeNode;
    function FindUnitTVNodeWithUnitName(TV: TTreeView; aUnitName: string): TTreeNode;
    procedure SetCurrentUnit(AValue: TUGUnit);
    procedure SetIdleConnected(AValue: boolean);
    procedure CreateGroups;
    function CreateProjectGroup(AProject: TLazProject): TUGGroup;
    function CreatePackageGroup(APackage: TIDEPackage): TUGGroup;
    procedure CreateFPCSrcGroups;
    procedure GuessGroupOfUnits;
    procedure MarkCycles(WithImplementationUses: boolean);
    procedure SetPendingUnitDependencyRoute(AValue: TStrings);
    procedure StartParsing;
    procedure ScopeChanged;
    procedure AddStartAndTargetUnits;
    procedure AddAdditionalFilesAsStartUnits;
    procedure SetupGroupsTabSheet;
    procedure SetupUnitsTabSheet;
    procedure UpdateUnitsButtons;
    procedure UpdateAll;
    procedure UpdateGroupsLvlGraph;
    procedure UpdateUnitsLvlGraph;
    procedure UpdateAllUnitsTreeView;
    procedure UpdateSelUnitsTreeView;
    procedure UpdateAllUnitsTreeViewSearch;
    procedure UpdateSelUnitsTreeViewSearch;
    function GetImgIndex(Node: TUDNode): integer;
    function NodeTextToUnit(NodeText: string): TUGUnit;
    function UGUnitToNodeText(UGUnit: TUGUnit): string;
    function GetFPCSrcDir: string;
    function IsFPCSrcGroup(Group: TUGGroup): boolean;
    function IsProjectGroup(Group: TUGGroup): boolean;
    function IsProjectGroup(GroupName: string): boolean;
    function GetFilename(UDNode: TUDNode): string;
    function GetAllUnitsFilter(Lower: boolean): string;
    function GetAllUnitsSearch(Lower: boolean): string;
    function GetSelUnitsSearch(Lower: boolean): string;
    function ResStrFilter: string;
    function ResStrSearch: string;
    function NodeTextFitsFilter(const NodeText, LowerFilter: string): boolean;
    procedure CreateUsesGraph(out TheUsesGraph: TUsesGraph; out TheGroups: TUGGroups);
  public
    GroupsLvlGraph: TLvlGraphControl; // Nodes.Data are TUGGroup of Groups
    UnitsLvlGraph: TLvlGraphControl; // Nodes.Data are Units in Groups
  public
    property IdleConnected: boolean read FIdleConnected write SetIdleConnected;
    property UsesGraph: TUsesGraph read FUsesGraph;
    property Groups: TUGGroups read FGroups;
    property CurrentUnit: TUGUnit read FCurrentUnit write SetCurrentUnit;
    property PendingUnitDependencyRoute: TStrings read FPendingUnitDependencyRoute
      write SetPendingUnitDependencyRoute; // list of unit names, missing links are automatically found
  end;

type

  { TQuickFixCircularUnitReference }

  TQuickFixCircularUnitReference = class(TMsgQuickFix)
  public
    function IsApplicable(Msg: TMessageLine; out Unitname1, Unitname2: string): boolean;
    procedure CreateMenuItems(Fixes: TMsgQuickFixes); override;
    procedure QuickFix({%H-}Fixes: TMsgQuickFixes; Msg: TMessageLine); override;
  end;

var
  UnitDependenciesWindow: TUnitDependenciesWindow;

procedure ShowUnitDependenciesClicked(Sender: TObject);
procedure ShowUnitDependencies(State: TIWGetFormState = iwgfShowOnTop);
procedure InitUnitDependenciesQuickFixItems;

function CompareUDBaseNodes(UDNode1, UDNode2: Pointer): integer;

implementation

{$R *.lfm}

procedure ShowUnitDependenciesClicked(Sender: TObject);
begin
  ShowUnitDependencies;
end;

procedure ShowUnitDependencies(State: TIWGetFormState);
begin
  if UnitDependenciesWindow = Nil then
    IDEWindowCreators.CreateForm(UnitDependenciesWindow,TUnitDependenciesWindow,
       State=iwgfDisabled,LazarusIDE.OwningComponent)
  else if State=iwgfDisabled then
    UnitDependenciesWindow.DisableAlign;
  if State>=iwgfShow then
    IDEWindowCreators.ShowForm(UnitDependenciesWindow,State=iwgfShowOnTop);
end;

procedure InitUnitDependenciesQuickFixItems;
begin
  RegisterIDEMsgQuickFix(TQuickFixCircularUnitReference.Create);
end;

function CompareUDBaseNodes(UDNode1, UDNode2: Pointer): integer;
var
  Node1: TUDBaseNode absolute UDNode1;
  Node2: TUDBaseNode absolute UDNode2;
begin
  Result:=ord(Node1.Typ)-ord(Node2.Typ);
  if Result<>0 then exit;
  case Node1.Typ of
  udnDirectory: Result:=CompareFilenames(Node1.NodeText,Node2.NodeText);
  else Result:=SysUtils.CompareText(Node1.NodeText,Node2.NodeText);
  end;
end;

{ TUDSCCNode }

function TUDSCCNode.AsString: string;
begin
  if UDItem is TUDUnit then
    Result:='Unit="'+ExtractFileNameOnly(TUDUnit(UDItem).Filename)+'"'
  else
    Result:='Uses="'+ExtractFileNameOnly(TUDUses(UDItem).Owner.Filename)+'"->"'+ExtractFileNameOnly(TUDUses(UDItem).UsesUnit.Filename)+'"';
  Result+=',Index='+dbgs(TarjanIndex)+',LowLink='+dbgs(TarjanLowLink)+',Visiting='+dbgs(TarjanVisiting);
end;

constructor TUDSCCNode.Create(Item: TObject);
begin
  UDItem:=Item;
  TarjanIndex:=-1;
end;

{ TUDUses }

function TUDUses.GetSCCNode: TUDSCCNode;
begin
  if SCCNode=nil then
    SCCNode:=TUDSCCNode.Create(Self);
  Result:=SCCNode;
end;

destructor TUDUses.Destroy;
begin
  FreeAndNil(SCCNode);
  inherited Destroy;
end;

{ TUDUnit }

function TUDUnit.GetSCCNode: TUDSCCNode;
begin
  if SCCNode=nil then
    SCCNode:=TUDSCCNode.Create(Self);
  Result:=SCCNode;
end;

function TUDUnit.HasImplementationUses: boolean;
var
  i: Integer;
begin
  Result:=false;
  if UsesUnits=nil then exit;
  for i:=0 to UsesUnits.Count-1 do
    if TUDUses(UsesUnits[i]).InImplementation then
      exit(true);
end;

destructor TUDUnit.Destroy;
begin
  FreeAndNil(SCCNode);
  inherited Destroy;
end;

{ TQuickFixCircularUnitReference }

function TQuickFixCircularUnitReference.IsApplicable(Msg: TMessageLine; out
  Unitname1, Unitname2: string): boolean;
begin
  Result:=IDEFPCParser.MsgLineIsId(Msg,10020,Unitname1,Unitname2);
end;

procedure TQuickFixCircularUnitReference.CreateMenuItems(Fixes: TMsgQuickFixes);
var
  Msg: TMessageLine;
  Unitname1: string;
  Unitname2: string;
  i: Integer;
begin
  for i:=0 to Fixes.LineCount-1 do begin
    Msg:=Fixes.Lines[i];
    if not IsApplicable(Msg,Unitname1,Unitname2) then continue;
    Fixes.AddMenuItem(Self,Msg,'Show unit dependencies');
    exit;
  end;
end;

procedure TQuickFixCircularUnitReference.QuickFix(Fixes: TMsgQuickFixes;
  Msg: TMessageLine);
var
  UnitName1: String;
  UnitName2: String;
  Path: TStringList;
begin
  if not IsApplicable(Msg,UnitName1,UnitName2) then exit;
  ShowUnitDependencies;
  Path:=TStringList.Create;
  try
    Path.Add(UnitName1);
    Path.Add(UnitName2);
    Path.Add(UnitName1);
    UnitDependenciesWindow.PendingUnitDependencyRoute:=Path;
  finally
    Path.Free;
  end;
end;

{ TUDNode }

constructor TUDNode.Create;
begin
  ChildNodes:=TAVLTree.Create(@CompareUDBaseNodes);
end;

destructor TUDNode.Destroy;
begin
  Clear;
  FreeAndNil(ChildNodes);
  inherited Destroy;
end;

procedure TUDNode.Clear;
begin
  ChildNodes.FreeAndClear;
end;

function TUDNode.GetNode(aTyp: TUDNodeType; const ANodeText: string;
  CreateIfNotExists: boolean): TUDNode;
var
  Node: TUDBaseNode;
  AVLNode: TAVLTreeNode;
begin
  Node:=TUDBaseNode.Create;
  Node.Typ:=aTyp;
  Node.NodeText:=ANodeText;
  AVLNode:=ChildNodes.Find(Node);
  Node.Free;
  if AVLNode<>nil then begin
    Result:=TUDNode(AVLNode.Data);
  end else if CreateIfNotExists then begin
    Result:=TUDNode.Create;
    Result.Typ:=aTyp;
    Result.NodeText:=ANodeText;
    ChildNodes.Add(Result);
    Result.Parent:=Self;
  end else
    Result:=nil;
end;

function TUDNode.FindFirst(aTyp: TUDNodeType): TUDNode;
var
  AVLNode: TAVLTreeNode;
begin
  AVLNode:=ChildNodes.FindLowest;
  while AVLNode<>nil do begin
    Result:=TUDNode(AVLNode.Data);
    if Result.Typ=aTyp then exit;
    AVLNode:=ChildNodes.FindSuccessor(AVLNode);
  end;
  Result:=nil;
end;

function TUDNode.FindUnit(const aUnitName: string): TUDNode;
var
  AVLNode: TAVLTreeNode;
begin
  AVLNode:=ChildNodes.FindLowest;
  while AVLNode<>nil do begin
    Result:=TUDNode(AVLNode.Data);
    if (Result.Typ=udnUnit)
    and (CompareText(ExtractFileNameOnly(Result.Identifier),aUnitName)=0) then
      exit;
    AVLNode:=ChildNodes.FindSuccessor(AVLNode);
  end;
  Result:=nil;
end;

function TUDNode.Count: integer;
begin
  Result:=ChildNodes.Count;
end;

{ TUnitDependenciesWindow }

procedure TUnitDependenciesWindow.FormCreate(Sender: TObject);
begin
  Name := NonModalIDEWindowNames[nmiwUnitDependenciesName];

  FPendingUnitDependencyRoute:=TStringList.Create;
  CreateUsesGraph(FUsesGraph,FGroups);

  fImgIndexProject   := IDEImages.LoadImage('item_project');
  fImgIndexUnit      := IDEImages.LoadImage('item_unit');
  fImgIndexPackage   := IDEImages.LoadImage('pkg_required');
  fImgIndexDirectory := IDEImages.LoadImage('pkg_files');
  fImgIndexOverlayImplUses := IDEImages.LoadImage('pkg_core_overlay');
  fImgIndexOverlayIntfCycle := IDEImages.LoadImage('ce_cycleinterface');
  fImgIndexOverlayImplCycle := IDEImages.LoadImage('ce_cycleimplementation');
  AllUnitsTreeView.Images:=IDEImages.Images_16;
  SelUnitsTreeView.Images:=IDEImages.Images_16;

  Caption:=lisMenuViewUnitDependencies;
  RefreshButton.Caption:=dlgUnitDepRefresh;

  MainPageControl.ActivePage:=UnitsTabSheet;

  SetupUnitsTabSheet;
  SetupGroupsTabSheet;

  StartParsing;
end;

procedure TUnitDependenciesWindow.AllUnitsSearchEditChange(Sender: TObject);
begin
  Include(FFlags,udwNeedUpdateAllUnitsTVSearch);
  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.AllUnitsSearchNextSpeedButtonClick(Sender: TObject);
begin
  SelectNextSearchTV(AllUnitsTreeView,AllUnitsTreeView.Selected,true,true);
  fAllUnitsTVSearchStartNode:=AllUnitsTreeView.Selected;
end;

procedure TUnitDependenciesWindow.AllUnitsSearchPrevSpeedButtonClick(Sender: TObject);
begin
  SelectNextSearchTV(AllUnitsTreeView,AllUnitsTreeView.Selected,false,true);
  fAllUnitsTVSearchStartNode:=AllUnitsTreeView.Selected;
end;

procedure TUnitDependenciesWindow.AllUnitsShowDirsSpeedButtonClick(Sender: TObject);
begin
  Include(FFlags,udwNeedUpdateAllUnitsTreeView);
  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.AllUnitsShowGroupNodesSpeedButtonClick(Sender: TObject);
begin
  Include(FFlags,udwNeedUpdateAllUnitsTreeView);
  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.FormShow(Sender: TObject);
begin
  AllUnitsFilterEdit.TextHint:=ResStrFilter;
  AllUnitsSearchEdit.TextHint:=ResStrSearch;
  SelUnitsSearchEdit.TextHint:=ResStrSearch;
end;

procedure TUnitDependenciesWindow.RefreshButtonClick(Sender: TObject);
begin
  if udwParsing in FFlags then exit;
  StartParsing;
end;

procedure TUnitDependenciesWindow.SelUnitsTreeViewExpanding(Sender: TObject;
  Node: TTreeNode; var AllowExpansion: Boolean);
var
  UDNode: TUDNode;
begin
  if Node.Count>0 then exit;
  if not (TObject(Node.Data) is TUDNode) then exit;
  UDNode:=TUDNode(Node.Data);
  if UDNode.Typ=udnUnit then begin
    AddUsesSubNodes(UDNode);
    CreateTVNodes(SelUnitsTreeView,Node,UDNode,false);
    AllowExpansion:=true;
  end;
end;

procedure TUnitDependenciesWindow.Timer1Timer(Sender: TObject);
var
  Cnt: Integer;
begin
  if (FNewUsesGraph=nil) then exit;
  Cnt:=0;
  if FNewUsesGraph.FilesTree<>nil then
    Cnt:=FNewUsesGraph.FilesTree.Count;
  StatsLabel.Caption:=Format(lisUDScanningUnits, [IntToStr(Cnt)]);
end;

procedure TUnitDependenciesWindow.UnitsLvlGraphMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  GraphNode: TLvlGraphNode;
  UGUnit: TUGUnit;
begin
  GraphNode:=UnitsLvlGraph.GetNodeAt(X,Y);
  if (Button=mbLeft) and (ssDouble in Shift) then begin
    if (GraphNode<>nil) and (GraphNode.Data<>nil) then begin
      UGUnit:=TUGUnit(GraphNode.Data);
      LazarusIDE.DoOpenEditorFile(UGUnit.Filename,-1,-1,[ofAddToRecent]);
    end;
  end;
end;

procedure TUnitDependenciesWindow.UnitsLvlGraphSelectionChanged(Sender: TObject);
var
  GraphNode: TLvlGraphNode;
  UGUnit: TUGUnit;
begin
  GraphNode:=UnitsLvlGraph.Graph.FirstSelected;
  while GraphNode<>nil do begin
    UGUnit:=TUGUnit(GraphNode.Data);
    if UGUnit<>nil then begin

    end;
    GraphNode:=GraphNode.NextSelected;
  end;
end;

procedure TUnitDependenciesWindow.UnitsTreeViewShowHint(Sender: TObject;
  HintInfo: PHintInfo);

  procedure CountUses(List: TFPList; out IntfCnt, ImplCnt: integer);
  var
    i: Integer;
  begin
    IntfCnt:=0;
    ImplCnt:=0;
    if List=nil then exit;
    for i:=0 to List.Count-1 do
      if TUDUses(List[i]).InImplementation then
        inc(ImplCnt)
      else
        inc(IntfCnt);
  end;

var
  TV: TTreeView;
  TVNode: TTreeNode;
  p: types.TPoint;
  UDNode: TUDNode;
  Filename: String;
  s: String;
  UGUnit: TUGUnit;
  UsedByIntf: Integer;
  UsedByImpl: Integer;
  UsesIntf: integer;
  UsesImpl: integer;
begin
  TV:=Sender as TTreeView;
  p:=HintInfo^.CursorPos;
  TVNode:=TV.GetNodeAt(p.X,p.Y);
  if (TVNode=nil) or not (TObject(TVNode.Data) is TUDNode) then exit;
  UDNode:=TUDNode(TVNode.Data);
  Filename:=GetFilename(UDNode);
  if Filename='' then exit;
  s:=Format(lisUDFile, [Filename]);
  if UDNode.Typ=udnUnit then begin
    UGUnit:=UsesGraph.GetUnit(Filename,false);
    if UGUnit<>nil then begin
      CountUses(UGUnit.UsesUnits,UsesIntf,UsesImpl);
      CountUses(UGUnit.UsedByUnits,UsedByIntf,UsedByImpl);
      if UsesIntf>0 then
        s+=LineEnding+Format(lisUDInterfaceUses, [IntToStr(UsesIntf)]);
      if UsesImpl>0 then
        s+=LineEnding+Format(lisUDImplementationUses, [IntToStr(UsesImpl)]);
      if UsedByIntf>0 then
        s+=LineEnding+Format(lisUDUsedByInterfaces, [IntToStr(UsedByIntf)]);
      if UsedByImpl>0 then
        s+=LineEnding+Format(lisUDUsedByImplementations, [IntToStr(UsedByImpl)]
          );
    end;
  end;
  HintInfo^.HintStr:=s;
end;

procedure TUnitDependenciesWindow.UnitsTreeViewMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  TVNode: TTreeNode;
  UDNode: TUDNode;
  UGGroup: TUGGroup;
  TV: TTreeView;
begin
  TV:=Sender as TTreeView;
  TVNode:=TV.GetNodeAt(X,Y);
  if TVNode=nil then exit;
  UDNode:=nil;
  if TObject(TVNode.Data) is TUDNode then
    UDNode:=TUDNode(TVNode.Data);
  if (Button=mbLeft) and (ssDouble in Shift) and (UDNode<>nil) then begin
    if UDNode.Typ=udnUnit then
      // open unit in source editor
      LazarusIDE.DoOpenEditorFile(UDNode.Identifier,-1,-1,[ofAddToRecent])
    else if UDNode.Typ=udnGroup then begin
      UGGroup:=Groups.GetGroup(UDNode.Group,false);
      if UGGroup=nil then exit;
      if IsProjectGroup(UGGroup) then begin
        // open project inspector
        ExecuteIDECommand(Self,ecProjectInspector);
      end else begin
        // open package editor
        PackageEditingInterface.DoOpenPackageWithName(UGGroup.Name,[pofAddToRecent],false);
      end;
    end;
  end;
end;

procedure TUnitDependenciesWindow.AllUnitsTreeViewSelectionChanged(
  Sender: TObject);
begin
  Include(FFlags,udwNeedUpdateSelUnitsTreeView);
  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.AllUnitsFilterEditChange(Sender: TObject);
begin
  Include(FFlags,udwNeedUpdateAllUnitsTreeView);
  IdleConnected:=true;
end;


procedure TUnitDependenciesWindow.FormDestroy(Sender: TObject);
begin
  IdleConnected:=false;

  FreeUsesGraph;
  FreeAndNil(FNewGroups);
  FreeAndNil(FNewUsesGraph);
  FreeAndNil(FPendingUnitDependencyRoute);
end;

procedure TUnitDependenciesWindow.GroupsLvlGraphSelectionChanged(Sender: TObject
  );
begin
  UpdateUnitsLvlGraph;
end;

procedure TUnitDependenciesWindow.OnIdle(Sender: TObject; var Done: Boolean);
var
  Completed: boolean;
begin
  if udwParsing in FFlags then begin
    fNewUsesGraph.Parse(true,Completed,200);
    if Completed then begin
      Exclude(FFlags,udwParsing);
      // free old uses graph
      FreeUsesGraph;
      // switch to new UsesGraph
      FUsesGraph:=FNewUsesGraph;
      FNewUsesGraph:=nil;
      FGroups:=FNewGroups;
      FNewGroups:=nil;
      // create Groups
      CreateGroups;
      // mark cycles
      MarkCycles(false);
      MarkCycles(true);
      // hide progress bar and update stats
      ProgressBar1.Visible:=false;
      ProgressBar1.Style:=pbstNormal;
      RefreshButton.Enabled:=true;
      Timer1.Enabled:=false;
      StatsLabel.Caption:=Format(lisUDUnits2, [IntToStr(
        FUsesGraph.FilesTree.Count)]);
      // update controls
      UpdateAll;
    end;
  end else if udwNeedUpdateGroupsLvlGraph in FFlags then
    UpdateGroupsLvlGraph
  else if udwNeedUpdateUnitsLvlGraph in FFlags then
    UpdateUnitsLvlGraph
  else if udwNeedUpdateAllUnitsTreeView in FFlags then
    UpdateAllUnitsTreeView
  else if udwNeedUpdateAllUnitsTVSearch in FFlags then
    UpdateAllUnitsTreeViewSearch
  else if udwNeedUpdateSelUnitsTreeView in FFlags then
    UpdateSelUnitsTreeView
  else if udwNeedUpdateSelUnitsTVSearch in FFlags then
    UpdateSelUnitsTreeViewSearch
  else
    IdleConnected:=false;
  Done:=not IdleConnected;
end;

procedure TUnitDependenciesWindow.SearchPkgsCheckBoxChange(Sender: TObject);
begin
  ScopeChanged;
end;

procedure TUnitDependenciesWindow.SearchSrcEditCheckBoxChange(Sender: TObject);
begin
  ScopeChanged;
end;

procedure TUnitDependenciesWindow.SelUnitsSearchEditChange(Sender: TObject);
begin
  Include(FFlags,udwNeedUpdateSelUnitsTVSearch);
  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.SelUnitsSearchNextSpeedButtonClick(Sender: TObject);
begin
  SelectNextSearchTV(SelUnitsTreeView,SelUnitsTreeView.Selected,true,true);
  fSelUnitsTVSearchStartNode:=SelUnitsTreeView.Selected;
end;

procedure TUnitDependenciesWindow.SelUnitsSearchPrevSpeedButtonClick(Sender: TObject);
begin
  SelectNextSearchTV(SelUnitsTreeView,SelUnitsTreeView.Selected,false,true);
  fSelUnitsTVSearchStartNode:=SelUnitsTreeView.Selected;
end;

procedure TUnitDependenciesWindow.SearchCustomFilesBrowseButtonClick(Sender: TObject);
var
  Dlg: TSelectDirectoryDialog;
  s: TCaption;
  aFilename: String;
  p: Integer;
begin
  Dlg:=TSelectDirectoryDialog.Create(nil);
  try
    InitIDEFileDialog(Dlg);
    Dlg.Options:=Dlg.Options+[ofPathMustExist];
    if not Dlg.Execute then exit;
    aFilename:=TrimFilename(Dlg.FileName);
    s:=SearchCustomFilesComboBox.Text;
    p:=1;
    if FindNextDelimitedItem(s,';',p,aFilename)<>'' then exit;
    if s<>'' then s+=';';
    s+=aFilename;
    SearchCustomFilesComboBox.Text:=s;
    ScopeChanged;
  finally
    Dlg.Free;
  end;
end;

procedure TUnitDependenciesWindow.SearchCustomFilesCheckBoxChange(Sender: TObject);
begin
  UpdateUnitsButtons;
  ScopeChanged;
end;

procedure TUnitDependenciesWindow.SearchCustomFilesComboBoxChange(Sender: TObject);
begin
  ScopeChanged;
end;

procedure TUnitDependenciesWindow.UnitsTVCollapseAllMenuItemClick(Sender: TObject);
var
  TV: TTreeView;
  i: Integer;
begin
  TV:=TTreeView(UnitsTVPopupMenu.PopupComponent);
  if not (TV is TTreeView) then exit;
  TV.BeginUpdate;
  for i:=0 to TV.Items.TopLvlCount-1 do
    TV.Items.TopLvlItems[i].Collapse(true);
  TV.EndUpdate;
end;

procedure TUnitDependenciesWindow.UnitsTVCopyFilenameMenuItemClick(Sender: TObject);
var
  UDNode: TUDNode;
begin
  if not GetPopupTV_UDNode(UDNode) then exit;
  Clipboard.AsText:=GetFilename(UDNode);
end;

procedure TUnitDependenciesWindow.UnitsTVExpandAllMenuItemClick(Sender: TObject);
var
  TV: TTreeView;
  i: Integer;
begin
  TV:=TTreeView(UnitsTVPopupMenu.PopupComponent);
  if not (TV is TTreeView) then exit;
  TV.BeginUpdate;
  for i:=0 to TV.Items.TopLvlCount-1 do
    TV.Items.TopLvlItems[i].Expand(true);
  TV.EndUpdate;
end;

procedure TUnitDependenciesWindow.UnitsTVOpenFileMenuItemClick(Sender: TObject);
var
  UDNode: TUDNode;
begin
  if not GetPopupTV_UDNode(UDNode) then exit;
  LazarusIDE.DoOpenEditorFile(GetFilename(UDNode),-1,-1,OpnFlagsPlainFile);
end;

procedure TUnitDependenciesWindow.UnitsTVPopupMenuPopup(Sender: TObject);
var
  TV: TTreeView;
  TVNode: TTreeNode;
  UDNode: TUDNode;
  aFilename: String;
  ShortFilename: String;
begin
  TV:=UnitsTVPopupMenu.PopupComponent as TTreeView;
  UnitsTVExpandAllMenuItem.Visible:=TV=AllUnitsTreeView;
  TVNode:=TV.Selected;
  if (TVNode<>nil) and (TObject(TVNode.Data) is TUDNode) then begin
    UDNode:=TUDNode(TVNode.Data);
    UnitsTVUnusedUnitsMenuItem.Enabled:=UDNode.Typ=udnUnit;
    aFilename:=GetFilename(UDNode);
    if aFilename<>'' then begin
      ShortFilename:=aFilename;
      if length(ShortFilename)>50 then
        ShortFilename:='...'+ExtractFilename(ShortFilename);
      UnitsTVCopyFilenameMenuItem.Enabled:=true;
      UnitsTVCopyFilenameMenuItem.Caption:=Format(lisCopyFilename, [
        ShortFilename]);
      UnitsTVOpenFileMenuItem.Visible:=true;
      UnitsTVOpenFileMenuItem.Caption:=Format(lisOpenLfm, [ShortFilename]);
    end else begin
      UnitsTVCopyFilenameMenuItem.Enabled:=false;
      UnitsTVCopyFilenameMenuItem.Caption:=uemCopyFilename;
      UnitsTVOpenFileMenuItem.Visible:=false;
    end;
  end else
    UnitsTVUnusedUnitsMenuItem.Enabled:=false;
end;

procedure TUnitDependenciesWindow.UnitsTVUnusedUnitsMenuItemClick(Sender: TObject);
var
  TV: TTreeView;
  TVNode: TTreeNode;
  UDNode: TUDNode;
  Filename: String;
  Code: TCodeBuffer;
begin
  TV:=TTreeView(UnitsTVPopupMenu.PopupComponent);
  if not (TV is TTreeView) then exit;
  TVNode:=TV.Selected;
  if (TVNode=nil) or not (TObject(TVNode.Data) is TUDNode) then exit;
  UDNode:=TUDNode(TVNode.Data);
  if UDNode.Typ<>udnUnit then exit;
  Filename:=GetFilename(UDNode);
  Code:=CodeToolBoss.LoadFile(Filename,true,false);
  ShowUnusedUnitsDialog(Code);
end;

procedure TUnitDependenciesWindow.SetIdleConnected(AValue: boolean);
begin
  if FIdleConnected=AValue then Exit;
  FIdleConnected:=AValue;
  if IdleConnected then
    Application.AddOnIdleHandler(@OnIdle)
  else
    Application.RemoveOnIdleHandler(@OnIdle);
end;

procedure TUnitDependenciesWindow.CreateGroups;
var
  i: Integer;
begin
  if FGroups=nil then
    RaiseCatchableException('');
  CreateProjectGroup(LazarusIDE.ActiveProject);
  for i:=0 to PackageEditingInterface.GetPackageCount-1 do
    CreatePackageGroup(PackageEditingInterface.GetPackages(i));
  CreateFPCSrcGroups;
  GuessGroupOfUnits;
end;

function TUnitDependenciesWindow.CreateProjectGroup(AProject: TLazProject): TUGGroup;
var
  i: Integer;
  Filename: String;
  CurUnit: TUGUnit;
  ProjFile: TLazProjectFile;
begin
  if AProject=nil then exit(nil);
  Result:=Groups.GetGroup(GroupPrefixProject,true);
  Result.BaseDir:=ExtractFilePath(AProject.ProjectInfoFile);
  if not FilenameIsAbsolute(Result.BaseDir) then
    Result.BaseDir:='';
  //debugln(['TUnitDependenciesDialog.CreateProjectGroup ',Result.Name,' FileCount=',AProject.FileCount]);
  for i:=0 to AProject.FileCount-1 do begin
    ProjFile:=AProject.Files[i];
    if not ProjFile.IsPartOfProject then continue;
    Filename:=AProject.Files[i].Filename;
    CurUnit:=UsesGraph.GetUnit(Filename,false);
    if CurUnit=nil then continue;
    if not (CurUnit is TUDUnit) then begin
      debugln(['TUnitDependenciesDialog.CreateProjectGroup WARNING: ',CurUnit.Filename,' ',CurUnit.Classname,' should be TUGGroupUnit']);
      continue;
    end;
    if TUDUnit(CurUnit).Group<>nil then continue;
    Result.AddUnit(TUDUnit(CurUnit));
  end;
end;

function TUnitDependenciesWindow.CreatePackageGroup(APackage: TIDEPackage): TUGGroup;
var
  i: Integer;
  Filename: String;
  CurUnit: TUGUnit;
begin
  if APackage=nil then exit(nil);
  Result:=Groups.GetGroup(APackage.Name,true);
  Result.BaseDir:=APackage.DirectoryExpanded;
  if not FilenameIsAbsolute(Result.BaseDir) then
    Result.BaseDir:='';
  //debugln(['TUnitDependenciesDialog.CreatePackageGroup ',Result.Name]);
  for i:=0 to APackage.FileCount-1 do begin
    Filename:=APackage.Files[i].GetFullFilename;
    CurUnit:=UsesGraph.GetUnit(Filename,false);
    if CurUnit is TUDUnit then begin
      if TUDUnit(CurUnit).Group<>nil then continue;
      Result.AddUnit(TUDUnit(CurUnit));
    end;
  end;
end;

procedure TUnitDependenciesWindow.CreateFPCSrcGroups;

  function ExtractFilePathStart(Filename: string; DirCount: integer): string;
  var
    p: Integer;
  begin
    p:=1;
    while p<=length(Filename) do begin
      if Filename[p]=PathDelim then begin
        DirCount-=1;
        if DirCount=0 then begin
          Result:=LeftStr(Filename,p-1);
          exit;
        end;
      end;
      inc(p);
    end;
    Result:=Filename;
  end;

var
  FPCSrcDir: String;
  Node: TAVLTreeNode;
  CurUnit: TUDUnit;
  Directory: String;
  Grp: TUGGroup;
  BaseDir: String;
begin
  FPCSrcDir:=AppendPathDelim(GetFPCSrcDir);

  // for each unit in the fpc source directory:
  // if in rtl/ put into group GroupPrefixFPCSrc+RTL
  // if in packages/<name>, put in group GroupPrefixFPCSrc+<name>
  Node:=UsesGraph.FilesTree.FindLowest;
  while Node<>nil do begin
    CurUnit:=TUDUnit(Node.Data);
    Node:=UsesGraph.FilesTree.FindSuccessor(Node);
    if TUDUnit(CurUnit).Group<>nil then continue;
    if CompareFilenames(FPCSrcDir,LeftStr(CurUnit.Filename,length(FPCSrcDir)))<>0
    then
      continue;
    // a unit in the FPC sources
    BaseDir:=ExtractFilePath(CurUnit.Filename);
    Directory:=copy(BaseDir,length(FPCSrcDir)+1,length(BaseDir));
    Directory:=ExtractFilePathStart(Directory,2);
    if LeftStr(Directory,length('rtl'))='rtl' then
      Directory:='RTL'
    else if LeftStr(Directory,length('packages'))='packages' then
      System.Delete(Directory,1,length('packages'+PathDelim));
    Grp:=Groups.GetGroup(GroupPrefixFPCSrc+Directory,true);
    if Grp.BaseDir='' then
      Grp.BaseDir:=BaseDir;
    //debugln(['TUnitDependenciesDialog.CreateFPCSrcGroups ',Grp.Name]);
    Grp.AddUnit(TUDUnit(CurUnit));
  end;
end;

procedure TUnitDependenciesWindow.GuessGroupOfUnits;
var
  Node: TAVLTreeNode;
  CurUnit: TUDUnit;
  Filename: String;
  Owners: TFPList;
  i: Integer;
  Group: TUGGroup;
  CurDirectory: String;
  LastDirectory: Char;
begin
  Owners:=nil;
  LastDirectory:='.';
  Node:=UsesGraph.FilesTree.FindLowest;
  while Node<>nil do begin
    CurUnit:=TUDUnit(Node.Data);
    if CurUnit.Group=nil then begin
      Filename:=CurUnit.Filename;
      //debugln(['TUnitDependenciesDialog.GuessGroupOfUnits no group for ',Filename]);
      CurDirectory:=ExtractFilePath(Filename);
      if CompareFilenames(CurDirectory,LastDirectory)<>0 then begin
        FreeAndNil(Owners);
        Owners:=PackageEditingInterface.GetPossibleOwnersOfUnit(Filename,[piosfIncludeSourceDirectories]);
      end;
      Group:=nil;
      if (Owners<>nil) then begin
        for i:=0 to Owners.Count-1 do begin
          if TObject(Owners[i]) is TLazProject then begin
            Group:=Groups.GetGroup(GroupPrefixProject,true);
            //debugln(['TUnitDependenciesDialog.GuessGroupOfUnits ',Group.Name]);
            break;
          end else if TObject(Owners[i]) is TIDEPackage then begin
            Group:=Groups.GetGroup(TIDEPackage(Owners[i]).Name,true);
            //debugln(['TUnitDependenciesDialog.GuessGroupOfUnits ',Group.Name]);
            break;
          end;
        end;
      end;
      if Group=nil then begin
        Group:=Groups.GetGroup(GroupNone,true);
        //debugln(['TUnitDependenciesDialog.GuessGroupOfUnits ',Group.Name]);
      end;
      Group.AddUnit(TUDUnit(CurUnit));
    end;
    Node:=UsesGraph.FilesTree.FindSuccessor(Node);
  end;
  FreeAndNil(Owners);
end;

procedure TUnitDependenciesWindow.MarkCycles(WithImplementationUses: boolean);
{ Using Tarjan's strongly connected components (SCC) algorithm
}
var
  TarjanIndex: integer;
  Stack: TFPList; // stack of TUDSCCNode

  function GetNode(UDItem: TObject): TUDSCCNode;
  begin
    if UDItem is TUDUnit then
      Result:=TUDUnit(UDItem).GetSCCNode
    else
      Result:=TUDUses(UDItem).GetSCCNode;
  end;

  procedure ClearNode(Node: TUDSCCNode);
  begin
    Node.TarjanIndex:=-1;
    Node.TarjanLowLink:=-1;
    Node.TarjanVisiting:=false;
    if WithImplementationUses then
      Node.InImplCycle:=false
    else
      Node.InIntfCycle:=false;
  end;

  procedure SearchNode(Node: TUDSCCNode); forward;

  procedure SearchEdge(FromNode, ToNode: TUDSCCNode);
  begin
    if ToNode.TarjanIndex<0 then begin
      // not yet visited
      SearchNode(ToNode);
      FromNode.TarjanLowLink:=Min(FromNode.TarjanLowLink,ToNode.TarjanLowLink);
    end else if ToNode.TarjanVisiting then begin
      // currently visiting => ToNode is in current SCC
      FromNode.TarjanLowLink:=Min(FromNode.TarjanLowLink,ToNode.TarjanIndex);
    end;
  end;

  procedure SearchNode(Node: TUDSCCNode);
  var
    UDUnit: TUDUnit;
    UDUses: TUDUses;
    i: Integer;
    CycleNode: TUDSCCNode;
    MoreThanOneNode: Boolean; // true = there is a cycle with more than one node
  begin
    //debugln(['SearchNode ',Node.AsString]);
    // Set the depth index for Node to the smallest unused index
    Node.TarjanIndex := TarjanIndex;
    Node.TarjanLowLink := TarjanIndex;
    inc(TarjanIndex);
    Stack.Add(Node);
    Node.TarjanVisiting:=true;

    // search all edges
    if Node.UDItem is TUDUnit then begin
      UDUnit:=TUDUnit(Node.UDItem);
      if UDUnit.UsesUnits<>nil then
        for i:=0 to UDUnit.UsesUnits.Count-1 do begin
          UDUses:=TUDUses(UDUnit.UsesUnits[i]);
          if (not WithImplementationUses) and UDUses.InImplementation then
            continue;
          SearchEdge(Node,GetNode(UDUses));
        end;
    end else begin
      UDUses:=TUDUses(Node.UDItem);
      SearchEdge(Node,GetNode(UDUses.UsesUnit));
    end;

    if Node.TarjanIndex=Node.TarjanLowLink then begin
      // this is a root node of a SCC
      MoreThanOneNode:=TUDSCCNode(Stack[Stack.Count-1])<>Node;
      repeat
        CycleNode:=TUDSCCNode(Stack[Stack.Count-1]);
        Stack.Delete(Stack.Count-1);
        CycleNode.TarjanVisiting:=false;
        if MoreThanOneNode then begin
          if WithImplementationUses then
            CycleNode.InImplCycle:=true
          else
            CycleNode.InIntfCycle:=true;
          //debugln(['SearchNode WithImpl=',WithImplementationUses,' Cycle=',CycleNode.AsString]);
        end;
      until CycleNode=Node;
    end;
  end;

var
  AVLNode: TAVLTreeNode;
  UDUnit: TUDUnit;
  Node: TUDSCCNode;
  i: Integer;
begin
  // init
  TarjanIndex:=0;
  for AVLNode in FUsesGraph.FilesTree do begin
    UDUnit:=TUDUnit(AVLNode.Data);
    Node:=GetNode(UDUnit);
    ClearNode(Node);
    if UDUnit.UsesUnits<>nil then
      for i:=0 to UDUnit.UsesUnits.Count-1 do
        ClearNode(GetNode(TObject(UDUnit.UsesUnits[i])));
  end;
  Stack:=TFPList.Create;
  try
    // depth first search through the forest
    for AVLNode in FUsesGraph.FilesTree do begin
      UDUnit:=TUDUnit(AVLNode.Data);
      //debugln(['TUnitDependenciesWindow.MarkCycles ',dbgsname(UDUnit)]);
      Node:=GetNode(UDUnit);
      if Node.TarjanIndex<0 then
        SearchNode(Node);
    end;
  finally
    Stack.Free;
  end;
end;

procedure TUnitDependenciesWindow.SetPendingUnitDependencyRoute(AValue: TStrings);
begin
  if FPendingUnitDependencyRoute.Equals(AValue) then Exit;
  FPendingUnitDependencyRoute.Assign(AValue);
  FFlags:=FFlags+[udwNeedUpdateAllUnitsTreeView,udwNeedUpdateSelUnitsTreeView];
  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.StartParsing;
begin
  if (FNewUsesGraph<>nil) or (udwParsing in FFlags) then
    RaiseCatchableException('');
  Include(FFlags,udwParsing);

  ProgressBar1.Visible:=true;
  ProgressBar1.Style:=pbstMarquee;
  StatsLabel.Caption:=lisUDScanning;
  Timer1.Enabled:=true;
  RefreshButton.Enabled:=false;

  CreateUsesGraph(FNewUsesGraph,FNewGroups);

  LazarusIDE.BeginCodeTools;
  AddStartAndTargetUnits;

  IdleConnected:=true;
end;

procedure TUnitDependenciesWindow.ScopeChanged;
begin
  FreeAndNil(FNewGroups);
  FreeAndNil(FNewUsesGraph);
  Exclude(FFlags,udwParsing);
  StartParsing;
end;

procedure TUnitDependenciesWindow.SetCurrentUnit(AValue: TUGUnit);
begin
  if FCurrentUnit=AValue then Exit;
  FCurrentUnit:=AValue;
end;

function TUnitDependenciesWindow.CreateAllUnitsTree: TUDNode;
var
  Node: TUDNode;
  ParentNode: TUDNode;
  GroupName: String;
  ShowDirectories: Boolean;
  ShowGroups: Boolean;
  NodeText: String;
  RootNode: TUDNode;
  Filter: String;
  UGUnit: TUDUnit;
  AVLNode: TAVLTreeNode;
  Group: TUGGroup;
  GroupNode: TUDNode;
  Filename: String;
  p: Integer;
  Dir: String;
  DirNode: TUDNode;
  BaseDir: String;
  CurDir: String;
begin
  Filter:=GetAllUnitsFilter(true);
  ShowGroups:=AllUnitsShowGroupNodesSpeedButton.Down;
  ShowDirectories:=AllUnitsShowDirsSpeedButton.Down;
  RootNode:=TUDNode.Create;
  for AVLNode in UsesGraph.FilesTree do begin
    UGUnit:=TUDUnit(AVLNode.Data);
    Filename:=UGUnit.Filename;
    NodeText:=ExtractFileName(Filename);
    if (Filter<>'') and (Pos(Filter, UTF8LowerCase(NodeText))<1) then
      continue;
    Group:=UGUnit.Group;
    BaseDir:='';
    if Group=nil then begin
      GroupName:=GroupNone
    end else begin
      GroupName:=Group.Name;
      if FilenameIsAbsolute(Group.BaseDir) then
        BaseDir:=ChompPathDelim(Group.BaseDir);
    end;
    ParentNode:=RootNode;
    if ShowGroups then begin
      // create group nodes
      GroupNode:=ParentNode.GetNode(udnGroup,GroupName,true);
      if GroupNode.Identifier='' then begin
        GroupNode.Identifier:=GroupName;
        GroupNode.Group:=GroupName;
      end;
      ParentNode:=GroupNode;
      if FilenameIsAbsolute(BaseDir) and FilenameIsAbsolute(Filename) then
        Filename:=CreateRelativePath(Filename,BaseDir);
    end;
    if ShowDirectories then begin
      // create directory nodes
      CurDir:=BaseDir;
      p:=1;
      repeat
        Dir:=FindNextDirectoryInFilename(Filename,p);
        if p>length(Filename) then break;
        if Dir<>'' then begin
          DirNode:=ParentNode.GetNode(udnDirectory,Dir,true);
          CurDir+=PathDelim+Dir;
          if DirNode.Identifier='' then begin
            DirNode.Identifier:=CurDir;
          end;
          ParentNode:=DirNode;
        end;
      until false;
    end;
    Node:=ParentNode.GetNode(udnUnit, NodeText, true);
    Node.Identifier:=UGUnit.Filename;
    Node.Group:=GroupName;
    Node.IntfCycle:=UGUnit.GetSCCNode.InIntfCycle;
    Node.ImplCycle:=UGUnit.GetSCCNode.InImplCycle;
    Node.HasImplementationUses:=UGUnit.HasImplementationUses;
  end;
  Result:=RootNode;
end;

function TUnitDependenciesWindow.CreateSelUnitsTree: TUDNode;
var
  RootNode: TUDNode;
  SelTVNode: TTreeNode;
  SelUDNode: TUDNode;
  UDNode: TUDNode;
begin
  RootNode:=TUDNode.Create;
  SelTVNode:=AllUnitsTreeView.GetFirstMultiSelected;
  if SelTVNode=nil then
    SelTVNode:=AllUnitsTreeView.Selected;
  //debugln(['TUnitDependenciesWindow.CreateSelUnitsTree SelTVNode=',SelTVNode<>nil]);
  while SelTVNode<>nil do begin
    if TObject(SelTVNode.Data) is TUDNode then begin
      SelUDNode:=TUDNode(SelTVNode.Data);
      if SelUDNode.Typ=udnUnit then begin
        UDNode:=RootNode.GetNode(udnUnit,SelUDNode.NodeText,true);
        UDNode.Identifier:=SelUDNode.Identifier;
        UDNode.Group:=SelUDNode.Group;
        AddUsesSubNodes(UDNode);
      end;
    end;
    SelTVNode:=SelTVNode.GetNextMultiSelected;
  end;

  ExpandPendingUnitDependencyRoute(RootNode);

  Result:=RootNode;
end;

procedure TUnitDependenciesWindow.ExpandPendingUnitDependencyRoute(RootNode: TUDNode);
var
  i: Integer;
  CurUnitName: String;
  UDNode: TUDNode;
  IntfUDNode: TUDNode;
  ParentUDNode: TUDNode;
begin
  if PendingUnitDependencyRoute.Count=0 then exit;
  ConvertUnitNameRouteToPath(PendingUnitDependencyRoute);
  try
    ParentUDNode:=RootNode;
    for i:=0 to PendingUnitDependencyRoute.Count-1 do begin
      CurUnitName:=PendingUnitDependencyRoute[i];
      UDNode:=ParentUDNode.FindUnit(CurUnitName);
      //debugln(['TUnitDependenciesWindow.ExpandPendingUnitDependencyPath CurUnitName="',CurUnitName,'" UDNode=',DbgSName(UDNode)]);
      if UDNode=nil then exit;
      if i=PendingUnitDependencyRoute.Count-1 then exit;
      IntfUDNode:=UDNode.FindFirst(udnInterface);
      if IntfUDNode=nil then begin
        if UDNode.Count>0 then
          exit; // already expanded -> has no interface
        // expand
        AddUsesSubNodes(UDNode);
        IntfUDNode:=UDNode.FindFirst(udnInterface);
        if IntfUDNode=nil then exit;
      end;
      ParentUDNode:=IntfUDNode;
    end;
  finally
    // apply only once => clear pending
    PendingUnitDependencyRoute.Clear;
  end;
end;

procedure TUnitDependenciesWindow.ConvertUnitNameRouteToPath(Route: TStrings);
var
  UGUnitList: TFPList;
  UGUnit: TUGUnit;
  i: Integer;
begin
  if Route.Count<=1 then exit;
  UGUnitList:=TFPList.Create;
  try
    // convert unit names to TUGUnit
    for i:=0 to Route.Count-1 do begin
      UGUnit:=FUsesGraph.FindUnit(Route[i]);
      if UGUnit=nil then continue;
      UGUnitList.Add(UGUnit);
    end;
    // insert missing links
    FUsesGraph.InsertMissingLinks(UGUnitList);
    // convert TUGUnit to unit names
    Route.Clear;
    for i:=0 to UGUnitList.Count-1 do
      Route.Add(ExtractFileNameOnly(TUGUnit(UGUnitList[i]).Filename));
  finally
    UGUnitList.Free;
  end;
end;

procedure TUnitDependenciesWindow.AddUsesSubNodes(UDNode: TUDNode);

  procedure AddUses(ParentUDNode: TUDNode; UsesList: TFPList;
    NodeTyp: TUDNodeType);
  var
    i: Integer;
    UGUses: TUDUses;
    NodeText: String;
    SectionUDNode: TUDNode;
    InImplementation: Boolean;
    UsedBy: Boolean;
    OtherUnit: TUDUnit;
    Filename: String;
    UDNode: TUDNode;
    GroupName: String;
    Cnt: Integer;
    HasIntfCycle: Boolean;
    HasImplCycle: Boolean;
  begin
    if ParentUDNode=nil then exit;
    if UsesList=nil then exit;
    if not (NodeTyp in [udnInterface,udnImplementation,udnUsedByInterface,udnUsedByImplementation])
    then exit;
    InImplementation:=(NodeTyp in [udnImplementation,udnUsedByImplementation]);
    UsedBy:=(NodeTyp in [udnUsedByInterface,udnUsedByImplementation]);

    // count the number of uses
    Cnt:=0;
    HasIntfCycle:=false;
    HasImplCycle:=false;
    for i:=0 to UsesList.Count-1 do begin
      UGUses:=TUDUses(UsesList[i]);
      if UGUses.InImplementation<>InImplementation then continue;
      HasIntfCycle:=HasIntfCycle or UGUses.GetSCCNode.InIntfCycle;
      HasImplCycle:=HasImplCycle or UGUses.GetSCCNode.InImplCycle;
      inc(Cnt);
    end;
    if Cnt=0 then exit;

    // create a section node
    NodeText:=IntToStr(Cnt);
    case NodeTyp of
    udnInterface: NodeText:=Format(lisUDInterfaceUses2, [NodeText]);
    udnImplementation: NodeText:=Format(lisUDImplementationUses2, [NodeText]);
    udnUsedByInterface: NodeText:=Format(lisUDUsedByInterfaces2, [NodeText]);
    udnUsedByImplementation: NodeText:=Format(lisUDUsedByImplementations2, [
      NodeText]);
    else exit;
    end;
    SectionUDNode:=ParentUDNode.GetNode(NodeTyp,NodeText,true);
    SectionUDNode.IntfCycle:=HasIntfCycle;
    SectionUDNode.ImplCycle:=HasImplCycle;

    // create unit nodes
    for i:=0 to UsesList.Count-1 do begin
      UGUses:=TUDUses(UsesList[i]);
      if UGUses.InImplementation<>InImplementation then continue;
      if UsedBy then
        OtherUnit:=TUDUnit(UGUses.Owner)
      else
        OtherUnit:=TUDUnit(UGUses.UsesUnit);
      Filename:=OtherUnit.Filename;
      NodeText:=ExtractFileName(Filename);
      UDNode:=SectionUDNode.GetNode(udnUnit,NodeText,true);
      UDNode.Identifier:=Filename;
      if OtherUnit.Group<>nil then
        GroupName:=OtherUnit.Group.Name
      else
        GroupName:=GroupNone;
      UDNode.Group:=GroupName;
      UDNode.HasChildren:=
         ((OtherUnit.UsedByUnits<>nil) and (OtherUnit.UsedByUnits.Count>0))
         or ((OtherUnit.UsesUnits<>nil) and (OtherUnit.UsesUnits.Count>0));
      UDNode.IntfCycle:=UGUses.GetSCCNode.InIntfCycle;
      UDNode.ImplCycle:=UGUses.GetSCCNode.InImplCycle;
    end;
  end;

var
  Filename: String;
  UGUnit: TUDUnit;
begin
  // add connected units
  Filename:=UDNode.Identifier;
  UGUnit:=TUDUnit(UsesGraph.GetUnit(Filename,false));
  if UGUnit<>nil then begin
    AddUses(UDNode,UGUnit.UsesUnits,udnInterface);
    AddUses(UDNode,UGUnit.UsesUnits,udnImplementation);
    AddUses(UDNode,UGUnit.UsedByUnits,udnUsedByInterface);
    AddUses(UDNode,UGUnit.UsedByUnits,udnUsedByImplementation);
  end;
end;

procedure TUnitDependenciesWindow.SelectNextSearchTV(TV: TTreeView;
  StartTVNode: TTreeNode; SearchNext, SkipStart: boolean);
var
  TVNode: TTreeNode;
  NextTVNode: TTreeNode;
  PrevTVNode: TTreeNode;
  LowerSearch: String;
begin
  //debugln(['TUnitDependenciesWindow.SelectNextSearchTV START ',DbgSName(TV),' ',StartTVNode<>nil,' SearchNext=',SearchNext,' SkipStart=',SkipStart]);
  TV.BeginUpdate;
  try
    TVNode:=StartTVNode;
    if TVNode=nil then begin
      if SearchNext then
        TVNode:=TV.Items.GetFirstNode
      else
        TVNode:=TV.Items.GetLastNode;
      SkipStart:=false;
    end;
    if TV=AllUnitsTreeView then
      LowerSearch:=GetAllUnitsSearch(true)
    else
      LowerSearch:=GetSelUnitsSearch(true);
    //if TVNode<>nil then debugln(['TUnitDependenciesWindow.SelectNextSearchTV searching "',LowerSearch,'" TVNode=',TVNode.Text,' SearchNext=',SearchNext,' SkipStart=',SkipStart]);
    TVNode:=FindNextTVNode(TVNode,LowerSearch,SearchNext,SkipStart);
    //if TVNode<>nil then debugln(['TUnitDependenciesWindow.SelectNextSearchTV found TVNode=',TVNode.Text]);
    NextTVNode:=nil;
    PrevTVNode:=nil;
    if TVNode<>nil then begin
      TV.Items.ClearMultiSelection(True);
      TV.Selected:=TVNode;
      TV.MakeSelectionVisible;
      NextTVNode:=FindNextTVNode(TVNode,LowerSearch,true,true);
      PrevTVNode:=FindNextTVNode(TVNode,LowerSearch,false,true);
    end;
    if TV=AllUnitsTreeView then begin
      AllUnitsSearchNextSpeedButton.Enabled:=NextTVNode<>nil;
      AllUnitsSearchPrevSpeedButton.Enabled:=PrevTVNode<>nil;
    end else begin
      SelUnitsSearchNextSpeedButton.Enabled:=NextTVNode<>nil;
      SelUnitsSearchPrevSpeedButton.Enabled:=PrevTVNode<>nil;
    end;
  finally
    TV.EndUpdate;
  end;
  //debugln(['TUnitDependenciesWindow.SelectNextSearchTV END']);
end;

procedure TUnitDependenciesWindow.AddStartAndTargetUnits;
var
  aProject: TLazProject;
  i: Integer;
  SrcEdit: TSourceEditorInterface;
  AFilename: String;
  Pkg: TIDEPackage;
  j: Integer;
  PkgFile: TLazPackageFile;
begin
  FNewUsesGraph.TargetAll:=true;

  // project lpr
  aProject:=LazarusIDE.ActiveProject;
  if (aProject<>nil) and (aProject.MainFile<>nil) then
    FNewUsesGraph.AddStartUnit(aProject.MainFile.Filename);

  // add all open packages
  if SearchPkgsCheckBox.Checked then begin
    for i:=0 to PackageEditingInterface.GetPackageCount-1 do begin
      Pkg:=PackageEditingInterface.GetPackages(i);
      if not FilenameIsAbsolute(Pkg.Filename) then continue;
      for j:=0 to Pkg.FileCount-1 do begin
        PkgFile:=Pkg.Files[j];
        if PkgFile.Removed then continue;
        if not (PkgFile.FileType in PkgFileRealUnitTypes) then continue;
        if not PkgFile.InUses then continue;
        aFilename:=PkgFile.GetFullFilename;
        if FilenameIsAbsolute(AFilename)
        and FilenameIsPascalUnit(AFilename) then
          FNewUsesGraph.AddStartUnit(AFilename);
      end;
    end;
  end;

  // add all source editor files
  if SearchSrcEditCheckBox.Checked then begin
    for i:=0 to SourceEditorManagerIntf.SourceEditorCount-1 do begin
      SrcEdit:=SourceEditorManagerIntf.SourceEditors[i];
      AFilename:=SrcEdit.FileName;
      if FilenameIsPascalUnit(AFilename) then
        FNewUsesGraph.AddStartUnit(AFilename);
    end;
  end;

  // additional units and directories
  if SearchCustomFilesCheckBox.Checked then
    AddAdditionalFilesAsStartUnits;
end;

procedure TUnitDependenciesWindow.AddAdditionalFilesAsStartUnits;
var
  List: TCaption;
  aFilename: String;
  Files: TStrings;
  i: Integer;
  p: Integer;
begin
  List:=SearchCustomFilesComboBox.Text;
  p:=1;
  while p<=length(List) do begin
    aFilename:=TrimAndExpandFilename(GetNextDelimitedItem(List,';',p));
    if (AFilename='') then continue;
    if not FileExistsCached(aFilename) then continue;
    if DirPathExistsCached(aFilename) then begin
      aFilename:=AppendPathDelim(aFilename);
      // add all units in directory
      Files:=nil;
      try
        CodeToolBoss.DirectoryCachePool.GetListing(aFilename,Files,false);
        if Files<>nil then begin
          for i:=0 to Files.Count-1 do begin
            if FilenameIsPascalUnit(Files[i]) then
              fNewUsesGraph.AddStartUnit(aFilename+Files[i]);
          end;
        end;
      finally
        Files.Free;
      end;
    end else begin
      // add a single file
      fNewUsesGraph.AddStartUnit(aFilename);
    end;
  end;
end;

procedure TUnitDependenciesWindow.SetupGroupsTabSheet;
begin
  GroupsTabSheet.Caption:=lisUDProjectsAndPackages;

  GroupsLvlGraph:=TLvlGraphControl.Create(Self);
  with GroupsLvlGraph do
  begin
    Name:='GroupsLvlGraph';
    Caption:='';
    Align:=alTop;
    Height:=200;
    NodeStyle.GapBottom:=5;
    Parent:=GroupsTabSheet;
    OnSelectionChanged:=@GroupsLvlGraphSelectionChanged;
  end;

  GroupsSplitter.Top:=GroupsLvlGraph.Height;

  UnitsLvlGraph:=TLvlGraphControl.Create(Self);
  with UnitsLvlGraph do
  begin
    Name:='UnitsLvlGraph';
    Caption:='';
    Align:=alClient;
    NodeStyle.GapBottom:=5;
    Parent:=GroupsTabSheet;
    OnSelectionChanged:=@UnitsLvlGraphSelectionChanged;
    OnMouseDown:=@UnitsLvlGraphMouseDown;
  end;
end;

procedure TUnitDependenciesWindow.SetupUnitsTabSheet;
begin
  UnitsTabSheet.Caption:=lisUDUnits;

  // start searching
  SearchCustomFilesCheckBox.Caption:=lisUDAdditionalDirectories;
  SearchCustomFilesCheckBox.Hint:=
    lisUDByDefaultOnlyTheProjectUnitsAndTheSourceEditorUnit;
  SearchCustomFilesComboBox.Text:='';
  SearchCustomFilesBrowseButton.Caption:=lisPathEditBrowse;

  SearchPkgsCheckBox.Caption:=lisUDAllPackageUnits;
  SearchSrcEditCheckBox.Caption:=lisUDAllSourceEditorUnits;

  // view all units
  AllUnitsGroupBox.Caption:=lisUDAllUnits;

  AllUnitsShowDirsSpeedButton.Hint:=lisUDShowNodesForDirectories;
  IDEImages.AssignImage(AllUnitsShowDirsSpeedButton, 'pkg_hierarchical');
  AllUnitsShowDirsSpeedButton.Down:=true;
  AllUnitsShowGroupNodesSpeedButton.Hint:=lisUDShowNodesForProjectAndPackages;
  IDEImages.AssignImage(AllUnitsShowGroupNodesSpeedButton, 'pkg_hierarchical');
  AllUnitsShowGroupNodesSpeedButton.Down:=true;

  AllUnitsSearchNextSpeedButton.Hint:=lisUDSearchNextOccurrenceOfThisPhrase;
  IDEImages.AssignImage(AllUnitsSearchNextSpeedButton, 'arrow_down');
  AllUnitsSearchPrevSpeedButton.Hint:=lisUDSearchPreviousOccurrenceOfThisPhrase;
  IDEImages.AssignImage(AllUnitsSearchPrevSpeedButton, 'arrow_up');

  // selected units
  SelectedUnitsGroupBox.Caption:=lisUDSelectedUnits;
  SelUnitsSearchNextSpeedButton.Hint:=lisUDSearchNextUnitOfThisPhrase;
  IDEImages.AssignImage(SelUnitsSearchNextSpeedButton, 'arrow_down');
  SelUnitsSearchPrevSpeedButton.Hint:=lisUDSearchPreviousUnitOfThisPhrase;
  IDEImages.AssignImage(SelUnitsSearchPrevSpeedButton, 'arrow_up');

  // popup menu
  UnitsTVCopyFilenameMenuItem.Caption:=uemCopyFilename;
  UnitsTVUnusedUnitsMenuItem.Caption:=lisShowUnusedUnits;
  UnitsTVExpandAllMenuItem.Caption:=lisUDExpandAllNodes;
  UnitsTVCollapseAllMenuItem.Caption:=lisUDCollapseAllNodes;

  UpdateUnitsButtons;
end;

procedure TUnitDependenciesWindow.UpdateUnitsButtons;
begin
  SearchCustomFilesComboBox.Enabled:=SearchCustomFilesCheckBox.Checked;
  SearchCustomFilesBrowseButton.Enabled:=SearchCustomFilesCheckBox.Checked;
end;

procedure TUnitDependenciesWindow.UpdateAll;
begin
  UpdateGroupsLvlGraph;
  UpdateUnitsLvlGraph;
  UpdateAllUnitsTreeView;
end;

procedure TUnitDependenciesWindow.UpdateGroupsLvlGraph;
var
  AVLNode: TAVLTreeNode;
  Group: TUGGroup;
  Graph: TLvlGraph;
  PkgList: TFPList;
  i: Integer;
  RequiredPkg: TIDEPackage;
  GroupObj: TObject;
  GraphGroup: TLvlGraphNode;
  UnitNode: TAVLTreeNode;
  GrpUnit: TUDUnit;
  UsedUnit: TUDUnit;
begin
  Exclude(FFlags,udwNeedUpdateGroupsLvlGraph);
  GroupsLvlGraph.BeginUpdate;
  Graph:=GroupsLvlGraph.Graph;
  Graph.Clear;
  AVLNode:=Groups.Groups.FindLowest;
  while AVLNode<>nil do begin
    Group:=TUGGroup(AVLNode.Data);
    AVLNode:=Groups.Groups.FindSuccessor(AVLNode);
    GraphGroup:=Graph.GetNode(Group.Name,true);
    GraphGroup.Data:=Group;
    GroupObj:=nil;
    if IsProjectGroup(Group) then begin
      // project
      GroupObj:=LazarusIDE.ActiveProject;
      GraphGroup.Selected:=true;
    end else begin
      // package
      GroupObj:=PackageEditingInterface.FindPackageWithName(Group.Name);
    end;
    if GroupObj<>nil then begin
      // add lpk dependencies
      PkgList:=nil;
      try
        PackageEditingInterface.GetRequiredPackages(GroupObj,PkgList,[pirNotRecursive]);
        if (PkgList<>nil) then begin
          // add for each dependency an edge in the Graph
          for i:=0 to PkgList.Count-1 do begin
            RequiredPkg:=TIDEPackage(PkgList[i]);
            Graph.GetEdge(GraphGroup,Graph.GetNode(RequiredPkg.Name,true),true);
          end;
        end;
      finally
        PkgList.Free;
      end;
    end else if IsFPCSrcGroup(Group) then begin
      // add FPC source dependencies
      UnitNode:=Group.Units.FindLowest;
      while UnitNode<>nil do begin
        GrpUnit:=TUDUnit(UnitNode.Data);
        UnitNode:=Group.Units.FindSuccessor(UnitNode);
        if GrpUnit.UsesUnits=nil then continue;
        for i:=0 to GrpUnit.UsesUnits.Count-1 do begin
          UsedUnit:=TUDUnit(TUDUses(GrpUnit.UsesUnits[i]).UsesUnit);
          if (UsedUnit.Group=nil) or (UsedUnit.Group=Group) then continue;
          Graph.GetEdge(GraphGroup,Graph.GetNode(UsedUnit.Group.Name,true),true);
        end;
      end;
    end;
  end;
  GroupsLvlGraph.EndUpdate;
end;

procedure TUnitDependenciesWindow.UpdateUnitsLvlGraph;

  function UnitToCaption(AnUnit: TUGUnit): string;
  begin
    Result:=ExtractFileNameOnly(AnUnit.Filename);
  end;

var
  GraphGroup: TLvlGraphNode;
  NewUnits: TFilenameToPointerTree;
  UnitGroup: TUGGroup;
  AVLNode: TAVLTreeNode;
  GroupUnit: TUDUnit;
  i: Integer;
  HasChanged: Boolean;
  Graph: TLvlGraph;
  CurUses: TUDUses;
  SourceGraphNode: TLvlGraphNode;
  TargetGraphNode: TLvlGraphNode;
  NewGroups: TStringToPointerTree;
  UsedUnit: TUDUnit;
begin
  Exclude(FFlags,udwNeedUpdateUnitsLvlGraph);
  NewGroups:=TStringToPointerTree.Create(false);
  NewUnits:=TFilenameToPointerTree.Create(false);
  try
    // fetch new list of units
    GraphGroup:=GroupsLvlGraph.Graph.FirstSelected;
    while GraphGroup<>nil do begin
      UnitGroup:=TUGGroup(GraphGroup.Data);
      if UnitGroup<>nil then begin
        NewGroups[UnitGroup.Name]:=UnitGroup;
        AVLNode:=UnitGroup.Units.FindLowest;
        while AVLNode<>nil do begin
          GroupUnit:=TUDUnit(AVLNode.Data);
          NewUnits[GroupUnit.Filename]:=GroupUnit;
          AVLNode:=UnitGroup.Units.FindSuccessor(AVLNode);
        end;
      end;
      GraphGroup:=GraphGroup.NextSelected;
    end;

    // check if something changed
    Graph:=UnitsLvlGraph.Graph;
    HasChanged:=false;
    i:=0;
    AVLNode:=NewUnits.Tree.FindLowest;
    while AVLNode<>nil do begin
      GroupUnit:=TUDUnit(NewUnits.GetNodeData(AVLNode)^.Value);
      if (Graph.NodeCount<=i) or (Graph.Nodes[i].Data<>Pointer(GroupUnit)) then
      begin
        HasChanged:=true;
        break;
      end;
      i+=1;
      AVLNode:=NewUnits.Tree.FindSuccessor(AVLNode);
    end;
    if i<Graph.NodeCount then HasChanged:=true;
    if not HasChanged then exit;

    // units changed -> update level graph of units
    UnitsLvlGraph.BeginUpdate;
    Graph.Clear;
    AVLNode:=NewUnits.Tree.FindLowest;
    while AVLNode<>nil do begin
      GroupUnit:=TUDUnit(NewUnits.GetNodeData(AVLNode)^.Value);
      SourceGraphNode:=Graph.GetNode(UnitToCaption(GroupUnit),true);
      SourceGraphNode.Data:=GroupUnit;
      if GroupUnit.UsesUnits<>nil then begin
        for i:=0 to GroupUnit.UsesUnits.Count-1 do begin
          CurUses:=TUDUses(GroupUnit.UsesUnits[i]);
          UsedUnit:=TUDUnit(CurUses.UsesUnit);
          if UsedUnit.Group=nil then continue;
          if not NewGroups.Contains(UsedUnit.Group.Name) then continue;
          TargetGraphNode:=Graph.GetNode(UnitToCaption(UsedUnit),true);
          TargetGraphNode.Data:=UsedUnit;
          Graph.GetEdge(SourceGraphNode,TargetGraphNode,true);
        end;
      end;
      AVLNode:=NewUnits.Tree.FindSuccessor(AVLNode);
    end;

    UnitsLvlGraph.EndUpdate;
  finally
    NewGroups.Free;
    NewUnits.Free;
  end;
end;

procedure TUnitDependenciesWindow.CreateTVNodes(TV: TTreeView;
  ParentTVNode: TTreeNode; ParentUDNode: TUDNode; Expand: boolean);
var
  AVLNode: TAVLTreeNode;
  UDNode: TUDNode;
  TVNode: TTreeNode;
begin
  if ParentUDNode=nil then exit;
  AVLNode:=ParentUDNode.ChildNodes.FindLowest;
  while AVLNode<>nil do begin
    UDNode:=TUDNode(AVLNode.Data);
    TVNode:=TV.Items.AddChild(ParentTVNode,UDNode.NodeText);
    UDNode.TVNode:=TVNode;
    TVNode.Data:=UDNode;
    TVNode.ImageIndex:=GetImgIndex(UDNode);
    TVNode.SelectedIndex:=TVNode.ImageIndex;
    TVNode.HasChildren:=UDNode.HasChildren;
    if UDNode.IntfCycle then
      TVNode.OverlayIndex:=fImgIndexOverlayIntfCycle
    else if UDNode.ImplCycle then
      TVNode.OverlayIndex:=fImgIndexOverlayImplCycle
    else if UDNode.HasImplementationUses then
      TVNode.OverlayIndex:=fImgIndexOverlayImplUses;
    //if TVNode.OverlayIndex>=0 then
    //  debugln(['TUnitDependenciesWindow.CreateTVNodes ',TVNode.Text,' Overlay=',TVNode.OverlayIndex,' ',TV.Images.Count]);
    CreateTVNodes(TV,TVNode,UDNode,Expand);
    TVNode.Expanded:=Expand and (TVNode.Count>0);
    AVLNode:=ParentUDNode.ChildNodes.FindSuccessor(AVLNode);
  end;
end;

procedure TUnitDependenciesWindow.FreeUsesGraph;
begin
  FreeAndNil(FAllUnitsRootUDNode);
  FreeAndNil(FSelUnitsRootUDNode);
  GroupsLvlGraph.Clear;
  UnitsLvlGraph.Clear;
  FreeAndNil(FGroups);
  FreeAndNil(FUsesGraph);
end;

function TUnitDependenciesWindow.GetPopupTV_UDNode(out UDNode: TUDNode
  ): boolean;
var
  TV: TTreeView;
  TVNode: TTreeNode;
begin
  Result:=false;
  UDNode:=nil;
  TV:=TTreeView(UnitsTVPopupMenu.PopupComponent);
  if not (TV is TTreeView) then exit;
  TVNode:=TV.Selected;
  if (TVNode=nil) or not (TObject(TVNode.Data) is TUDNode) then exit;
  UDNode:=TUDNode(TVNode.Data);
  Result:=true;
end;

procedure TUnitDependenciesWindow.UpdateAllUnitsTreeView;
var
  TV: TTreeView;
  OldExpanded: TTreeNodeExpandedState;
  SrcEdit: TSourceEditorInterface;
  SelPath: String;
begin
  Exclude(FFlags,udwNeedUpdateAllUnitsTreeView);
  TV:=AllUnitsTreeView;
  TV.BeginUpdate;
  // save old expanded state
  if (TV.Items.Count>1) and (GetAllUnitsFilter(false)='') then
    OldExpanded:=TTreeNodeExpandedState.Create(TV)
  else
    OldExpanded:=nil;
  SelPath:='';
  if TV.Selected<>nil then
    SelPath:=TV.Selected.GetTextPath;
  // clear
  FreeAndNil(FAllUnitsRootUDNode);
  fAllUnitsTVSearchStartNode:=nil;
  TV.Items.Clear;
  // create nodes
  FAllUnitsRootUDNode:=CreateAllUnitsTree;
  CreateTVNodes(TV,nil,FAllUnitsRootUDNode,true);
  // restore old expanded state
  if OldExpanded<>nil then begin
    OldExpanded.Apply(TV);
    OldExpanded.Free;
  end;
  // update search
  UpdateAllUnitsTreeViewSearch;
  // select an unit
  if PendingUnitDependencyRoute.Count>0 then begin
    TV.Selected:=FindUnitTVNodeWithUnitName(TV,PendingUnitDependencyRoute[0]);
  end;
  if (TV.Selected=nil) and (SelPath<>'') then begin
    TV.Selected:=TV.Items.FindNodeWithTextPath(SelPath);
  end;
  if (TV.Selected=nil) then begin
    SrcEdit:=SourceEditorManagerIntf.ActiveEditor;
    if SrcEdit<>nil then
      TV.Selected:=FindUnitTVNodeWithFilename(TV,SrcEdit.FileName);
  end;
  if (TV.Selected=nil) and (LazarusIDE.ActiveProject<>nil)
  and (LazarusIDE.ActiveProject.MainFile<>nil) then
    TV.Selected:=FindUnitTVNodeWithFilename(TV,LazarusIDE.ActiveProject.MainFile.Filename);

  TV.EndUpdate;
end;

procedure TUnitDependenciesWindow.UpdateSelUnitsTreeView;
var
  TV: TTreeView;
begin
  //debugln(['TUnitDependenciesWindow.UpdateSelUnitsTreeView START']);
  Exclude(FFlags,udwNeedUpdateSelUnitsTreeView);
  TV:=SelUnitsTreeView;
  TV.BeginUpdate;
  // clear
  FreeAndNil(FSelUnitsRootUDNode);
  fSelUnitsTVSearchStartNode:=nil;
  TV.Items.Clear;
  // create nodes
  FSelUnitsRootUDNode:=CreateSelUnitsTree;
  CreateTVNodes(TV,nil,FSelUnitsRootUDNode,true);
  // update search
  UpdateSelUnitsTreeViewSearch;
  TV.EndUpdate;
end;

procedure TUnitDependenciesWindow.UpdateAllUnitsTreeViewSearch;
begin
  Exclude(FFlags,udwNeedUpdateAllUnitsTVSearch);
  SelectNextSearchTV(AllUnitsTreeView,fAllUnitsTVSearchStartNode,true,false);
  AllUnitsTreeView.Invalidate;
end;

procedure TUnitDependenciesWindow.UpdateSelUnitsTreeViewSearch;
begin
  Exclude(FFlags,udwNeedUpdateSelUnitsTVSearch);
  SelectNextSearchTV(SelUnitsTreeView,fSelUnitsTVSearchStartNode,true,false);
  SelUnitsTreeView.Invalidate;
end;

function TUnitDependenciesWindow.FindNextTVNode(StartNode: TTreeNode;
  LowerSearch: string; SearchNext, SkipStart: boolean): TTreeNode;
begin
  Result:=StartNode;
  while Result<>nil do begin
    if ((Result<>StartNode) or (not SkipStart))
    and NodeTextFitsFilter(Result.Text,LowerSearch) then
      exit;
    if SearchNext then
      Result:=Result.GetNext
    else
      Result:=Result.GetPrev;
  end;
end;

function TUnitDependenciesWindow.FindUnitTVNodeWithFilename(TV: TTreeView;
  aFilename: string): TTreeNode;
var
  i: Integer;
  UDNode: TUDNode;
begin
  for i:=0 to TV.Items.Count-1 do begin
    Result:=TV.Items[i];
    if TObject(Result.Data) is TUDNode then begin
      UDNode:=TUDNode(Result.Data);
      if (UDNode.Typ in [udnDirectory,udnUnit])
      and (CompareFilenames(UDNode.Identifier,aFilename)=0) then
        exit;
    end;
  end;
  Result:=nil;
end;

function TUnitDependenciesWindow.FindUnitTVNodeWithUnitName(TV: TTreeView;
  aUnitName: string): TTreeNode;
var
  i: Integer;
  UDNode: TUDNode;
begin
  for i:=0 to TV.Items.Count-1 do begin
    Result:=TV.Items[i];
    if TObject(Result.Data) is TUDNode then begin
      UDNode:=TUDNode(Result.Data);
      if (UDNode.Typ in [udnUnit])
      and (CompareText(ExtractFileNameOnly(UDNode.Identifier),aUnitName)=0) then
        exit;
    end;
  end;
  Result:=nil;
end;

function TUnitDependenciesWindow.GetImgIndex(Node: TUDNode): integer;
begin
  case Node.Typ of
  //udnNone: ;
  udnGroup:
    if IsProjectGroup(Node.Group) then
      Result:=fImgIndexProject
    else
      Result:=fImgIndexPackage;
  udnDirectory: Result:=fImgIndexDirectory;
  //udnInterface: ;
  //udnImplementation: ;
  //udnUsedByInterface: ;
  //udnUsedByImplementation: ;
  udnUnit: Result:=fImgIndexUnit;
  else
    Result:=fImgIndexDirectory;
  end;
end;

function TUnitDependenciesWindow.NodeTextToUnit(NodeText: string): TUGUnit;
var
  AVLNode: TAVLTreeNode;
begin
  AVLNode:=UsesGraph.FilesTree.FindLowest;
  while AVLNode<>nil do begin
    Result:=TUGUnit(AVLNode.Data);
    if NodeText=UGUnitToNodeText(Result) then exit;
    AVLNode:=UsesGraph.FilesTree.FindSuccessor(AVLNode);
  end;
  Result:=nil;
end;

function TUnitDependenciesWindow.UGUnitToNodeText(UGUnit: TUGUnit): string;
begin
  Result:=ExtractFileName(UGUnit.Filename);
end;

function TUnitDependenciesWindow.GetFPCSrcDir: string;
var
  UnitSet: TFPCUnitSetCache;
begin
  UnitSet:=CodeToolBoss.GetUnitSetForDirectory('');
  Result:=UnitSet.FPCSourceDirectory;
end;

function TUnitDependenciesWindow.IsFPCSrcGroup(Group: TUGGroup): boolean;
begin
  Result:=(Group<>nil) and (LeftStr(Group.Name,length(GroupPrefixFPCSrc))=GroupPrefixFPCSrc);
end;

function TUnitDependenciesWindow.IsProjectGroup(Group: TUGGroup): boolean;
begin
  Result:=(Group<>nil) and IsProjectGroup(Group.Name);
end;

function TUnitDependenciesWindow.IsProjectGroup(GroupName: string): boolean;
begin
  Result:=(GroupName=GroupPrefixProject);
end;

function TUnitDependenciesWindow.GetFilename(UDNode: TUDNode): string;
var
  Pkg: TIDEPackage;
begin
  Result:='';
  if UDNode.Typ in [udnUnit,udnDirectory] then
    Result:=UDNode.Identifier
  else if UDNode.Typ=udnGroup then begin
    if IsProjectGroup(UDNode.Group) then begin
      if (LazarusIDE.ActiveProject<>nil) then
        Result:=LazarusIDE.ActiveProject.ProjectInfoFile;
    end else begin
      Pkg:=PackageEditingInterface.FindPackageWithName(UDNode.Group);
      if Pkg<>nil then
        Result:=Pkg.Filename;
    end;
  end;
end;

function TUnitDependenciesWindow.GetAllUnitsFilter(Lower: boolean): string;
begin
  Result:=AllUnitsFilterEdit.Text;
  if Lower then
    Result:=UTF8LowerCase(Result);
end;

function TUnitDependenciesWindow.GetAllUnitsSearch(Lower: boolean): string;
begin
  Result:=AllUnitsSearchEdit.Text;
  if Lower then
    Result:=UTF8LowerCase(Result);
end;

function TUnitDependenciesWindow.GetSelUnitsSearch(Lower: boolean): string;
begin
  Result:=SelUnitsSearchEdit.Text;
  if Lower then
    Result:=UTF8LowerCase(Result);
end;

function TUnitDependenciesWindow.ResStrFilter: string;
begin
  Result:=lisUDFilter;
end;

function TUnitDependenciesWindow.ResStrSearch: string;
begin
  Result:=lisUDSearch;
end;

function TUnitDependenciesWindow.NodeTextFitsFilter(const NodeText,
  LowerFilter: string): boolean;
begin
  Result:=Pos(LowerFilter,UTF8LowerCase(NodeText))>0;
end;

procedure TUnitDependenciesWindow.CreateUsesGraph(out TheUsesGraph: TUsesGraph;
  out TheGroups: TUGGroups);
begin
  TheUsesGraph:=CodeToolBoss.CreateUsesGraph;
  TheGroups:=TUGGroups.Create(TheUsesGraph);
  if not TUDUnit.InheritsFrom(TheUsesGraph.UnitClass) then
    RaiseCatchableException('');
  TheUsesGraph.UnitClass:=TUDUnit;
  if not TUDUses.InheritsFrom(TheUsesGraph.UsesClass) then
    RaiseCatchableException('');
  TheUsesGraph.UsesClass:=TUDUses;
end;

end.