-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathDGVisualStudioCodeIntegration.pas
More file actions
2723 lines (2435 loc) · 94.5 KB
/
Copy pathDGVisualStudioCodeIntegration.pas
File metadata and controls
2723 lines (2435 loc) · 94.5 KB
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
unit DGVisualStudioCodeIntegration;
interface
procedure Register;
implementation
uses
System.Classes,
System.SysUtils,
System.IOUtils,
System.JSON,
System.Variants,
System.UITypes,
System.Generics.Collections,
System.Win.Registry,
ToolsAPI,
DCCStrs,
CommonOptionStrs,
Vcl.Menus,
Vcl.Dialogs,
Vcl.ActnList,
Vcl.ExtCtrls,
Vcl.Forms,
FrmVSCodeLaunchError,
FrmSettingsFrame,
PluginSettings,
OSCmdLineExecutor,
Winapi.Windows;
// Returns true if the module was saved successfully (or it didn't need to be saved)
function SaveModule(Module: IOTAModule): boolean;
var
i: Integer;
editor: IOTAEditor;
begin
for i := 0 to Module.ModuleFileCount - 1 do begin
editor := Module.ModuleFileEditors[i];
if not Editor.Modified then
continue;
Result := Module.Save(False, True);
Exit;
end;
Result := True;
Exit;
end;
function SaveAllModules: boolean;
var
Services: IOTAModuleServices;
I: Integer;
Module: IOTAModule;
begin
Services := BorlandIDEServices as IOTAModuleServices;
for I := 0 to Services.ModuleCount - 1 do begin
Module := Services.Modules[I];
if not SaveModule(Module) then begin
Result := False;
Exit;
end;
end;
result := true;
end;
function FindSourceEditor(Module: IOTAModule; const FileExtensions: array of string): IOTASourceEditor;
var
i: Integer;
editor: IOTAEditor;
begin
for i := 0 to Module.ModuleFileCount - 1 do
begin
editor := Module.ModuleFileEditors[i];
if not Supports(editor, IOTASourceEditor, Result) then
continue;
var ext := ExtractFileExt(Result.FileName).toUpper;
for var scan in FileExtensions do
if scan = ext then
Exit;
end;
Result := nil;
end;
type
TCurrentSourceFileInfos = record
FileName: string;
Line: Integer;
Column: Integer;
end;
function TryGetCurrentSourceFileInfos(out FileInfos: TCurrentSourceFileInfos): Boolean;
var
EditView: IOTAEditView;
begin
FileInfos.FileName := '';
FileInfos.Line := -1;
FileInfos.Column := -1;
var Module := (BorlandIDEServices as IOTAModuleServices).CurrentModule;
if Module = nil then
Exit(False);
var Editor := FindSourceEditor(Module, ['.PAS', '.DPR', '.INC', '.DPK', '.DFM', '.FMX']);
if Editor = nil then
Exit(False);
if Editor.EditViewCount = 0 then
Exit(False);
FileInfos.FileName := Editor.FileName;
EditView := Editor.GetEditView(0);
if EditView <> nil then begin
FileInfos.Line := EditView.CursorPos.Line;
FileInfos.Column := EditView.CursorPos.Col;
end;
Result := True;
end;
function GetActiveProjectGroup: IOTAProjectGroup;
var
ModuleServices: IOTAModuleServices;
Module: IOTAModule;
begin
Result := nil;
ModuleServices := BorlandIDEServices as IOTAModuleServices;
for var i := 0 to ModuleServices.ModuleCount - 1 do begin
Module := ModuleServices.Modules[i];
if Supports(Module, IOTAProjectGroup, Result) then
Exit;
end;
end;
// Converts an absolute Windows path to a file URI as expected by VSCode:
// C:\foo\bar.json → file:///c%3A/foo/bar.json
function PathToFileUri(const Path: string): string;
var
S: string;
begin
S := StringReplace(Path, '\', '/', [rfReplaceAll]);
if (Length(S) >= 2) and (S[2] = ':') then
S[1] := LowerCase(S[1])[1];
S := StringReplace(S, ':', '%3A', [rfReplaceAll]);
Result := 'file:///' + S;
end;
// Builds the plugin's built-in default settings.
// These are used ONLY to create the shared defaults file the first time; from
// then on that versioned file is the source of truth and this is not consulted.
function BuildBuiltInWorkspaceSettings: TJSONObject;
begin
var Settings := TJSONObject.Create;
Result := Settings;
var FilesExclude := TJSONObject.Create;
for var Pattern in ['**/Debug', '**/Release',
'**/Win32/Debug', '**/Win32/Release',
'**/Win64/Debug', '**/Win64/Release',
'**/__recovery', '**/__history',
'**/.#*', '**/*.rc', '**/*.res', '**/*.RES',
'**/*.bak', '**/*.BAK'] do
FilesExclude.AddPair(Pattern, TJSONBool.Create(True));
Settings.AddPair('files.exclude', FilesExclude);
Settings.AddPair('files.trimTrailingWhitespace', TJSONBool.Create(True));
Settings.AddPair('files.autoGuessEncoding', TJSONBool.Create(True));
Settings.AddPair('editor.detectIndentation', TJSONBool.Create(False));
Settings.AddPair('editor.foldingMaximumRegions', TJSONNumber.Create(8000));
// [objectpascal]: bracket pairs for begin/end, case/end, etc.
var PascalSettings := TJSONObject.Create;
var PascalBrackets := TJSONArray.Create;
for var OpenClose in ['begin|end', 'case|end', 'repeat|until',
'try|end', 'while|do', 'if|then', 'for|do'] do begin
var Parts := OpenClose.Split(['|']);
var BracketPair := TJSONArray.Create;
BracketPair.Add(Parts[0]);
BracketPair.Add(Parts[1]);
PascalBrackets.Add(BracketPair);
end;
PascalSettings.AddPair('editor.language.brackets', PascalBrackets);
Settings.AddPair('[objectpascal]', PascalSettings);
// [markdown]: preserve trailing whitespace
var MarkdownSettings := TJSONObject.Create;
MarkdownSettings.AddPair('files.trimTrailingWhitespace', TJSONBool.Create(False));
MarkdownSettings.AddPair('editor.trimAutoWhitespace', TJSONBool.Create(False));
Settings.AddPair('[markdown]', MarkdownSettings);
end;
// Copies every key of ASource that ATarget does not already define. Objects are
// merged one key at a time rather than replaced, so a user who customised one
// entry of "files.exclude" still receives the other defaults. A value the user
// already set is never overwritten.
procedure MergeMissingInto(ATarget, ASource: TJSONObject);
begin
if (ATarget = nil) or (ASource = nil) then
Exit;
for var Pair in ASource do begin
var Key := Pair.JsonString.Value;
var Existing := ATarget.GetValue(Key);
if Existing = nil then begin
ATarget.AddPair(Key, Pair.JsonValue.Clone as TJSONValue);
Continue;
end;
if (Existing is TJSONObject) and (Pair.JsonValue is TJSONObject) then
MergeMissingInto(TJSONObject(Existing), TJSONObject(Pair.JsonValue));
end;
end;
// Applies standard Delphi settings to a JSON object.
// Used both in .code-workspace (Settings is the "settings" sub-object)
// and in .vscode/settings.json (Settings is the file root).
// The shared values come from the versioned defaults file; only the
// project-specific ones are still produced here.
procedure ApplyStandardDelphiSettings(Settings: TJSONObject; ActiveProject: IOTAProject;
ADefaults: TJSONObject);
begin
if ADefaults <> nil then
MergeMissingInto(Settings, ADefaults.GetValue('settings') as TJSONObject);
// delphiLsp.settingsFile: points at THIS project's .delphilsp.json, on THIS
// machine, so it stays generated and never enters the shared file.
if ActiveProject <> nil then begin
var DelphiLspFile := ChangeFileExt(ActiveProject.FileName, '.delphilsp.json');
if TFile.Exists(DelphiLspFile) and (Settings.GetValue('delphiLsp.settingsFile') = nil) then
Settings.AddPair('delphiLsp.settingsFile', PathToFileUri(DelphiLspFile));
end;
end;
function BuildExtensionRecommendations: TJSONArray;
begin
Result := TJSONArray.Create;
for var ExtId in ['embarcaderotechnologies.delphilsp'] do
Result.Add(ExtId);
end;
const
PLUGIN_MANAGED_BY_FIELD = 'managedBy';
PLUGIN_MANAGED_BY_VALUE = 'editinvscode-delphi-plugin';
PLUGIN_SETTINGS_MENU_CAPTION = 'Edit in VS Code Settings...';
// Adds the recommendations declared in the shared defaults file that the target
// does not list yet. User-added entries are preserved.
procedure MergeExtensionRecommendations(ExtensionsObject: TJSONObject; ADefaults: TJSONObject);
var
ExistingRecommendations: TJSONArray;
DefaultRecommendations: TJSONArray;
OwnsDefaults: Boolean;
HasItem: Boolean;
begin
DefaultRecommendations := nil;
OwnsDefaults := False;
if ADefaults <> nil then begin
var SharedExtensions := ADefaults.GetValue('extensions') as TJSONObject;
if SharedExtensions <> nil then
DefaultRecommendations := SharedExtensions.GetValue('recommendations') as TJSONArray;
end;
if DefaultRecommendations = nil then begin
DefaultRecommendations := BuildExtensionRecommendations;
OwnsDefaults := True;
end;
try
ExistingRecommendations := ExtensionsObject.GetValue('recommendations') as TJSONArray;
if ExistingRecommendations = nil then begin
ExtensionsObject.AddPair('recommendations', DefaultRecommendations.Clone as TJSONValue);
Exit;
end;
for var DefaultItem in DefaultRecommendations do begin
HasItem := False;
for var ExistingItem in ExistingRecommendations do
if SameText(ExistingItem.Value, DefaultItem.Value) then begin
HasItem := True;
Break;
end;
if not HasItem then
ExistingRecommendations.AddElement(DefaultItem.Clone as TJSONValue);
end;
finally
if OwnsDefaults then
DefaultRecommendations.Free;
end;
end;
procedure WriteTextIfChanged(const AFileName, AContent: string; AEncoding: TEncoding); forward;
const
// Shared with the team and meant to be put under version control, next to the
// .groupproj (or next to the project, in folder mode). The generated
// .code-workspace should NOT be versioned: it holds the checkout path, the
// project that happened to be active, and a per-developer debug configuration.
WORKSPACE_DEFAULTS_FILE = 'vscode-workspace-defaults.json';
WORKSPACE_DEFAULTS_VERSION = 1;
// Reads the shared defaults file, creating it from the plugin's built-in
// defaults when it is absent. The caller owns the result.
// An existing but unreadable file is never overwritten: the built-in defaults
// are used in memory and the user's file is left untouched.
function LoadOrCreateWorkspaceDefaults(const ADir: string): TJSONObject;
begin
var FileName := IncludeTrailingPathDelimiter(ADir) + WORKSPACE_DEFAULTS_FILE;
var AlreadyExists := TFile.Exists(FileName);
if AlreadyExists then begin
Result := nil;
try
Result := TJSONObject.ParseJSONValue(TFile.ReadAllText(FileName)) as TJSONObject;
except
Result := nil;
end;
if Result <> nil then
Exit;
end;
Result := TJSONObject.Create;
Result.AddPair('$comment', 'Shared VS Code settings for this project. Put this file under ' +
'version control. The generated .code-workspace next to it should not be versioned: it ' +
'contains machine-specific paths and a per-developer debug configuration.');
Result.AddPair('version', TJSONNumber.Create(WORKSPACE_DEFAULTS_VERSION));
Result.AddPair('settings', BuildBuiltInWorkspaceSettings);
var Extensions := TJSONObject.Create;
Extensions.AddPair('recommendations', BuildExtensionRecommendations);
Result.AddPair('extensions', Extensions);
if not AlreadyExists then
try
WriteTextIfChanged(FileName, Result.Format, TEncoding.UTF8);
except
// A read-only checkout must not break workspace generation.
end;
end;
procedure GenerateOrUpdateVSCodeFolderSettings(const FolderPath: string; ActiveProject: IOTAProject);
var
VscodePath, SettingsFile, ExtFile: string;
Root, ExtRoot: TJSONObject;
begin
VscodePath := IncludeTrailingPathDelimiter(FolderPath) + '.vscode';
if not TDirectory.Exists(VscodePath) then
TDirectory.CreateDirectory(VscodePath);
SettingsFile := VscodePath + '\settings.json';
if TFile.Exists(SettingsFile) then
Root := TJSONObject.ParseJSONValue(TFile.ReadAllText(SettingsFile)) as TJSONObject
else
Root := nil;
if Root = nil then
Root := TJSONObject.Create;
// Same shared file as in workspace mode, here next to the project.
var SharedDefaults := LoadOrCreateWorkspaceDefaults(FolderPath);
try
try
ApplyStandardDelphiSettings(Root, ActiveProject, SharedDefaults);
WriteTextIfChanged(SettingsFile, Root.Format, TEncoding.UTF8);
finally
Root.Free;
end;
ExtFile := VscodePath + '\extensions.json';
if TFile.Exists(ExtFile) then
ExtRoot := TJSONObject.ParseJSONValue(TFile.ReadAllText(ExtFile)) as TJSONObject
else
ExtRoot := nil;
if ExtRoot = nil then
ExtRoot := TJSONObject.Create;
try
MergeExtensionRecommendations(ExtRoot, SharedDefaults);
WriteTextIfChanged(ExtFile, ExtRoot.Format, TEncoding.UTF8);
finally
ExtRoot.Free;
end;
finally
SharedDefaults.Free;
end;
end;
// Writes AContent to AFileName only if it differs from the current content.
// Leaving an unchanged file completely untouched matters for more than editor
// file-watcher noise: a version-control client that decides by timestamp
// reports a rewritten-but-identical file as locally modified.
procedure WriteTextIfChanged(const AFileName, AContent: string; AEncoding: TEncoding);
begin
try
if TFile.Exists(AFileName) and (TFile.ReadAllText(AFileName, AEncoding) = AContent) then
Exit;
except
// Existing file unreadable: fall through and rewrite it.
end;
TFile.WriteAllText(AFileName, AContent, AEncoding);
end;
function GetDelphiBaseRegistryKey: string;
begin
Result := '';
var Services := BorlandIDEServices as IOTAServices;
if Services = nil then
Exit;
Result := Services.GetBaseRegistryKey;
if Result.StartsWith('\') then
Result := Result.Substring(1);
end;
function GetDelphiVersionFromRegistry: string;
begin
Result := '';
var BaseKey := GetDelphiBaseRegistryKey;
if BaseKey = '' then
Exit;
var SeparatorPos := LastDelimiter('\', BaseKey);
if SeparatorPos <= 0 then
Exit;
Result := Copy(BaseKey, SeparatorPos + 1, MaxInt);
end;
function ExpandDelphiMacros(const APath: string): string; forward;
// User-defined IDE macros (Tools > Options > Environment Variables), which live
// only in the IDE's registry hive and are NOT necessarily in the process
// environment. Library and browsing paths routinely refer to them, and an entry
// whose macro does not expand is discarded, so without this the directory is
// silently never searched.
function GetIdeEnvironmentVariable(const AName: string): string;
begin
Result := '';
var BaseKey := GetDelphiBaseRegistryKey;
if BaseKey = '' then
Exit;
var Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKeyReadOnly(BaseKey + '\Environment Variables') then
try
if Reg.ValueExists(AName) then
Result := Reg.ReadString(AName);
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
// Guards the mutual recursion between macro expansion and this fallback. An IDE
// variable may be defined in terms of others, and self-reference is normal:
// the IDE ships PATH = "$(PUBLIC)\...;$(PATH)". Depth-limited rather than
// cycle-detecting, because the caller already discards anything still holding
// an unexpanded macro.
threadvar
GMacroExpansionDepth: Integer;
function ResolveDelphiMacroFallback(const AMacroName: string): string;
begin
Result := '';
if SameText(AMacroName, 'BDS') then begin
var IdeExeDir := ExcludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)));
if IdeExeDir <> '' then
Exit(IdeExeDir);
Exit;
end;
if SameText(AMacroName, 'BDSCOMMONDIR') then begin
var PublicDir := GetEnvironmentVariable('PUBLIC');
var DelphiVersion := GetDelphiVersionFromRegistry;
if (PublicDir = '') or (DelphiVersion = '') then
Exit;
Exit(TPath.Combine(PublicDir, TPath.Combine('Documents\Embarcadero\Studio', DelphiVersion)));
end;
if SameText(AMacroName, 'BDSLIB') then begin
var BdsDir := ResolveDelphiMacroFallback('BDS');
if BdsDir = '' then
Exit;
Exit(TPath.Combine(BdsDir, 'lib'));
end;
Result := GetIdeEnvironmentVariable(AMacroName);
if (Result <> '') and Result.Contains('$(') and (GMacroExpansionDepth < 4) then begin
Inc(GMacroExpansionDepth);
try
Result := ExpandDelphiMacros(Result);
finally
Dec(GMacroExpansionDepth);
end;
end;
end;
// Expands Delphi make-style macros like $(BDS), $(BDSLIB) by reading env vars,
// falling back to derived values when the variable is not in the environment.
function ExpandDelphiMacros(const APath: string): string;
var
S, MacroName: string;
P1, P2: Integer;
begin
S := APath;
Result := '';
var Pos := 1;
while True do begin
P1 := S.IndexOf('$(', Pos - 1);
if P1 < 0 then begin
Result := Result + S.Substring(Pos - 1);
Break;
end;
Result := Result + S.Substring(Pos - 1, P1 - (Pos - 1));
P2 := S.IndexOf(')', P1 + 2);
if P2 < 0 then begin
Result := Result + S.Substring(P1);
Break;
end;
MacroName := S.Substring(P1 + 2, P2 - P1 - 2);
var EnvVal := GetEnvironmentVariable(MacroName);
if EnvVal = '' then
EnvVal := ResolveDelphiMacroFallback(MacroName);
if EnvVal <> '' then
Result := Result + EnvVal
else
Result := Result + '$(' + MacroName + ')';
Pos := P2 + 2;
end;
end;
function NormalizePathForJson(const APath: string): string;
begin
Result := StringReplace(Trim(APath), '\', '/', [rfReplaceAll]);
while (Result <> '') and (Result[High(Result)] = '/') do
SetLength(Result, Length(Result) - 1);
end;
function ExpandProjectMacros(const ARawPath, AProjectDir, AProjectName,
APlatformName, AConfigName: string): string;
begin
Result := ARawPath;
Result := StringReplace(Result, '$(Platform)', APlatformName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '$(Config)', AConfigName, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '$(ProjectDir)', AProjectDir, [rfReplaceAll, rfIgnoreCase]);
Result := StringReplace(Result, '$(ProjectName)', AProjectName, [rfReplaceAll, rfIgnoreCase]);
Result := ExpandDelphiMacros(Result);
end;
procedure GetActiveProjectBuildContext(AProject: IOTAProject;
out AProjectDir, AProjectName, APlatformName, AConfigName: string);
var
Confs: IOTAProjectOptionsConfigurations140;
begin
AProjectDir := '';
AProjectName := '';
APlatformName := 'Win64';
AConfigName := 'Debug';
if AProject = nil then
Exit;
AProjectDir := IncludeTrailingPathDelimiter(ExtractFilePath(AProject.FileName));
AProjectName := ChangeFileExt(ExtractFileName(AProject.FileName), '');
if Supports(AProject.ProjectOptions, IOTAProjectOptionsConfigurations140, Confs) then begin
var ActiveConfig := Confs.ActiveConfiguration;
if ActiveConfig <> nil then begin
if Trim(ActiveConfig.Platform) <> '' then
APlatformName := ActiveConfig.Platform;
if Trim(ActiveConfig.Name) <> '' then
AConfigName := ActiveConfig.Name;
end;
end;
end;
function GetProjectOptionValue(AProject: IOTAProject; const AOptionName: string): string;
var
Confs: IOTAProjectOptionsConfigurations140;
begin
Result := '';
if AProject = nil then
Exit;
if Supports(AProject.ProjectOptions, IOTAProjectOptionsConfigurations140, Confs) then begin
var ActiveConfig := Confs.ActiveConfiguration;
if ActiveConfig <> nil then begin
Result := Trim(ActiveConfig.GetValue(AOptionName, True));
if Result = '' then
Result := Trim(ActiveConfig.GetValue(AOptionName, False));
end;
end;
if Result = '' then begin
var Opts := AProject.GetProjectOptions;
if Opts <> nil then
Result := Trim(VarToStrDef(Opts.GetOptionValue(AOptionName), ''));
end;
end;
function ResolveProjectOutputDir(AProject: IOTAProject; const AOptionName,
AFallbackRelative: string): string;
var
ProjectDir, ProjectName, PlatformName, ConfigName: string;
RawPath, FullPath: string;
begin
Result := '';
if AProject = nil then
Exit;
GetActiveProjectBuildContext(AProject, ProjectDir, ProjectName, PlatformName, ConfigName);
RawPath := GetProjectOptionValue(AProject, AOptionName);
if RawPath = '' then
RawPath := AFallbackRelative;
RawPath := ExpandProjectMacros(RawPath, ProjectDir, ProjectName, PlatformName, ConfigName);
if RawPath = '' then
Exit;
FullPath := RawPath;
if not TPath.IsPathRooted(FullPath) then
FullPath := TPath.Combine(ProjectDir, FullPath);
FullPath := TPath.GetFullPath(FullPath);
Result := NormalizePathForJson(FullPath);
end;
function ResolveProjectOptionPathList(AProject: IOTAProject;
const AOptionName: string): TArray<string>;
var
ProjectDir, ProjectName, PlatformName, ConfigName: string;
RawList: string;
begin
Result := [];
if AProject = nil then
Exit;
RawList := GetProjectOptionValue(AProject, AOptionName);
if RawList = '' then
Exit;
GetActiveProjectBuildContext(AProject, ProjectDir, ProjectName, PlatformName, ConfigName);
for var RawPart in RawList.Split([';']) do begin
var Part := Trim(RawPart);
if Part = '' then
Continue;
Part := ExpandProjectMacros(Part, ProjectDir, ProjectName, PlatformName, ConfigName);
if Part = '' then
Continue;
if not TPath.IsPathRooted(Part) then
Part := TPath.Combine(ProjectDir, Part);
Part := NormalizePathForJson(TPath.GetFullPath(Part));
if Part = '' then
Continue;
var AlreadyAdded := False;
for var Existing in Result do
if SameText(Existing, Part) then begin
AlreadyAdded := True;
Break;
end;
if not AlreadyAdded then
Result := Result + [Part];
end;
end;
function ResolveIdePackageOutputDirs(AProject: IOTAProject): TArray<string>;
var
ProjectDir, ProjectName, PlatformName, ConfigName: string;
BaseKey: string;
PlatformsToScan: TArray<string>;
procedure AddDirFromRawValue(const ARawValue: string);
begin
var Expanded := Trim(ARawValue);
if Expanded = '' then
Exit;
Expanded := ExpandProjectMacros(Expanded, ProjectDir, ProjectName, PlatformName, ConfigName);
if Expanded = '' then
Exit;
Expanded := StringReplace(Expanded, '/', '\', [rfReplaceAll]);
if Pos('$(', Expanded) > 0 then
Exit;
if not TPath.IsPathRooted(Expanded) then
Exit;
Expanded := NormalizePathForJson(TPath.GetFullPath(Expanded));
if Expanded = '' then
Exit;
for var Existing in Result do
if SameText(Existing, Expanded) then
Exit;
Result := Result + [Expanded];
end;
begin
Result := [];
if AProject = nil then
Exit;
GetActiveProjectBuildContext(AProject, ProjectDir, ProjectName, PlatformName, ConfigName);
BaseKey := GetDelphiBaseRegistryKey;
if BaseKey = '' then
Exit;
PlatformsToScan := [PlatformName];
if not SameText(PlatformName, 'Win64') then
PlatformsToScan := PlatformsToScan + ['Win64'];
var Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
for var PlatformToScan in PlatformsToScan do begin
var LibraryKey := BaseKey + '\Library\' + PlatformToScan;
if not Reg.OpenKeyReadOnly(LibraryKey) then
Continue;
try
if Reg.ValueExists('Package DPL Output') then
AddDirFromRawValue(Reg.ReadString('Package DPL Output'));
if Reg.ValueExists('Package DCP Output') then
AddDirFromRawValue(Reg.ReadString('Package DCP Output'));
finally
Reg.CloseKey;
end;
if Length(Result) > 0 then
Break;
end;
finally
Reg.Free;
end;
end;
function ResolveProjectOutputFile(AProject: IOTAProject; const AFileName: string;
const ACandidateOptions: array of string; const ADefaultOption,
AFallbackRelative: string; const AExtraDirs: array of string): string;
var
CandidateDirs: TArray<string>;
procedure AddCandidate(const ADir: string);
begin
if ADir = '' then
Exit;
for var Existing in CandidateDirs do
if SameText(Existing, ADir) then
Exit;
CandidateDirs := CandidateDirs + [ADir];
end;
begin
CandidateDirs := [];
for var Opt in ACandidateOptions do
AddCandidate(ResolveProjectOutputDir(AProject, Opt, AFallbackRelative));
for var Dir in ResolveIdePackageOutputDirs(AProject) do
AddCandidate(Dir);
for var Dir in ResolveProjectOptionPathList(AProject, sUnitSearchPath) do
AddCandidate(Dir);
for var Dir in ResolveProjectOptionPathList(AProject, sLibraryPath) do
AddCandidate(Dir);
for var Dir in AExtraDirs do
AddCandidate(NormalizePathForJson(Dir));
if Length(CandidateDirs) = 0 then
AddCandidate(ResolveProjectOutputDir(AProject, ADefaultOption, AFallbackRelative));
for var Dir in CandidateDirs do begin
var Candidate := TPath.Combine(StringReplace(Dir, '/', PathDelim, [rfReplaceAll]), AFileName);
if TFile.Exists(Candidate) then
Exit(NormalizePathForJson(Candidate));
end;
if Length(CandidateDirs) > 0 then begin
var FirstCandidate := TPath.Combine(StringReplace(CandidateDirs[0], '/', PathDelim, [rfReplaceAll]), AFileName);
Exit(NormalizePathForJson(FirstCandidate));
end;
Result := NormalizePathForJson(AFileName);
end;
// Collects all source search paths visible to Delphi for AProject:
// - $(BDS)\source
// - project-level DCC_UnitSearchPath, for the ACTIVE build configuration
// - the IDE's global "Search Path" for the project's platform (registry)
// - the IDE's global "Browsing Path" for that platform (registry)
// There is deliberately no project-level browsing path: Delphi has none.
// DCCStrs.pas declares Include/Obj/Resource/UnitSearch/Framework/Library and
// nothing else, and no .dproj carries such a setting - it is an IDE-wide,
// per-platform value only.
// Returns a JSON array of forward-slash absolute paths ready for launch.json.
function CollectSourceSearchPaths(AProject: IOTAProject): TJSONArray;
var
Seen: TDictionary<string, Boolean>;
ProjectDir, ProjectName, PlatformName, ConfigName: string;
// Resolves one raw search-path entry to an absolute, forward-slash path.
// The entry arrives straight from the project options or the IDE registry,
// so it may be relative and may still contain Delphi macros.
procedure AddPath(const APath: string);
var
Norm: string;
begin
Norm := Trim(APath);
if Norm = '' then
Exit;
// Expand the full project macro set, not just the environment/BDS ones:
// a library or unit search path routinely contains $(Platform), $(Config)
// or $(ProjectDir). An unexpanded macro that reaches launch.json is not
// understood by VS Code and is discarded by the debug adapter, so the
// directory is silently never searched.
Norm := ExpandProjectMacros(Norm, ProjectDir, ProjectName, PlatformName, ConfigName);
if (Norm = '') or Norm.Contains('$(') then
Exit;
// A relative entry is relative to the project directory, exactly as the
// compiler resolves it.
if not TPath.IsPathRooted(Norm) then begin
if ProjectDir = '' then
Exit;
Norm := TPath.Combine(ProjectDir, Norm);
end;
try
Norm := NormalizePathForJson(TPath.GetFullPath(Norm));
except
Exit; // malformed entry (e.g. stale registry value): skip it
end;
if (Norm = '') or Seen.ContainsKey(LowerCase(Norm)) then
Exit;
Seen.Add(LowerCase(Norm), True);
Result.Add(Norm);
end;
procedure AddSemicolonList(const AList: string);
begin
for var Part in AList.Split([';']) do
AddPath(Part);
end;
begin
Result := TJSONArray.Create;
Seen := TDictionary<string, Boolean>.Create;
GetActiveProjectBuildContext(AProject, ProjectDir, ProjectName, PlatformName, ConfigName);
try
// Write the literal expanded BDS path -- VS Code cannot expand ${env:BDS}
// unless BDS is in VS Code's own process environment (it is not).
var BdsDir := GetEnvironmentVariable('BDS');
if BdsDir <> '' then
AddPath(BdsDir + '\source');
// Project-level paths. Read through GetProjectOptionValue so the ACTIVE
// build configuration wins: the raw IOTAProjectOptions getter returns the
// project-wide value and misses per-configuration overrides.
//
// The include path belongs here as much as the unit search path does. Code
// inside a `{$I foo.inc}` is attributed to foo.inc in the line table, not to
// the unit that includes it - one real project's map carries 654 such
// references - so stopping on such a line means the debugger has to find the
// .inc on disk, and this is where it is declared.
//
// Of the six path options Delphi declares per project (DCCStrs.pas:
// Include/Obj/Resource/UnitSearch/Framework/Library), these two are the only
// ones that name SOURCE directories; the rest point at .obj, .res,
// frameworks and libraries. There is no per-project browsing path.
if AProject <> nil then begin
AddSemicolonList(GetProjectOptionValue(AProject, sUnitSearchPath));
AddSemicolonList(GetProjectOptionValue(AProject, sIncludePath));
end;
// Global library / source paths stored by the IDE in the registry, for the
// platform the project actually builds for (PlatformName defaults to Win64).
var Services := BorlandIDEServices as IOTAServices;
if Services <> nil then begin
var BaseKey := Services.GetBaseRegistryKey;
if BaseKey.StartsWith('\') then
BaseKey := BaseKey.Substring(1);
var Reg := TRegistry.Create(KEY_READ);
try
Reg.RootKey := HKEY_CURRENT_USER;
if Reg.OpenKeyReadOnly(BaseKey + '\Library\' + PlatformName) then
try
if Reg.ValueExists('Search Path') then
AddSemicolonList(Reg.ReadString('Search Path'));
// The browsing path matters MORE than the search path here. Delphi
// uses the search path to find compiled units and the browsing path
// to find the SOURCES that go with them - which is exactly what a
// debugger needs to show you a line it has already resolved.
// Measured on one real installation: 89 of the 91 browsing entries
// appear nowhere in the search path, and 37 of those are
// third-party source trees. Without them the debugger resolves a
// frame in, say, a component library and then cannot display it.
if Reg.ValueExists('Browsing Path') then
AddSemicolonList(Reg.ReadString('Browsing Path'));
finally
Reg.CloseKey;
end;
finally
Reg.Free;
end;
end;
finally
Seen.Free;
end;
end;
procedure AddSearchPathIfMissing(APaths: TJSONArray; const APath: string);
begin
if APaths = nil then
Exit;
var Norm := Trim(APath);
if Norm = '' then
Exit;
Norm := StringReplace(Norm, '\', '/', [rfReplaceAll]);
while (Norm <> '') and (Norm[High(Norm)] = '/') do
SetLength(Norm, Length(Norm) - 1);
if Norm = '' then
Exit;
for var I := 0 to APaths.Count - 1 do begin
var V := APaths.Items[I];
if (V <> nil) and SameText(StringReplace(V.Value, '\', '/', [rfReplaceAll]), Norm) then
Exit;
end;
APaths.Add(Norm);
end;
const
// VS Code substitutes this before the configuration reaches the debug adapter,
// so the generated file carries no machine-specific root.
WORKSPACE_FOLDER_MACRO = '${workspaceFolder}';
// Rewrites an absolute path relative to the workspace root when it can be
// expressed that way, so the generated configuration does not depend on where
// the sources happen to be checked out. A dependency kept beside the workspace
// becomes "${workspaceFolder}/../shared/lib".
//
// The relative form is DERIVED from the real paths, never assumed: a path on a
// different drive, or one with no common root, is left absolute, which is still
// correct - only less portable.
function MakePathWorkspaceRelative(const APath, AWorkspaceDir: string): string;
begin
Result := NormalizePathForJson(APath);
if (Result = '') or (AWorkspaceDir = '') or Result.StartsWith('$') then
Exit;
if not TPath.IsPathRooted(Result) then
Exit;
var Base := IncludeTrailingPathDelimiter(
StringReplace(NormalizePathForJson(AWorkspaceDir), '/', '\', [rfReplaceAll]));
var Dest := StringReplace(Result, '/', '\', [rfReplaceAll]);
if not SameText(ExtractFileDrive(Base), ExtractFileDrive(Dest)) then
Exit;
// The path IS the workspace root (the common case for sourceRoot).
// ExtractRelativePath treats the last segment as a file name and would answer
// "..\<rootname>", which silently breaks the moment the project is checked out
// into a differently named folder.
if SameText(ExcludeTrailingPathDelimiter(Base), Dest) then
Exit(WORKSPACE_FOLDER_MACRO);
var Rel := ExtractRelativePath(Base, Dest);
if (Rel = '') or TPath.IsPathRooted(Rel) then
Exit;
Rel := NormalizePathForJson(Rel);
if Rel.StartsWith('./') then
Rel := Rel.Substring(2);
if (Rel = '') or (Rel = '.') then
Exit(WORKSPACE_FOLDER_MACRO);
Result := WORKSPACE_FOLDER_MACRO + '/' + Rel;
end;
// Applies MakePathWorkspaceRelative to every path a delphi-win64 configuration
// carries. Called once on the finished configuration, where the workspace root
// is known - CollectSourceSearchPaths itself has no way to know it.
procedure MakeLaunchConfigPortable(AConfig: TJSONObject; const AWorkspaceDir: string);
procedure RewritePathPair(AObj: TJSONObject; const AName: string);
begin
if AObj = nil then
Exit;
var Value := AObj.GetValue(AName);
if not (Value is TJSONString) then
Exit;
var Portable := MakePathWorkspaceRelative(Value.Value, AWorkspaceDir);
if Portable = Value.Value then
Exit;
AObj.RemovePair(AName).Free;
AObj.AddPair(AName, Portable);
end;
begin
if (AConfig = nil) or (AWorkspaceDir = '') then
Exit;
for var PairName in ['program', 'sourceRoot', 'mapFile', 'rsmFile'] do
RewritePathPair(AConfig, PairName);
var Paths := AConfig.GetValue('sourceSearchPaths');
if Paths is TJSONArray then begin
var Portable := TJSONArray.Create;
for var I := 0 to TJSONArray(Paths).Count - 1 do
Portable.Add(MakePathWorkspaceRelative(TJSONArray(Paths).Items[I].Value, AWorkspaceDir));
AConfig.RemovePair('sourceSearchPaths').Free;
AConfig.AddPair('sourceSearchPaths', Portable);