-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathProjectParser.pas
1871 lines (1803 loc) · 60.9 KB
/
ProjectParser.pas
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
/// Software Architecture documentation generation from Delphi source code
// - this unit is part of SynProject, under GPL 3.0 license; version 1.7
unit ProjectParser;
(*
This file is part of SynProject.
Synopse SynProject. Copyright (C) 2008-2023 Arnaud Bouchez
Synopse Informatique - https://synopse.info
SynProject 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 3 of the License, or (at
your option) any later version.
SynProject 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 Lesser General Public License for more details.
You should have received a copy of the GNU General Public License
along with SynProject. If not, see <http://www.gnu.org/licenses/>.
*)
interface
{$define WITH_GRAPHVIZ}
// if defined, the WinGraphviz COM server will be used to generated diagrams
// (must be defined in ProjectParser, ProjectEditor and ProjectTypes)
// - the WinGraphviz.dll is embedded into the main executable, and will be
// uncompressed and installed on the computer if necessary
uses
Windows,
ProjectCommons,
Classes,
SysUtils,
SynZipFiles,
{$ifdef WITH_GRAPHVIZ}
Graphics,
Variants,
{$endif}
ProjectTypes,
ProjectSections,
ProjectRTF,
PasDoc_Hashes,
PasDoc_Types,
PasDoc_Items,
PasDoc_SortSettings,
PasDoc_HierarchyTree,
PasDoc_Light;
type
TProjectFooter = procedure(WR: TProjectWriter; const FooterTitle: string) of object;
/// Delphi project parser (PasDoc based), for creating source documentation
TProjectBrowser = class(TPasDocLight)
private
FProject: TProject;
CurrentSection,
SAD: TSection;
LogFile: Text;
SADUpperDefaultPath,
LogBuf: string; // 8kb memory buffer for log, autoreleased in Destroy
FClassHierarchy: TStringCardinalTree;
FDefaultDirectives: string;
private
{$ifdef WITH_GRAPHVIZ}
function GraphFileNameOk(const name: string; addLastMinus: boolean): string;
{$endif}
procedure LogMessage(const MessageType: TMessageType;
const AMessage: string; const AVerbosity: Cardinal);
public
// list of already written units filenames
UnitsDescription: TStringList;
// list of SourceIgnoreSymbol=.... CSV values
SourceIgnoreSymbol: TObjectHash;
{$ifdef WITH_GRAPHVIZ}
// path to GraphViz generated *.emf files
GraphValues: TSection;
GraphValuesModified: boolean;
// '.emf' or '.png'
GraphExt: string;
procedure LoadGraphValues;
{$endif}
//
constructor Create(aProject: TProject); reintroduce;
destructor Destroy; override;
// fill ClassHierarchy with all classes of all units
procedure CreateClassHierarchy;
// fill ClassHierarchy with all classes of this unit
procedure CreateClassHierarchyFor(PU: TPasUnit; NoClear: boolean = false);
// [SAD-LIS].SourceFile -> Units[]
// - if WithViz is true, all diagrams are recreated
procedure FillUnits(Section: TSection; WithViz: boolean);
// write description of this Item, RTF-formated
function RtfDescription(Item: TPasItem; W: TProjectWriter): boolean;
// write used unit table
procedure RtfUsesUnits(WR: TProjectWriter; const ExternalPath: string);
{$ifdef WITH_GRAPHVIZ}
// create graphics with diagrams
function GraphVizEmf(aSection: TSection): boolean;
// add the the corresponding graph to the output RTF buffer, from its filename
procedure AddGraph(graph: string; WR: TProjectWriter);
{$endif}
// write the description of this unit
procedure RtfUnitDescription(aUnit: TPasUnit; WR: TProjectWriter; TitleLevel: integer;
withFields: boolean; const ExternalPath,ExternalTitle: string; OnFooter: TProjectFooter);
// write all used unit detailled description if not already done
procedure RtfUsesUnitsDescription(WR: TProjectWriter; TitleLevel: integer;
const CSVUnitsWithFields,ExternalPath,ExternalTitle: string; OnFooter: TProjectFooter);
// search for a symbol name inside all units
function FindGlobal(const NameParts: TNameParts; const CurrentUnit: string='';
const CurrentObject: string=''): TBaseItem;
// the associated project
property Project: TProject read FProject;
// the current class hierarchy
property ClassHierarchy: TStringCardinalTree read FClassHierarchy;
end;
{$ifdef WITH_GRAPHVIZ}
/// get Wingraphviz.dot COM object into a Variant
// - return false on error, true on success
// - display an error message if failed
function GetWingraphviz(out Dot: Variant): boolean;
/// create a picture from a .dot content
// - the picture will be created in DestDir+FileName+GraphExt
// - will set GraphValues[GraphPath+FileName+GraphExt]='230x123 90% GraphTitle'
function WingraphvizCreateFile(Dot: Variant; const FileName, DestDir, GraphExt, Source: string;
const GraphPath: string=''; const GraphTitle: string=''; GraphValues: TSection=nil;
Perc: integer=0): boolean;
{$endif}
/// convert a \graph content (from lines) into a .dot compatible
function WingraphvizFromText(const UniqueImageName: string; Buffer: TStrings;
BufferStartIndex: integer=0): string;
{/// retrieve common data directory
// - Vista: C:\ProgramData
// - XP: C:\Documents and Settings\All Users\Application Data
function GetCommonAppDataPath: AnsiString;}
/// retrieve common data directory for Synopse applications
// - Vista: C:\ProgramData\Synopse
// - XP: C:\Documents and Settings\All Users\Application Data\Synopse
function GetSynopseCommonAppDataPath: AnsiString;
/// convert a supplied SVG textual content into an .emf file
// - will only handle SVG content as created by GraphViz
// - if Dest='', will return the created TMetaFile instance (caller must free it)
function SVGToEMF(const Source: string; const Dest: TFileName;
WhiteBackground: boolean=false): TMetaFile;
implementation
uses
ShlObj, ComObj, ActiveX, SynZip,
ProjectDiff; // for Alder32Asm
resourcestring
sUsedFor = 'Used for';
sImplementedInN = '%s implemented in the {\i %%s} unit';
sPurpose = 'Purpose';
sQuotedInN = 'The {\i %s} unit is quoted in the following items';
sUnitN = '%s unit';
sUnitsUsedInN = 'Units used in the {\i %s} unit';
sUnitsUsed = 'Uses';
sUnitName = 'Unit Name';
sUnitsLocatedInN = 'Units located in the "%s" directory';
sSourceFileName = 'Source File Name';
sUnitDependenciesInDir = 'Unit dependencies in the "%s" directory';
sClassHierarchy = '{\i %s} class hierarchy';
sHierarchy = 'Hierarchy';
sMainPageDesc = 'Returns to the main documentation';
sApiReference = 'API Reference';
{ TProjectBrowser }
{$ifdef WITH_GRAPHVIZ}
procedure TProjectBrowser.AddGraph(graph: string; WR: TProjectWriter);
begin
LoadGraphValues;
graph := GraphDirName+graph;
if FileExists(Project.FileNameDir+graph+GraphExt) then
graph := graph+GraphExt else
if FileExists(Project.FileNameDir+graph+'.emf') then
graph := graph+'.emf' else
if FileExists(Project.FileNameDir+graph+'.png') then
graph := graph+'.png' else
graph := graph+'.gif';
if FileExists(Project.FileNameDir+graph) then
Project.PictureAdd(graph,nil,WR);
end;
{$endif}
{$I-}
constructor TProjectBrowser.Create(aProject: TProject);
begin
inherited Create(nil);
OnMessage := LogMessage;
FProject := aProject;
// init default parsing values from Project+SAD
CacheName := Project.FileNameDir+Project.Project['Name']+'.sad'; // zip file name for caching
CacheNameSAE := ChangeFileExt(CacheName,'.sae');
AssignFile(LogFile,Project.DestinationDir+'SAD.log'); // 'D:\Documents\Product New Version\'
SetLength(LogBuf,8192); // autoreleased in TProjectBrowser.Destroy
SetTextBuf(LogFile,LogBuf[1],length(LogBuf)); // 8kb memory buffer for log
Rewrite(LogFile); // new file each time
WriteLn(LogFile,DateTimeToStr(Now));
DoMessage(0,mtInformation,'Cache file = %s',[CacheName]);
ioresult;
SAD := Project.ParseSAD.Params;
if SAD=nil then exit;
if SAD['DefaultPath']<>'' then // D:\DEV\
SADUpperDefaultPath := SysUtils.UpperCase(
IncludeTrailingPathDelimiter(SAD['DefaultPath']));
DoMessage(0,mtInformation,'[%s].Source = %s',[SAD.SectionName,SAD['Source']]);
FDefaultDirectives := SAD['Directives'];
if FDefaultDirectives<>'' then
FDefaultDirectives := FDefaultDirectives+';';
FDefaultDirectives := FDefaultDirectives+ // Delphi 7 conditionals
'WIN32;VER150;MSWINDOWS;CONDITIONALEXPRESSIONS';
CommentMarkers := '/{*'; // parsed comments are: /// {{ (** e.g.
MarkerOptional := false; // if true, CommentMarkers are ignored
ShowVisibilities := [viPublic, viPublished, viAutomated];
ImplicitVisibility := ivPublic;
OutdatedCacheAutoRecreate := false;
ForceCacheRecreateAll := false;
HandleMacros := false;
UnitUsesAlsoInImplementation := true;
UnitsDescription := TStringList.Create;
UnitsDescription.Sorted := true;
UnitsDescription.Duplicates := dupIgnore;
{$ifdef WITH_GRAPHVIZ}
if not DirectoryExists(Project.FileNameDir+GraphDirName) then
mkDir(Project.FileNameDir+GraphDirName);
GraphExt := '.emf'; // by default
{$endif}
// Verbosity := 5; // used for debug only
end;
{$I+}
procedure TProjectBrowser.CreateClassHierarchy;
var unitLoop: Integer;
begin
FClassHierarchy.Free;
FClassHierarchy := TStringCardinalTree.Create;
for unitLoop := 0 to Units.Count - 1 do
CreateClassHierarchyFor(TPasUnit(Units[unitLoop]),true);
FClassHierarchy.Sort;
end;
procedure TProjectBrowser.CreateClassHierarchyFor(PU: TPasUnit; NoClear: boolean = false);
function FindGlobalPasItem(const NameParts: TNameParts): TPasItem;
var BaseResult: TBaseItem;
begin
BaseResult := FindGlobal(NameParts);
if (BaseResult <> nil) and (BaseResult is TPasItem) then
Result := TPasItem(BaseResult) else
Result := nil;
end;
var
classLoop: Integer;
ACIO: TPasCio;
ParentItem: TPasItem;
Parent, Child: TPasItemNode;
begin
if not NoClear then begin
FClassHierarchy.Free;
FClassHierarchy := TStringCardinalTree.Create;
end;
if PU.CIOs = nil then exit;
for classLoop := 0 to PU.CIOs.Count - 1 do begin
ACIO := TPasCio(PU.CIOs.PasItemAt[classLoop]);
if ACIO.MyType in CIONonHierarchy then continue;
if Assigned(ACIO.Ancestors) and (ACIO.Ancestors.Count > 0) then begin
ParentItem := FindGlobalPasItem(OneNamePart(ACIO.Ancestors.FirstName));
if Assigned(ParentItem) then begin
Parent := FClassHierarchy.ItemOfName(ParentItem.Name);
// Add parent if not already there
if Parent = nil then
Parent := FClassHierarchy.InsertItem(ParentItem);
end else begin
Parent := FClassHierarchy.ItemOfName(ACIO.Ancestors.FirstName);
if Parent = nil then
Parent := FClassHierarchy.InsertName(ACIO.Ancestors.FirstName);
end;
end else
Parent := nil;
Child := FClassHierarchy.ItemOfName(ACIO.Name);
if Child = nil then
FClassHierarchy.InsertItemParented(Parent, ACIO)
else
if Parent <> nil then
FClassHierarchy.MoveChildLast(Child, Parent);
end;
if not NoClear then
FClassHierarchy.Sort;
end;
{$I-}
destructor TProjectBrowser.Destroy;
begin
WriteLn(LogFile);
DoMessage(2,mtInformation,'Files not found during process:'#13#10'%s',[FilesNotFoundList]);
WriteLn(LogFile);
Close(LogFile);
ioresult;
UnitsDescription.Free;
SourceIgnoreSymbol.Free;
{$ifdef WITH_GRAPHVIZ}
if GraphValues<>nil then begin
if GraphValuesModified then
GraphValues.SaveToFile(Project.FileNameDir+GraphDirName+GraphValues.SectionName+'.ini');
GraphValues.Free;
end;
{$endif}
inherited;
end;
{$I+}
procedure TProjectBrowser.FillUnits(Section: TSection; WithViz: boolean);
procedure ParseFiles;
var i, j: integer;
U: TPasUnit;
begin
// add all the depending units to SourceFileNames[]
SourceFileNames.Clear;
for i := 0 to Units.Count-1 do begin
U := TPasUnit(Units[i]); // add all units in uses clause
for j := 0 to U.UsesUnits.Count-1 do
if Units.FindName(U.UsesUnits[j])=nil then // add once
AddOneSourceUnit(U.UsesUnits[j]);
end;
// parse the SourceFileNames[] files -> Units[]
for i := 0 to SourceFileNames.Count-1 do
ParseFile(SourceFileNames[i]);
end;
var D: TSectionsStorage;
procedure Update(Items: TPasItems; const SectionName: string);
var Sec: TSection;
i: Integer;
s: string;
begin
Sec := D.Section[SectionName];
if Sec=nil then
Exit;
for i := 0 to Items.Count-1 do
with TPasItem(Items[i]) do begin
s := trim(Sec[Name]);
if s<>'' then // leave any existing description, if no newer available
RawDescription := s; // override existing item description
end;
end;
procedure AddSourceIgnoreSymbol(P: PAnsiChar);
var symbol: string;
begin
if P<>nil then
repeat
symbol := GetNextItem(P);
if symbol<>'' then
SourceIgnoreSymbol.SetObject(LowerCase(symbol),self);
until P=nil;
end;
var i, j, k: integer;
Dir, data, txt, SourceIgnoreSymbolByUnit: string;
begin // Section = [SAD-EIA] e.g.
Units.Clear;
if Section=nil then
exit;
CurrentSection := Section;
CloseCacheSAE(False,False); // FreeAndNil(FCacheReaderSAE)
// default subpath for ZipName Entry -> 'EIA\'
CacheZipPath := IncludeTrailingPathDelimiter(Section.SectionNameValue);
if Section['DefaultPath']<>'' then // D:\DEV\
UpperDefaultPath := SysUtils.UpperCase(
IncludeTrailingPathDelimiter(Section['DefaultPath'])) else
UpperDefaultPath := SADUpperDefaultPath;
IncludeDirectories := Section['IncludePath']; // D:\DEV\LIB;D:\DEV\TMS
SourceDefaultPath := Section['SourcePath']; // D:\Dev\Synopse\EIA
if SourceDefaultPath<>'' then begin
if not DirectoryExists(SourceDefaultPath) then
SourceDefaultPath := UpperDefaultPath+Section['SourcePath']; // D:\Dev\Synopse\EIA
SourceDefaultPath := IncludeTrailingPathDelimiter(SourceDefaultPath);
end;
SourceIgnoreSymbol.Free;
SourceIgnoreSymbol := TObjectHash.Create;
for i := 0 to high(PASCALKEYWORDS) do
SourceIgnoreSymbol.SetObject(LowerCase(PASCALKEYWORDS[i]),self);
AddSourceIgnoreSymbol('the,you,use,will,must,copy,format,have,some,get,call,'+
'method,any,all,from,this');
AddSourceIgnoreSymbol(pointer(Section['SourceIgnoreSymbol']));
SourceFileNames.Clear;
AddSourceFileName(Section['SourceFile']); // fill SourceFileNames[]
if SourceFileNames.Count=0 then
exit; // nothing to parse
{$I-}
WriteLn(LogFile,#13#10' FillUnits(',Section.SectionName,') -> ',
Section['SourceFile']);
{$I+}
DoMessage(0,mtInformation,'DefaultPath = %s',[UpperDefaultPath]);
DoMessage(0,mtInformation,'IncludePath = %s',[Section['IncludePath']]);
Dir := Section['Directives'];
if Dir<>'' then begin
if pos('VER70',Dir)=0 then // allow Turbo Pascal only parsing
Dir := FDefaultDirectives+';'+Dir;
Directives := Dir;
end else
Directives := FDefaultDirectives;
DoMessage(0,mtInformation,'Directives = %s',[Dir]);
if ForceCacheRecreateAll then
DoMessage(0,mtInformation,'ForceCacheRecreateAll is ON',[]) else
if OutdatedCacheAutoRecreate then
DoMessage(0,mtInformation,'OutdatedCacheAutoRecreate is ON',[]);
if isTrue(Section['ExternalDescription']) then begin
if FileExists(CacheNameSAE) then begin
FCacheReaderSAE := TZipReader.Create(CacheNameSAE);
DoMessage(0,mtInformation,'ExternalDescription=Yes from %s',[CacheNameSAE]);
end else
DoMessage(0,mtError,'ExternalDescription=Yes but no %s file yet',[CacheNameSAE]);
end;
try
// Parse the main files -> Units[]
for i := 0 to SourceFileNames.Count-1 do
ParseFile(SourceFileNames[i]);
// Units[].Use->Units[]
ParseFiles;
// Units[].Use->Units[] twice
ParseFiles;
// init OutputFileName = SourceFileName for display
SourceIgnoreSymbolByUnit := LowerCase(Section['SourceIgnoreSymbolByUnit']);
if UpperDefaultPath<>'' then
for i := 0 to Units.Count-1 do
with TPasUnit(Units[i]) do begin
IncludedInFindGlobal := CSVIndexOf(SourceIgnoreSymbolByUnit,LowerCase(Name))<0;
if IdemPChar(pointer(SourceFileName),pointer(UpperDefaultPath)) then
DisplayFileName := copy(SourceFileName,length(UpperDefaultPath)+1,maxInt) else
DisplayFileName := SourceFileName;
if FCacheReaderSAE<>nil then begin // override by hand-made description
j := FCacheReaderSAE.ZipNameIndexOf(DisplayFileName);
if j<0 then
j := FCacheReaderSAE.ZipNameIndexOf(SourceFileName);
if j>=0 then begin
data := FCacheReaderSAE.GetString(j);
if data<>'' then begin
D := TSectionsStorage.Create;
try
D.LoadFromMemory(Pointer(data));
txt := D.ReadHeader('Description','');
if txt<>'' then // leave any existing description, if no newer
RawDescription := txt;
Update(Types,'Types');
Update(Constants,'Constants');
Update(FuncsProcs,'Functions');
Update(Variables,'Variables');
Update(CIOs,'Objects');
for k := 0 to CIOs.Count-1 do
if CIOs[k].InheritsFrom(TPasCIO) then
with TPasCio(CIOs[k]) do begin
Update(Fields,Name);
Update(Methods,Name);
Update(Properties,Name);
end;
finally
D.Free;
end;
end;
end;
end;
end;
// update cache file
ZipCacheUpdate;
Units.SortByDirectory; // directory order is needed for the API reference
Units.SortOnlyInsideItems([
ssConstants, ssFuncsProcs, ssTypes, ssVariables, ssUsesClauses,
ssRecordFields, ssNonRecordFields, ssMethods, ssProperties]);
{$ifdef WITH_GRAPHVIZ}
if WithViz then
GraphVizEmf(Section);
{$endif}
except
on E: Exception do
DoMessage(0,mtError,E.Message,[]);
end;
end;
function TProjectBrowser.FindGlobal(const NameParts: TNameParts;
const CurrentUnit,CurrentObject: string): TBaseItem;
var i: Integer;
Item: TBaseItem;
U: TPasUnit;
expectedInclusion: boolean;
begin
Result := nil;
if (Units=nil) or (Units.Count=0) then Exit;
case Length(NameParts) of
1: begin { field/method/property }
Result := TPasUnit(Units.FindName(NameParts[0]));
if Result<>nil then
exit;
if CurrentUnit<>'' then begin
U := TPasUnit(Units.FindName(CurrentUnit));
if U<>nil then begin
result := U.FindItem(NameParts[0]);
if result <> nil then
exit;
if CurrentObject<>'' then begin
result := U.FindFieldMethodProperty(CurrentObject,NameParts[0]);
if result <> nil then
exit;
end;
expectedInclusion := U.IncludedInFindGlobal;
end else
expectedInclusion := true;
end else
expectedInclusion := true;
for i := 0 to Units.Count - 1 do
with TPasUnit(Units.List[i]) do
if IncludedInFindGlobal=expectedInclusion then begin
Result := FindItem(NameParts[0]);
if Result <> nil then Exit;
end;
if not expectedInclusion then // e.g. crossplatform, then main
for i := 0 to Units.Count - 1 do
with TPasUnit(Units.List[i]) do
if IncludedInFindGlobal then begin
Result := FindItem(NameParts[0]);
if Result <> nil then Exit;
end;
end;
2: begin { object.field/method/property }
for i := 0 to Units.Count - 1 do
if TPasUnit(Units.List[i]).IncludedInFindGlobal then begin
Result := TPasUnit(Units.List[i]).FindFieldMethodProperty(
NameParts[0], NameParts[1]);
if Assigned(Result) then Exit;
end;
{ unit.cio/var/const/type }
U := TPasUnit(Units.FindName(NameParts[0]));
if Assigned(U) then
Result := U.FindItem(NameParts[1]);
end;
3: begin { unit.object/class/interface.field/method/property }
U := TPasUnit(Units.FindName(NameParts[0]));
if (not Assigned(U)) or (not U.IncludedInFindGlobal) then Exit;
Item := U.FindItem(NameParts[1]);
if (not Assigned(Item)) then Exit;
Item := Item.FindItem(NameParts[2]);
if (not Assigned(Item)) then Exit;
Result := Item;
Exit;
end;
end;
end;
function GetShellFolderPath(const FolderID: Integer): AnsiString;
var pidl: PItemIDList;
Buffer: array[0..MAX_PATH-1] of AnsiChar;
Malloc: IMalloc;
begin
Result := '';
if Win32MajorVersion<4 then Exit;
if FAILED(SHGetMalloc(Malloc)) then
Malloc := nil;
if SUCCEEDED(SHGetSpecialFolderLocation(0, FolderID, pidl)) then begin
if SHGetPathFromIDListA(pidl, Buffer) then begin
Result := Buffer;
if Result[length(Result)]<>'\' then
Result := Result+'\';
end;
if Assigned(Malloc) then
Malloc.Free(pidl);
end;
end;
/// retrieve common data directory
// - Vista: C:\ProgramData
// - XP: C:\Documents and Settings\All Users\Application Data
function GetCommonAppDataPath: AnsiString;
const CSIDL_COMMON_APPDATA = $0023;
begin
result := GetShellFolderPath(CSIDL_COMMON_APPDATA); // Vista: c:\ProgramData
if result='' then
result := ExtractFilePath(paramstr(0));
end;
function GetSynopseCommonAppDataPath: AnsiString;
const CSIDL_LOCAL_APPDATA = $001C;
begin
{ result := GetCommonAppDataPath+'Synopse\';
if not DirectoryExists(result) then begin
CreateDirectory(pointer(result),nil);
if not DirectoryExists(result) then begin // read-only problem (Vista UAC?) }
result := GetShellFolderPath(CSIDL_LOCAL_APPDATA)+'Synopse\';
if not DirectoryExists(result) then
CreateDirectory(pointer(result),nil);
{ end;
end; }
end;
{$ifdef WITH_GRAPHVIZ}
(*
function WinExecAndWait(const FileName: String; Visibility: integer=SW_SHOWNORMAL): cardinal;
var StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
Options: cardinal;
begin
FillChar(StartupInfo,Sizeof(StartupInfo),0);
StartupInfo.cb := Sizeof(StartupInfo);
StartupInfo.dwFlags := STARTF_USESHOWWINDOW;
StartupInfo.wShowWindow := Visibility;
if Visibility=0 then
Options := NORMAL_PRIORITY_CLASS else
Options := CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS;
if not CreateProcess(nil,
pointer(FileName), { pointer to command line string }
nil, { pointer to process security attributes }
nil, { pointer to thread security attributes }
false, { handle inheritance flag }
Options, { creation flags }
nil, { pointer to new environment block }
nil, { pointer to current directory name }
StartupInfo, { pointer to STARTUPINFO }
ProcessInfo) then { pointer to PROCESS_INF }
Result := cardinal(-1) else begin
WaitforSingleObject(ProcessInfo.hProcess,INFINITE);
GetExitCodeProcess(ProcessInfo.hProcess,Result);
end;
end;
*)
function WinExecAndWait32(Path: PChar; Visibility: Word; Timeout : DWORD): integer;
var
StartupInfo: TStartupInfo;
ProcessInfo: TProcessInformation;
begin
FillChar(StartupInfo, SizeOf(TStartupInfo), 0);
with StartupInfo do
begin
cb := SizeOf(TStartupInfo);
dwFlags := STARTF_USESHOWWINDOW or STARTF_FORCEONFEEDBACK;
wShowWindow := visibility;
end;
if CreateProcess(nil,path,nil, nil, False, NORMAL_PRIORITY_CLASS, nil, nil,
StartupInfo, ProcessInfo) then
{ timeout is in miliseconds or INFINITE if you want to wait forever }
result := Integer(WaitForSingleObject(ProcessInfo.hProcess, timeout)) else
result := GetLastError;
end;
var
GetWingraphvizDlg: boolean = False;
function GetWingraphviz(out Dot: Variant): boolean;
procedure Retry;
var TempDll, TempReg, TempPath: TFileName;
Reg: function: HResult; stdcall;
H: THandle;
begin
// library not available -> register now
TempPath := GetSynopseCommonAppDataPath;
TempDll := TempPath+'WinGraphviz.dll';
TempReg := TempPath+'WinGraphviz.reg';
if not FileExists(TempDll) or not FileExists(TempReg) then
with TZipRead.Create(HInstance,'Zip','ZIP') do
try // get embedded WinGraphviz server
StringToFile(TempDll,UnZip(NameToIndex('WinGraphviz.dll')));
StringToFile(TempReg,StringReplace(UnZip(NameToIndex('WinGraphviz.reg')),
'WinGraphviz.dll',StringReplace(TempDll,'\','\\',[rfReplaceAll]),
[rfReplaceAll,rfIgnoreCase]));
finally
Free;
end;
result := false;
// first try to register as normal COM library
H := SafeLoadLibrary(TempDll);
if H<>0 then
try
@Reg := GetProcAddress(H,'DllRegisterServer');
if Assigned(@Reg) then
result := (Reg=S_OK);
finally
FreeLibrary(H);
end;
// on failure, register COM library for the current user
if not result then
result := WinExecAndWait32(pointer(format('reg.exe import "%s"',[TempReg])),
SW_SHOWMINIMIZED,INFINITE)=0;
if result then
try
Dot := CreateOleObject('Wingraphviz.DOT');
except
on E: Exception do
result := false; // WinGraphviz was not successfully registered
end;
if not result then
if not GetWingraphvizDlg then begin
MessageBox(0,pointer('Please run as Administrator:'#13#13+
'either SynProject.exe and this button'#13#13+
'either the following command line:'#13' regsvr32.exe "'+
TempDll+'"'),nil,MB_ICONERROR);
GetWingraphvizDlg := true;
end;
end;
begin
try
Dot := CreateOleObject('Wingraphviz.DOT');
result := true;
except // library not available -> register now
on E: Exception do
Retry;
end;
end;
function SVGToEMF(const Source: string; const Dest: TFileName;
WhiteBackground: boolean=false): TMetaFile;
function GetInt(var S: PChar): integer;
begin
result := 0;
if S=nil then
exit;
while S^=' ' do inc(S);
if (S=nil) or not (ord(S^) in [ord('0')..ord('9')]) then
exit;
repeat
result := result*10+ord(S^)-48;
inc(S);
until not (ord(S^) in [ord('0')..ord('9')]);
while S^ in [',',' '] do inc(S);
if S^=#0 then
S := nil;
end;
function GetTag(var S: PChar): PChar;
begin // '<?xml >next' -> result='?xml' S='next'
if S<>nil then begin
while (S^<>'<') and (S^<>#0) do inc(S);
if S^=#0 then
S := nil;
end;
result := S;
if result<>nil then begin
inc(result);
repeat
inc(S);
until (S^='>') or (S^=#0);
if S^=#0 then
S := nil else
inc(S);
end;
end;
function GetAttr(var S: PChar; Names: PChar; IntValues: array of Pinteger;
out StrValue: string): integer;
var L, i, err: integer;
Beg: PChar;
begin
result := 0;
if (Names=nil) or (S=nil) or (S^=#0) then
exit;
while S^=' ' do inc(S);
if not (S^ in ['a'..'z']) then
exit;
i := 0;
repeat
inc(i);
while Names^=' ' do inc(Names);
L := 0;
while not (Names[L] in ['=',#0]) do inc(L);
if StrLComp(S,Names,L)=0 then begin
result := i;
break;
end;
inc(Names,L);
if Names^='=' then
inc(Names);
until Names^=#0;
if cardinal(result-1)>cardinal(high(IntValues)) then
exit;
inc(S,L);
while S^ in [' ','='] do inc(S);
if S^<>'"' then begin
result := 0;
exit;
end;
inc(S);
Beg := S;
repeat
inc(S);
until S^ in [#0,'"'];
SetString(StrValue,Beg,S-Beg);
if IntValues[result-1]<>nil then
val(StrValue,IntValues[result-1]^,err);
if S^<>#0 then
inc(S);
end;
procedure FillStroke(Style: PChar; Canvas: TCanvas);
function HtmlToTColor(Hexa: PChar): TColor;
var err, color: integer;
col: string;
begin
result := 0;
if Hexa^='#' then begin
SetString(col,Hexa,7);
Hexa[0] := '$';
val(Hexa,color,err); // hexa $RRGGBB
with TRGBQuad(color) do
result := RGB(rgbRed,rgbGreen,rgbBlue);
end;
end;
begin
repeat
if StrLComp(Style,'fill:',5)=0 then begin
inc(Style,5);
if StrLComp(Style,'none',4)=0 then begin
Canvas.Brush.Style := bsClear;
end else begin
Canvas.Brush.Style := bsSolid;
Canvas.Brush.Color := HtmlToTColor(Style);
end;
end else
if StrLComp(Style,'stroke:',7)=0 then begin
inc(Style,7);
Canvas.Pen.Color := HtmlToTColor(Style);
end;
while not (Style^ in [';',' ',#0]) do inc(Style);
while Style^ in [';',' '] do inc(Style);
until Style^=#0;
end;
var S: PChar;
Cmd: char;
style, path: string;
Width, Height, X, Y, n: integer;
DC: HDC;
Canvas: TMetaFileCanvas;
R: TRect;
Tag, P: PChar;
Points: array of TPoint;
Str: string;
function GetStylePoints: boolean;
var n: integer;
P: PChar;
Str: string;
begin
n := 0;
while true do
case GetAttr(Tag,'style=points=',[nil,nil],Str) of
0: break;
1: style := Str;
2: begin
P := pointer(Str);
while P<>nil do begin
SetLength(Points,n+1);
with Points[n] do begin
X := GetInt(P);
Y := GetInt(P);
end;
inc(n);
end;
end;
end;
result := (n>0);
if result then
FillStroke(pointer(style),Canvas);
end;
begin
result := nil;
S := pointer(Source);
repeat
Tag := GetTag(S);
if S=nil then
exit;
until StrLComp(Tag,'svg ',4)=0;
inc(Tag,4);
width := 0;
height := 0;
repeat until GetAttr(Tag,'width=height=',[@width,@height],Str)=0;
result := TMetaFile.Create;
try
result.Width := Width;
result.Height := Height;
DC := GetDC(0);
Canvas := TMetaFileCanvas.Create(result,DC);
try
if WhiteBackground then begin
Canvas.Brush.Color := clWhite;
Canvas.FillRect(Rect(0,0,Width,Height));
end;
Canvas.Font.Name := 'Calibri';
Canvas.Font.Size := 14;
SetTextAlign(Canvas.Handle,TA_NOUPDATECP or TA_LEFT or TA_BASELINE);
Canvas.Pen.Width := 2;
repeat
Tag := GetTag(S);
if S=nil then break;
case Tag[0] of
'p':
if StrLComp(Tag,'polyline ',9)=0 then begin
inc(Tag,9);
if GetStylePoints then
Canvas.Polyline(Points);
end else
if StrLComp(Tag,'polygon ',8)=0 then begin
inc(Tag,8);
if GetStylePoints then begin
if pos('fill:none',style)>0 then
Canvas.Polyline(Points) else
Canvas.Polygon(Points);
end;
end else
if StrLComp(Tag,'path ',5)=0 then begin
inc(Tag,5);
path := '';
while true do
case GetAttr(Tag,'style=d=',[nil,nil],Str) of
0: break;
1: style := Str;
2: path := Str;
end;
if path<>'' then begin
FillStroke(pointer(style),Canvas);
P := pointer(path);
n := 0;
while P<>nil do begin
while P^=' ' do inc(P);
cmd := P^;
case cmd of
'M': begin
inc(P);
n := 1;
SetLength(Points,1);
Points[0].X := GetInt(P);
Points[0].Y := GetInt(P);
end;
'C', 'L': if n<>1 then break else begin
inc(P);
repeat
SetLength(Points,n+1);
with Points[n] do begin
X := GetInt(P);
Y := GetInt(P);
end;
inc(n);
until (P=nil) or not (P^ in ['0'..'9']);
case cmd of
'C': Canvas.PolyBezier(Points);
'L': Canvas.Polyline(Points);
end;
n := 0;
end;
end;
end;
end;
end;
'e': if StrLComp(Tag,'ellipse ',8)=0 then begin
inc(Tag,8);
while true do
case GetAttr(Tag,'style=cx=cy=rx=ry=',[nil,@R.Left,@R.Top,@R.Right,@R.Bottom],Str) of
0: break;
1: style := Str;
end;
dec(R.Left,R.Right);
dec(R.Top,R.Bottom);
R.Right := R.Right*2+R.Left;
R.Bottom := R.Bottom*2+R.Top;
FillStroke(pointer(style),Canvas);
Canvas.Ellipse(R);
end;
't': if StrLComp(Tag,'text ',5)=0 then begin
inc(Tag,5);
X := -1;
Y := -1;
while true do
case GetAttr(Tag,'text-anchor=x=y=style=',[nil,@X,@Y,nil],Str) of
0: break;
1: style := Str;
end;
Tag := GetTag(S);
if (X>=0) and (Y>=0) and (StrLComp(Tag,'![CDATA[',8)=0) then begin
inc(Tag,8);
SetString(Str,Tag,S-Tag-3);
Str := StringReplaceAll(Str,'<','<');
Str := StringReplaceAll(Str,'>','>');
Str := StringReplaceAll(Str,'&','&');