Debian Codegraph @

tools/common-code/toolmanifest.pas

raw
1 {
2 Copyright 2021-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 { Parsing of CastleEngineManifest.xml files (shared by CGE build tool and CGE editor).
17 The central class in @link(TCastleManifest). }
18 unit ToolManifest;
19
20 {$I castleconf.inc}
21
22 interface
23
24 uses DOM, Classes, Generics.Collections,
25 CastleStringUtils, CastleImages, CastleUtils, CastleFindFiles, CastleColors,
26 CastleInternalTools, CastleUnicode,
27 ToolServices, ToolAssocDocTypes;
28
29 type
30 TCompiler = (coAutodetect, coFpc, coDelphi);
31
32 TScreenOrientation = (soAny, soLandscape, soPortrait);
33
34 TLocalizedAppName = class
35 Language: String;
36 AppName: String;
37 constructor Create(const ALanguage, AAppName: String);
38 end;
39 TLocalizedAppNameList = {$ifdef FPC}specialize{$endif} TObjectList<TLocalizedAppName>;
40
41 TIncludePath = class
42 Path: String;
43 Recursive: Boolean;
44 ExecutablePermission: Boolean;
45 end;
46 TIncludePathList = {$ifdef FPC}specialize{$endif} TObjectList<TIncludePath>;
47
48 TProjectVersion = class(TComponent)
49 public
50 DisplayValue: String;
51 Code: Cardinal;
52 { Version components separated by dots in DisplayValue:
53 Major, Minor, Release, Build.
54 Calculated by InitializeItems. }
55 Items: array [0..3] of Cardinal;
56 procedure InitializeItems;
57 end;
58
59 TImageFileNames = class(TCastleStringList)
60 private
61 FBaseUrl: String;
62 public
63 property BaseUrl: String read FBaseUrl write FBaseUrl;
64 { Find image with given extension, or '' if not found.
65 Note that the returned image filename is relative to project path,
66 usually you should process it like @code(IconPath := CombinePaths(Project.Path, IconPath)). }
67 function FindExtension(const Extensions: array of string): String;
68 { Find and read an image format that we can process with our CastleImages.
69 Try to read it to a class that supports nice-quality resizing (TResizeInterpolationFpImage).
70 @nil if not found. }
71 function FindReadable: TCastleImage;
72 end;
73
74 TLaunchImageStoryboard = class
75 BaseUrl, Path: String;
76 Scale: Single;
77 BackgroundColor: TCastleColor;
78 constructor Create;
79 end;
80
81 { Parsing of CastleEngineManifest.xml files. }
82 TCastleManifest = class
83 strict private
84 const
85 { Google Play requires version code to be >= 1 }
86 DefautVersionCode = 1;
87 { iOS requires version display to be <> '' }
88 DefautVersionDisplayValue = '0.1';
89 DefaultUsesNonExemptEncryption = true;
90 DefaultDataExists = true;
91 DefaultFullscreenImmersive = true;
92 DefaultDetectMemoryLeaks = false;
93 DefaultMacAppBundle = true;
94
95 { character sets }
96 ControlChars = [#0 .. Chr(Ord(' ') - 1)];
97 AlphaNum = ['a'..'z', 'A'..'Z', '0'..'9'];
98
99 { qualified_name is also a Java package name for Android, so it
100 cannot contain dash character.
101
102 As for underscore:
103 On Android, using _ is allowed,
104 but on iOS it is not (it fails at signing),
105 possibly because _ inside URLs is (in general) not allowed:
106 http://stackoverflow.com/questions/2180465/can-domain-name-subdomains-have-an-underscore-in-it }
107 QualifiedNameAllowedChars = AlphaNum + ['.'];
108
109 var
110 OwnerComponent: TComponent;
111 FName, FExecutableName, FQualifiedName, FAuthor, FCaption: String;
112 FIOSOverrideQualifiedName: String;
113 FIOSOverrideVersion: TProjectVersion; //< nil if not overridden, should use FVersion then
114 FUsesNonExemptEncryption: boolean;
115 FDataExists: Boolean;
116 FPath, FPathUrl, FDataPath: String;
117 FIncludePaths: TIncludePathList;
118 FExcludePaths: TCastleStringList;
119 FExtraCompilerOptions, FExtraCompilerOptionsAbsolute: TCastleStringList;
120 FDefines: TCastleStringList;
121 FIcons, FLaunchImages: TImageFileNames;
122 FLaunchImageStoryboard: TLaunchImageStoryboard;
123 FSearchPaths, FLibraryPaths: TStringList;
124 FStandaloneSource, FAndroidSource, FIOSSource, FPluginSource: String;
125 FCompiler: TCompiler;
126 FLazarusProject, FDelphiProject: String;
127 FBuildUsingLazbuild: Boolean;
128 FGameUnits, FEditorUnits: String;
129 FVersion: TProjectVersion;
130 FFullscreenImmersive: boolean;
131 FScreenOrientation: TScreenOrientation;
132 FAndroidCompileSdkVersion, FAndroidMinSdkVersion, FAndroidTargetSdkVersion: Cardinal;
133 FAndroidServices, FIOSServices: TServiceList;
134 FAssociateDocumentTypes: TAssociatedDocTypeList;
135 FLocalizedAppNames: TLocalizedAppNameList;
136 FIOSTeam: String;
137 FindPascalFilesResult: TStringList; // valid only during FindPascalFilesCallback
138 FDebianMenuSection: String;
139 FDebianControlSection: String;
140 FFreeDesktopCategories: String;
141 FFreeDesktopComment: String;
142 FDetectMemoryLeaks: Boolean;
143 FMacAppBundle: Boolean;
144 FProjectDependencies: TProjectDependencies;
145
146 function DefaultQualifiedName(const AName: String): String;
147 procedure CheckMatches(const Name, Value: String; const AllowedChars: TSetOfChars);
148 class procedure CheckUnicodeDoesNotContain(
149 const Name, Value: String; const DisallowedChars: TUnicodeCharList);
150 procedure CheckValidQualifiedName(const OptionName: String; const QualifiedName: String);
151 { Change compiler option @xxx to use absolute paths.
152 Important for "castle-engine editor" where ExtraCompilerOptionsAbsolute is inserted
153 into lpk, but lpk is in a different directory.
154 Testcase: unholy_society. }
155 function MakeAbsoluteCompilerOption(const Option: String): String;
156 { Create and read version from given DOM element.
157 Returns @nil if Element is @nil. }
158 function ReadVersion(const Element: TDOMElement): TProjectVersion;
159 procedure CreateFinish;
160 procedure FindPascalFilesCallback(const FileInfo: TFileInfo; var StopSearch: boolean);
161 procedure SetBaseUrl(const Value: String);
162 public
163 const
164 { Android SDK versions.
165 See https://castle-engine.io/project_manifest#_android_information . }
166 DefaultAndroidCompileSdkVersion = 34;
167 DefaultAndroidTargetSdkVersion = DefaultAndroidCompileSdkVersion;
168 { See https://castle-engine.io/android_faq
169 for reasons behind this minimal version. }
170 DefaultAndroidMinSdkVersion = 21;
171
172 DataName = 'data';
173
174 { Load defaults.
175 @param APath Project path, must be absolute. }
176 constructor Create(const APath: String);
177 { Load manifest file.
178 @param APath Project path, must be absolute.
179 @param ManifestUrl Full URL to CastleEngineManifest.xml, must be absolute. }
180 constructor CreateFromUrl(const APath, ManifestUrl: String); overload;
181 { Load manifest file.
182 @param ManifestUrl Full URL to CastleEngineManifest.xml, must be absolute. }
183 constructor CreateFromUrl(const ManifestUrl: String); overload;
184 { Guess values for the manifest.
185 @param APath Project path, must be absolute.
186 @param AStandaloneSource Guessed StandaloneSource value. Project Name will be derived from it too. }
187 constructor CreateGuess(const APath, AStandaloneSource: String);
188
189 destructor Destroy; override;
190
191 { Detailed information about the project, read-only and useful for
192 various project operations. }
193 { }
194
195 property Version: TProjectVersion read FVersion;
196 property Compiler: TCompiler read FCompiler;
197 property LazarusProject: String read FLazarusProject;
198 property DelphiProject: String read FDelphiProject;
199 property BuildUsingLazbuild: Boolean read FBuildUsingLazbuild;
200 property GameUnits: String read FGameUnits;
201 property EditorUnits: String read FEditorUnits;
202 property QualifiedName: String read FQualifiedName;
203 { Dependencies of this project.
204 Read-only from the outside, do not call any methods that modify
205 the contents of it. }
206 property ProjectDependencies: TProjectDependencies read FProjectDependencies;
207 { Shortcut for ProjectDependencies.Dependencies. }
208 function Dependencies: TDependencies;
209 property Name: String read FName;
210 { Project path. Absolute.
211 Always ends with path delimiter, like a slash or backslash. }
212 property Path: String read FPath;
213 { Same thing as @link(Path), but expressed as an URL. }
214 property PathUrl: String read FPathUrl;
215 property DataExists: Boolean read FDataExists;
216 { Project data path. Absolute.
217 Always ends with path delimiter, like a slash or backslash.
218 Should be ignored if not @link(DataExists). }
219 property DataPath: String read FDataPath;
220 property Caption: String read FCaption;
221 property Author: String read FAuthor;
222 property ExecutableName: String read FExecutableName;
223 property FullscreenImmersive: boolean read FFullscreenImmersive;
224 property ScreenOrientation: TScreenOrientation read FScreenOrientation;
225 property Icons: TImageFileNames read FIcons;
226 property LaunchImages: TImageFileNames read FLaunchImages;
227 { iOS launch image storyboard (see https://castle-engine.io/project_manifest#launch-images-for-now-only-for-ios ).
228 Never @nil (but check Path <> '' before actually using it). }
229 property LaunchImageStoryboard: TLaunchImageStoryboard read FLaunchImageStoryboard;
230 property SearchPaths: TStringList read FSearchPaths;
231 property LibraryPaths: TStringList read FLibraryPaths;
232 property AssociateDocumentTypes: TAssociatedDocTypeList read FAssociateDocumentTypes;
233 property LocalizedAppNames: TLocalizedAppNameList read FLocalizedAppNames;
234 property IncludePaths: TIncludePathList read FIncludePaths;
235 property ExcludePaths: TCastleStringList read FExcludePaths;
236 property ExtraCompilerOptions: TCastleStringList read FExtraCompilerOptions;
237 property ExtraCompilerOptionsAbsolute: TCastleStringList read FExtraCompilerOptionsAbsolute;
238 property Defines: TCastleStringList read FDefines;
239
240 { iOS-specific things }
241 property IOSOverrideQualifiedName: String read FIOSOverrideQualifiedName;
242 property IOSOverrideVersion: TProjectVersion read FIOSOverrideVersion; //< nil if not overridden, should use FVersion then
243 property UsesNonExemptEncryption: boolean read FUsesNonExemptEncryption;
244 property IOSServices: TServiceList read FIOSServices;
245 property IOSTeam: String read FIOSTeam;
246
247 { Android-specific things }
248 property AndroidCompileSdkVersion: Cardinal read FAndroidCompileSdkVersion;
249 property AndroidMinSdkVersion: Cardinal read FAndroidMinSdkVersion;
250 property AndroidTargetSdkVersion: Cardinal read FAndroidTargetSdkVersion;
251 property AndroidServices: TServiceList read FAndroidServices;
252
253 { Standalone source specified in CastleEngineManifest.xml.
254 Most build tool code should use TCastleProject.StandaloneSourceFile instead,
255 that can optionally auto-create the source file. }
256 property StandaloneSource: String read FStandaloneSource;
257
258 { Android source specified in CastleEngineManifest.xml.
259 Most build tool code should use TCastleProject.AndroidSourceFile instead,
260 that can optionally auto-create Android source file. }
261 property AndroidSource: String read FAndroidSource;
262
263 { iOS source specified in CastleEngineManifest.xml.
264 Most build tool code should use TCastleProject.IOSSourceFile instead,
265 that can optionally auto-create iOS source file. }
266 property IOSSource: String read FIOSSource;
267
268 { Plugin source specified in CastleEngineManifest.xml.
269 Most build tool code should use TCastleProject.PluginSourceFile instead,
270 that can optionally auto-create the source file. }
271 property PluginSource: String read FPluginSource;
272
273 { Debian-specific section name, for Debian control file.
274 See https://www.debian.org/doc/debian-policy/ch-archive.html#s-subsections
275 for allowed values.
276 Used only by --package-format=deb.
277
278 Default: 'games'. }
279 property DebianControlSection: String read FDebianControlSection;
280
281 { Debian-specific section name, for Debian menu.
282 See https://www.debian.org/doc/packaging-manuals/menu.html/ch3.html#s3.5 and
283 "man menufile" on Debian for more information.
284 Used only by --package-format=deb.
285
286 Default: 'Games'. }
287 property DebianMenuSection: String read FDebianMenuSection;
288
289 { Freedesktop category of the app,
290 see https://www.freedesktop.org/wiki/Specifications/menu-spec/ for more info.
291 Used only by --package-format=deb right now.
292 Default: Game }
293 property FreeDesktopCategories: String read FFreeDesktopCategories;
294
295 { A short description of the project.
296 See https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html for more info.
297 Used only by --package-format=deb right now. }
298 property FreeDesktopComment: String read FFreeDesktopComment;
299
300 property DetectMemoryLeaks: Boolean read FDetectMemoryLeaks;
301
302 property MacAppBundle: Boolean read FMacAppBundle;
303
304 { Find a file with given BaseName (contains filename, with extension, but without any path)
305 among SearchPaths of this project.
306 Returns absolute filename, or '' if not found. }
307 // unused: function SearchFile(const BaseName: String): String;
308
309 { Find a unit with given name among SearchPaths of this project.
310 Returns absolute filename, or '' if not found.
311 AUnitName is a Pascal unit name (not a filename, without any extension). }
312 function SearchPascalUnit(const AUnitName: String): String;
313
314 { Find a Pascal source file with given name among SearchPaths of this project.
315 Returns absolute filename, or '' if not found.
316 ABaseFileName is a filename (without any path separators) to search for. }
317 function SearchPascalFile(const ABaseFileName: String): String;
318
319 { Finds all Pascal files (units and includes -- not lpr / dpr for now).
320 Returns a list with filenames relative to Path. }
321 function FindPascalFiles: TStringList;
322
323 { Convert possible manifest value of standalone_source into implied Pascal
324 program name. }
325 class function StandaloneSourceToProgramName(const AStandaloneSource: String): String;
326
327 { Raise exception if AExecutableName not valid. }
328 class procedure CheckExecutableName(const AExecutableName: String);
329 end;
330
331 function CompilerToString(const C: TCompiler): String;
332 function StringToCompiler(const S: String): TCompiler;
333
334 function ScreenOrientationToString(const O: TScreenOrientation): String;
335 function StringToScreenOrientation(const S: String): TScreenOrientation;
336
337 const
338 DefaultCompiler = coAutodetect;
339
340 implementation
341
342 uses SysUtils, Math, StrUtils,
343 CastleXmlUtils, CastleFilesUtils, CastleLog, CastleUriUtils,
344 ToolCommonUtils;
345
346 function CompilerToString(const C: TCompiler): String;
347 const
348 Names: array [TCompiler] of String = (
349 'autodetect',
350 'fpc',
351 'delphi'
352 );
353 begin
354 Result := Names[C];
355 end;
356
357 function StringToCompiler(const S: String): TCompiler;
358 begin
359 for Result in TCompiler do
360 if SameText(CompilerToString(Result), S) then
361 Exit;
362 raise Exception.CreateFmt('Invalid compiler name "%s"', [S]);
363 end;
364
365 { TProjectVersion ------------------------------------------------------------- }
366
367 procedure TProjectVersion.InitializeItems;
368 var
369 Strs: TCastleStringList;
370 I: Integer;
371 begin
372 Strs := CastleStringUtils.SplitString(DisplayValue, '.');
373 try
374 for I := 0 to High(Items) do
375 if I < Strs.Count then
376 Items[I] := StrToIntDef(Trim(Strs[I]), 0)
377 else
378 Items[I] := 0;
379 finally FreeAndNil(Strs) end;
380 end;
381
382 { TImageFileNames ------------------------------------------------------------- }
383
384 function TImageFileNames.FindExtension(const Extensions: array of string): String;
385 var
386 I, J: Integer;
387 begin
388 Result := '';
389 for J := 0 to Length(Extensions) - 1 do
390 for I := 0 to Count - 1 do
391 if AnsiSameText(ExtractFileExt(Strings[I]), Extensions[J]) then
392 Exit(Strings[I]);
393 end;
394
395 function TImageFileNames.FindReadable: TCastleImage;
396 var
397 I: Integer;
398 MimeType, Url: String;
399 begin
400 for I := 0 to Count - 1 do
401 begin
402 Url := CombineUri(BaseUrl, Strings[I]);
403 MimeType := UriMimeType(Url);
404 if (MimeType <> '') and IsImageMimeType(MimeType, true, false) then
405 Exit(LoadImage(Url, [TRGBImage, TRGBAlphaImage]));
406 end;
407 Result := nil;
408 end;
409
410 { TLocalizedAppName ---------------------------------------------------------- }
411
412 constructor TLocalizedAppName.Create(const ALanguage, AAppName: String);
413 begin
414 inherited Create;
415 Language := ALanguage;
416 AppName := AAppName;
417 end;
418
419 { TLaunchImageStoryboard ----------------------------------------------------- }
420
421 constructor TLaunchImageStoryboard.Create;
422 begin
423 inherited;
424 // default values
425 Scale := 1;
426 BackgroundColor := Black;
427 end;
428
429 { TCastleManifest ------------------------------------------------------------ }
430
431 constructor TCastleManifest.Create(const APath: String);
432 begin
433 inherited Create;
434 OwnerComponent := TComponent.Create(nil);
435 FIncludePaths := TIncludePathList.Create(true);
436 FExcludePaths := TCastleStringList.Create;
437 FExtraCompilerOptions := TCastleStringList.Create;
438 FExtraCompilerOptionsAbsolute := TCastleStringList.Create;
439 FDefines := TCastleStringList.Create;
440 FIcons := TImageFileNames.Create;
441 FLaunchImages := TImageFileNames.Create;
442 FLaunchImageStoryboard := TLaunchImageStoryboard.Create;
443 FSearchPaths := TStringList.Create;
444 FLibraryPaths := TStringList.Create;
445 FAndroidServices := TServiceList.Create(true);
446 FIOSServices := TServiceList.Create(true);
447 FAssociateDocumentTypes := TAssociatedDocTypeList.Create;
448 FProjectDependencies := TProjectDependencies.Create;
449
450 { set defaults (only on fields that are not already in good default state after construction) }
451 FDataExists := DefaultDataExists;
452 FAndroidCompileSdkVersion := DefaultAndroidCompileSdkVersion;
453 FAndroidMinSdkVersion := DefaultAndroidMinSdkVersion;
454 FAndroidTargetSdkVersion := DefaultAndroidTargetSdkVersion;
455 FUsesNonExemptEncryption := DefaultUsesNonExemptEncryption;
456 FFullscreenImmersive := DefaultFullscreenImmersive;
457 FDetectMemoryLeaks := DefaultDetectMemoryLeaks;
458 FMacAppBundle := DefaultMacAppBundle;
459
460 FPath := InclPathDelim(APath);
461 FPathUrl := FilenameToUriSafe(FPath);
462 FDataPath := InclPathDelim(FPath + DataName);
463 end;
464
465 constructor TCastleManifest.CreateGuess(const APath, AStandaloneSource: String);
466 begin
467 Create(APath);
468
469 FDataPath := InclPathDelim(Path + DataName);
470 FName := DeleteFileExt(AStandaloneSource);
471 FCaption := FName;
472 FQualifiedName := DefaultQualifiedName(FName);
473 FExecutableName := FName;
474 FCompiler := DefaultCompiler;
475 FStandaloneSource := AStandaloneSource;
476 FLazarusProject := FName + '.lpi';
477 FDelphiProject := FName + '.dproj';
478 FVersion := TProjectVersion.Create(OwnerComponent);
479 FVersion.Code := DefautVersionCode;
480 FVersion.DisplayValue := DefautVersionDisplayValue;
481 SetBaseUrl(FilenameToUriSafe(InclPathDelim(GetCurrentDir)));
482
483 CreateFinish;
484 end;
485
486 constructor TCastleManifest.CreateFromUrl(const APath, ManifestUrl: String);
487
488 { Get XML element attribute as Cardinal,
489 using DefaultAndMinimum as default (if not exists in XML).
490
491 Moreover, if value in XML exists but is smaller than DefaultAndMinimum,
492 then we make a warning and use DefaultAndMinimum anyway. }
493 function GetAttributeCardinalWithMinimum(const Element: TDOMElement;
494 const AttributeName: String; const DefaultAndMinimum: Cardinal): Cardinal;
495 begin
496 Result := Element.AttributeCardinalDef(AttributeName, DefaultAndMinimum);
497 if Result < DefaultAndMinimum then
498 begin
499 WritelnWarning('Manifest', Format('Value "%d" of attribute "%s.%s" in "CastleEngineManifest.xml" is smaller than default "%d", using default instead', [
500 Result,
501 Element.TagName,
502 AttributeName,
503 DefaultAndMinimum
504 ]));
505 Result := DefaultAndMinimum;
506 end;
507 end;
508
509 var
510 Doc: TXMLDocument;
511 AndroidProjectTypeStr: String;
512 ChildElements: TXMLElementIterator;
513 Element, ChildElement: TDOMElement;
514 NewCompilerOption, DefaultLazarusProject, DefaultDelphiProject, NewSearchPath: String;
515 IncludePath: TIncludePath;
516 begin
517 Create(APath);
518 SetBaseUrl(ManifestUrl);
519
520 Doc := UrlReadXML(ManifestUrl);
521 try
522 Check(Doc.DocumentElement.TagName = 'project',
523 'Root node of CastleEngineManifest.xml must be <project>');
524 FName := Doc.DocumentElement.AttributeString('name');
525 FCaption := Doc.DocumentElement.AttributeStringDef('caption', FName);
526 FQualifiedName := Doc.DocumentElement.AttributeStringDef('qualified_name', DefaultQualifiedName(FName));
527 FExecutableName := Doc.DocumentElement.AttributeStringDef('executable_name', FName);
528 FStandaloneSource := Doc.DocumentElement.AttributeStringDef('standalone_source', '');
529 FCompiler := StringToCompiler(Doc.DocumentElement.AttributeStringDef('compiler', 'autodetect'));
530 if FStandaloneSource <> '' then
531 begin
532 DefaultLazarusProject := ChangeFileExt(FStandaloneSource, '.lpi');
533 DefaultDelphiProject := ChangeFileExt(FStandaloneSource, '.dproj');
534 end else
535 begin
536 DefaultLazarusProject := '';
537 DefaultDelphiProject := '';
538 end;
539 FLazarusProject := Doc.DocumentElement.AttributeStringDef('lazarus_project', DefaultLazarusProject);
540 FDelphiProject := Doc.DocumentElement.AttributeStringDef('delphi_project', DefaultDelphiProject);
541 FAndroidSource := Doc.DocumentElement.AttributeStringDef('android_source', '');
542 FIOSSource := Doc.DocumentElement.AttributeStringDef('ios_source', '');
543 FPluginSource := Doc.DocumentElement.AttributeStringDef('plugin_source', '');
544 FAuthor := Doc.DocumentElement.AttributeStringDef('author', '');
545 FGameUnits := Doc.DocumentElement.AttributeStringDef('game_units', '');
546 FEditorUnits := Doc.DocumentElement.AttributeStringDef('editor_units', '');
547 FScreenOrientation := StringToScreenOrientation(
548 Doc.DocumentElement.AttributeStringDef('screen_orientation', 'any'));
549 FFullscreenImmersive := Doc.DocumentElement.AttributeBooleanDef('fullscreen_immersive', true);
550 FBuildUsingLazbuild := Doc.DocumentElement.AttributeBooleanDef('build_using_lazbuild', false);
551 FMacAppBundle := Doc.DocumentElement.AttributeBooleanDef('mac_app_bundle',
552 DefaultMacAppBundle);
553
554 FVersion := ReadVersion(Doc.DocumentElement.ChildElement('version', false));
555 // create default FVersion value, if necessary
556 if FVersion = nil then
557 begin
558 FVersion := TProjectVersion.Create(OwnerComponent);
559 FVersion.Code := DefautVersionCode;
560 FVersion.DisplayValue := DefautVersionDisplayValue;
561 end;
562
563 ProjectDependencies.ReadFromManifest(Doc);
564
565 Element := Doc.DocumentElement.ChildElement('package', false);
566 if Element <> nil then
567 begin
568 ChildElements := Element.ChildrenIterator('include');
569 try
570 while ChildElements.GetNext do
571 begin
572 ChildElement := ChildElements.Current;
573 IncludePath := TIncludePath.Create;
574 IncludePath.Path := ChildElement.AttributeString('path');
575 IncludePath.Recursive := ChildElement.AttributeBooleanDef('recursive', false);
576 IncludePath.ExecutablePermission := ChildElement.AttributeBooleanDef('executable_permission', false);
577 FIncludePaths.Add(IncludePath);
578 end;
579 finally FreeAndNil(ChildElements) end;
580
581 ChildElements := Element.ChildrenIterator('exclude');
582 try
583 while ChildElements.GetNext do
584 begin
585 ChildElement := ChildElements.Current;
586 FExcludePaths.Add(ChildElement.AttributeString('path'));
587 end;
588 finally FreeAndNil(ChildElements) end;
589 end;
590
591 Element := Doc.DocumentElement.ChildElement('icons', false);
592 if Element <> nil then
593 begin
594 ChildElements := Element.ChildrenIterator('icon');
595 try
596 while ChildElements.GetNext do
597 begin
598 ChildElement := ChildElements.Current;
599 Icons.Add(ChildElement.AttributeString('path'));
600 end;
601 finally FreeAndNil(ChildElements) end;
602 end;
603
604 Element := Doc.DocumentElement.ChildElement('launch_images', false);
605 if Element <> nil then
606 begin
607 ChildElements := Element.ChildrenIterator('image');
608 try
609 while ChildElements.GetNext do
610 begin
611 ChildElement := ChildElements.Current;
612 LaunchImages.Add(ChildElement.AttributeString('path'));
613 end;
614 finally FreeAndNil(ChildElements) end;
615
616 Element := Element.ChildElement('storyboard', false);
617 if Element <> nil then
618 begin
619 FLaunchImageStoryboard.Path := Element.AttributeString('path');
620 FLaunchImageStoryboard.Scale := Element.AttributeSingleDef('scale', 1.0);
621 FLaunchImageStoryboard.BackgroundColor := Element.AttributeColorDef('background_color', Black);
622 if not SameValue(FLaunchImageStoryboard.BackgroundColor[3], 1) then
623 raise Exception.Create('Launch image storyboard background_color alpha must be 1.0, meaning of other values is not defined for now');
624 end;
625 end;
626
627 Element := Doc.DocumentElement.ChildElement('localization', false);
628 if Element <> nil then
629 begin
630 FLocalizedAppNames := TLocalizedAppNameList.Create(true);
631 ChildElements := Element.ChildrenIterator;
632 try
633 while ChildElements.GetNext do
634 begin
635 Check(ChildElements.Current.TagName = 'caption', 'Each child of the localization node must be an <caption> element.');
636 FLocalizedAppNames.Add(TLocalizedAppName.Create(
637 ChildElements.Current.AttributeString('lang'),
638 ChildElements.Current.AttributeString('value')));
639 end;
640 finally
641 FreeAndNil(ChildElements);
642 end;
643 end;
644
645 FAndroidCompileSdkVersion := DefaultAndroidCompileSdkVersion;
646 FAndroidMinSdkVersion := DefaultAndroidMinSdkVersion;
647 FAndroidTargetSdkVersion := DefaultAndroidTargetSdkVersion;
648 Element := Doc.DocumentElement.ChildElement('android', false);
649
650 if Element <> nil then
651 begin
652 FAndroidCompileSdkVersion := GetAttributeCardinalWithMinimum(Element, 'compile_sdk_version', DefaultAndroidCompileSdkVersion);
653 FAndroidMinSdkVersion := GetAttributeCardinalWithMinimum(Element, 'min_sdk_version', DefaultAndroidMinSdkVersion);
654 FAndroidTargetSdkVersion := GetAttributeCardinalWithMinimum(Element, 'target_sdk_version', DefaultAndroidTargetSdkVersion);
655
656 if Element.AttributeString('project_type', AndroidProjectTypeStr) then
657 begin
658 WritelnWarning('Specifying android project_type in CastleEngineManifest.xml is deprecated, all projects are "integrated" always. Remove the project_type="..." attribute from <android ...> element in CastleEngineManifest.xml.');
659 end;
660
661 ChildElement := Element.ChildElement('components', false);
662 if ChildElement <> nil then
663 begin
664 FAndroidServices.ReadCastleEngineManifest(ChildElement);
665 WritelnWarning('Android', 'The name <components> is deprecated, use <services> now to refer to Android services');
666 end;
667 ChildElement := Element.ChildElement('services', false);
668 if ChildElement <> nil then
669 FAndroidServices.ReadCastleEngineManifest(ChildElement);
670 end;
671
672 Element := Doc.DocumentElement.ChildElement('ios', false);
673 FUsesNonExemptEncryption := DefaultUsesNonExemptEncryption;
674 if Element <> nil then
675 begin
676 FIOSTeam := Element.AttributeStringDef('team', '');
677
678 FIOSOverrideQualifiedName := Element.AttributeStringDef('override_qualified_name', '');
679 if FIOSOverrideQualifiedName <> '' then
680 CheckValidQualifiedName('override_qualified_name', FIOSOverrideQualifiedName);
681
682 FIOSOverrideVersion := ReadVersion(Element.Child('override_version', false));
683
684 FUsesNonExemptEncryption := Element.AttributeBooleanDef('uses_non_exempt_encryption',
685 DefaultUsesNonExemptEncryption);
686
687 ChildElement := Element.ChildElement('services', false);
688 if ChildElement <> nil then
689 FIOSServices.ReadCastleEngineManifest(ChildElement);
690 end;
691
692 Element := Doc.DocumentElement.ChildElement('associate_document_types', false);
693 if Element <> nil then
694 begin
695 FAssociateDocumentTypes.ReadCastleEngineManifest(Element);
696 if FAssociateDocumentTypes.Count > 0 then
697 FAndroidServices.AddService('open_associated_urls');
698 end;
699
700 Element := Doc.DocumentElement.ChildElement('compiler_options', false);
701 if Element <> nil then
702 begin
703 FDetectMemoryLeaks := Element.AttributeBooleanDef('detect_memory_leaks', DefaultDetectMemoryLeaks);
704
705 ChildElement := Element.ChildElement('custom_options', false);
706 if ChildElement <> nil then
707 begin
708 ChildElements := ChildElement.ChildrenIterator('option');
709 try
710 while ChildElements.GetNext do
711 begin
712 NewCompilerOption := ChildElements.Current.TextData;
713 FExtraCompilerOptions.Add(NewCompilerOption);
714 FExtraCompilerOptionsAbsolute.Add(MakeAbsoluteCompilerOption(NewCompilerOption));
715 end;
716 finally FreeAndNil(ChildElements) end;
717 end;
718
719 ChildElement := Element.ChildElement('defines', false);
720 if ChildElement <> nil then
721 begin
722 ChildElements := ChildElement.ChildrenIterator('define');
723 try
724 while ChildElements.GetNext do
725 FDefines.Add(Trim(ChildElements.Current.TextData));
726 finally FreeAndNil(ChildElements) end;
727 end;
728
729 ChildElement := Element.ChildElement('search_paths', false);
730 if ChildElement <> nil then
731 begin
732 ChildElements := ChildElement.ChildrenIterator('path');
733 try
734 while ChildElements.GetNext do
735 begin
736 NewSearchPath := ChildElements.Current.AttributeString('value');
737 if IsPathAbsoluteOnDrive(NewSearchPath) then
738 WritelnWarning('Search path "%s" is an absolute path, it will likely not work on other systems.', [NewSearchPath]);
739 FSearchPaths.Add(NewSearchPath);
740 end;
741 finally FreeAndNil(ChildElements) end;
742 end;
743
744 ChildElement := Element.ChildElement('library_paths', false);
745 if ChildElement <> nil then
746 begin
747 ChildElements := ChildElement.ChildrenIterator('path');
748 try
749 while ChildElements.GetNext do
750 FLibraryPaths.Add(ChildElements.Current.AttributeString('value'));
751 finally FreeAndNil(ChildElements) end;
752 end;
753 end;
754
755 Element := Doc.DocumentElement.ChildElement('data', false);
756 if Element <> nil then
757 FDataExists := Element.AttributeBooleanDef('exists', DefaultDataExists)
758 else
759 FDataExists := DefaultDataExists;
760
761 if FAndroidServices.HasService('open_associated_urls') then
762 FAndroidServices.AddService('download_urls'); // downloading is needed when opening files from web
763
764 FDebianControlSection := 'games';
765 FDebianMenuSection := 'Games';
766 Element := Doc.DocumentElement.ChildElement('debian', false);
767 if Element <> nil then
768 begin
769 FDebianControlSection := Element.AttributeStringDef('control_section', FDebianControlSection);
770 FDebianMenuSection := Element.AttributeStringDef('menu_section', FDebianMenuSection);
771 end;
772
773 FFreeDesktopCategories := 'Game';
774 FFreeDesktopComment := '';
775 Element := Doc.DocumentElement.ChildElement('free_desktop', false);
776 if Element <> nil then
777 begin
778 FFreeDesktopCategories := Element.AttributeStringDef('categories', FFreeDesktopCategories);
779 FFreeDesktopComment := Element.AttributeStringDef('comment', FFreeDesktopComment);
780 end;
781 finally FreeAndNil(Doc) end;
782
783 CreateFinish;
784 end;
785
786 constructor TCastleManifest.CreateFromUrl(const ManifestUrl: String);
787 begin
788 CreateFromUrl(ExtractFilePath(UriToFilenameSafe(ManifestUrl)), ManifestUrl);
789 end;
790
791 destructor TCastleManifest.Destroy;
792 begin
793 FreeAndNil(FProjectDependencies);
794 FreeAndNil(OwnerComponent);
795 FreeAndNil(FIncludePaths);
796 FreeAndNil(FExcludePaths);
797 FreeAndNil(FExtraCompilerOptions);
798 FreeAndNil(FExtraCompilerOptionsAbsolute);
799 FreeAndNil(FDefines);
800 FreeAndNil(FIcons);
801 FreeAndNil(FLaunchImages);
802 FreeAndNil(FLaunchImageStoryboard);
803 FreeAndNil(FSearchPaths);
804 FreeAndNil(FLibraryPaths);
805 FreeAndNil(FAndroidServices);
806 FreeAndNil(FIOSServices);
807 FreeAndNil(FAssociateDocumentTypes);
808 FreeAndNil(FLocalizedAppNames);
809 inherited;
810 end;
811
812 procedure TCastleManifest.SetBaseUrl(const Value: String);
813 begin
814 Icons.BaseUrl := Value;
815 LaunchImages.BaseUrl := Value;
816 LaunchImageStoryboard.BaseUrl := Value;
817 end;
818
819 function TCastleManifest.DefaultQualifiedName(const AName: String): String;
820 begin
821 Result := SDeleteChars(FName, AllChars - QualifiedNameAllowedChars);
822 { On Android, package name cannot be just a word, it must have some dot. }
823 if Pos('.', Result) = 0 then
824 Result := 'com.mycompany.' + Result;
825 end;
826
827 procedure TCastleManifest.CheckMatches(const Name, Value: String; const AllowedChars: TSetOfChars);
828 var
829 I: Integer;
830 begin
831 for I := 1 to Length(Value) do
832 if not (Value[I] in AllowedChars) then
833 raise Exception.CreateFmt('Project %s contains invalid characters: "%s", this character is not allowed: "%s"',
834 [Name, Value, SReadableForm(Value[I])]);
835 end;
836
837 class procedure TCastleManifest.CheckUnicodeDoesNotContain(
838 const Name, Value: String; const DisallowedChars: TUnicodeCharList);
839 var
840 Iter: TCastleStringIterator;
841 begin
842 Iter.Start(Value);
843 while Iter.GetNext do
844 begin
845 if DisallowedChars.IndexOf(Iter.Current) <> -1 then
846 raise Exception.CreateFmt('Project %s contains invalid characters: "%s", this character is not allowed: "%s"', [
847 Name,
848 Value,
849 UnicodeCharToReadableString(Iter.Current)
850 ]);
851 end;
852 end;
853
854 class procedure TCastleManifest.CheckExecutableName(const AExecutableName: String);
855 var
856 DisallowedChars: TUnicodeCharList;
857 DisallowedChar: TUnicodeChar;
858 begin
859 { Executable name can contain everything that is an allowed filename
860 on modern platforms.
861 See https://superuser.com/questions/358855/what-characters-are-safe-in-cross-platform-file-names-for-linux-windows-and-os .
862 In particular, most local (Chinese, Polish...) characters are OK. }
863 DisallowedChars := TUnicodeCharList.Create;
864 try
865 DisallowedChars.Add('\/:*?"<>|');
866 for DisallowedChar := 0 to 31 do // disallow null, ASCII control characters
867 DisallowedChars.Add(DisallowedChar);
868 CheckUnicodeDoesNotContain('executable_name', AExecutableName, DisallowedChars);
869 finally FreeAndNil(DisallowedChars) end;
870 end;
871
872 procedure TCastleManifest.CheckValidQualifiedName(const OptionName: String; const QualifiedName: String);
873 var
874 Components: TStringList;
875 I: Integer;
876 begin
877 CheckMatches(OptionName, QualifiedName, QualifiedNameAllowedChars);
878
879 if (QualifiedName <> '') and
880 ((QualifiedName[1] = '.') or
881 (QualifiedName[Length(QualifiedName)] = '.')) then
882 raise Exception.CreateFmt('%s (in %s) cannot start or end with a dot: "%s"', [
883 OptionName,
884 ManifestName,
885 QualifiedName
886 ]);
887
888 Components := CastleStringUtils.SplitString(QualifiedName, '.');
889 try
890 for I := 0 to Components.Count - 1 do
891 begin
892 if Components[I] = '' then
893 raise Exception.CreateFmt('%s (in %s) must contain a number of non-empty components separated with dots: "%s"', [
894 OptionName,
895 ManifestName,
896 QualifiedName
897 ]);
898 if Components[I][1] in ['0'..'9'] then
899 raise Exception.CreateFmt('%s (in %s) components must not start with a digit: "%s"', [
900 OptionName,
901 ManifestName,
902 QualifiedName
903 ]);
904 end;
905 finally FreeAndNil(Components) end;
906 end;
907
908 function TCastleManifest.ReadVersion(const Element: TDOMElement): TProjectVersion;
909 begin
910 if Element = nil then
911 Exit(nil);
912 Result := TProjectVersion.Create(OwnerComponent);
913 Result.DisplayValue := Element.AttributeString('value');
914 CheckMatches('version value', Result.DisplayValue, AlphaNum + ['_','-','.']);
915 Result.Code := Element.AttributeCardinalDef('code', DefautVersionCode);
916 end;
917
918 function TCastleManifest.MakeAbsoluteCompilerOption(const Option: String): String;
919 begin
920 Result := Trim(Option);
921 if (Length(Result) >= 2) and (Result[1] = '@') then
922 Result := '@' + CombinePaths(Path, SEnding(Result, 2));
923 end;
924
925 procedure TCastleManifest.CreateFinish;
926
927 { If DataExists, check whether DataPath really exists.
928 If it doesn't exist, make a warning and set FDataExists to false. }
929 procedure CheckDataExists;
930 begin
931 if FDataExists then
932 begin
933 if DirectoryExists(DataPath) then
934 WritelnLog('Found data in "' + DataPath + '"')
935 else
936 begin
937 WritelnWarning('Data directory not found (tried "' + DataPath + '"). If this project has no data, add <data exists="false"/> to CastleEngineManifest.xml.');
938 FDataExists := false;
939 end;
940 end else
941 begin
942 if DirectoryExists(DataPath) then
943 WritelnWarning('Possible data directory found in "' + DataPath + '", but your project has <data exists="false"/> in CastleEngineManifest.xml, so it will be ignored.' + NL +
944 ' To remove this warning:' + NL +
945 ' 1. Rename this directory to something else than "data" (if it should not be packaged),' + NL +
946 ' 2. Remove <data exists="false"/> from CastleEngineManifest.xml (if "data" should be packaged).');
947 end;
948 end;
949
950 { Check correctness. }
951 procedure CheckManifestCorrect;
952 var
953 ProgramName: String;
954 begin
955 { Note that project "name" can contain minus ("-")
956 character which is not allowed inside a Pascal identifier.
957 This is a deliberate feature (we like names like "castle-model-viewer").
958 When we have to derive some Pascal identifier from it, we use
959 MakeProjectPascalName , TCastleProject.NamePascal and related. }
960 CheckMatches('name', Name, AlphaNum + ['_','-']);
961
962 CheckExecutableName(ExecutableName);
963
964 { non-filename stuff: allow also dots }
965 CheckValidQualifiedName('qualified_name', QualifiedName);
966
967 { more user-visible stuff, where we allow spaces, local characters and so on }
968 CheckMatches('caption', Caption, AllChars - ControlChars);
969 CheckMatches('author', Author , AllChars - ControlChars);
970
971 { StandaloneSource, if specified, determines the dpr filename
972 and (sans extension) the Pascal "program" declaration
973 (these 2 things have to match exactly, compilers check this when "program"
974 is specified, and we have to specify "program" otherwise Delphi IDE
975 breaks "uses" clause when adding units).
976 As such, it has to be a valid Pascal identifier. }
977 if StandaloneSource <> '' then
978 begin
979 ProgramName := StandaloneSourceToProgramName(StandaloneSource);
980 if not IsValidIdent(ProgramName) then
981 //raise Exception.CreateFmt
982 WritelnWarning('Program name "%s" (determined by standalone_source "%s" in CastleEngineManifest.xml) is not a valid Pascal identifier. This will be an error in future CGE versions, please rename your DPR / LPR.', [
983 ProgramName,
984 StandaloneSource
985 ]);
986 end;
987
988 if AndroidMinSdkVersion > AndroidTargetSdkVersion then
989 raise Exception.CreateFmt('Android min_sdk_version %d is larger than target_sdk_version %d, this is incorrect',
990 [AndroidMinSdkVersion, AndroidTargetSdkVersion]);
991 end;
992
993 begin
994 Version.InitializeItems;
995 CheckDataExists;
996
997 // depends on FDataExists finalized, so must be after CheckDataExists
998 if DataExists then
999 FProjectDependencies.GuessDependencies(DataPath);
1000
1001 // must be after GuessDependencies, to close also guessed dependencies
1002 FProjectDependencies.CloseDependencies;
1003
1004 CheckManifestCorrect; // must be at end, to validate all
1005 end;
1006
1007 function TCastleManifest.Dependencies: TDependencies;
1008 begin
1009 Result := FProjectDependencies.Dependencies;
1010 end;
1011
1012 {
1013 function TCastleManifest.SearchFile(const BaseName: String): String;
1014 var
1015 SearchPath, FileNameAbsolute: String;
1016 begin
1017 for SearchPath in SearchPaths do
1018 begin
1019 FileNameAbsolute := CombinePaths(CombinePaths(Path, SearchPath), BaseName);
1020 if RegularFileExists(FileNameAbsolute) then
1021 Exit(FileNameAbsolute);
1022 end;
1023 Result := '';
1024 end;
1025 }
1026
1027 function TCastleManifest.SearchPascalUnit(const AUnitName: String): String;
1028
1029 function SearchInPath(const SearchPathAbsolute: String): String;
1030 var
1031 FileNameAbsolute: String;
1032 begin
1033 FileNameAbsolute := CombinePaths(SearchPathAbsolute, AUnitName + '.pas');
1034 if RegularFileExists(FileNameAbsolute) then
1035 Exit(FileNameAbsolute);
1036
1037 FileNameAbsolute := CombinePaths(SearchPathAbsolute, AUnitName + '.pp');
1038 if RegularFileExists(FileNameAbsolute) then
1039 Exit(FileNameAbsolute);
1040
1041 { for case-sensitive filesystems, search also for lowercase version,
1042 just like FPC does. }
1043
1044 FileNameAbsolute := CombinePaths(SearchPathAbsolute, LowerCase(AUnitName) + '.pas');
1045 if RegularFileExists(FileNameAbsolute) then
1046 Exit(FileNameAbsolute);
1047
1048 FileNameAbsolute := CombinePaths(SearchPathAbsolute, LowerCase(AUnitName) + '.pp');
1049 if RegularFileExists(FileNameAbsolute) then
1050 Exit(FileNameAbsolute);
1051
1052 Result := '';
1053 end;
1054
1055 var
1056 SearchPath: String;
1057 begin
1058 Result := SearchInPath(Path);
1059 if Result <> '' then
1060 Exit;
1061
1062 for SearchPath in SearchPaths do
1063 begin
1064 Result := SearchInPath(CombinePaths(Path, SearchPath));
1065 if Result <> '' then
1066 Exit;
1067 end;
1068 end;
1069
1070 function TCastleManifest.SearchPascalFile(const ABaseFileName: String): String;
1071
1072 function SearchInPath(const SearchPathAbsolute: String): String;
1073 var
1074 FileNameAbsolute: String;
1075 begin
1076 FileNameAbsolute := CombinePaths(SearchPathAbsolute, ABaseFileName);
1077 if RegularFileExists(FileNameAbsolute) then
1078 Exit(FileNameAbsolute);
1079
1080 Result := '';
1081 end;
1082
1083 var
1084 SearchPath: String;
1085 begin
1086 Result := SearchInPath(Path);
1087 if Result <> '' then
1088 Exit;
1089
1090 for SearchPath in SearchPaths do
1091 begin
1092 Result := SearchInPath(CombinePaths(Path, SearchPath));
1093 if Result <> '' then
1094 Exit;
1095 end;
1096 end;
1097
1098 function TCastleManifest.FindPascalFiles: TStringList;
1099
1100 procedure ScanSearchPath(const SearchPath: String);
1101 var
1102 SearchPathAbsolute: String;
1103 begin
1104 SearchPathAbsolute := CombinePaths(Path, SearchPath);
1105 FindFiles(SearchPathAbsolute, '*.pas', false, @FindPascalFilesCallback, []);
1106 FindFiles(SearchPathAbsolute, '*.pp', false, @FindPascalFilesCallback, []);
1107 FindFiles(SearchPathAbsolute, '*.inc', false, @FindPascalFilesCallback, []);
1108 end;
1109
1110 var
1111 SearchPath: String;
1112 begin
1113 Result := TStringList.Create;
1114 FindPascalFilesResult := Result;
1115
1116 ScanSearchPath(''); // the project root is implicitly always on search path
1117 for SearchPath in SearchPaths do
1118 ScanSearchPath(SearchPath);
1119
1120 FindPascalFilesResult := nil; // nothing should use it, but don't leave dangling pointer anyway
1121 end;
1122
1123 procedure TCastleManifest.FindPascalFilesCallback(
1124 const FileInfo: TFileInfo; var StopSearch: boolean);
1125 var
1126 Relative: String;
1127 begin
1128 Relative := ExtractRelativePath(Path, FileInfo.AbsoluteName);
1129 {$ifdef MSWINDOWS}
1130 { Use forward slashes also on Windows,
1131 this way LPI generated on Windows and Unix will look the same
1132 (so e.g. version control systems will not report differences). }
1133 StringReplaceAllVar(Relative, '\', '/');
1134 {$endif}
1135 FindPascalFilesResult.Add(Relative);
1136 end;
1137
1138 class function TCastleManifest.StandaloneSourceToProgramName(const AStandaloneSource: String): String;
1139 begin
1140 { Use ExtractFileName to ignore path in AStandaloneSource
1141 which is possible, user can specify path like "code/myprogram_standalone.lpr". }
1142 Result := ExtractFileName(DeleteFileExt(AStandaloneSource));
1143 end;
1144
1145 { globals -------------------------------------------------------------------- }
1146
1147 const
1148 ScreenOrientationNames: array [TScreenOrientation] of string =
1149 ('any', 'landscape', 'portrait');
1150
1151 function ScreenOrientationToString(const O: TScreenOrientation): String;
1152 begin
1153 Result := ScreenOrientationNames[O];
1154 end;
1155
1156 function StringToScreenOrientation(const S: String): TScreenOrientation;
1157 begin
1158 for Result in TScreenOrientation do
1159 if AnsiSameText(ScreenOrientationNames[Result], S) then
1160 Exit;
1161 raise Exception.CreateFmt('Invalid orientation name "%s"', [S]);
1162 end;
1163
1164 end.