Debian Codegraph @

src/delphi/castleinternaldelphidesign.pas

raw
1 {
2 Copyright 2022-2024 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Utilities for Delphi (both VCL and FMX), only design-time.
17
18 - Sets OnGetDesignTimeProjectPath so that other code
19 (design-time or not only design-time) can use it, if assigned.
20
21 - Sets up Delphi IDE menu items to configure project for Castle Game Engine. }
22 unit CastleInternalDelphiDesign;
23
24 interface
25
26 //procedure Register;
27
28 implementation
29
30 { Documentation:
31
32 Embarcadero:
33 https://docwiki.embarcadero.com/RADStudio/Athens/en/Extending_the_IDE_Using_the_Tools_API
34 https://docwiki.embarcadero.com/RADStudio/Athens/en/Adding_an_Item_to_the_Main_Menu_of_the_IDE
35 https://docwiki.embarcadero.com/RADStudio/Athens/en/Creating_or_Extending_a_Package_to_Use_the_Tools_API
36 https://docwiki.embarcadero.com/RADStudio/Athens/en/Obtaining_Tools_API_Services
37
38 Others:
39 https://www.gexperts.org/open-tools-api-faq/#menuitem
40 Note: Do not actually search by menu item Caption, because IDE may be localized,
41 instead hardcode the Name.
42 Embarcadero docs say so.
43 https://www.davidghoyle.co.uk/WordPress/?p=777
44
45 See sources, e.g.
46 C:\Program Files (x86)\Embarcadero\Studio\22.0\source\ToolsAPI\ToolsAPI.pas
47
48 See tests in
49 https://github.com/michaliskambi/delphi-test-package-design-features
50 }
51
52 uses SysUtils, Classes,
53 { In practice, this unit is Windows-only, just like Delphi IDE.
54 But we make some effort to use only cross-platform API,
55 and put platform-specific API under $ifdef, in the hope to use
56 in a cross-platform IDE some day. }
57 {$ifdef MSWINDOWS} Windows, ShellApi, Registry, {$endif}
58 ToolsAPI, PlatformConst, // design-time only unit
59 Vcl.Menus, Vcl.Dialogs, Vcl.FileCtrl, Vcl.ActnList, Vcl.Controls,
60 CastleInternalDelphiUtils, CastleConfig, CastleApplicationProperties,
61 CastleUtils, CastleInternalTools, CastleStringUtils, CastleOpenDocument,
62 Dom, CastleXmlUtils, CastleUriUtils, CastleFilesUtils;
63
64 { Utilities ------------------------------------------------------------------ }
65
66 { Current Delphi project path.
67 Ends with path delimiter.
68 Exception if no project is open now. }
69 function GetProjectPath: String;
70 begin
71 if GetActiveProject = nil then
72 raise Exception.Create('No active Delphi project');
73
74 Result := ExtractFilePath(GetActiveProject.FileName);
75 end;
76
77 { Get the current project CastleEngineManifest.xml filename,
78 but *without yet checking does it actually exist (so it may not be a CGE project at all).
79 Exception if no project is open now. }
80 function GetPotentialProjectCastleManifest: String;
81 begin
82 Result := InclPathDelim(GetProjectPath) + 'CastleEngineManifest.xml';
83 end;
84
85 { Run a process.
86 Does not wait for process to finish,
87 does not capture any process output (stdout, stderr),
88 does not pass anything to process input.
89
90 @param(ExeName Executable filename.
91 Make it always an absolute path, though it actually supports now
92 also filenames relative to current working dir.)
93
94 @param(Parameters Parameters to pass.
95
96 Can specify multiple parameters,
97 but for now suffering from the same weirdness as underlying Windows API
98 -- instead of taking a list of String,
99 all parameters are specified as one long String with parameters
100 separated by spaces and optionally surrounded by double quotes.)
101
102 @param(WorkingDirectory Working directory for the process.)
103 }
104 procedure ExecuteProcess(const ExeName, Parameters, WorkingDirectory: String);
105 {$ifdef MSWINDOWS}
106 var
107 ShExecInfo: TShellExecuteInfo;
108 Service: IOTAServices;
109 begin
110 if not FileExists(ExeName) then
111 raise Exception.CreateFmt('File to execute not found: "%s"', [ExeName]);
112
113 Service := BorlandIDEServices as IOTAServices;
114
115 FillChar(ShExecInfo, SizeOf(ShExecInfo), 0);
116 ShExecInfo.cbSize := SizeOf(ShExecInfo);
117 ShExecInfo.Wnd := Service.GetParentHandle;
118 ShExecInfo.lpVerb := 'open';
119 ShExecInfo.lpFile := PWideChar(ExeName);
120 ShExecInfo.lpParameters := PWideChar(Parameters);
121 ShExecInfo.lpDirectory := PWideChar(WorkingDirectory);
122 ShExecInfo.nShow := SW_SHOWNORMAL;
123 if not ShellExecuteEx(@ShExecInfo) then
124 RaiseLastOSError;
125 {$else}
126 begin
127 raise Exception.Create('Executing process not implemented on this platform');
128 {$endif}
129 end;
130
131 { Like ExtractFilePath, but honors both / and PathDelim, just like Windows does.
132 Delphi's ExtractFilePath doesn't stop at / (slash), although it is accepted
133 as a path delimiter on all platforms, including Windows. }
134 function RobustExtractFilePath(const S: String): String;
135 begin
136 if '/' <> PathDelim then
137 Result := SReplaceChars(S, '/', PathDelim);
138 Result := ExtractFilePath(Result);
139 end;
140
141 { Like ExtractFileName, but honors both / and PathDelim, just like Windows does.
142 Delphi's ExtractFileName doesn't stop at / (slash), although it is accepted
143 as a path delimiter on all platforms, including Windows. }
144 function RobustExtractFileName(const S: String): String;
145 begin
146 if '/' <> PathDelim then
147 Result := SReplaceChars(S, '/', PathDelim);
148 Result := ExtractFileName(Result);
149 end;
150
151 { TCompileNotifier ----------------------------------------------------------- }
152
153 type
154 TProjectCompileFinishedEvent = procedure(
155 const Project: IOTAProject; const Result: TOTACompileResult) of object;
156
157 TCompileNotifier = class(TComponent, IOTACompileNotifier)
158 public
159 OnProjectCompileFinished: TProjectCompileFinishedEvent;
160 procedure ProjectCompileStarted(const Project: IOTAProject; Mode: TOTACompileMode);
161 procedure ProjectCompileFinished(const Project: IOTAProject; Result: TOTACompileResult);
162 procedure ProjectGroupCompileStarted(Mode: TOTACompileMode);
163 procedure ProjectGroupCompileFinished(Result: TOTACompileResult);
164 end;
165
166 procedure TCompileNotifier.ProjectCompileStarted(const Project: IOTAProject; Mode: TOTACompileMode);
167 begin
168 end;
169
170 procedure TCompileNotifier.ProjectCompileFinished(const Project: IOTAProject; Result: TOTACompileResult);
171 begin
172 if Assigned(OnProjectCompileFinished) then
173 OnProjectCompileFinished(Project, Result);
174 end;
175
176 procedure TCompileNotifier.ProjectGroupCompileStarted(Mode: TOTACompileMode);
177 begin
178 end;
179
180 procedure TCompileNotifier.ProjectGroupCompileFinished(Result: TOTACompileResult);
181 begin
182 end;
183
184 { TCastleDelphiIdeIntegration ----------------------------------------------- }
185
186 type
187 TCastleDelphiIdeIntegration = class(TComponent)
188 strict private
189 FEnginePath: String;
190 FEnginePathInitialized: Boolean;
191 MenuEngineRoot,
192 MenuSetEnginePath, MenuOpenEditor,
193 MenuAddPathsProject, MenuRemovePathsProject,
194 MenuAddPathsGlobal, MenuRemovePathsGlobal,
195 MenuWebsite, MenuDelphiDocs, MenuApiReference, MenuDonate: TMenuItem;
196 ActionSetEnginePath, ActionOpenEditor,
197 ActionAddPathsProject, ActionRemovePathsProject,
198 ActionAddPathsGlobal, ActionRemovePathsGlobal,
199 ActionWebsite, ActionDelphiDocs, ActionApiReference, ActionDonate: TAction;
200
201 CompileNotifier: TCompileNotifier;
202 CompileNotifierIndexInitialized: Boolean;
203 CompileNotifierIndex: Integer;
204
205 procedure EnsureConfigInitialized;
206
207 function GetEnginePath: String;
208 procedure SetEnginePath(const Value: String);
209
210 { Engine path, as provided by user.
211 This may but doesn't have to end with path delimiter,
212 it depends on what user provided. So be safe when using it,
213 e.g. InclPathDelim(EnginePath) + 'something'. }
214 property EnginePath: String read GetEnginePath write SetEnginePath;
215
216 procedure ProjectCompileFinished(const Project: IOTAProject;
217 const Result: TOTACompileResult);
218
219 { Does given source dir (assumed to be absolute, for relative we'll always
220 answer "false") is equal to EngineSrcDir (relative to CGE src/).
221
222 Tolerates various ways how the paths can be written,
223 to avoid adding duplicates (in ClickAddPaths*)
224 and to remove correctly (in ClickRemovePaths*). }
225 function DirIsEngineDir(
226 const SrcDir, EngineSrcDir: String): Boolean;
227
228 { Add CGE paths to the semicolon-separated paths in Paths.
229 Paths may be absolute.
230 Returns number of paths added. }
231 function AddPaths(var Paths: String): Cardinal;
232
233 { Remove CGE paths from the semicolon-separated paths in Paths.
234 See AddPaths for details.
235 Returns number of paths removed. }
236 function RemovePaths(var Paths: String): Cardinal;
237
238 { Action event handlers }
239 procedure ClickSetEnginePath(Sender: TObject);
240 procedure ClickOpenEditor(Sender: TObject);
241 procedure ClickAddPathsProject(Sender: TObject);
242 procedure ClickRemovePathsProject(Sender: TObject);
243 procedure ClickAddPathsGlobal(Sender: TObject);
244 procedure ClickRemovePathsGlobal(Sender: TObject);
245 procedure ClickWebsite(Sender: TObject);
246 procedure ClickDelphiDocs(Sender: TObject);
247 procedure ClickApiReference(Sender: TObject);
248 procedure ClickDonate(Sender: TObject);
249 procedure UpdateEnabledIfProjectAndCgeInitialized(Sender: TObject);
250 procedure UpdateEnabledIfCgeInitialized(Sender: TObject);
251 public
252 constructor Create(AOwner: TComponent); override;
253 destructor Destroy; override;
254 end;
255
256 constructor TCastleDelphiIdeIntegration.Create(AOwner: TComponent);
257
258 { Check menu item with given name exists. }
259 function MenuItemExists(MenuItems: TMenuItem; const SearchName: String): Boolean;
260 var
261 I: Integer;
262 Mi: TMenuItem;
263 begin
264 for I := 0 To MenuItems.Count - 1 do
265 begin
266 Mi := MenuItems[I];
267 if (Mi.Name = SearchName) or MenuItemExists(Mi, SearchName) then
268 Exit(true);
269 end;
270 Result := false;
271 end;
272
273 procedure InitializeMenu;
274 var
275 Services: INTAServices;
276 MenuSeparator1, MenuSeparator2, MenuSeparator3: TMenuItem;
277 PreviousSiblingMenuItemName: String;
278 begin
279 if not Supports(BorlandIDEServices, INTAServices, Services) then
280 Exit;
281
282 ActionSetEnginePath := TAction.Create(Self);
283 ActionSetEnginePath.Caption := 'Set Engine Path...';
284 ActionSetEnginePath.OnExecute := ClickSetEnginePath;
285 MenuSetEnginePath := TMenuItem.Create(Self);
286 MenuSetEnginePath.Action := ActionSetEnginePath;
287
288 ActionOpenEditor := TAction.Create(Self);
289 ActionOpenEditor.Caption := 'Open Editor';
290 ActionOpenEditor.OnExecute := ClickOpenEditor;
291 ActionOpenEditor.OnUpdate := UpdateEnabledIfProjectAndCgeInitialized;
292 MenuOpenEditor := TMenuItem.Create(Self);
293 MenuOpenEditor.Action := ActionOpenEditor;
294
295 MenuSeparator1 := TMenuItem.Create(Self);
296 MenuSeparator1.Caption := '-';
297
298 ActionAddPathsGlobal := TAction.Create(Self);
299 ActionAddPathsGlobal.Caption := 'Configure Delphi to Use Engine';
300 ActionAddPathsGlobal.OnExecute := ClickAddPathsGlobal;
301 ActionAddPathsGlobal.OnUpdate := UpdateEnabledIfCgeInitialized;
302 MenuAddPathsGlobal := TMenuItem.Create(Self);
303 MenuAddPathsGlobal.Action := ActionAddPathsGlobal;
304
305 ActionRemovePathsGlobal := TAction.Create(Self);
306 ActionRemovePathsGlobal.Caption := 'Remove Engine Configuration from Delphi';
307 ActionRemovePathsGlobal.OnExecute := ClickRemovePathsGlobal;
308 ActionRemovePathsGlobal.OnUpdate := UpdateEnabledIfCgeInitialized;
309 MenuRemovePathsGlobal := TMenuItem.Create(Self);
310 MenuRemovePathsGlobal.Action := ActionRemovePathsGlobal;
311
312 MenuSeparator2 := TMenuItem.Create(Self);
313 MenuSeparator2.Caption := '-';
314
315 ActionAddPathsProject := TAction.Create(Self);
316 ActionAddPathsProject.Caption := 'Configure Only Current Project (for Current Platform and Debug/Release Config) to Use Engine';
317 ActionAddPathsProject.OnExecute := ClickAddPathsProject;
318 ActionAddPathsProject.OnUpdate := UpdateEnabledIfProjectAndCgeInitialized;
319 MenuAddPathsProject := TMenuItem.Create(Self);
320 MenuAddPathsProject.Action := ActionAddPathsProject;
321
322 ActionRemovePathsProject := TAction.Create(Self);
323 ActionRemovePathsProject.Caption := 'Remove Engine Configuration from the Current Project';
324 ActionRemovePathsProject.OnExecute := ClickRemovePathsProject;
325 ActionRemovePathsProject.OnUpdate := UpdateEnabledIfProjectAndCgeInitialized;
326 MenuRemovePathsProject := TMenuItem.Create(Self);
327 MenuRemovePathsProject.Action := ActionRemovePathsProject;
328
329 MenuSeparator3 := TMenuItem.Create(Self);
330 MenuSeparator3.Caption := '-';
331
332 ActionWebsite := TAction.Create(Self);
333 ActionWebsite.Caption := 'Engine Documentation';
334 ActionWebsite.OnExecute := ClickWebsite;
335 MenuWebsite := TMenuItem.Create(Self);
336 MenuWebsite.Action := ActionWebsite;
337
338 ActionDelphiDocs := TAction.Create(Self);
339 ActionDelphiDocs.Caption := 'Documentation of Delphi Integration';
340 ActionDelphiDocs.OnExecute := ClickDelphiDocs;
341 MenuDelphiDocs := TMenuItem.Create(Self);
342 MenuDelphiDocs.Action := ActionDelphiDocs;
343
344 ActionApiReference := TAction.Create(Self);
345 ActionApiReference.Caption := 'API Reference';
346 ActionApiReference.OnExecute := ClickApiReference;
347 MenuApiReference := TMenuItem.Create(Self);
348 MenuApiReference.Action := ActionApiReference;
349
350 ActionDonate := TAction.Create(Self);
351 ActionDonate.Caption := 'Support us on Patreon';
352 ActionDonate.OnExecute := ClickDonate;
353 MenuDonate := TMenuItem.Create(Self);
354 MenuDonate.Action := ActionDonate;
355
356 MenuEngineRoot := TMenuItem.Create(Self);
357 MenuEngineRoot.Caption := 'Castle Game Engine';
358 MenuEngineRoot.Name := 'CastleGameEngineMenu';
359
360 { Use hardcoded menu item name, like
361 - ToolsToolsItem ("Configure Tools")
362 - ToolsMenu ("Tools" from main menu)
363 - ViewTranslationManagerMenu ("Translation Manager")
364 This is the proper approach, acoording to
365 https://docwiki.embarcadero.com/RADStudio/Athens/en/Adding_an_Item_to_the_Main_Menu_of_the_IDE .
366
367 Note: Do not add menu items after "Configure Tools" (name 'ToolsToolsItem').
368 These will be removed when Delphi IDE is started, and replaced with
369 menu items that correspond to stuff confiured in "Configure Tools".
370 E.g. this will not work reliably, stuff will disappear after Delphi restart:
371
372 Services.AddActionMenu('ToolsToolsItem', nil, MenuEngineRoot, true, true);
373
374 So a custom "Tools" submenu should be added before "Configure Tools". }
375 PreviousSiblingMenuItemName := 'ViewTranslationManagerMenu';
376 if not MenuItemExists(Services.MainMenu.Items, PreviousSiblingMenuItemName) then
377 begin
378 { Delphi 10.2.3 and 11.3 have 'ViewTranslationManagerMenu'.
379 Delphi 12.0 does not.
380 Use 'CustomToolsItem' there. }
381 PreviousSiblingMenuItemName := 'CustomToolsItem';
382 { Some additional fallbacks, just to be safer for the future,
383 and eventually to make a good error message. }
384 if not MenuItemExists(Services.MainMenu.Items, PreviousSiblingMenuItemName) then
385 begin
386 PreviousSiblingMenuItemName := 'ToolsOptionsItem';
387 if not MenuItemExists(Services.MainMenu.Items, PreviousSiblingMenuItemName) then
388 begin
389 raise Exception.Create('Cannot find a reasonable sibling menu item for "Castle Game Engine" menu. Please report a bug to the CGE developers, making a note of your Delphi IDE version and possible custom plugings.');
390 end;
391 end;
392 end;
393
394 { ToolsAPI comments recommend to wrap menu udpates in MenuBegin/EndUpdate.
395 No noticeable effect observed, but makes sense, let's follow the recommendation. }
396 Services.MenuBeginUpdate;
397 try
398 Services.AddActionMenu(PreviousSiblingMenuItemName, nil, MenuEngineRoot, true, false);
399
400 { We can add submenu items using MenuEngineRoot.Add,
401 like " MenuEngineRoot.Add(MenuSetEnginePath);",
402 or by adding using Services.AddActionMenu. }
403 Services.AddActionMenu('CastleGameEngineMenu', ActionSetEnginePath, MenuSetEnginePath, true, true);
404 Services.AddActionMenu('CastleGameEngineMenu', ActionOpenEditor, MenuOpenEditor, true, true);
405 Services.AddActionMenu('CastleGameEngineMenu', nil, MenuSeparator1, true, true);
406 Services.AddActionMenu('CastleGameEngineMenu', ActionAddPathsGlobal, MenuAddPathsGlobal, true, true);
407 Services.AddActionMenu('CastleGameEngineMenu', ActionRemovePathsGlobal, MenuRemovePathsGlobal, true, true);
408 Services.AddActionMenu('CastleGameEngineMenu', nil, MenuSeparator2, true, true);
409 Services.AddActionMenu('CastleGameEngineMenu', ActionAddPathsProject, MenuAddPathsProject, true, true);
410 Services.AddActionMenu('CastleGameEngineMenu', ActionRemovePathsProject, MenuRemovePathsProject, true, true);
411 Services.AddActionMenu('CastleGameEngineMenu', nil, MenuSeparator3, true, true);
412 Services.AddActionMenu('CastleGameEngineMenu', ActionWebsite, MenuWebsite, true, true);
413 Services.AddActionMenu('CastleGameEngineMenu', ActionDelphiDocs, MenuDelphiDocs, true, true);
414 Services.AddActionMenu('CastleGameEngineMenu', ActionApiReference, MenuApiReference, true, true);
415 Services.AddActionMenu('CastleGameEngineMenu', ActionDonate, MenuDonate, true, true);
416
417 finally Services.MenuEndUpdate end;
418 end;
419
420 procedure InitializeCompileNotification;
421 var
422 Services: IOTACompileServices;
423 begin
424 if not Supports(BorlandIDEServices, IOTACompileServices, Services) then
425 Exit;
426
427 CompileNotifier := TCompileNotifier.Create(Self);
428 CompileNotifier.OnProjectCompileFinished := ProjectCompileFinished;
429 CompileNotifierIndex := Services.AddNotifier(CompileNotifier);
430 CompileNotifierIndexInitialized := true;
431 end;
432
433 begin
434 inherited;
435 InitializeMenu;
436 InitializeCompileNotification;
437 end;
438
439 destructor TCastleDelphiIdeIntegration.Destroy;
440
441 procedure FinalizeCompileNotification;
442 var
443 Services: IOTACompileServices;
444 begin
445 if not Supports(BorlandIDEServices, IOTACompileServices, Services) then
446 Exit;
447
448 if CompileNotifierIndexInitialized then
449 begin
450 CompileNotifierIndexInitialized := false;
451 Services.RemoveNotifier(CompileNotifierIndex);
452 end;
453
454 { Note that we don't free CompileNotifier,
455 and our code works regardless of if Services.RemoveNotifier frees it or not.
456 CompileNotifier is owned by this component. }
457 end;
458
459 begin
460 { Note: It seems that MenuEngineRoot is not removed from ToolsMenu automatically when
461 TTestDelphiIdeIntegration instance is destroyed,
462 even when MenuEngineRoot is owned by TTestDelphiIdeIntegration (was created as
463 "MenuEngineRoot := TMenuItem.Create(Self)").
464 Freing it explicitly here works.
465
466 Note that we shouldn't free subitems like "FreeAndNil(MenuSetEnginePath);"
467 they will be freed automatically
468 (trying to free them would result in invalid pointer exceptions).
469
470 Why? It seems Delphi IDE does something funny and changes ownership
471 of items added using Services.AddActionMenu -- so they are owned by their parents
472 effectively?
473
474 We create them all now with Owner=nil, to avoid confusion.
475 }
476 FreeAndNil(MenuEngineRoot);
477
478 FinalizeCompileNotification;
479
480 inherited;
481 end;
482
483 procedure TCastleDelphiIdeIntegration.UpdateEnabledIfProjectAndCgeInitialized(Sender: TObject);
484 begin
485 (Sender as TAction).Enabled :=
486 (GetActiveProject <> nil) and
487 (EnginePath <> '');
488 end;
489
490 procedure TCastleDelphiIdeIntegration.UpdateEnabledIfCgeInitialized(Sender: TObject);
491 begin
492 (Sender as TAction).Enabled :=
493 (EnginePath <> '');
494 end;
495
496 procedure TCastleDelphiIdeIntegration.EnsureConfigInitialized;
497 begin
498 { Read our config file on demand.
499
500 Reason: for robustness: in initialization / finalization of this unit,
501 we try to do as little as possible, because this happens when Delphi IDE
502 starts / stops, and any errors are hard to debug there
503 (hard to even pinpoint "this is CGE code fault").
504 We prefer to do all possible work in response to use clicking
505 on CGE menu items.
506
507 Note: Since the introduction of UpdateEnabledIfProjectAndCgeInitialized,
508 this is somewhat pointless: UpdateEnabledIfProjectAndCgeInitialized will
509 read EnginePath as soon as any project is opened.
510 And we decided to go with it: the UX improvement thanks
511 to UpdateEnabledIfProjectAndCgeInitialized (clearly communicates
512 that engine path must be set) is worth it.
513
514 We store our config in CGE UserConfig.
515 We do not use registry and Delphi GetBaseRegistryKey.
516
517 Reason: It is actually nice that CGE config is cross-Delphi-version.
518 And this way we can read it easily from other CGE code,
519 if it will ever be needed (but we don't plan to need it -- CGE
520 path set in Delphi should be independent from everything else,
521 to be simple).
522 }
523 if not FEnginePathInitialized then
524 begin
525 FEnginePathInitialized := true;
526 ApplicationProperties.ApplicationName := 'delphi_ide_with_castle_game_engine';
527 UserConfig.Load;
528 FEnginePath := UserConfig.GetValue('engine_path', '');
529 end;
530 Assert(FEnginePathInitialized);
531 end;
532
533 function TCastleDelphiIdeIntegration.GetEnginePath: String;
534 begin
535 EnsureConfigInitialized;
536 Result := FEnginePath;
537 end;
538
539 procedure TCastleDelphiIdeIntegration.SetEnginePath(const Value: String);
540 begin
541 // make sure we initialized UserConfig
542 EnsureConfigInitialized;
543 if FEnginePath <> Value then
544 begin
545 FEnginePath := Value;
546 UserConfig.SetDeleteValue('engine_path', FEnginePath, '');
547 UserConfig.Save;
548 end;
549 end;
550
551 procedure TCastleDelphiIdeIntegration.ClickSetEnginePath(Sender: TObject);
552 var
553 S: String;
554 Directories: TArray<string>;
555 begin
556 S := EnginePath;
557
558 { Note: Delphi has 3 SelectDirectory overloads with vastly different UI,
559 see http://docwiki.embarcadero.com/Libraries/Sydney/en/Vcl.FileCtrl.SelectDirectory . }
560
561 { Do not use this style: Looks really dated.
562 if SelectDirectory(S, [], 0) then
563 EnginePath := S;
564 }
565
566 { Do not use this style:
567
568 The validation message is bad UX, main Delphi IDE form is then
569 shown, but modal form to choose another directory blocks it.
570 Maybe it is better if one passes non-nil Parent (last parameter),
571 but we don't have it, we only have Services.GetParentHandle:HWND.
572 (from IOTAServices)
573
574 if SelectDirectory('Castle Game Engine Path', '', S,
575 [sdShowEdit, sdNewUI, sdValidateDir], nil) then
576 }
577
578 if SelectDirectory('', Directories, [], 'Castle Game Engine Path') then
579 begin
580 S := Directories[0];
581 if not SysUtils.DirectoryExists(S) then
582 raise Exception.CreateFmt('Directory "%s" does not exist', [S]);
583 if not SysUtils.DirectoryExists(InclPathDelim(S) + 'src') then
584 raise Exception.CreateFmt('Directory "%s" does not look like CGE root directory, missing "src" subdirectory', [S]);
585 EnginePath := S;
586 end;
587 end;
588
589 procedure TCastleDelphiIdeIntegration.ClickOpenEditor(Sender: TObject);
590 const
591 ManifestTemplate =
592 '<?xml version="1.0" encoding="utf-8"?>' + NL +
593 '<project name="${PROJECT_NAME}"' + NL +
594 ' standalone_source="${PROJECT_NAME}.dpr"' + NL +
595 ' compiler="delphi"' + NL +
596 '>' + NL +
597 '</project>' + NL;
598 var
599 ExeName, Proj, ProjManifest, ProposedProjectName, ManifestContents: String;
600 begin
601 Proj := GetProjectPath;
602 Assert(GetActiveProject <> nil); // otherwise GetProjectPath would raise exception
603
604 if EnginePath = '' then // this action should ctually be disabled in such case
605 Exit;
606
607 ProjManifest := GetPotentialProjectCastleManifest;
608 if not FileExists(ProjManifest) then
609 begin
610 ProposedProjectName := ChangeFileExt(RobustExtractFileName(GetActiveProject.ProjectOptions.TargetName), '');
611 if MessageDlg(Format(
612 'To open project using Castle Game Engine editor, it needs to have CastleEngineManifest.xml file. See the https://castle-engine.io/control_on_form for details.' + NL +
613 NL +
614 'Create a simplest CastleEngineManifest.xml for a project named "%s" with Delphi as default compiler?', [
615 ProposedProjectName
616 ]), mtInformation, [mbOK, mbCancel], 0) <> mrOK then
617 Exit;
618
619 // auto-create simple manifest, just like https://castle-engine.io/control_on_form#_opening_the_project_in_cge_editor proposes
620 ManifestContents := StringReplace(ManifestTemplate, '${PROJECT_NAME}', ProposedProjectName, [rfReplaceAll]);
621 StringToFile(FilenameToUriSafe(ProjManifest), AnsiString(ManifestContents));
622 end;
623
624 ExeName := InclPathDelim(EnginePath) + 'bin' + PathDelim + 'castle-editor' + ExeExtension;
625 { Note: Do not use Proj as editor working directory,
626 as then editor on Windows could use DLLs from the project dir,
627 locking them -- so e.g. "clean" from editor then cannot remove DLLs. }
628 ExecuteProcess(ExeName, '"' + ProjManifest + '"', RobustExtractFilePath(ExeName));
629 end;
630
631 function TCastleDelphiIdeIntegration.DirIsEngineDir(
632 const SrcDir, EngineSrcDir: String): Boolean;
633
634 { Normalize directory: only slashes (no \), and not ending with / or \. }
635 function NormalizePath(const S: String): String;
636 begin
637 Result := ExclPathDelim(S);
638 Result := SReplaceChars(Result, '\', '/');
639 end;
640
641 var
642 SrcDirNormalized: String;
643 begin
644 SrcDirNormalized := NormalizePath(SrcDir);
645 Result := SameFileName(SrcDirNormalized,
646 NormalizePath(InclPathDelim(EnginePath) + 'src' + PathDelim + EngineSrcDir));
647 end;
648
649 function TCastleDelphiIdeIntegration.AddPaths(var Paths: String): Cardinal;
650
651 { Add EngineSrcDir (relative to CGE src/) to
652 SrcDirs (absolute or relative to project, though we just ignore relative ones
653 when comparing),
654 unless it is there already. }
655 procedure AddEngineSrcDir(const EngineSrcDir: String; const SrcDirs: TStringList);
656 var
657 HasEngineSrcDir: Boolean;
658 SrcDir, NewDir: String;
659 begin
660 HasEngineSrcDir := false;
661 for SrcDir in SrcDirs do
662 if DirIsEngineDir(SrcDir, EngineSrcDir) then
663 HasEngineSrcDir := true;
664 if not HasEngineSrcDir then
665 begin
666 NewDir := InclPathDelim(EnginePath) + 'src' + PathDelim + EngineSrcDir;
667 { Use platform-specific path delimiter consistently, to look nice.
668 Do not use /, since Delphi IDE uses \ in project options by convention,
669 so we want our paths to look consistent. }
670 NewDir := SReplaceChars(NewDir, '/', PathDelim);
671 SrcDirs.Add(NewDir);
672 Inc(Result);
673 end;
674 end;
675
676 var
677 EngineSrcDir: String;
678 SrcDirs: TStringList;
679 begin
680 SrcDirs := TStringList.Create;
681 try
682 SrcDirs.Delimiter := ';';
683 SrcDirs.StrictDelimiter := true;
684 SrcDirs.DelimitedText := Paths;
685 Result := 0;
686
687 for EngineSrcDir in EnginePaths do
688 AddEngineSrcDir(EngineSrcDir, SrcDirs);
689 for EngineSrcDir in EnginePathsDelphi do
690 AddEngineSrcDir(EngineSrcDir, SrcDirs);
691
692 if Result <> 0 then
693 Paths := SrcDirs.DelimitedText;
694 finally FreeAndNil(SrcDirs) end;
695 end;
696
697 function TCastleDelphiIdeIntegration.RemovePaths(var Paths: String): Cardinal;
698
699 { Is source path equivalent to some engine standard dir. }
700 function DirIsSomeEngineDir(const SrcDir: String): Boolean;
701 var
702 EngineSrcDir: String;
703 begin
704 for EngineSrcDir in EnginePaths do
705 if DirIsEngineDir(SrcDir, EngineSrcDir) then
706 Exit(true);
707 for EngineSrcDir in EnginePathsDelphi do
708 if DirIsEngineDir(SrcDir, EngineSrcDir) then
709 Exit(true);
710 Result := false;
711 end;
712
713 var
714 SrcDirs: TStringList;
715 I: Integer;
716 begin
717 SrcDirs := TStringList.Create;
718 try
719 SrcDirs.Delimiter := ';';
720 SrcDirs.StrictDelimiter := true;
721 SrcDirs.DelimitedText := Paths;
722 Result := 0;
723
724 I := 0;
725 while I < SrcDirs.Count do
726 begin
727 if DirIsSomeEngineDir(SrcDirs[I]) then
728 begin
729 SrcDirs.Delete(I);
730 Inc(Result);
731 end else
732 Inc(I);
733 end;
734
735 if Result <> 0 then
736 Paths := SrcDirs.DelimitedText;
737 finally FreeAndNil(SrcDirs) end;
738 end;
739
740 procedure TCastleDelphiIdeIntegration.ClickAddPathsProject(Sender: TObject);
741 var
742 AddedCount: Cardinal;
743 Paths: String;
744 begin
745 if GetActiveProject = nil then
746 raise Exception.Create('No active Delphi project');
747 if EnginePath = '' then
748 raise Exception.Create('Engine path not set');
749
750 Paths := GetActiveProject.ProjectOptions.Values['SrcDir'];
751 AddedCount := AddPaths(Paths);
752 if AddedCount <> 0 then
753 begin
754 GetActiveProject.ProjectOptions.Values['SrcDir'] := Paths;
755 ShowMessageFmt('Added %d paths to the project source directories', [AddedCount]);
756 end else
757 ShowMessage('No paths added, the project already uses the engine correctly');
758 end;
759
760 procedure TCastleDelphiIdeIntegration.ClickRemovePathsProject(Sender: TObject);
761 var
762 RemovedCount: Cardinal;
763 Paths: String;
764 begin
765 if GetActiveProject = nil then
766 raise Exception.Create('No active Delphi project');
767 if EnginePath = '' then
768 raise Exception.Create('Engine path not set');
769
770 Paths := GetActiveProject.ProjectOptions.Values['SrcDir'];
771 RemovedCount := RemovePaths(Paths);
772 if RemovedCount <> 0 then
773 begin
774 GetActiveProject.ProjectOptions.Values['SrcDir'] := Paths;
775 ShowMessageFmt('Removed %d paths from the project source directories', [RemovedCount]);
776 end else
777 ShowMessage('No paths removed, the project did not use the engine');
778 end;
779
780 const
781 RegSearchPath = 'Search Path';
782
783 { Open Windows registry (TRegistry) with platform-specific config of Delphi.
784
785 Note:
786 IOTAEnvironmentOptions is broken for platform-specific options,
787 it allows only to get / set LibraryPath for a random platform,
788 not all platforms.
789 There are multiple "LibraryPath" names,
790 and we can only query for random "LibraryPath" value using ToolsAPI.
791 See http://www.devsuperpage.com/search/Articles.aspx?G=2&ArtID=37222 .
792 Test:
793
794 EnvironmentOptions := Services.GetEnvironmentOptions;
795 if EnvironmentOptions = nil then
796 raise Exception.Create('Cannot access IOTAEnvironmentOptions');
797
798 Paths := EnvironmentOptions.Values['LibraryPath'];
799
800 See raport generated by
801 https://github.com/michaliskambi/delphi-test-package-design-features too.
802
803 So we try alternative: use registry.
804 }
805 function OpenRegistryForPlatform(
806 const Reg: TRegistry;
807 const PlatformName: String): Boolean;
808 var
809 Services: IOTAServices;
810 FixedPlatformName, KeyName: String;
811 begin
812 if not Supports(BorlandIDEServices, IOTAServices, Services) then
813 raise Exception.Create('Cannot access IOTAServices');
814
815 // 32-bit Android platform name in registry differs from what GetAllPlatforms returns
816 if PlatformName = 'Android' then
817 FixedPlatformName := 'Android32'
818 else
819 FixedPlatformName := PlatformName;
820
821 KeyName := IncludeTrailingPathDelimiter(Services.GetBaseRegistryKey) +
822 'Library\' + FixedPlatformName;
823
824 Result := Reg.OpenKey(KeyName, false);
825 end;
826
827 procedure TCastleDelphiIdeIntegration.ClickAddPathsGlobal(Sender: TObject);
828 var
829 AddedCount, NewAddedCount, PlatformsCount: Cardinal;
830 Paths: String;
831 Reg: TRegistry;
832 PlatformName: String;
833 begin
834 if EnginePath = '' then
835 raise Exception.Create('Engine path not set');
836
837 AddedCount := 0;
838 PlatformsCount := 0;
839 Reg := TRegistry.Create;
840 try
841 for PlatformName in GetAllPlatforms do
842 begin
843 if OpenRegistryForPlatform(Reg, PlatformName) then
844 begin
845 Inc(PlatformsCount);
846 Paths := Reg.ReadString(RegSearchPath);
847 NewAddedCount := AddPaths(Paths);
848 if NewAddedCount <> 0 then
849 begin
850 Reg.WriteString(RegSearchPath, Paths);
851 Inc(AddedCount, NewAddedCount);
852 end;
853 end;
854 end;
855 finally FreeAndNil(Reg) end;
856
857 if AddedCount <> 0 then
858 begin
859 ShowMessageFmt('Added paths to the Delphi "Library Path" (%d platforms, total %d paths added).' + NL + NL + 'Restart the Delphi IDE now to use the new settings.', [
860 PlatformsCount,
861 AddedCount
862 ]);
863 end else
864 ShowMessage('No paths added, Delphi already refers to the engine correctly.');
865 end;
866
867 procedure TCastleDelphiIdeIntegration.ClickRemovePathsGlobal(Sender: TObject);
868 var
869 RemovedCount, NewRemovedCount, PlatformsCount: Cardinal;
870 Paths: String;
871 Reg: TRegistry;
872 PlatformName: String;
873 begin
874 if EnginePath = '' then
875 raise Exception.Create('Engine path not set');
876
877 RemovedCount := 0;
878 PlatformsCount := 0;
879 Reg := TRegistry.Create;
880 try
881 for PlatformName in GetAllPlatforms do
882 begin
883 if OpenRegistryForPlatform(Reg, PlatformName) then
884 begin
885 Inc(PlatformsCount);
886 Paths := Reg.ReadString(RegSearchPath);
887 NewRemovedCount := RemovePaths(Paths);
888 if NewRemovedCount <> 0 then
889 begin
890 Reg.WriteString(RegSearchPath, Paths);
891 Inc(RemovedCount, NewRemovedCount);
892 end;
893 end;
894 end;
895 finally FreeAndNil(Reg) end;
896
897 if RemovedCount <> 0 then
898 begin
899 ShowMessageFmt('Removed paths from the Delphi "Library Path" (%d platforms, total %d paths removed).' + NL + NL + 'Restart the Delphi IDE now to use the new settings.', [
900 PlatformsCount,
901 RemovedCount
902 ]);
903 end else
904 ShowMessage('No paths removed, Delphi did not use the engine.');
905 end;
906
907 procedure TCastleDelphiIdeIntegration.ClickWebsite(Sender: TObject);
908 begin
909 OpenUrl('https://castle-engine.io/');
910 end;
911
912 procedure TCastleDelphiIdeIntegration.ClickDelphiDocs(Sender: TObject);
913 begin
914 OpenUrl('https://castle-engine.io/delphi_packages');
915 end;
916
917 procedure TCastleDelphiIdeIntegration.ClickApiReference(Sender: TObject);
918
919 function ApiReferenceUrl: String;
920 begin
921 Result := ApiReferenceUrlCore(EnginePath);
922 end;
923
924 begin
925 OpenUrl(ApiReferenceUrl + 'index.html');
926 end;
927
928 procedure TCastleDelphiIdeIntegration.ClickDonate(Sender: TObject);
929 begin
930 OpenUrl('https://patreon.com/castleengine/');
931 end;
932
933 procedure TCastleDelphiIdeIntegration.ProjectCompileFinished(const Project: IOTAProject;
934 const Result: TOTACompileResult);
935
936 procedure ReadDependenciesFromManifest(const ProjectDependencies: TProjectDependencies;
937 const ManifestFile: String);
938 var
939 Doc: TXmlDocument;
940 begin
941 Doc := UrlReadXml(FilenameToUriSafe(ManifestFile));
942 try
943 ProjectDependencies.ReadFromManifest(Doc);
944 finally FreeAndNil(Doc) end;
945 end;
946
947 var
948 MessageServices: IOTAMessageServices;
949
950 procedure RegularMessage(const S: String);
951 var
952 LineRef: Pointer;
953 begin
954 LineRef := nil; // just secure, to avoid passing something undefined to AddToolMessage
955 MessageServices.AddToolMessage('', S,
956 'castle-engine', -1, -1, nil, LineRef, nil);
957 end;
958
959 var
960 ProjManifest, SourceFile, DestFile, DeployTargetPath: String;
961 Files: TStringList;
962 FileToDeploy: String;
963 ProjectDependencies: TProjectDependencies;
964 begin
965 if Result = crOTASucceeded then
966 begin
967 if not Supports(BorlandIDEServices, IOTAMessageServices, MessageServices) then
968 Exit;
969
970 // don't do anything on non-CGE projects
971 ProjManifest := GetPotentialProjectCastleManifest;
972 if not FileExists(ProjManifest) then
973 Exit;
974
975 ProjectDependencies := TProjectDependencies.Create;
976 try
977 ReadDependenciesFromManifest(ProjectDependencies, ProjManifest);
978 if SysUtils.DirectoryExists(GetProjectPath + 'data') then
979 ProjectDependencies.GuessDependencies(GetProjectPath + 'data');
980 ProjectDependencies.CloseDependencies;
981
982 Files := TStringList.Create;
983 try
984 if Project.CurrentPlatform = cWin32Platform then
985 ProjectDependencies.DeployFiles(dpWin32, Files);
986 if Project.CurrentPlatform = cWin64Platform then
987 ProjectDependencies.DeployFiles(dpWin64, Files);
988
989 if Files.Count <> 0 then
990 begin
991 MessageServices.AddTitleMessage(Format('[castle-engine] Deploying %d libraries alongside the executable', [
992 Files.Count
993 ]));
994 if EnginePath = '' then
995 MessageServices.AddTitleMessage('[castle-engine] Engine path not set, cannot deploy libraries')
996 else
997 begin
998 DeployTargetPath := RobustExtractFilePath(Project.ProjectOptions.TargetName);
999 for FileToDeploy in Files do
1000 begin
1001 SourceFile := InclPathDelim(EnginePath) + 'tools' + PathDelim + 'build-tool' +
1002 PathDelim + 'data' + PathDelim + FileToDeploy;
1003 DestFile := DeployTargetPath + RobustExtractFileName(FileToDeploy);
1004 try
1005 CheckCopyFile(SourceFile, DestFile);
1006 RegularMessage('Deploying library "' + FileToDeploy + '"');
1007 except
1008 { The error may happen e.g. because the EXE is running,
1009 so make sure to have nice message in this case. }
1010 on E: Exception do
1011 RegularMessage('Error deploying library "' + FileToDeploy + '": ' + E.Message);
1012 end;
1013 end;
1014 end;
1015 end;
1016 finally FreeAndNil(Files) end;
1017 finally FreeAndNil(ProjectDependencies) end;
1018 end;
1019 end;
1020
1021 { initialization / finalization ---------------------------------------------- }
1022
1023 var
1024 DelphiIdeIntegration: TCastleDelphiIdeIntegration;
1025
1026 // procedure Register;
1027 // begin
1028 // end;
1029
1030 initialization
1031 { It seems it doesn't matter do we put this in Register or unit initialization.
1032 Sample on
1033 https://docwiki.embarcadero.com/CodeExamples/Athens/en/Third-Party_Help_Menu_Item_(Delphi)
1034 does this in unit initilization / finalization, so we follow it, }
1035 OnGetDesignTimeProjectPath := GetProjectPath;
1036 DelphiIdeIntegration := TCastleDelphiIdeIntegration.Create(nil);
1037
1038 // Does not seem necessary in practice, so not doing this.
1039 { Without this, package is loaded (and so menu items added) only once
1040 CGE component is accessed. }
1041 // ForceDemandLoadState(dlDisable);
1042 finalization
1043 // When unloading the package, make sure to remove menu items
1044 FreeAndNil(DelphiIdeIntegration);
1045 end.