Debian Codegraph @

tools/castle-editor/code/formnewunit.pas

raw
1 {
2 Copyright 2021-2023 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 { Dialog to configure new unit properties (TNewUnitForm). }
17 unit FormNewUnit;
18
19 {$mode objfpc}{$H+}
20
21 interface
22
23 uses
24 Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls, EditBtn,
25 ButtonPanel, ExtCtrls,
26 ToolManifest;
27
28 type
29 TNewUnitType = (utEmpty, utClass, utView, utBehavior);
30
31 { Dialog to configure new unit properties. }
32 TNewUnitForm = class(TForm)
33 ButtonViewDir: TButton;
34 ButtonUnitDir: TButton;
35 ButtonPanel1: TButtonPanel;
36 CheckViewInitialize: TCheckBox;
37 ComboUnitType: TComboBox;
38 EditClassName: TEdit;
39 EditDesignDir: TEdit;
40 EditBaseName: TEdit;
41 EditUnitName: TEdit;
42 EditUnitDir: TEdit;
43 LabelFinalUnitFile: TLabel;
44 LabelFinalDesignFile: TLabel;
45 LabelClassName: TLabel;
46 LabelDesignDir: TLabel;
47 LabelBaseName: TLabel;
48 LabelViewInitializeInfo: TLabel;
49 LabelUnitName: TLabel;
50 LabelCreateUnit: TLabel;
51 LabelUnitDir: TLabel;
52 PanelUnitClass: TPanel;
53 PanelUnitView: TPanel;
54 SelectDirectoryDialog1: TSelectDirectoryDialog;
55 procedure ButtonUnitDirClick(Sender: TObject);
56 procedure ButtonViewDirClick(Sender: TObject);
57 procedure ComboUnitTypeChange(Sender: TObject);
58 procedure EditBaseNameChange(Sender: TObject);
59 procedure EditDesignDirChange(Sender: TObject);
60 procedure EditUnitDirChange(Sender: TObject);
61 procedure EditUnitNameChange(Sender: TObject);
62 procedure FormCloseQuery(Sender: TObject; var CanClose: boolean);
63 procedure FormShow(Sender: TObject);
64 private
65 FCreatedUnitRelative, FCreatedDesignRelative: String;
66 FCreatedUnitAbsolute, FCreatedDesignAbsolute: String;
67 FUnitType: TNewUnitType;
68 { Absolute directory (with final path delim) of the directory where
69 unit should be created. }
70 FUnitOutputPath: String;
71 { Current project manifest. }
72 FProjectManifest: TCastleManifest;
73 UnitToInitializeView: String;
74 procedure GetFinalFilenames(out FinalUnitRelative, FinalDesignRelative: String);
75 procedure GetFinalFilenames(out FinalUnitRelative, FinalDesignRelative: String;
76 out FinalUnitAbsolute, FinalDesignAbsolute: String);
77 procedure SetUnitType(const AValue: TNewUnitType);
78 procedure UpdateFinalFilenames;
79 property UnitType: TNewUnitType read FUnitType write SetUnitType default utEmpty;
80 procedure RefreshUiDependingOnUnitType;
81 public
82 { After ShowModel, the Created* contain filenames created (or empty if none). }
83 property CreatedUnitRelative: String read FCreatedUnitRelative;
84 property CreatedUnitAbsolute: String read FCreatedUnitAbsolute;
85 property CreatedDesignRelative: String read FCreatedDesignRelative;
86 property CreatedDesignAbsolute: String read FCreatedDesignAbsolute;
87
88 procedure InitializeUi(const AUnitType: TNewUnitType;
89 const AUnitOutputPath: String; const AProjectManifest: TCastleManifest);
90 end;
91
92 var
93 NewUnitForm: TNewUnitForm;
94
95 implementation
96
97 uses Generics.Collections,
98 CastleFilesUtils, CastleUriUtils, CastleLog, CastleUtils, CastleStringUtils,
99 EditorUtils, ProjectUtils, EditorCodeTools;
100
101 {$R *.lfm}
102
103 { Like ExtractRelativePath but prefer to end result with PathDelim,
104 as it just seems cleaner (it is then obvious that edit box shows
105 a directory). }
106 function ExtractRelativePathDelim(const Base, Target: String): String;
107 begin
108 if DirectoryExists(Base) and
109 SameFileName(InclPathDelim(Base), InclPathDelim(Target)) then
110 Exit(''); // otherwise ExtractRelativePath returns '../my_dir_name/'
111 Result := ExtractRelativePath(Base, Target);
112 if Result <> '' then
113 Result := InclPathDelim(Result);
114 end;
115
116 { TNewUnitForm --------------------------------------------------------------- }
117
118 procedure TNewUnitForm.ButtonUnitDirClick(Sender: TObject);
119 begin
120 SelectDirectoryDialog1.InitialDir := CombinePaths(FProjectManifest.Path, EditUnitDir.Text);
121 SelectDirectoryDialog1.FileName := CombinePaths(FProjectManifest.Path, EditUnitDir.Text);
122 if SelectDirectoryDialog1.Execute then
123 begin
124 EditUnitDir.Text := ExtractRelativePathDelim(FProjectManifest.Path, SelectDirectoryDialog1.FileName);
125 UpdateFinalFilenames;
126 end;
127 end;
128
129 procedure TNewUnitForm.SetUnitType(const AValue: TNewUnitType);
130 begin
131 if FUnitType = AValue then Exit;
132 FUnitType := AValue;
133 RefreshUiDependingOnUnitType;
134 end;
135
136 procedure TNewUnitForm.InitializeUi(const AUnitType: TNewUnitType;
137 const AUnitOutputPath: String; const AProjectManifest: TCastleManifest);
138 begin
139 FUnitType := AUnitType;
140 FProjectManifest := AProjectManifest;
141 FUnitOutputPath := AUnitOutputPath;
142 RefreshUiDependingOnUnitType;
143 end;
144
145 procedure TNewUnitForm.RefreshUiDependingOnUnitType;
146 const
147 ButtonsMargin = 16;
148 var
149 RelativeUnitPath: String;
150 begin
151 ComboUnitType.OnChange := nil; // avoid recursive ComboUnitType.OnChange calls
152 ComboUnitType.ItemIndex := Ord(FUnitType);
153 ComboUnitType.OnChange := @ComboUnitTypeChange;
154
155 RelativeUnitPath := ExtractRelativePathDelim(FProjectManifest.Path, FUnitOutputPath);
156 EditUnitDir.Text := RelativeUnitPath;
157
158 SetEnabledVisible(PanelUnitClass, FUnitType in [utClass, utBehavior, utView]);
159 SetEnabledVisible(PanelUnitView, FUnitType = utView);
160
161 EditBaseName.Text := 'Something';
162
163 case UnitType of
164 utEmpty:
165 begin
166 { adjust form height }
167 ClientHeight := LabelFinalUnitFile.Top + LabelFinalUnitFile.Height + ButtonsMargin + ButtonPanel1.Height;
168 end;
169 utClass, utBehavior:
170 begin
171 { adjust form height }
172 ClientHeight := PanelUnitClass.Top + PanelUnitClass.Height + ButtonsMargin + ButtonPanel1.Height;
173 end;
174 utView:
175 begin
176 UnitToInitializeView := FindUnitToInitializeView(FProjectManifest);
177
178 EditDesignDir.Text := 'data/';
179 CheckViewInitialize.Checked := UnitToInitializeView <> '';
180 CheckViewInitialize.Enabled := UnitToInitializeView <> '';
181
182 if UnitToInitializeView <> '' then
183 LabelViewInitializeInfo.Caption := Format(
184 'Select above checkbox to modify %s to add view initialization.', [
185 UnitToInitializeView
186 ])
187 else
188 LabelViewInitializeInfo.Caption :=
189 'WARNING: Cannot find unit with view initialization. We search units listed in game_units in CastleEngineManifest.xml, among the search paths, for special comments like {$region ''Castle...''} (see the new project templates for a precise example).' + NL + NL +
190 'You will need to manually create the view somewhere, like "ViewMy := TViewMy.Create(Application);".';
191
192 { adjust form height }
193 PanelUnitView.ClientHeight := LabelViewInitializeInfo.Top + LabelViewInitializeInfo.Height;
194 ClientHeight := PanelUnitView.Top + PanelUnitView.Height + ButtonsMargin + ButtonPanel1.Height;
195 end;
196 end;
197
198 EditBaseNameChange(nil);
199 end;
200
201 procedure TNewUnitForm.ButtonViewDirClick(Sender: TObject);
202 var
203 DataPath: String;
204 begin
205 SelectDirectoryDialog1.InitialDir := CombinePaths(FProjectManifest.Path, EditDesignDir.Text);
206 SelectDirectoryDialog1.FileName := CombinePaths(FProjectManifest.Path, EditDesignDir.Text);
207 if SelectDirectoryDialog1.Execute then
208 begin
209 DataPath := UriToFilenameSafe(ResolveCastleDataURL('castle-data:/'));
210 if not IsPrefix(DataPath, InclPathDelim(SelectDirectoryDialog1.FileName), not FileNameCaseSensitive) then
211 begin
212 MessageDlg('Design outside data', 'You are saving a design outside of the project''s "data" directory.' + NL +
213 NL +
214 'The view design file will not be automatically referenced correctly from code (using "castle-data:/" protocol) and will not be automatically packaged in the project.' + NL +
215 NL +
216 'Unless you really know what you''re doing, we heavily advice to change the directory to be inside the project "data" directory.',
217 mtWarning, [mbOK], 0);
218 end;
219
220 EditDesignDir.Text := ExtractRelativePathDelim(FProjectManifest.Path, SelectDirectoryDialog1.FileName);
221 UpdateFinalFilenames;
222 end;
223 end;
224
225 procedure TNewUnitForm.ComboUnitTypeChange(Sender: TObject);
226 begin
227 UnitType := TNewUnitType(ComboUnitType.ItemIndex);
228 end;
229
230 procedure TNewUnitForm.EditBaseNameChange(Sender: TObject);
231 begin
232 { automatically change lower edit boxes }
233 case UnitType of
234 utBehavior:
235 begin
236 EditClassName.Text := 'T' + EditBaseName.Text + 'Behavior';
237 EditUnitName.Text := 'Game' + EditBaseName.Text + 'Behavior';
238 end;
239 utView:
240 begin
241 EditClassName.Text := 'TView' + EditBaseName.Text;
242 EditUnitName.Text := 'GameView' + EditBaseName.Text;
243 end;
244 else
245 begin
246 EditClassName.Text := 'T' + EditBaseName.Text;
247 EditUnitName.Text := 'Game' + EditBaseName.Text;
248 end;
249 end;
250
251 UpdateFinalFilenames;
252 end;
253
254 procedure TNewUnitForm.EditDesignDirChange(Sender: TObject);
255 begin
256 UpdateFinalFilenames;
257 end;
258
259 procedure TNewUnitForm.EditUnitDirChange(Sender: TObject);
260 begin
261 UpdateFinalFilenames;
262 end;
263
264 procedure TNewUnitForm.EditUnitNameChange(Sender: TObject);
265 begin
266 UpdateFinalFilenames;
267 end;
268
269 procedure TNewUnitForm.FormCloseQuery(Sender: TObject; var CanClose: boolean);
270
271 function CheckValidPascalIdentifiers: Boolean;
272 begin
273 Result := true;
274
275 if not IsValidIdent(EditUnitName.Text, true) then
276 begin
277 ErrorBox(Format('Unit name "%s" is not a valid Pascal identifier.', [
278 EditUnitName.Text
279 ]));
280 Exit(false);
281 end;
282
283 if (UnitType in [utClass, utBehavior]) and (not IsValidIdent(EditClassName.Text, true)) then
284 begin
285 ErrorBox(Format('Class name "%s" is not a valid Pascal identifier.', [
286 EditClassName.Text
287 ]));
288 Exit(false);
289 end;
290
291 if (UnitType = utView) and (not IsPrefix('t', EditClassName.Text, true)) then
292 begin
293 ErrorBox(Format('View name "%s" must start with letter "T" (following Pascal conventions for type names; this allows to declare singleton variable, with consistent name but without the "T" prefix).', [
294 EditClassName.Text
295 ]));
296 Exit(false);
297 end;
298
299 if (UnitType = utView) and
300 SameText(PrefixRemove('t', EditClassName.Text, true), EditUnitName.Text) then
301 begin
302 ErrorBox(Format('View unit name "%s" must be different than class name (with "T" prefix removed), otherwise we cannot declare view singleton variable.', [
303 EditUnitName.Text
304 ]));
305 Exit(false);
306 end;
307 end;
308
309 procedure CreateFiles(
310 const FinalUnitRelative, FinalDesignRelative: String;
311 const FinalUnitAbsolute, FinalDesignAbsolute: String);
312
313 { Like StringtoFile, but makes sure the directory of FileName exists,
314 creating it if necessary.
315 This extra comfort sometimes makes sense, e.g. when using "New View"
316 on new project that has no "data" or "code" directory,
317 because someone created new project in Delphi, not in CGE editor. }
318 procedure StringToFileAutoDir(const Filename, Contents: String);
319 begin
320 ForceDirectories(ExtractFileDir(Filename));
321 StringToFile(Filename, Contents);
322 end;
323
324 var
325 Macros: TStringStringMap;
326 TemplateSource, Contents, ViewVariableName: String;
327 begin
328 Macros := TStringStringMap.Create;
329 try
330 Macros.Add('${UNIT_NAME}', EditUnitName.Text);
331 Macros.Add('${BASE_NAME}', EditBaseName.Text);
332 case UnitType of
333 utEmpty:
334 begin
335 TemplateSource := 'newunit.pas';
336 end;
337 utClass:
338 begin
339 TemplateSource := 'newunitclass.pas';
340 Macros.Add('${CLASS_NAME}', EditClassName.Text);
341 end;
342 utBehavior:
343 begin
344 TemplateSource := 'newunitbehavior.pas';
345 Macros.Add('${CLASS_NAME}', EditClassName.Text);
346 end;
347 utView:
348 begin
349 TemplateSource := 'newunitview.pas';
350 ViewVariableName := PrefixRemove('t', EditClassName.Text, true);
351 Macros.Add('${VIEW_CLASS_NAME}', EditClassName.Text);
352 Macros.Add('${VIEW_VARIABLE_NAME}', ViewVariableName);
353 Macros.Add('${DESIGN_FILE_URL}', MaybeUseDataProtocol(FilenameToUriSafe(FinalDesignAbsolute)));
354
355 StringToFileAutoDir(FinalDesignAbsolute, FileToString(
356 InternalCastleDesignData + 'templates/newunitview.castle-user-interface'));
357 FCreatedDesignRelative := FinalDesignRelative;
358 FCreatedDesignAbsolute := FinalDesignAbsolute;
359
360 if CheckViewInitialize.Checked then
361 begin
362 Assert(UnitToInitializeView <> '');
363 AddInitializeView(CombinePaths(FProjectManifest.Path, UnitToInitializeView),
364 EditUnitName.Text,
365 EditClassName.Text,
366 ViewVariableName
367 );
368 end;
369 end;
370 end;
371
372 Contents := FileToString(InternalCastleDesignData + 'templates/' + TemplateSource);
373 Contents := SReplacePatterns(Contents, Macros, false);
374 StringToFileAutoDir(FinalUnitAbsolute, Contents);
375 FCreatedUnitRelative := FinalUnitRelative;
376 FCreatedUnitAbsolute := FinalUnitAbsolute;
377 finally FreeAndNil(Macros) end;
378 end;
379
380 function CheckCanOverwriteFiles(
381 const FinalUnitRelative, FinalDesignRelative: String;
382 const FinalUnitAbsolute, FinalDesignAbsolute: String): Boolean;
383 begin
384 Result := true;
385
386 Assert(FinalUnitAbsolute <> '');
387 if FileExists(FinalUnitAbsolute) or DirectoryExists(FinalUnitAbsolute) then
388 begin
389 if not YesNoBox('Overwrite unit', Format('Unit file already exists: "%s".' + NL + NL + 'Overwrite file?', [
390 FinalUnitRelative
391 ])) then
392 Exit(false);
393 end;
394
395 if (FinalDesignAbsolute <> '') and
396 (FileExists(FinalDesignAbsolute) or DirectoryExists(FinalDesignAbsolute)) then
397 begin
398 if not YesNoBox('Overwrite design', Format('Design file already exists: "%s".' + NL + NL + 'Overwrite file?', [
399 FinalDesignRelative
400 ])) then
401 Exit(false);
402 end;
403 end;
404
405 var
406 FinalUnitRelative, FinalDesignRelative: String;
407 FinalUnitAbsolute, FinalDesignAbsolute: String;
408 begin
409 // reset output properties
410 FCreatedUnitRelative := '';
411 FCreatedUnitAbsolute := '';
412 FCreatedDesignRelative := '';
413 FCreatedDesignAbsolute := '';
414
415 if ModalResult = mrOK then
416 begin
417 if not CheckValidPascalIdentifiers then
418 begin
419 CanClose := false;
420 Exit;
421 end;
422
423 GetFinalFilenames(
424 FinalUnitRelative, FinalDesignRelative,
425 FinalUnitAbsolute, FinalDesignAbsolute);
426
427 if not CheckCanOverwriteFiles(
428 FinalUnitRelative, FinalDesignRelative,
429 FinalUnitAbsolute, FinalDesignAbsolute) then
430 begin
431 CanClose := false;
432 Exit;
433 end;
434
435 CreateFiles(
436 FinalUnitRelative, FinalDesignRelative,
437 FinalUnitAbsolute, FinalDesignAbsolute);
438 end;
439 end;
440
441 procedure TNewUnitForm.FormShow(Sender: TObject);
442 begin
443 ActiveControl := EditBaseName; // set focus on EditBaseName each time you open this form
444 EditBaseName.SelectAll; // allow to easily type something from scratch
445 end;
446
447 procedure TNewUnitForm.GetFinalFilenames(
448 out FinalUnitRelative, FinalDesignRelative: String);
449 begin
450 FinalUnitRelative := CombinePaths(EditUnitDir.Text, LowerCase(EditUnitName.Text) + '.pas');
451
452 if UnitType = utView then
453 FinalDesignRelative := CombinePaths(EditDesignDir.Text, LowerCase(EditUnitName.Text) + '.castle-user-interface')
454 else
455 FinalDesignRelative := '';
456 end;
457
458 procedure TNewUnitForm.GetFinalFilenames(
459 out FinalUnitRelative, FinalDesignRelative: String;
460 out FinalUnitAbsolute, FinalDesignAbsolute: String);
461 begin
462 GetFinalFilenames(FinalUnitRelative, FinalDesignRelative);
463
464 FinalUnitAbsolute := CombinePaths(FProjectManifest.Path, FinalUnitRelative);
465
466 if FinalDesignRelative <> '' then
467 FinalDesignAbsolute := CombinePaths(FProjectManifest.Path, FinalDesignRelative)
468 else
469 FinalDesignAbsolute := '';
470 end;
471
472 procedure TNewUnitForm.UpdateFinalFilenames;
473 var
474 FinalUnitRelative, FinalDesignRelative: String;
475 begin
476 GetFinalFilenames(FinalUnitRelative, FinalDesignRelative);
477 LabelFinalUnitFile.Caption := 'Final Unit File: ' + FinalUnitRelative;
478 LabelFinalDesignFile.Caption := 'Final Design File: ' + FinalDesignRelative;
479 end;
480
481 end.
482