Debian Codegraph @

tools/castle-editor/code/formchooseproject.pas

raw
1 {
2 Copyright 2018-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 { Form to choose project (@link(TChooseProjectForm)). }
17 unit FormChooseProject;
18
19 {$mode objfpc}{$H+}
20
21 interface
22
23 uses
24 Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
25 StdCtrls, Buttons, Menus,
26 CastleDialogs, CastleLCLRecentFiles, CastleSoundEngine;
27
28 type
29 { Choose project (new or existing). }
30 TChooseProjectForm = class(TForm)
31 ButtonOpen: TBitBtn;
32 ButtonOpenRecent: TBitBtn;
33 ButtonOpenExample: TBitBtn;
34 ButtonNew: TBitBtn;
35 ButtonPreferences: TBitBtn;
36 ButtonSupportUs: TBitBtn;
37 GroupBoxOpen: TGroupBox;
38 Image1: TImage;
39 LabelWarning: TLabel;
40 OpenProject: TCastleOpenDialog;
41 ImageLogo: TImage;
42 LabelTitle: TLabel;
43 PanelBottom: TPanel;
44 PanelWarning: TPanel;
45 PopupMenuRecentProjects: TPopupMenu;
46 procedure ButtonOpenExampleClick(Sender: TObject);
47 procedure ButtonPreferencesClick(Sender: TObject);
48 procedure ButtonNewClick(Sender: TObject);
49 procedure ButtonOpenClick(Sender: TObject);
50 procedure ButtonOpenRecentClick(Sender: TObject);
51 procedure ButtonSupportUsClick(Sender: TObject);
52 procedure FormCreate(Sender: TObject);
53 procedure FormDestroy(Sender: TObject);
54 procedure FormShow(Sender: TObject);
55 procedure FormHide(Sender: TObject);
56 private
57 RecentProjects: TCastleRecentFiles;
58 CommandLineHandled: Boolean;
59 CodingTheme: TCastleSound;
60 CodingThemePlaying: TCastlePlayingSound;
61 procedure MenuItemRecentClick(Sender: TObject);
62 procedure OpenProjectFromCommandLine;
63 procedure UpdateWarning;
64 { Open ProjectForm.
65 ManifestUrl may be absolute or relative here. }
66 procedure ProjectOpen(ManifestUrl: String);
67 public
68
69 end;
70
71 var
72 ChooseProjectForm: TChooseProjectForm;
73
74 implementation
75
76 {$R *.lfm}
77
78 uses CastleConfig, CastleLCLUtils, CastleUriUtils, CastleUtils, CastleOpenDocument,
79 CastleFilesUtils, CastleParameters, CastleLog, CastleStringUtils, CastleGLUtils,
80 CastleApplicationProperties, CastleInternalTools,
81 ProjectUtils, EditorUtils, FormNewProject, FormPreferences,
82 ToolCompilerInfo, ToolFpcVersion, ToolManifest, ToolCommonUtils,
83 FormProject, FormNewUnit;
84
85 { TChooseProjectForm ------------------------------------------------------------- }
86
87 procedure TChooseProjectForm.ProjectOpen(ManifestUrl: String);
88 begin
89 ManifestUrl := AbsoluteURI(ManifestUrl);
90
91 // Validate
92 if not URIFileExists(ManifestUrl) then
93 raise Exception.CreateFmt('Cannot find CastleEngineManifest.xml at this location: "%s". Invalid project opened.',
94 [ManifestUrl]);
95
96 ProjectForm := TProjectForm.Create(Application);
97 ProjectForm.OpenProject(ManifestUrl);
98 ProjectForm.Show;
99
100 { Do this even if you just opened this project through "recent" menu.
101 This way URL is moved to the top. }
102 RecentProjects.Add(ManifestUrl);
103 end;
104
105 procedure TChooseProjectForm.ButtonOpenClick(Sender: TObject);
106 begin
107 { This is critical in a corner case:
108 - You run CGE editor such that it detects as "data directory"
109 current directory. E.g. you compiled it manually and run on Unix as
110 "tools/castle-editor/castle-editor"
111 - Now you open project in subdirectory. (E.g. some CGE example,
112 to continue previous example.)
113 - With UseCastleDataProtocol, OpenProject.URL will now be like
114 'castle-data:/examples/xxx/CastleEngineManifest.xml'.
115 Which means that it's absolute (AbsoluteURI in ProjectOpen will not change it),
116 but it's also bad to be used (because later we will set ApplicationDataOverride
117 to something derived from it, thus ResolveCastleDataURL will resolve
118 castle-data:/ to another castle-data:/ , and it will make no sense
119 since one castle-data:/ assumes ApplicationDataOverride = '' ...).
120 }
121 OpenProject.UseCastleDataProtocol := false;
122
123 if OpenProject.Execute then
124 begin
125 Hide;
126 try
127 ProjectOpen(OpenProject.URL);
128 except
129 Show;
130 raise;
131 end;
132 end;
133 end;
134
135 procedure TChooseProjectForm.ButtonNewClick(Sender: TObject);
136 var
137 ManifestUrl, TemplateName, ProjectDirUrl: String;
138 Options: TProjectCreationOptions;
139 begin
140 Hide;
141
142 if NewProjectForm.ShowModal = mrOK then
143 begin
144 UseEditorApplicationData; // we use our castle-data:/xxx to copy template
145
146 try
147 // Calculate TemplateName
148 if NewProjectForm.ButtonTemplateEmpty.Down then
149 TemplateName := 'empty'
150 else
151 if NewProjectForm.ButtonTemplate3dModelViewer.Down then
152 TemplateName := '3d_model_viewer'
153 else
154 if NewProjectForm.ButtonTemplate3dFps.Down then
155 TemplateName := '3d_fps_game'
156 else
157 if NewProjectForm.ButtonTemplate2d.Down then
158 TemplateName := '2d_game'
159 else
160 raise EInternalError.Create('Unknown project template selected');
161
162 // Fill Options
163 Options.ParentDir := NewProjectForm.EditLocation.Text;
164 Options.TemplateName := TemplateName;
165 Options.ProjectName := NewProjectForm.EditProjectName.Text;
166 Options.ProjectCaption := NewProjectForm.EditProjectCaption.Text;
167 Options.MainView := NewProjectForm.EditViewName.Text;
168
169 ProjectCreateFromTemplate(CastleEnginePath, Options, ProjectDirUrl);
170 GenerateProgramWithBuildTool(ProjectDirUrl);
171
172 // Open new project
173 ManifestUrl := CombineURI(ProjectDirUrl, 'CastleEngineManifest.xml');
174 ProjectOpen(ManifestUrl);
175 except
176 on E: Exception do
177 begin
178 Show;
179 ErrorBox(ExceptMessage(E));
180 end;
181 end;
182 end else
183 Show;
184 end;
185
186 procedure TChooseProjectForm.ButtonPreferencesClick(Sender: TObject);
187 begin
188 PreferencesForm.ShowModal;
189 UpdateWarning;
190 end;
191
192 procedure TChooseProjectForm.ButtonOpenExampleClick(Sender: TObject);
193 begin
194 if CastleEnginePath <> '' then
195 begin
196 OpenProject.FileName := CastleEnginePath + 'examples' + PathDelim;
197 end else
198 WritelnWarning('Cannot find CGE directory');
199
200 ButtonOpenClick(nil);
201 end;
202
203 procedure TChooseProjectForm.ButtonOpenRecentClick(Sender: TObject);
204 var
205 MenuItem: TMenuItem;
206 I: Integer;
207 Url, S, NotExistingSuffix: String;
208 begin
209 PopupMenuRecentProjects.Items.Clear;
210 for I := 0 to RecentProjects.URLs.Count - 1 do
211 begin
212 Url := RecentProjects.URLs[I];
213 MenuItem := TMenuItem.Create(Self);
214
215 if URIExists(Url) in [ueFile, ueUnknown] then
216 NotExistingSuffix := ''
217 else
218 NotExistingSuffix := ' (PROJECT FILES MISSING)';
219
220 // show file URLs simpler, esp to avoid showing space as %20
221 Url := SuffixRemove('/CastleEngineManifest.xml', Url, true);
222 if URIProtocol(Url) = 'file' then
223 S := UriToFilenameSafeUTF8(Url)
224 else
225 S := UriDisplay(Url);
226 MenuItem.Caption := SQuoteLCLCaption(S + NotExistingSuffix);
227
228 MenuItem.Tag := I;
229 MenuItem.OnClick := @MenuItemRecentClick;
230 PopupMenuRecentProjects.Items.Add(MenuItem);
231 end;
232 PopupMenuRecentProjects.PopupComponent := ButtonOpenRecent;
233 PopupMenuRecentProjects.Popup;
234 end;
235
236 procedure TChooseProjectForm.ButtonSupportUsClick(Sender: TObject);
237 begin
238 OpenUrl('https://patreon.com/castleengine/');
239 end;
240
241 procedure TChooseProjectForm.FormCreate(Sender: TObject);
242
243 procedure ConfigLoad;
244 begin
245 FpcCustomPath := UserConfig.GetValue('fpc_custom_path', '');
246 LazarusCustomPath := UserConfig.GetValue('lazarus_custom_path', '');
247 CastleEngineOverridePath := UserConfig.GetValue('castle_engine_override_path', '');
248 CodeEditor := TCodeEditor(UserConfig.GetValue('code_editor/setting', Ord(DefaultCodeEditor)));
249 CodeEditorCommand := UserConfig.GetValue('code_editor/command', '');
250 CodeEditorCommandLineColumn := UserConfig.GetValue('code_editor/command_line_column', '');
251 CodeEditorCommandProject := UserConfig.GetValue('code_editor/command_project', '');
252 MuteOnRun := UserConfig.GetValue('sound/mute_on_run', DefaultMuteOnRun);
253 EditorVolume := UserConfig.GetFloat('sound/editor_volume', DefaultEditorVolume);
254 Compiler := StringToCompiler(UserConfig.GetValue('compiler', CompilerToString(DefaultCompiler)));
255 AndroidHome := UserConfig.GetValue('android_home', '');
256 JavaHome := UserConfig.GetValue('java_home', '');
257 SoundEngineSetVolume;
258 end;
259
260 begin
261 UserConfig.Load;
262 RecentProjects := TCastleRecentFiles.Create(Self);
263 RecentProjects.LoadFromConfig(UserConfig);
264 // RecentProjects.NextMenuItem := ; // unused for now
265 ConfigLoad;
266
267 UseEditorApplicationData;
268 InternalCastleDesignData := ResolveCastleDataUrl('castle-data:/');
269 end;
270
271 procedure TChooseProjectForm.FormDestroy(Sender: TObject);
272
273 procedure ConfigSave;
274 begin
275 UserConfig.SetDeleteValue('fpc_custom_path', FpcCustomPath, '');
276 UserConfig.SetDeleteValue('lazarus_custom_path', LazarusCustomPath, '');
277 UserConfig.SetDeleteValue('castle_engine_override_path', CastleEngineOverridePath, '');
278 UserConfig.SetDeleteValue('code_editor/setting', Ord(CodeEditor), Ord(DefaultCodeEditor));
279 UserConfig.SetDeleteValue('code_editor/command', CodeEditorCommand, '');
280 UserConfig.SetDeleteValue('code_editor/command_line_column', CodeEditorCommandLineColumn, '');
281 UserConfig.SetDeleteValue('code_editor/command_project', CodeEditorCommandProject, '');
282 UserConfig.SetDeleteValue('sound/mute_on_run', MuteOnRun, DefaultMuteOnRun);
283 UserConfig.SetDeleteFloat('sound/editor_volume', EditorVolume, DefaultEditorVolume);
284 UserConfig.SetDeleteValue('compiler', CompilerToString(Compiler), CompilerToString(DefaultCompiler));
285 UserConfig.SetDeleteValue('android_home', AndroidHome, '');
286 UserConfig.SetDeleteValue('java_home', JavaHome, '');
287 end;
288
289 begin
290 ConfigSave;
291 RecentProjects.SaveToConfig(UserConfig);
292 UserConfig.Save;
293 end;
294
295 procedure TChooseProjectForm.FormShow(Sender: TObject);
296 begin
297 ButtonOpenRecent.Enabled := RecentProjects.URLs.Count <> 0;
298 OpenProjectFromCommandLine;
299 UpdateWarning;
300
301 if (CastleEnginePath <> '') and URIFileExists(CastleEnginePath + 'game.pas:666') then
302 begin
303 CodingTheme := TCastleSound.Create(Self);
304 CodingTheme.Stream := true;
305 CodingTheme.Url := InternalCastleDesignData + 'not_an_easter_egg/ente_evil.ogg';
306 CodingThemePlaying := TCastlePlayingSound.Create(Self);
307 CodingThemePlaying.Loop := true;
308 CodingThemePlaying.Sound := CodingTheme;
309 SoundEngine.Play(CodingThemePlaying);
310 end;
311 end;
312
313 procedure TChooseProjectForm.FormHide(Sender: TObject);
314 begin
315 FreeAndNil(CodingThemePlaying);
316 FreeAndNil(CodingTheme);
317 end;
318
319 procedure TChooseProjectForm.UpdateWarning;
320
321 function CompilerFound: Boolean;
322 begin
323 Result := false;
324 try
325 FindExeFpcCompiler;
326 FpcVersion;
327 Result := true;
328 except
329 { FindExeFpcCompiler exits with EExecutableNotFound,
330 but FpcVersion may fail with any Exception unfortunately
331 (it runs external process, and many things can go wrong). }
332 on E: Exception do
333 begin
334 WritelnLog('FPC not found, or cannot run FPC to get version: ' + ExceptMessage(E));
335
336 { if FPC failed, try to find Delphi }
337 if FindDelphiPath(false) <> '' then
338 Result := true;
339 end;
340 end;
341 end;
342
343 begin
344 if (CastleEnginePath = '') or not CgePathStatus(CastleEnginePath) then
345 begin
346 PanelWarning.Visible := true;
347 LabelWarning.Caption :=
348 'Warning: Engine path not found or invalid.' + NL +
349 'Configure valid path in "Preferences".';
350 end else
351 if not CompilerFound then
352 begin
353 PanelWarning.Visible := true;
354 LabelWarning.Caption :=
355 'Warning: Compiler (FPC or Delphi) not found.' + NL +
356 'Install a compiler and configure in "Preferences".';
357 end else
358 PanelWarning.Visible := false;
359 end;
360
361 procedure TChooseProjectForm.MenuItemRecentClick(Sender: TObject);
362 var
363 Url: String;
364 begin
365 Url := RecentProjects.URLs[(Sender as TMenuItem).Tag];
366
367 if not (URIExists(Url) in [ueFile, ueUnknown]) then
368 begin
369 if YesNoBox(Format('Project file "%s" does not exist. Remove the project from the recent list?', [
370 UriDisplay(Url)
371 ])) then
372 begin
373 RecentProjects.Remove(Url);
374 PopupMenuRecentProjects.Items.Remove(Sender as TMenuItem);
375 end;
376 Exit;
377 end;
378
379 Hide;
380 try
381 ProjectOpen(Url);
382 except
383 Show;
384 raise;
385 end;
386 end;
387
388 procedure OptionProc(OptionNum: Integer; HasArgument: boolean;
389 const Argument: string; const SeparateArgs: TSeparateArgs; Data: Pointer);
390 begin
391 case OptionNum of
392 0: begin
393 InfoWrite(
394 'castle-editor: Create, build and design Castle Game Engine applications.' + NL +
395 NL +
396 'Usually run without any command-line paramaters, to present to user a choice' + NL +
397 'which project to open. But you can also specify project to open' + NL +
398 '(provide a full path, including the CastleEngineManifest.xml file).' + NL +
399 NL +
400 'Other available options are:' + NL +
401 OptionDescription('-h / --help', 'Print this help message and exit.') + NL +
402 OptionDescription('-v / --version', 'Print the version number and exit.') + NL +
403 OptionDescription('--capabilities automatic|force-fixed-function|force-modern', 'Force OpenGL context to have specific capabilities, to test rendering on modern or ancient GPUs.') + NL +
404 NL +
405 ApplicationProperties.Description);
406 Halt;
407 end;
408 1: begin
409 // include ApplicationName in version, good for help2man
410 InfoWrite(ApplicationName + ' ' + ApplicationProperties.Version);
411 Halt;
412 end;
413 2: TGLFeatures.RequestCapabilities := StrToCapabilities(Argument);
414 else raise EInternalError.Create('ApplicationOptionProc: unhandled OptionNum');
415 end;
416 end;
417
418 procedure TChooseProjectForm.OpenProjectFromCommandLine;
419
420 {$ifdef DARWIN}
421 { On macOS, on the first run (after accepting "open application downloaded from the Internet")
422 we may get additional command-line parameter -psn_...,
423 which stands for "Process Serial Number".
424
425 See e.g.
426 https://stackoverflow.com/questions/10242115/os-x-strange-psn-command-line-parameter-when-launched-from-finder
427 https://forums.macrumors.com/threads/application-adding-argument.207344/
428 Note: It definitely happens even for Cocoa-based editor, not only Carbon,
429 despite some suggestions on the Internet that it's Carbon-specific.
430 Unfortunately there no (not anymore) official docs about it from Apple.
431
432 We have to remove it, to not confuse it with a project name. }
433 procedure RemoveMacOsProcessSerialNumber;
434 var
435 I: Integer;
436 begin
437 for I := 1 to Parameters.Count - 1 do
438 if IsPrefix('-psn_', Parameters[I], false) then
439 begin
440 Parameters.Delete(I);
441 Exit;
442 end;
443 end;
444 {$endif}
445
446 const
447 Options: array [0..2] of TOption =
448 (
449 (Short: 'h'; Long: 'help'; Argument: oaNone),
450 (Short: 'v'; Long: 'version'; Argument: oaNone),
451 (Short: #0 ; Long: 'capabilities'; Argument: oaRequired)
452 );
453
454 begin
455 if CommandLineHandled then Exit;
456 CommandLineHandled := true;
457
458 {$ifdef DARWIN}
459 RemoveMacOsProcessSerialNumber;
460 {$endif}
461
462 Parameters.Parse(Options, @OptionProc, nil, true);
463
464 Parameters.CheckHighAtMost(1);
465 if Parameters.High = 1 then
466 begin
467 Hide;
468 try
469 ProjectOpen(Parameters[1]);
470 except
471 Show;
472 raise;
473 end;
474 end;
475 end;
476
477 initialization
478 ApplicationProperties.ApplicationName := 'castle-editor';
479 ApplicationProperties.Version := CastleEngineVersion;
480 end.