File: codyfindoverloads.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 (1101 lines) | stat: -rw-r--r-- 34,326 bytes parent folder | download | duplicates (5)
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
{
 ***************************************************************************
 *                                                                         *
 *   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:
    Shows all overloads of the procedure/method at sourcee editor position.
    Sortable columns:
      Path: unitnames.classes
      (If not filtered:) Compatibility: exact, compatible, incompatible
      Distance
      Last visited
    Filter:
      Params must be compatible: Yes, No
      (Only for method:) Only descendants, have same ancestor method, all
      (Only for method:) Show abstract methods and interfaces

  ToDo:
    -show line number to distinguish overloads in same unit
    -last visited
    -hint: show file name + param list
}
unit CodyFindOverloads;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, contnrs, Laz_AVL_Tree,
  // LazUtils
  FileUtil, LazLoggerBase, LazUtilities,
  // LCL
  Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, Grids, ComCtrls,
  // Codetools
  CodeToolManager, CodeTree, CodeCache, FindDeclarationTool,
  PascalParserTool, BasicCodeTools, CTUnitGraph, FileProcs, StdCodeTools,
  CodeGraph, CodyUtils, CodyStrConsts,
  // IdeIntf
  LazIDEIntf, IDEWindowIntf, ProjectIntf;

type
  TCFOUnit = class(TUGUnit)
  public
  end;

  TCFONode = class(TCodeGraphNode)
  public
    Tool: TFindDeclarationTool;

    // for ctnProcedure
    Compatibility: TTypeCompatibility;
    // for ctnClass
    TheClassName: string;
    // path and distance to target proc
    Distance: integer;
    ShortestPathNode: TCFONode;
  end;

  TCFOEdgeType = (
    cfoetMethodOf,  // FromNode (proc) is method of ToNode (class)
    cfoetDescendantOf  // FromNode (descendant class) is descendant of ToNode (ancestor class)
    );

  TCFOEdge = class(TCodeGraphEdge)
  public
    Typ: TCFOEdgeType;
  end;

  TCFOProc = class
  public
    XYPos: TCodeXYPosition;
    Name: string;
    ClassPath: string;
    TheUnitName: string;
    Caption: string;
    Params: string;
    Distance: integer;
    Compatibility: TTypeCompatibility;
  end;

  TCFOFilterRelation = (
    cfofrAny, // no filtering
    cfofrOnlyNonMethods,
    cfofrOnlyMethods,
    cfofrOnlyDescendantsOf
    );

type
  TCFOFlag = (
    cfofParsing,
    cfofGatherProcs
    );
  TCFOFlags = set of TCFOFlag;

  { TCodyFindOverloadsWindow }

  TCodyFindOverloadsWindow = class(TForm)
    BtnPanel: TPanel;
    CompatibleParamsCheckBox: TCheckBox;
    FilterGroupBox: TGroupBox;
    HideAbstractCheckBox: TCheckBox;
    JumpToButton: TButton;
    ProgressBar1: TProgressBar;
    RefreshButton: TButton;
    RelationComboBox: TComboBox;
    RelationLabel: TLabel;
    ResultsGroupBox: TGroupBox;
    ResultsStringGrid: TStringGrid;
    Timer1: TTimer;
    procedure CompatibleParamsCheckBoxChange(Sender: TObject);
    procedure FormClose(Sender: TObject; var {%H-}CloseAction: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure HideAbstractCheckBoxChange(Sender: TObject);
    procedure JumpToButtonClick(Sender: TObject);
    procedure OnIdle(Sender: TObject; var Done: Boolean);
    procedure RefreshButtonClick(Sender: TObject);
    procedure RelationComboBoxChange(Sender: TObject);
    procedure ResultsStringGridColRowExchanged(Sender: TObject;
      IsColumn: Boolean; sIndex, tIndex: Integer);
    procedure ResultsStringGridCompareCells(Sender: TObject; ACol, ARow, BCol,
      BRow: Integer; var Result: integer);
    procedure ResultsStringGridMouseDown(Sender: TObject; {%H-}Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure Timer1Timer(Sender: TObject);
  private
    FFilterAncestor: string;
    FFilterRelation: TCFOFilterRelation;
    FHideAbstractMethods: Boolean;
    FIdleConnected: boolean;
    FFlags: TCFOFlags;
    FProcList: TObjectList;
    FTargetInProject: boolean;
    FTargetName: string;
    FTargetPath: string;
    FTargetXYPosition: TCodeXYPosition;
    FUsesGraph: TUsesGraph;
    function GetProcCount: integer;
    function GetProcs(Index: integer): TCFOProc;
    procedure ReadRelationComboBox;
    procedure SetIdleConnected(AValue: boolean);
    procedure CreateUsesGraph(out TheUsesGraph: TUsesGraph);
    procedure FreeUsesGraph;
    procedure StartParsing;
    procedure AbortParsing;
    procedure AddStartAndTargetUnits;
    procedure GatherProcsOfAllUnits;
    function AddClassNode(NodeGraph: TCodeGraph; Tool: TFindDeclarationTool;
      ClassNode: TCodeTreeNode): TCFONode;
    procedure AddAncestors(NodeGraph: TCodeGraph; Tool: TFindDeclarationTool;
      ClassNode: TCodeTreeNode);
    procedure AddProcNode(NodeGraph: TCodeGraph; Tool: TFindDeclarationTool;
      ProcNode: TCodeTreeNode; TargetCleanPos: integer;
      var TargetGraphNode: TCFONode);
    procedure GatherProcsOfUnit(NodeGraph: TCodeGraph;
      CurUnit: TCFOUnit; var TargetGraphNode: TCFONode);
    function IsClassNodeDescendantOf(NodeGraph: TCodeGraph;
      GraphClassNode: TCFONode; Ancestor: string): boolean;
    procedure CalcCompatibilities(NodeGraph: TCodeGraph; TargetGraphNode: TCFONode);
    procedure CalcDistances(NodeGraph: TCodeGraph; TargetGraphNode: TCFONode);
    procedure CreateProcList(NodeGraph: TCodeGraph; TargetGraphNode: TCFONode;
      out NewProclist: TObjectList);
    procedure FillGrid;
    function GetDefaultCaption: string;
    procedure FillFilterControls(ProcTool: TFindDeclarationTool;
      ProcNode: TCodeTreeNode);
    procedure FilterChanged;
  protected
    procedure UpdateShowing; override;
  public
    procedure JumpToIdentifier;
    function Init: boolean;
    property IdleConnected: boolean read FIdleConnected write SetIdleConnected;
    property ProcCount: integer read GetProcCount;
    property Procs[Index: integer]: TCFOProc read GetProcs;
    property TargetXYPosition: TCodeXYPosition read FTargetXYPosition;
    property TargetName: string read FTargetName;
    property TargetPath: string read FTargetPath;
    property TargetInProject: boolean read FTargetInProject;
    property UsesGraph: TUsesGraph read FUsesGraph;
    property FilterRelation: TCFOFilterRelation read FFilterRelation;
    property FilterAncestor: string read FFilterAncestor;
    property HideAbstractMethods: Boolean read FHideAbstractMethods;
  end;

var
  CodyFindOverloadsWindow: TCodyFindOverloadsWindow;

procedure ShowFindOverloadsClicked(Sender: TObject);
procedure ShowFindOverloads(State: TIWGetFormState = iwgfShowOnTop);

function CompareCFONodeByDistance(Node1, Node2: Pointer): integer;

implementation

procedure ShowFindOverloadsClicked(Sender: TObject);
begin
  ShowFindOverloads;
end;

procedure ShowFindOverloads(State: TIWGetFormState);
begin
  if CodyFindOverloadsWindow = nil then
    IDEWindowCreators.CreateForm(CodyFindOverloadsWindow,TCodyFindOverloadsWindow,
       State=iwgfDisabled,LazarusIDE.OwningComponent)
  else if State=iwgfDisabled then
    CodyFindOverloadsWindow.DisableAlign;
  if State>=iwgfShow then
    IDEWindowCreators.ShowForm(CodyFindOverloadsWindow,State=iwgfShowOnTop);
end;

function CompareCFONodeByDistance(Node1, Node2: Pointer): integer;
var
  n1: TCFONode absolute Node1;
  n2: TCFONode absolute Node2;
begin
  if n1.Distance<n2.Distance then
    exit(-1)
  else if n1.Distance>n2.Distance then
    exit(1)
  else
    Result:=ComparePointers(n1.Node,n2.Node);
end;

{$R *.lfm}

{ TCodyFindOverloadsWindow }

procedure TCodyFindOverloadsWindow.FormCreate(Sender: TObject);
begin
  AbortParsing;
  FProcList:=TObjectList.Create(true);

  Caption:=GetDefaultCaption;
  RefreshButton.Caption:=crsRefresh;
  JumpToButton.Caption:=crsJumpTo2;

  FilterGroupBox.Caption:=crsFilter2;
  CompatibleParamsCheckBox.Caption:=crsOnlyProceduresWithCompatibleParameters;
  CompatibleParamsCheckBox.Hint:=
    crsIfUncheckedListAlsoProceduresWithSameNameAndIncomp;
  HideAbstractCheckBox.Caption:=
    crsHideAbstractMethodsAndMethodsOfClassInterfaces;
  RelationLabel.Caption:=crsRelations;
  ResultsStringGrid.Visible:=false;
end;

procedure TCodyFindOverloadsWindow.FormDestroy(Sender: TObject);
begin
  FreeAndNil(FProcList);
end;

procedure TCodyFindOverloadsWindow.HideAbstractCheckBoxChange(Sender: TObject);
begin
  fHideAbstractMethods:=HideAbstractCheckBox.Checked;
  FilterChanged;
end;

procedure TCodyFindOverloadsWindow.FormClose(Sender: TObject;
  var CloseAction: TCloseAction);
begin
  AbortParsing;
  FreeUsesGraph;
end;

procedure TCodyFindOverloadsWindow.CompatibleParamsCheckBoxChange(
  Sender: TObject);
begin
  FilterChanged;
end;

procedure TCodyFindOverloadsWindow.JumpToButtonClick(Sender: TObject);
begin
  JumpToIdentifier;
end;

procedure TCodyFindOverloadsWindow.OnIdle(Sender: TObject; var Done: Boolean);
var
  Completed: boolean;
begin
  if cfofParsing in FFlags then begin
    fUsesGraph.Parse(true,Completed,200);
    if Completed then begin
      FFlags:=FFlags-[cfofParsing]+[cfofGatherProcs];
    end;
  end else if cfofGatherProcs in FFlags then begin
    GatherProcsOfAllUnits;
  end else
    IdleConnected:=false;
  Done:=not IdleConnected;
end;

procedure TCodyFindOverloadsWindow.RefreshButtonClick(Sender: TObject);
begin
  if cfofParsing in FFlags then exit;
  Init;
end;

procedure TCodyFindOverloadsWindow.RelationComboBoxChange(Sender: TObject);
begin
  ReadRelationComboBox;
  FilterChanged;
end;

procedure TCodyFindOverloadsWindow.ResultsStringGridColRowExchanged(
  Sender: TObject; IsColumn: Boolean; sIndex, tIndex: Integer);
begin
  if (not IsColumn) and (sIndex>0) and (sIndex<=ProcCount)
  and (tIndex>0) and (tIndex<=ProcCount) then
    FProcList.Exchange(sIndex-1,tIndex-1);
end;

procedure TCodyFindOverloadsWindow.ResultsStringGridCompareCells(
  Sender: TObject; ACol, ARow, BCol, BRow: Integer; var Result: integer);
var
  AProc, BProc: TCFOProc;
begin
  if (ARow>0) and (ARow<=ProcCount) and (ACol=BCol)
  and (BRow>0) and (BRow<=ProcCount) then begin
    AProc:=Procs[ARow-1];
    BProc:=Procs[BRow-1];
    case ACol of
    0: Result:=CompareText(AProc.Caption,BProc.Caption);
    1: Result:=ord(AProc.Compatibility)-ord(BProc.Compatibility);
    2: Result:=ord(AProc.Distance)-ord(BProc.Distance);
    end;
    if ResultsStringGrid.SortOrder=soDescending then
      Result:=-Result;
    //debugln(['TCodyFindOverloadsWindow.ResultsStringGridCompareCells "',AProc.Caption,'" "',BProc.Caption,'" ',Result]);
  end else
    debugln(['TCodyFindOverloadsWindow.ResultsStringGridCompareCells invalid ACol=',ACol,' ARow=',ARow,' BCol=',BCol,' BRow=',BRow]);
end;

procedure TCodyFindOverloadsWindow.ResultsStringGridMouseDown(Sender: TObject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  Col, Row: Longint;
begin
  Col:=0;
  Row:=0;
  ResultsStringGrid.MouseToCell(X,Y,Col,Row);
  if (Row>0) and (ssDouble in Shift) then
    JumpToIdentifier;
end;

procedure TCodyFindOverloadsWindow.Timer1Timer(Sender: TObject);
var
  Cnt: Integer;
begin
  if (FUsesGraph=nil) then exit;
  Cnt:=0;
  if FUsesGraph.FilesTree<>nil then
    Cnt:=FUsesGraph.FilesTree.Count;
  ResultsGroupBox.Caption:=Format(crsScanningSUnits, [IntToStr(Cnt)]);
end;

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

function TCodyFindOverloadsWindow.GetProcCount: integer;
begin
  Result:=FProcList.Count;
end;

function TCodyFindOverloadsWindow.GetProcs(Index: integer): TCFOProc;
begin
  Result:=TCFOProc(FProcList[Index]);
end;

procedure TCodyFindOverloadsWindow.ReadRelationComboBox;
var
  RelationText: TCaption;
begin
  RelationText:=RelationComboBox.Text;
  if RelationText=crsOnlyMethods then
    FFilterRelation:=cfofrOnlyMethods
  else if RelationText=crsOnlyNonMethods then
    FFilterRelation:=cfofrOnlyNonMethods
  else if GetPatternValue1(crsOnlyDescendantsOf, '%s', RelationText,
    FFilterAncestor)
  then begin
    FFilterRelation:=cfofrOnlyDescendantsOf;
  end else
    FFilterRelation:=cfofrAny;
end;

procedure TCodyFindOverloadsWindow.CreateUsesGraph(out TheUsesGraph: TUsesGraph
  );
begin
  TheUsesGraph:=CodeToolBoss.CreateUsesGraph;
  if not TCFOUnit.InheritsFrom(TheUsesGraph.UnitClass) then
    RaiseCatchableException('');
  TheUsesGraph.UnitClass:=TCFOUnit;
end;

procedure TCodyFindOverloadsWindow.FreeUsesGraph;
begin
  FreeAndNil(FUsesGraph);
end;

procedure TCodyFindOverloadsWindow.StartParsing;
begin
  if (FUsesGraph<>nil) or (cfofParsing in FFlags) then
    RaiseCatchableException('');
  Include(FFlags,cfofParsing);

  ProgressBar1.Visible:=true;
  ProgressBar1.Style:=pbstMarquee;
  ResultsGroupBox.Caption:=crsScanning;
  Timer1.Enabled:=true;
  RefreshButton.Enabled:=false;

  CreateUsesGraph(FUsesGraph);

  LazarusIDE.BeginCodeTools;
  AddStartAndTargetUnits;

  IdleConnected:=true;
end;

procedure TCodyFindOverloadsWindow.AbortParsing;
begin
  FFlags:=[];
  IdleConnected:=false;
  ProgressBar1.Visible:=false;
  if not (csDestroying in ComponentState) then
    RefreshButton.Enabled:=true;
  FreeUsesGraph;
end;

procedure TCodyFindOverloadsWindow.AddStartAndTargetUnits;
var
  aProject: TLazProject;
begin
  FUsesGraph.TargetAll:=true;
  // project lpr
  aProject:=LazarusIDE.ActiveProject;
  if (aProject<>nil) and (aProject.MainFile<>nil) then
    FUsesGraph.AddStartUnit(aProject.MainFile.Filename);
end;

procedure TCodyFindOverloadsWindow.GatherProcsOfAllUnits;
var
  FileNode: TAVLTreeNode;
  CurUnit: TCFOUnit;
  NodeGraph: TCodeGraph;
  TargetGraphNode: TCFONode;
  NewProcList: TObjectList;
  s: String;
begin
  Exclude(FFlags,cfofGatherProcs);
  Timer1.Enabled:=false;
  // hide progress bar and update stats
  ProgressBar1.Visible:=false;
  RefreshButton.Enabled:=true;
  ResultsGroupBox.Caption:=Format(crsUnitsS, [IntToStr(FUsesGraph.FilesTree.
    Count)]);

  if FUsesGraph=nil then
    exit;
  debugln(['TCodyFindOverloadsWindow.GatherProcsOfAllUnits START Proc="',TargetName,'"']);

  // get filter
  FHideAbstractMethods:=HideAbstractCheckBox.Checked;
  ReadRelationComboBox;

  NodeGraph:=TCodeGraph.Create(TCFONode,TCFOEdge);
  try
    TargetGraphNode:=nil;
    FileNode:=FUsesGraph.FilesTree.FindLowest;
    while FileNode<>nil do begin
      CurUnit:=TCFOUnit(FileNode.Data);
      GatherProcsOfUnit(NodeGraph,CurUnit,TargetGraphNode);
      FileNode:=FUsesGraph.FilesTree.FindSuccessor(FileNode);
    end;

    FTargetInProject:=TargetGraphNode<>nil;
    if TargetInProject then begin
      CalcCompatibilities(NodeGraph,TargetGraphNode);
      CalcDistances(NodeGraph,TargetGraphNode);
    end;

    CreateProcList(NodeGraph,TargetGraphNode,NewProcList);
    FreeAndNil(FProcList);
    FProcList:=NewProcList;
    if ProcCount=0 then begin
      s:=', ';
      if TargetInProject then begin
        s+=crsNoOverloadsFoundInProjectUnits;
      end else begin
        s+=crsErrorCursorIsNotInAProjectUnit;
      end;
      ResultsGroupBox.Caption:=ResultsGroupBox.Caption+s;
    end;

    FillGrid;
  finally
    NodeGraph.Free;
  end;
  debugln(['TCodyFindOverloadsWindow.GatherProcsOfAllUnits END']);
end;

function TCodyFindOverloadsWindow.AddClassNode(NodeGraph: TCodeGraph;
  Tool: TFindDeclarationTool; ClassNode: TCodeTreeNode): TCFONode;
begin
  if ClassNode=nil then
    RaiseCatchableException('');
  Result:=TCFONode(NodeGraph.GetGraphNode(ClassNode,false));
  if Result<>nil then exit;
  //debugln(['AddClassNode ',Tool.ExtractClassName(ClassNode,false)]);
  Result:=TCFONode(NodeGraph.AddGraphNode(ClassNode));
  Result.Tool:=Tool;
  Result.TheClassName:=Tool.ExtractClassName(ClassNode,false);
  AddAncestors(NodeGraph,Tool,ClassNode);
end;

procedure TCodyFindOverloadsWindow.AddAncestors(NodeGraph: TCodeGraph;
  Tool: TFindDeclarationTool; ClassNode: TCodeTreeNode);
var
  ListOfPFindContext: TFPList;
  Params: TFindDeclarationParams;
  Ancestor: PFindContext;
  i: Integer;
  Edge: TCFOEdge;
begin
  //debugln(['AddAncestors ',Tool.ExtractClassName(ClassNode,false)]);
  ListOfPFindContext:=nil;
  Params:=TFindDeclarationParams.Create(nil);
  try
    Tool.FindAncestorsOfClass(ClassNode,ListOfPFindContext,Params,true,false);
    if ListOfPFindContext<>nil then begin
      for i:=0 to ListOfPFindContext.Count-1 do begin
        Ancestor:=PFindContext(ListOfPFindContext[i]);
        AddClassNode(NodeGraph,Ancestor^.Tool,Ancestor^.Node);
        // create edge "descendant of"
        Edge:=TCFOEdge(NodeGraph.AddEdge(ClassNode,Ancestor^.Node));
        Edge.Typ:=cfoetDescendantOf;
      end;
    end;
  finally
    Params.Free;
    FreeListOfPFindContext(ListOfPFindContext);
  end;
end;

procedure TCodyFindOverloadsWindow.AddProcNode(NodeGraph: TCodeGraph;
  Tool: TFindDeclarationTool; ProcNode: TCodeTreeNode;
  TargetCleanPos: integer; var TargetGraphNode: TCFONode);
var
  CurProcName: String;
  GraphProcNode, GraphClassNode: TCFONode;
  ClassNode: TCodeTreeNode;
  Edge: TCFOEdge;
begin
  // check name
  CurProcName:=Tool.ExtractProcName(ProcNode,[phpWithoutClassName]);
  if CompareIdentifiers(PChar(CurProcName),PChar(FTargetName))<>0 then exit;

  //debugln(['TCodyFindOverloadsWindow.GatherProcsOfUnit ',Tool.CleanPosToStr(ProcNode.StartPos,true)]);

  // check if method
  ClassNode:=ProcNode.Parent;
  while ClassNode<>nil do begin
    if ClassNode.Desc in AllClasses then break;
    ClassNode:=ClassNode.Parent;
  end;
  if ClassNode<>nil then begin
    // a method
    if HideAbstractMethods then begin
      if ClassNode.Desc in AllClassInterfaces then exit;
      if Tool.ProcNodeHasSpecifier(ProcNode,psABSTRACT) then exit;
    end;
    if FilterRelation=cfofrOnlyNonMethods then
      exit;
  end else begin
    // a non method
    if FilterRelation in [cfofrOnlyMethods,cfofrOnlyDescendantsOf] then
      exit;
  end;

  // add node
  GraphProcNode:=TCFONode(NodeGraph.AddGraphNode(ProcNode));
  GraphProcNode.Tool:=Tool;
  GraphProcNode.Compatibility:=tcCompatible; // default, will be set later

  // check if this is the target proc
  if (TargetGraphNode=nil)
  and (ProcNode.StartPos<=TargetCleanPos)
  and (TargetCleanPos<ProcNode.EndPos)
  and (TargetPath=Tool.ExtractProcName(ProcNode,[phpAddClassName])) then begin
    TargetGraphNode:=GraphProcNode;
    TargetGraphNode.Compatibility:=tcExact;
  end;

  // add edges
  if ClassNode<>nil then begin
    // create nodes for class and ancestors
    GraphClassNode:=AddClassNode(NodeGraph,Tool,ClassNode);
    if (FilterRelation=cfofrOnlyDescendantsOf)
    and (not IsClassNodeDescendantOf(NodeGraph,GraphClassNode,FilterAncestor))
    then begin
      NodeGraph.DeleteGraphNode(ProcNode);
      exit;
    end;

    // create edge "is method of"
    Edge:=TCFOEdge(NodeGraph.AddEdge(ProcNode,ClassNode));
    Edge.Typ:=cfoetMethodOf;
  end;
end;

procedure TCodyFindOverloadsWindow.GatherProcsOfUnit(NodeGraph: TCodeGraph;
  CurUnit: TCFOUnit; var TargetGraphNode: TCFONode);
var
  Tool: TStandardCodeTool;
  ProcNode: TCodeTreeNode;
  TargetCleanPos: integer;
begin
  if ugufLoadError in CurUnit.Flags then exit;
  if not (ugufReached in CurUnit.Flags) then exit; // this unit was not reached
  if ugufIsIncludeFile in CurUnit.Flags then exit;
  Tool:=CurUnit.Tool;
  if (TargetGraphNode<>nil)
  or (Tool.CaretToCleanPos(TargetXYPosition,TargetCleanPos)<>0) then
    TargetCleanPos:=0;

  ProcNode:=Tool.Tree.Root;
  while ProcNode<>nil do begin
    if ProcNode.Desc in [ctnImplementation,ctnBeginBlock] then break;
    if ProcNode.Desc=ctnProcedure then
      AddProcNode(NodeGraph,Tool,ProcNode,TargetCleanPos,TargetGraphNode);
    ProcNode:=ProcNode.Next;
  end;
end;

function TCodyFindOverloadsWindow.IsClassNodeDescendantOf(
  NodeGraph: TCodeGraph; GraphClassNode: TCFONode; Ancestor: string): boolean;
var
  AVLNode: TAVLTreeNode;
  Edge: TCFOEdge;
begin
  if CompareText(Ancestor,GraphClassNode.TheClassName)=0 then exit(true);
  if GraphClassNode.OutTree=nil then exit(false);
  AVLNode:=GraphClassNode.OutTree.FindLowest;
  while AVLNode<>nil do begin
    Edge:=TCFOEdge(AVLNode.Data);
    if Edge.Typ=cfoetDescendantOf then begin
      if IsClassNodeDescendantOf(NodeGraph,TCFONode(Edge.ToNode),Ancestor) then
        exit(true);
    end;
    AVLNode:=GraphClassNode.OutTree.FindSuccessor(AVLNode);
  end;
  Result:=false;
end;

procedure TCodyFindOverloadsWindow.CalcCompatibilities(NodeGraph: TCodeGraph;
  TargetGraphNode: TCFONode);
var
  AVLNode: TAVLTreeNode;
  GraphNode: TCFONode;
  Params: TFindDeclarationParams;
  ExprList: TExprTypeList;
  ParamNode: TCodeTreeNode;
begin
  ExprList:=nil;
  Params:=TFindDeclarationParams.Create(TargetGraphNode.Tool,TargetGraphNode.Node);
  try
    ExprList:=TargetGraphNode.Tool.CreateParamExprListFromProcNode(
                                                   TargetGraphNode.Node,Params);

    AVLNode:=NodeGraph.Nodes.FindLowest;
    while AVLNode<>nil do begin
      GraphNode:=TCFONode(AVLNode.Data);
      if GraphNode.Node.Desc=ctnProcedure then begin
        if GraphNode=TargetGraphNode then
          GraphNode.Compatibility:=tcExact
        else begin
          ParamNode:=GraphNode.Tool.GetFirstParameterNode(GraphNode.Node);
          GraphNode.Compatibility:=
            GraphNode.Tool.IsParamNodeListCompatibleToExprList(ExprList,
              ParamNode,Params);
          //debugln(['TCodyFindOverloadsWindow.CalcCompatibilities ',GraphNode.Tool.ExtractProcName(GraphNode.Node,[phpAddClassName]),' Compatible=',TypeCompatibilityNames[GraphNode.Compatibility]]);
        end;
      end;
      AVLNode:=NodeGraph.Nodes.FindSuccessor(AVLNode);
    end;
  finally
    ExprList.Free;
    Params.Free;
  end;
end;

procedure TCodyFindOverloadsWindow.CalcDistances(NodeGraph: TCodeGraph;
  TargetGraphNode: TCFONode);
var
  Unvisited: TAVLTree;

  procedure UpdateDistancesAlongEdges(GraphNode: TCFONode; Edges: TAVLTree);
  var
    AVLNode: TAVLTreeNode;
    Edge: TCFOEdge;
    NewDistance: Integer;
    OtherNode: TCFONode;
    WasUnvisited: Boolean;
  begin
    if Edges=nil then exit;
    AVLNode:=Edges.FindLowest;
    while AVLNode<>nil do begin
      Edge:=TCFOEdge(AVLNode.Data);
      NewDistance:=GraphNode.Distance;
      case Edge.Typ of
      cfoetMethodOf: ; // methods within one class are close
      cfoetDescendantOf:
        if GraphNode=Edge.FromNode then
          NewDistance+=100  // going to the ancestors
        else
          NewDistance+=1;  // going to the descendants
      end;
      if GraphNode=Edge.FromNode then begin
        OtherNode:=TCFONode(Edge.ToNode);
      end else begin
        OtherNode:=TCFONode(Edge.FromNode);
      end;
      if NewDistance<OtherNode.Distance then begin
        WasUnvisited:=Unvisited.Find(OtherNode)<>nil;
        if not WasUnvisited then
          RaiseCatchableException(''); // visited nodes must have minimal distance
        Unvisited.Remove(OtherNode);
        OtherNode.Distance:=NewDistance;
        OtherNode.ShortestPathNode:=GraphNode;
        Unvisited.Add(OtherNode);
      end;
      AVLNode:=Edges.FindSuccessor(AVLNode);
    end;
  end;

var
  AVLNode: TAVLTreeNode;
  GraphNode: TCFONode;
begin
  //debugln(['TCodyFindOverloadsWindow.CalcDistances ']);

  Unvisited:=TAVLTree.Create(@CompareCFONodeByDistance);
  try
    // Dijkstra's shotest path algorithm

    // build Unvisited queue, set Distance of TargetGraphNode to 0
    // infinite Distance all other
    AVLNode:=NodeGraph.Nodes.FindLowest;
    while AVLNode<>nil do begin
      GraphNode:=TCFONode(AVLNode.Data);
      if GraphNode=TargetGraphNode then
        GraphNode.Distance:=0
      else
        GraphNode.Distance:=100000;
      GraphNode.ShortestPathNode:=nil;
      Unvisited.Add(GraphNode);
      AVLNode:=NodeGraph.Nodes.FindSuccessor(AVLNode);
    end;

    // for each node with minimum distance ...
    while Unvisited.Count>0 do begin
      // get unvisited node with minimum distance
      AVLNode:=Unvisited.FindLowest;
      GraphNode:=TCFONode(AVLNode.Data);
      //debugln(['TCodyFindOverloadsWindow.CalcDistances GraphNode=',GraphNode.Tool.ExtractProcName(GraphNode.Node,[phpAddClassName]),' Distance=',GraphNode.Distance]);
      Unvisited.Delete(AVLNode);
      UpdateDistancesAlongEdges(GraphNode,GraphNode.InTree);
      UpdateDistancesAlongEdges(GraphNode,GraphNode.OutTree);
    end;
  finally
    Unvisited.Free;
  end;
end;

procedure TCodyFindOverloadsWindow.CreateProcList(NodeGraph: TCodeGraph;
  TargetGraphNode: TCFONode; out NewProclist: TObjectList);
var
  AVLNode: TAVLTreeNode;
  aProc: TCFOProc;
  GraphNode: TCFONode;
  Tool: TFindDeclarationTool;
  Node: TCodeTreeNode;
  OnlyCompatible: Boolean;
begin
  NewProcList:=TObjectList.Create(true);
  OnlyCompatible:=CompatibleParamsCheckBox.Checked;

  AVLNode:=NodeGraph.Nodes.FindLowest;
  while AVLNode<>nil do begin
    GraphNode:=TCFONode(AVLNode.Data);
    AVLNode:=NodeGraph.Nodes.FindSuccessor(AVLNode);
    if GraphNode=TargetGraphNode then continue;
    if GraphNode.Node.Desc<>ctnProcedure then continue;
    if OnlyCompatible and (GraphNode.Compatibility=tcIncompatible) then continue;

    aProc:=TCFOProc.Create;

    Tool:=GraphNode.Tool;
    Node:=GraphNode.Node;
    Tool.CleanPosToCaret(Node.FirstChild.StartPos,aProc.XYPos);
    aProc.Name:=Tool.ExtractProcName(Node,[phpWithoutClassName]);
    aProc.ClassPath:=Tool.ExtractClassPath(Node);
    aProc.TheUnitName:=Tool.GetSourceName(false);
    aProc.Compatibility:=GraphNode.Compatibility;
    aProc.Distance:=GraphNode.Distance;
    NewProcList.Add(aProc);
  end;
end;

procedure TCodyFindOverloadsWindow.FillGrid;
var
  Grid: TStringGrid;
  Row: Integer;
  s, OldSelectedProcName: String;
  aProc: TCFOProc;
begin
  Grid:=ResultsStringGrid;
  if Grid.RowCount>0 then begin
    Grid.BeginUpdate;
    OldSelectedProcName:='';
    if Grid.Row>0 then
      OldSelectedProcName:=Grid.Cells[0,Grid.Row];
    Grid.Columns[0].Title.Caption:=crsName;
    Grid.Columns[1].Title.Caption:=crsCompatibility;
    Grid.Columns[2].Title.Caption:=crsDistance;

    Grid.RowCount:=ProcCount+1;
    for Row:=1 to ProcCount do begin
      aProc:=Procs[Row-1];

      // path
      s:=aProc.TheUnitName+': ';
      if aProc.ClassPath<>'' then
        s+=aProc.ClassPath+'.';
      s+=aProc.Name;
      aProc.Caption:=s;
      Grid.Cells[0,Row]:=s;
      if s=OldSelectedProcName then
        Grid.Row:=Row;

      case aProc.Compatibility of
      tcExact: s:=crsExact;
      tcCompatible: s:=crsCompatible;
      tcIncompatible: s:=crsIncompatible;
      end;
      Grid.Cells[1,Row]:=s;

      Grid.Cells[2,Row]:=IntToStr(aProc.Distance);
    end;

    Grid.SortColRow(true,0);
    Grid.Visible:=true;
    Grid.EndUpdate(true);

    Grid.HandleNeeded;
    Grid.AutoAdjustColumns;
  end else begin
    Grid.Visible:=false;
  end;

  JumpToButton.Enabled:=Grid.Row>0;
end;

function TCodyFindOverloadsWindow.GetDefaultCaption: string;
begin
  Result:=crsCodyFindOverloads;
end;

procedure TCodyFindOverloadsWindow.FillFilterControls(
  ProcTool: TFindDeclarationTool; ProcNode: TCodeTreeNode);
var
  sl: TStringList;
  ClassNode: TCodeTreeNode;
  ListOfPFindContext: TFPList;
  i: Integer;
  aContext: PFindContext;
begin
  // RelationComboBox
  sl:=TStringList.Create;
  try
    ClassNode:=ProcNode;
    while (ClassNode<>nil) and (not (ClassNode.Desc in AllClasses)) do
      ClassNode:=ClassNode.Parent;
    if ClassNode<>nil then begin
      // method
      ListOfPFindContext:=nil;
      try
        try
          ProcTool.FindClassAndAncestors(ClassNode,ListOfPFindContext,false);
        except
        end;
        if ListOfPFindContext<>nil then begin
          for i:=0 to ListOfPFindContext.Count-1 do begin
            aContext:=PFindContext(ListOfPFindContext[i]);
            sl.Add(Format(crsOnlyDescendantsOf, [aContext^.Tool.ExtractClassName
              (aContext^.Node, false)]));
          end;
        end else begin
          sl.Add(Format(crsOnlyDescendantsOf, [ProcTool.ExtractClassName(
            ClassNode, false)]));
        end;
      finally
        FreeListOfPFindContext(ListOfPFindContext);
      end;
      sl.Add(crsOnlyMethods);
    end else begin
      // procedure, non method
      sl.Add(crsOnlyNonMethods);
    end;
    sl.Add(crsAny);
    RelationComboBox.Items:=sl;
    if sl.IndexOf(RelationComboBox.Text)<0 then
      RelationComboBox.Text:=crsAny;
  finally
    sl.Free;
  end;
end;

procedure TCodyFindOverloadsWindow.FilterChanged;
begin
  if csDestroying in ComponentState then exit;
  AbortParsing;
  StartParsing;
end;

procedure TCodyFindOverloadsWindow.UpdateShowing;
begin
  inherited UpdateShowing;
  if IsVisible and (FUsesGraph=nil) then begin
    Init;
  end;
end;

procedure TCodyFindOverloadsWindow.JumpToIdentifier;
var
  i: Integer;
  aProc: TCFOProc;
begin
  i:=ResultsStringGrid.Row-1;
  if (i<0) or (i>=ProcCount) then exit;
  aProc:=Procs[i];
  LazarusIDE.DoOpenFileAndJumpToPos(aProc.XYPos.Code.Filename,
    Point(aProc.XYPos.X,aProc.XYPos.Y),-1,-1,-1,[]);
end;

function TCodyFindOverloadsWindow.Init: boolean;
var
  CurTool: TCodeTool;
  CurNode: TCodeTreeNode;
  CurCodePos: TCodeXYPosition;
  CurCleanPos: integer;

  procedure FindProcDeclaration(ProcTool: TFindDeclarationTool;
    var ProcNode: TCodeTreeNode);
  // find the method declaration of a method body
  // find the forward or interface declaration of a proc body
  var
    Node: TCodeTreeNode;
  begin
    if ProcNode=nil then exit;
    if ProcNode.Desc=ctnProcedureHead then
      ProcNode:=ProcNode.Parent;
    if ProcNode.Desc<>ctnProcedure then exit;
    if ProcNode.GetNodeOfType(ctnInterface)<>nil then exit;
    if ProcTool.NodeIsForwardProc(ProcNode) then exit;
    Node:=ProcTool.FindCorrespondingProcNode(ProcNode,[phpWithoutClassName]);
    if Node=nil then exit;
    ProcNode:=Node;
  end;

  function IsCursorAtProcCall(StatementNode: TCodeTreeNode;
    out ProcTool: TFindDeclarationTool; out ProcNode: TCodeTreeNode): boolean;
  var
    CurIdentStart, CurIdentEnd, NewTopLine: integer;
    NewTool: TFindDeclarationTool;
    NewNode: TCodeTreeNode;
    NewPos: TCodeXYPosition;
  begin
    Result:=true;
    ProcTool:=nil;
    ProcNode:=nil;
    if StatementNode=nil then exit;
    // cursor in statement => check if on a proc call.
    if (CurCodePos.Code=nil) then exit;
    GetIdentStartEndAtPosition(CurTool.Src,CurCleanPos,CurIdentStart,CurIdentEnd);
    if CurIdentStart>=CurIdentEnd then exit;
    DebugLn(['TCodyFindOverloadsDialog.Init.IsCursorAtProcCall checking identifier "',copy(CurTool.Src,CurIdentStart,CurIdentEnd-CurIdentStart),'"']);
    if not CurTool.FindDeclaration(CurCodePos,DefaultFindSmartFlags,
      NewTool,NewNode,NewPos,NewTopLine)
    then begin
      ResultsGroupBox.Caption:=crsParseError;
      LazarusIDE.DoJumpToCodeToolBossError;
      exit(false);
    end;
    if NewNode.Desc in [ctnProcedure,ctnProcedureHead] then begin
      ProcTool:=NewTool;
      ProcNode:=NewNode;
      FindProcDeclaration(ProcTool,ProcNode);
      debugln(['TCodyFindOverloadsDialog.Init.IsCursorAtProcCall TargetProc ',ProcTool.CleanPosToStr(ProcNode.StartPos,true),' Class=',ProcTool.ExtractProcName(ProcNode,[phpAddClassName])]);
    end;
  end;

var
  ProcNode, Node, BeginNode, TargetProcNode: TCodeTreeNode;
  ErrorHandled: boolean;
  CurInitError: TCUParseError;
  TargetTool: TFindDeclarationTool;
begin
  Result:=false;
  AbortParsing;
  if csDestroying in ComponentState then exit;

  Caption:=GetDefaultCaption;
  JumpToButton.Enabled:=false;
  FTargetName:='';
  FTargetPath:='';
  FTargetXYPosition:=CleanCodeXYPosition;
  FreeUsesGraph;

  // parse source
  CurInitError:=ParseTilCursor(CurTool, CurCleanPos, CurNode, ErrorHandled, true, @CurCodePos);
  if CurInitError<>cupeSuccess then begin
    ResultsGroupBox.Caption:=crsParseError;
    exit;
  end;

  // find target proc node
  ProcNode:=nil;
  BeginNode:=nil;
  Node:=CurNode;
  TargetTool:=nil;
  TargetProcNode:=nil;
  while Node<>nil do begin
    if Node.Desc=ctnProcedure then begin
      ProcNode:=Node;
      break;
    end else if (BeginNode=nil) and (Node.Desc=ctnBeginBlock) then begin
      BeginNode:=Node;
      if not IsCursorAtProcCall(BeginNode,TargetTool,TargetProcNode) then
        exit;
    end;
    Node:=Node.Parent;
  end;

  FindProcDeclaration(CurTool,ProcNode);
  if ProcNode<>nil then begin
    // ToDo: add to visited procs
    debugln(['TCodyFindOverloadsDialog.Init ContextProc ',CurTool.CleanPosToStr(ProcNode.StartPos,true),' Class=',CurTool.ExtractProcName(ProcNode,[phpAddClassName])]);
  end;

  if TargetProcNode=nil then begin
    TargetTool:=CurTool;
    TargetProcNode:=ProcNode;
  end;
  if TargetProcNode=nil then begin
    ResultsGroupBox.Caption:=
      crsErrorNeedSourceEditorAtProcedureCallOrDeclaration;
    exit;
  end;

  FTargetName:=TargetTool.ExtractProcName(TargetProcNode,[phpWithoutClassName]);
  FTargetPath:=TargetTool.ExtractProcName(TargetProcNode,[phpAddClassName]);
  TargetTool.CleanPosToCaret(TargetProcNode.StartPos,FTargetXYPosition);
  Caption:=GetDefaultCaption+' - '+FTargetPath;

  FillFilterControls(TargetTool,TargetProcNode);

  StartParsing;

  Result:=true;
end;

end.