This file is indexed.

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

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

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
{
/***************************************************************************
                             unitdependencies.pas
                             --------------------

 ***************************************************************************/

 ***************************************************************************
 *                                                                         *
 *   This source is free software; you can redistribute it and/or modify   *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This code is distributed in the hope that it will be useful, but      *
 *   WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *
 *   General Public License for more details.                              *
 *                                                                         *
 *   A copy of the GNU General Public License is available on the World    *
 *   Wide Web at <http://www.gnu.org/copyleft/gpl.html>. You can also      *
 *   obtain it by writing to the Free Software Foundation,                 *
 *   Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.        *
 *                                                                         *
 ***************************************************************************
 
 
  Author: Mattias Gaertner
 
  Abstract:
    Defines the TUnitDependenciesView form.
    The Unit Dependencies shows the used units in a treeview.
 
}
unit UnitDependencies;

{$mode objfpc}{$H+}

interface

{$I ide.inc}

uses
  {$IFDEF IDE_MEM_CHECK}
  MemCheck,
  {$ENDIF}
  Classes, SysUtils, Controls, Forms, Dialogs, Buttons, ComCtrls, StdCtrls,
  Graphics, LCLType, FileUtil, LCLProc,
  CodeToolManager, CodeCache,
  IDECommands, IDEImagesIntf,
  EnvironmentOpts, IDEOptionDefs, LazarusIDEStrConsts, InputHistory;
  
type

  { TUnitNode }
  
  TUnitNodeFlag = (
    unfImplementation, // this unit was used in an implementation uses section
    unfCircle,         // this unit is the parent of itself
    unfForbiddenCircle,// forbidden circle
    unfFileNotFound,   // this unit file was not found
    unfParseError      // error parsing the source
    );
  TUnitNodeFlags = set of TUnitNodeFlag;
  
  TUnitNodeSourceType = (
    unstUnknown,
    unstUnit,
    unstProgram,
    unstLibrary,
    unstPackage
    );
    
const
  UnitNodeSourceTypeNames: array[TUnitNodeSourceType] of string = (
    '?',
    'Unit',
    'Program',
    'Library',
    'Package'
    );

type
  TUnitDependenciesView = class;


  { TUnitNode }

  TUnitNode = class
  private
    FChildCount: integer;
    FCodeBuffer: TCodeBuffer;
    FFilename: string;
    FFirstChild: TUnitNode;
    FFlags: TUnitNodeFlags;
    FLastChild: TUnitNode;
    FNextSibling: TUnitNode;
    FParent: TUnitNode;
    FPrevSibling: TUnitNode;
    FShortFilename: string;
    FSourceType: TUnitNodeSourceType;
    FTreeNode: TTreeNode;
    procedure SetCodeBuffer(const AValue: TCodeBuffer);
    procedure SetFilename(const AValue: string);
    procedure SetParent(const AValue: TUnitNode);
    procedure SetShortFilename(const AValue: string);
    procedure SetTreeNode(const AValue: TTreeNode);
    procedure CreateShortFilename;
    procedure UnbindFromParent;
    procedure AddToParent;
    procedure AddChild(const AFilename: string; ACodeBuffer: TCodeBuffer;
      InImplementation: boolean);
    procedure UpdateSourceType;
    function ForbiddenCircle: boolean;
  public
    constructor Create;
    destructor Destroy; override;
    procedure ClearChildren;
    procedure CreateChildren;
    procedure ClearGrandChildren;
    procedure CreateGrandChildren;
    function FindParentWithCodeBuffer(ACodeBuffer: TCodeBuffer): TUnitNode;
    function HasChildren: boolean;
    function ImageIndex: integer;
    function IsFirstImplementationNode: boolean;
    function IsImplementationNode: boolean;
    property ChildCount: integer read FChildCount;
    property CodeBuffer: TCodeBuffer read FCodeBuffer write SetCodeBuffer;
    property Filename: string read FFilename write SetFilename;
    property FirstChild: TUnitNode read FFirstChild;
    property Flags: TUnitNodeFlags read FFlags;
    property LastChild: TUnitNode read FLastChild;
    property NextSibling: TUnitNode read FNextSibling;
    property PrevSibling: TUnitNode read FPrevSibling;
    property Parent: TUnitNode read FParent write SetParent;
    property ShortFilename: string read FShortFilename write SetShortFilename;
    property SourceType: TUnitNodeSourceType read FSourceType;
    property TreeNode: TTreeNode read FTreeNode write SetTreeNode;
  end;
  
  
  { TUnitDependenciesView }
  
  TOnGetProjectMainFilename = function(Sender: TObject): string of object;
  TOnOpenFile = procedure(Sender: TObject; const Filename: string) of object;

  TUnitDependenciesView = class(TForm)
    CloseButton: TBitBtn;
    ToolBar: TToolBar;
    RefreshButton: TToolButton;
    ShowProjectButton: TToolButton;
    SelectUnitButton: TToolButton;
    UnitHistoryList: TComboBox;
    UnitTreeView: TTreeView;
    procedure RefreshButtonClick(Sender: TObject);
    procedure SelectUnitButtonClick(Sender: TObject);
    procedure ShowProjectButtonClick(Sender: TObject);
    procedure UnitHistoryListEditingDone(Sender: TObject);
    procedure UnitTreeViewAdvancedCustomDrawItem(Sender: TCustomTreeView;
          Node: TTreeNode; State: TCustomDrawState; Stage: TCustomDrawStage;
          var PaintImages, DefaultDraw: Boolean);
    procedure UnitTreeViewCollapsing(Sender: TObject; Node: TTreeNode;
          var AllowCollapse: Boolean);
    procedure UnitTreeViewExpanding(Sender: TObject; Node: TTreeNode;
          var AllowExpansion: Boolean);
    procedure UnitTreeViewMouseDown(Sender: TOBject; Button: TMouseButton;
          Shift: TShiftState; X, Y: Integer);
  private
    FCommitUnitHistoryListSelectionNeeded: boolean;
    FOnAccessingSources: TNotifyEvent;
    FOnGetProjectMainFilename: TOnGetProjectMainFilename;
    FOnOpenFile: TOnOpenFile;
    FRefreshNeeded: boolean;
    FRebuildTreeNeeded: boolean;
    FRefreshHistoryListNeeded: boolean;
    FRootCodeBuffer: TCodeBuffer;
    FRootFilename: string;
    FRootNode: TUnitNode;
    FRootShortFilename: string;
    FRootValid: boolean;
    FUpdateCount: integer;
    procedure ClearTree;
    procedure RebuildTree;
    procedure SetRootFilename(const AValue: string);
    procedure SetRootShortFilename(const AValue: string);
    procedure CommitUnitHistoryListSelection;
  public
    constructor Create(TheOwner: TComponent); override;
    destructor Destroy; override;
    procedure BeginUpdate;
    procedure EndUpdate;
    procedure Refresh;
    procedure RefreshHistoryList;
    function RootValid: boolean;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    property OnAccessingSources: TNotifyEvent
      read FOnAccessingSources write FOnAccessingSources;
    property OnGetProjectMainFilename: TOnGetProjectMainFilename
      read FOnGetProjectMainFilename write FOnGetProjectMainFilename;
    property OnOpenFile: TOnOpenFile read FOnOpenFile write FOnOpenFile;
    property RootFilename: string read FRootFilename write SetRootFilename;
    property RootShortFilename: string read FRootShortFilename write SetRootShortFilename;
    property RefreshNeeded: boolean read FRefreshNeeded write FRefreshNeeded;
  end;
  
var
  UnitDependenciesView: TUnitDependenciesView = nil;

implementation

{$R *.lfm}

type
  { TExpandedUnitNodeState
    Used to save which TUnitNodes are expanded during a Refresh }

  TExpandedUnitNodeState = class
  private
    FPaths: TStringList;
  public
    constructor Create;
    destructor Destroy; override;
    procedure Clear;
    procedure Assign(ANode: TUnitNode);
    procedure AssignTo(ANode: TUnitNode);
  end;

{ TUnitDependenciesView }

procedure TUnitDependenciesView.RefreshButtonClick(Sender: TObject);
begin
  Refresh;
end;

procedure TUnitDependenciesView.SelectUnitButtonClick(Sender: TObject);
var
  OpenDialog: TOpenDialog;
begin
  OpenDialog:=TOpenDialog.Create(nil);
  try
    InputHistories.ApplyFileDialogSettings(OpenDialog);
    OpenDialog.Title:=lisOpenFile;
    OpenDialog.Options:=OpenDialog.Options+[ofFileMustExist];
    if OpenDialog.Execute then begin
      RootFilename:=ExpandFileNameUTF8(OpenDialog.Filename);
    end;
    InputHistories.StoreFileDialogSettings(OpenDialog);
  finally
    OpenDialog.Free;
  end;
end;

procedure TUnitDependenciesView.ShowProjectButtonClick(Sender: TObject);
var
  NewFilename: string;
begin
  if Assigned(OnGetProjectMainFilename) then begin
    NewFilename:=OnGetProjectMainFilename(Self);
    if NewFilename<>'' then
      RootFilename:=NewFilename;
  end;
end;

procedure TUnitDependenciesView.UnitHistoryListEditingDone(Sender: TObject);
begin
  //DebugLn('TUnitDependenciesView.UnitHistoryListEditingDone ',UnitHistoryList.Text,' ',dbgs(UnitHistoryList.Items.IndexOf(UnitHistoryList.Text)));
  if UnitHistoryList.Items.IndexOf(UnitHistoryList.Text)<0 then exit;
  CommitUnitHistoryListSelection;
end;

procedure TUnitDependenciesView.UnitTreeViewAdvancedCustomDrawItem(
  Sender: TCustomTreeView; Node: TTreeNode; State: TCustomDrawState;
  Stage: TCustomDrawStage; var PaintImages, DefaultDraw: Boolean);
var
  UnitNode: TUnitNode;
  NodeRect: TRect;
begin
  if Stage<>cdPostPaint then exit;
  UnitNode:=TUnitNode(Node.Data);
  if (UnitNode<>nil) and UnitNode.IsFirstImplementationNode then begin
    NodeRect:=Node.DisplayRect(false);
    NodeRect.Left:=Node.DisplayStateIconLeft;
    with Node.TreeView.Canvas do begin
      Pen.Color:=clRed;
      MoveTo(NodeRect.Left,NodeRect.Top);
      LineTo(NodeRect.Right,NodeRect.Top);
    end;
  end;
end;

procedure TUnitDependenciesView.UnitTreeViewCollapsing(Sender: TObject;
  Node: TTreeNode; var AllowCollapse: Boolean);
var
  UnitNode: TUnitNode;
begin
  AllowCollapse:=true;
  UnitNode:=TUnitNode(Node.Data);
  UnitNode.ClearGrandChildren;
end;

procedure TUnitDependenciesView.UnitTreeViewExpanding(Sender: TObject;
  Node: TTreeNode; var AllowExpansion: Boolean);
var
  UnitNode: TUnitNode;
begin
  UnitNode:=TUnitNode(Node.Data);
  if UnitNode.HasChildren then begin
    UnitTreeView.BeginUpdate;
    try
      AllowExpansion:=true;
      UnitNode.CreateGrandChildren;
    finally
      UnitTreeView.EndUpdate;
    end;
  end else begin
    AllowExpansion:=false;
  end;
end;

procedure TUnitDependenciesView.UnitTreeViewMouseDown(Sender: TOBject;
  Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
  ATreeNode: TTreeNode;
  CurNode: TUnitNode;
begin
  if ssDouble in Shift then begin
    ATreeNode:=UnitTreeView.GetNodeAt(X,Y);
    if ATreeNode=nil then exit;
    CurNode:=TUnitNode(ATreeNode.Data);
    if Assigned(OnOpenFile) then OnOpenFile(Self,CurNode.Filename);;
  end;
end;

procedure TUnitDependenciesView.ClearTree;
begin
  FreeThenNil(FRootNode);
end;

procedure TUnitDependenciesView.RebuildTree;
var
  ExpandState: TExpandedUnitNodeState;
begin
  if FUpdateCount>0 then begin
    FRebuildTreeNeeded:=true;
    exit;
  end;
  FRebuildTreeNeeded:=false;

  CodeToolBoss.ActivateWriteLock;
  ExpandState:=TExpandedUnitNodeState.Create;
  BeginUpdate;
  try
    ExpandState.Assign(FRootNode);
    ClearTree;
    if RootFilename='' then exit;
    FRootNode:=TUnitNode.Create;
    FRootNode.CodeBuffer:=FRootCodeBuffer;
    FRootNode.Filename:=RootFilename;
    //debugln('TUnitDependenciesView.RebuildTree RootFilename=',RootFilename);
    FRootNode.ShortFilename:=FRootShortFilename;
    UnitTreeView.Items.Clear;
    FRootNode.TreeNode:=UnitTreeView.Items.Add(nil,'');
    FRootNode.CreateChildren;
    ExpandState.AssignTo(FRootNode);
  finally
    FRebuildTreeNeeded:=false;
    EndUpdate;
    ExpandState.Free;
    CodeToolBoss.DeActivateWriteLock;
  end;
end;

procedure TUnitDependenciesView.SetRootFilename(const AValue: string);
begin
  //DebugLn('TUnitDependenciesView.SetRootFilename Old=',FRootFilename,' New',AValue);
  if FRootFilename=AValue then exit;
  FRootFilename:=AValue;
  FRootCodeBuffer:=CodeToolBoss.LoadFile(FRootFilename,false,false);
  FRootShortFilename:=FRootFilename;
  FRootValid:=FRootCodeBuffer<>nil;
  RebuildTree;
  RefreshHistoryList;
end;

procedure TUnitDependenciesView.SetRootShortFilename(const AValue: string);
begin
  if FRootShortFilename=AValue then exit;
  FRootShortFilename:=AValue;
  if FRootNode<>nil then
    FRootNode.ShortFilename:=AValue;
end;

procedure TUnitDependenciesView.CommitUnitHistoryListSelection;
begin
  //DebugLn('TUnitDependenciesView.CommitUnitHistoryListSelection Old=',FRootFilename,' New=',UnitHistoryList.Text,' FUpdateCount=',dbgs(FUpdateCount));
  if FUpdateCount>0 then begin
    FCommitUnitHistoryListSelectionNeeded:=true;
    exit;
  end;
  FCommitUnitHistoryListSelectionNeeded:=false;
  if UnitHistoryList.Items.IndexOf(UnitHistoryList.Text)<0 then exit;
  RootFilename:=ExpandFileNameUTF8(UnitHistoryList.Text);
end;

procedure TUnitDependenciesView.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited KeyUp(Key, Shift);
  ExecuteIDEShortCut(Self,Key,Shift,nil);
end;

function TUnitDependenciesView.RootValid: boolean;
begin
  Result:=FRootValid;
end;

constructor TUnitDependenciesView.Create(TheOwner: TComponent);
begin
  inherited Create(TheOwner);

  Name:=NonModalIDEWindowNames[nmiwUnitDependenciesName];
  Caption := dlgUnitDepCaption;

  RefreshHistoryList;

  SelectUnitButton.Caption:=dlgUnitDepBrowse;
  RefreshButton.Caption:=dlgUnitDepRefresh;
  ShowProjectButton.Caption:=dlgEnvProject;
  CloseButton.Caption:=lisClose;
  UnitTreeView.Images := IDEImages.Images_16;
  ToolBar.Images := IDEImages.Images_16;
  ShowProjectButton.ImageIndex := IDEImages.LoadImage(16, 'item_project');
  SelectUnitButton.ImageIndex := IDEImages.LoadImage(16, 'laz_open');
  RefreshButton.ImageIndex := IDEImages.LoadImage(16, 'laz_refresh');
end;

destructor TUnitDependenciesView.Destroy;
begin
  ClearTree;
  inherited Destroy;
end;

procedure TUnitDependenciesView.BeginUpdate;
begin
  inc(FUpdateCount);
end;

procedure TUnitDependenciesView.EndUpdate;
begin
  if FUpdateCount<0 then RaiseGDBException('TUnitDependenciesView.EndUpdate');
  dec(FUpdateCount);
  if FUpdateCount=0 then begin
    if FCommitUnitHistoryListSelectionNeeded then
      CommitUnitHistoryListSelection;
    if FRefreshNeeded then
      Refresh;
    if FRebuildTreeNeeded then
      RebuildTree;
    if FRefreshHistoryListNeeded then
      RefreshHistoryList;
  end;
end;

procedure TUnitDependenciesView.Refresh;
begin
  if FUpdateCount>0 then begin
    FRefreshNeeded:=true;
    exit;
  end;
  FRefreshNeeded:=false;
  BeginUpdate;
  try
    if Assigned(OnAccessingSources) then OnAccessingSources(Self);
    RebuildTree;
  finally
    FRefreshNeeded:=false;
    EndUpdate;
  end;
end;

procedure TUnitDependenciesView.RefreshHistoryList;
begin
  if FUpdateCount>0 then begin
    FRefreshHistoryListNeeded:=true;
    exit;
  end;
  FRefreshHistoryListNeeded:=false;
  BeginUpdate;
  try
    if RootFilename<>'' then
      if not InputHistories.AddToUnitDependenciesHistory(RootFilename) then
        exit;
    UnitHistoryList.Items.Assign(InputHistories.UnitDependenciesHistory);
    if UnitHistoryList.Items.Count>0 then
      UnitHistoryList.Text:=UnitHistoryList.Items[0]
    else
      UnitHistoryList.Text:=RootFilename;
  finally
    FRefreshHistoryListNeeded:=false;
    EndUpdate;
  end;
end;

{ TUnitNode }

procedure TUnitNode.SetCodeBuffer(const AValue: TCodeBuffer);
begin
  if CodeBuffer=AValue then exit;
  FCodeBuffer:=AValue;
  if CodeBuffer<>nil then
    Filename:=CodeBuffer.Filename;
end;

procedure TUnitNode.SetFilename(const AValue: string);
begin
  if Filename=AValue then exit;
  FFilename:=AValue;
  FSourceType:=unstUnknown;
  CreateShortFilename;
end;

procedure TUnitNode.SetParent(const AValue: TUnitNode);
begin
  if Parent=AValue then exit;
  UnbindFromParent;
  FParent:=AValue;
  if Parent<>nil then AddToParent;
end;

procedure TUnitNode.SetShortFilename(const AValue: string);
begin
  if ShortFilename=AValue then exit;
  FShortFilename:=AValue;
  if TreeNode<>nil then
    TreeNode.Text:=FShortFilename;
end;

procedure TUnitNode.SetTreeNode(const AValue: TTreeNode);
begin
  if TreeNode=AValue then exit;
  FTreeNode:=AValue;
  if TreeNode<>nil then begin
    TreeNode.Text:=ShortFilename;
    TreeNode.Data:=Self;
    TreeNode.HasChildren:=HasChildren;
    TreeNode.ImageIndex:=ImageIndex;
    TreeNode.SelectedIndex:=ImageIndex;
  end;
end;

procedure TUnitNode.CreateShortFilename;
begin
  ShortFilename:=Filename;
  if (Parent<>nil) and (FilenameIsAbsolute(Parent.Filename))
  and (FilenameIsAbsolute(Filename)) then begin
    ShortFilename:=ExtractRelativePath(ExtractFilePath(Parent.Filename),
                                       Filename);
  end;
end;

procedure TUnitNode.UnbindFromParent;
begin
  if TreeNode<>nil then begin
    TreeNode.Free;
    TreeNode:=nil;
  end;
  if Parent<>nil then begin
    if Parent.FirstChild=Self then Parent.FFirstChild:=NextSibling;
    if Parent.LastChild=Self then Parent.FLastChild:=PrevSibling;
    Dec(Parent.FChildCount);
  end;
  if NextSibling<>nil then NextSibling.FPrevSibling:=PrevSibling;
  if PrevSibling<>nil then PrevSibling.FNextSibling:=NextSibling;
  FNextSibling:=nil;
  FPrevSibling:=nil;
  FParent:=nil;
end;

procedure TUnitNode.AddToParent;
begin
  if Parent=nil then exit;
  
  FPrevSibling:=Parent.LastChild;
  FNextSibling:=nil;
  Parent.FLastChild:=Self;
  if Parent.FirstChild=nil then Parent.FFirstChild:=Self;
  if PrevSibling<>nil then PrevSibling.FNextSibling:=Self;
  Inc(Parent.FChildCount);
  CreateShortFilename;

  if FindParentWithCodeBuffer(CodeBuffer)<>nil then begin
    Include(FFlags,unfCircle);
    if ForbiddenCircle then
      Include(FFlags,unfForbiddenCircle);
  end;

  if Parent.TreeNode<>nil then begin
    Parent.TreeNode.HasChildren:=true;
    TreeNode:=Parent.TreeNode.TreeNodes.AddChild(Parent.TreeNode,'');
    if Parent.TreeNode.Expanded then begin
      CreateChildren;
    end;
  end;
end;

procedure TUnitNode.AddChild(const AFilename: string; ACodeBuffer: TCodeBuffer;
  InImplementation: boolean);
var
  NewNode: TUnitNode;
begin
  NewNode:=TUnitNode.Create;
  NewNode.CodeBuffer:=ACodeBuffer;
  NewNode.Filename:=AFilename;
  if InImplementation then
    Include(NewNode.FFlags,unfImplementation);
  if ACodeBuffer=nil then begin
    Include(NewNode.FFlags,unfFileNotFound);
  end;
  NewNode.Parent:=Self;
end;

procedure TUnitNode.UpdateSourceType;
var
  SourceKeyWord: string;
  ASrcType: TUnitNodeSourceType;
begin
  FSourceType:=unstUnknown;
  if CodeBuffer=nil then exit;
  SourceKeyWord:=CodeToolBoss.GetSourceType(CodeBuffer,false);
  for ASrcType:=Low(TUnitNodeSourceType) to High(TUnitNodeSourceType) do
    if CompareText(SourceKeyWord,UnitNodeSourceTypeNames[ASrcType])=0
    then
      FSourceType:=ASrcType;
  if TreeNode<>nil then begin
    TreeNode.ImageIndex:=ImageIndex;
    TreeNode.SelectedIndex:=ImageIndex;
  end;
end;

function TUnitNode.ForbiddenCircle: boolean;
var
  ParentNode, CurNode: TUnitNode;
begin
  Result:=false;
  if CodeBuffer=nil then exit;
  CurNode:=Self;
  ParentNode:=Parent;
  if (ParentNode<>nil) and (ParentNode.CodeBuffer=CodeBuffer) then begin
    // unit includes itself -> forbidden
    Result:=true;
    exit;
  end;
  while ParentNode<>nil do begin
    if (unfImplementation in CurNode.Flags) then begin
      // pascal allows to use nearly anything in the implementation section
      exit;
    end;
    if ParentNode.CodeBuffer=CodeBuffer then begin
      // interface circle detected
      Result:=true;
      exit;
    end;
    CurNode:=ParentNode;
    ParentNode:=ParentNode.Parent;
  end;
end;

constructor TUnitNode.Create;
begin
  inherited Create;
  FSourceType:=unstUnknown;
end;

destructor TUnitNode.Destroy;
begin
  ClearChildren;
  Parent:=nil;
  inherited Destroy;
end;

procedure TUnitNode.ClearChildren;
begin
  while LastChild<>nil do
    LastChild.Free;
end;

procedure TUnitNode.CreateChildren;
var
  UsedInterfaceFilenames, UsedImplementationFilenames: TStrings;
  i: integer;
begin
  ClearChildren;
  UpdateSourceType;
  if CodeBuffer=nil then exit;
  if CodeToolBoss.FindUsedUnitFiles(CodeBuffer,
                                    UsedInterfaceFilenames,
                                    UsedImplementationFilenames) then
  begin
    Exclude(FFlags,unfParseError);
    for i:=0 to UsedInterfaceFilenames.Count-1 do
      AddChild(UsedInterfaceFilenames[i],
               TCodeBuffer(UsedInterfaceFilenames.Objects[i]),false);
    UsedInterfaceFilenames.Free;
    for i:=0 to UsedImplementationFilenames.Count-1 do
      AddChild(UsedImplementationFilenames[i],
               TCodeBuffer(UsedImplementationFilenames.Objects[i]),true);
    UsedImplementationFilenames.Free;
  end else begin
    Include(FFlags,unfParseError);
  end;
end;

procedure TUnitNode.ClearGrandChildren;
var
  AChildNode: TUnitNode;
begin
  AChildNode:=FirstChild;
  while AChildNode<>nil do begin
    AChildNode.ClearChildren;
    AChildNode:=AChildNode.NextSibling;
  end;
end;

procedure TUnitNode.CreateGrandChildren;
var
  AChildNode: TUnitNode;
begin
  AChildNode:=FirstChild;
  while AChildNode<>nil do begin
    AChildNode.CreateChildren;
    AChildNode:=AChildNode.NextSibling;
  end;
end;

function TUnitNode.FindParentWithCodeBuffer(ACodeBuffer: TCodeBuffer
  ): TUnitNode;
begin
  Result:=Parent;
  while (Result<>nil) and (Result.CodeBuffer<>ACodeBuffer) do begin
    Result:=Result.Parent;
  end;
end;

function TUnitNode.HasChildren: boolean;
begin
  Result:=FChildCount>0;
end;

function TUnitNode.ImageIndex: integer;
begin
  if not (unfCircle in FFlags) then 
  begin
    case SourceType of
      unstUnit:    Result := IDEImages.LoadImage(16, 'item_unit');
      unstProgram: Result := IDEImages.LoadImage(16, 'item_project');
      unstLibrary: Result := IDEImages.LoadImage(16, 'item_library');
      unstPackage: Result := IDEImages.LoadImage(16, 'item_package');
    else
      begin
        if unfFileNotFound in Flags then
          Result := IDEImages.LoadImage(16, 'state_not_found')
        else if unfParseError in Flags then
          Result := IDEImages.LoadImage(16, 'state_error')
        else
          Result := IDEImages.LoadImage(16, 'state_unknown');
      end;
    end;
  end else 
  begin
    if unfForbiddenCircle in Flags then 
      Result := IDEImages.LoadImage(16, 'state_circular_reference')
    else 
      Result := IDEImages.LoadImage(16, 'state_unit_circular_reference');
  end;
end;

function TUnitNode.IsFirstImplementationNode: boolean;
begin
  Result:=IsImplementationNode
    and ((PrevSibling=nil) or (not PrevSibling.IsImplementationNode));
end;

function TUnitNode.IsImplementationNode: boolean;
begin
  Result:=unfImplementation in FFlags;
end;

//-----------------------------------------------------------------------------

{ TExpandedUnitNodeState }

constructor TExpandedUnitNodeState.Create;
begin
  inherited Create;
end;

destructor TExpandedUnitNodeState.Destroy;
begin
  Clear;
  inherited Destroy;
end;

procedure TExpandedUnitNodeState.Clear;

  procedure ClearPathTree(StringListNode: TStringList);
  var
    i: integer;
  begin
    if StringListNode=nil then exit;
    for i:=0 to StringListNode.Count-1 do
      ClearPathTree(TStringList(StringListNode.Objects[i]));
    FreeAndNil(StringListNode);
  end;
  
begin
  ClearPathTree(FPaths);
end;

procedure TExpandedUnitNodeState.Assign(ANode: TUnitNode);

  procedure AssignRecursive(var CurPathList: TStringList; CurNode: TUnitNode);
  var
    ChildNode: TUnitNode;
    CurChildList: TStringList;
  begin
    if (CurNode=nil) or (not CurNode.HasChildren) or (CurNode.TreeNode=nil) then
      exit;
    if not CurNode.TreeNode.Expanded then exit;
    if CurPathList=nil then
      CurPathList:=TStringList.Create;

    CurPathList.Add(CurNode.Filename);
    CurChildList:=nil;
    ChildNode:=CurNode.FirstChild;
    while ChildNode<>nil do begin
      AssignRecursive(CurChildList,ChildNode);
      ChildNode:=ChildNode.NextSibling;
    end;
    CurPathList.Objects[CurPathList.Count-1]:=CurChildList;
  end;

begin
  Clear;
  AssignRecursive(FPaths,ANode);
end;

procedure TExpandedUnitNodeState.AssignTo(ANode: TUnitNode);

  procedure AssignToRecursive(CurPathList: TStringList; CurNode: TUnitNode);
  var
    ChildNode: TUnitNode;
    CurChildList: TStringList;
    i: integer;
  begin
    if (CurNode=nil) or (not CurNode.HasChildren) or (CurNode.TreeNode=nil) then
      exit;
    if CurPathList=nil then exit;
    i:=CurPathList.IndexOf(CurNode.Filename);
    if i<0 then exit;

    CurNode.TreeNode.Expand(false);
    CurChildList:=TStringList(CurPathList.Objects[i]);
    if CurChildList=nil then exit;

    ChildNode:=CurNode.FirstChild;
    while ChildNode<>nil do begin
      AssignToRecursive(CurChildList,ChildNode);
      ChildNode:=ChildNode.NextSibling;
    end;
  end;

begin
  AssignToRecursive(FPaths,ANode);
end;

end.