Debian Codegraph @

tools/build-tool/code/toolios.pas

raw
1 {
2 Copyright 2014-2022 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 { iOS specific utilities. }
17 unit ToolIOS;
18
19 interface
20
21 uses Classes,
22 CastleUtils, CastleStringUtils,
23 ToolUtils, ToolArchitectures, ToolCompile, ToolProject, ToolPackageFormat,
24 ToolManifest;
25
26 var
27 IosSimulatorSupport: Boolean = false;
28
29 type
30 TIosArchiveType = (
31 atDevelopment,
32 atAdHoc,
33 atAppStore
34 );
35
36 { Compile all IOS libraries (4 or 2 versions, depending on IosSimulatorSupport).
37
38 CompilerOptions.OS andCompilerOptions.CPU are ignored by this routine.
39 This routine may modify CompilerOptions contents. }
40 procedure CompileIOS(const Compiler: TCompiler;
41 const WorkingDirectory, CompileFile: string;
42 const CompilerOptions: TCompilerOptions);
43
44 procedure LinkIOSLibrary(const Compiler: TCompiler;
45 const CompilationWorkingDirectory, OutputFile: string);
46
47 function PackageFormatWantsIOSArchive(const PackageFormat: TPackageFormatNoDefault;
48 out ArchiveType: TIosArchiveType; out ExportMethod: String): Boolean;
49
50 procedure PackageIOS(const Project: TCastleProject;
51 const UpdateOnlyCode: Boolean);
52 { Call ArchiveIOS immediately after PackageIOS to perform build + archive using Xcode command-line. }
53 procedure ArchiveIOS(const Project: TCastleProject; const ArchiveType: TIosArchiveType);
54 procedure RunIOS(const Project: TCastleProject);
55
56 procedure MergeIOSAppDelegate(const Source, Destination: string;
57 const ReplaceMacros: TReplaceMacros);
58 procedure MergeIOSPodfile(const Source, Destination: string;
59 const ReplaceMacros: TReplaceMacros);
60 procedure MergeIOSInfoPlist(const Source, Destination: string;
61 const ReplaceMacros: TReplaceMacros);
62
63 implementation
64
65 uses SysUtils, DOM,
66 CastleImages, CastleUriUtils, CastleLog, CastleFilesUtils, CastleXmlUtils,
67 ToolEmbeddedImages, ToolIosPbxGeneration, ToolServices, ToolCommonUtils,
68 ToolServicesOperations;
69
70 const
71 IOSPartialLibraryName = 'lib_cge_project.a';
72
73 procedure CompileIOS(const Compiler: TCompiler;
74 const WorkingDirectory, CompileFile: string;
75 const CompilerOptions: TCompilerOptions);
76
77 procedure CompileLibrary(const OS: TOS; const CPU: TCPU);
78 var
79 CompilationOutput, LinkRes, OutputLibrary: string;
80 LinkResContents, ObjectFiles: TCastleStringList;
81 I: Integer;
82 begin
83 CompilerOptions.OS := OS;
84 CompilerOptions.CPU := CPU;
85 Compile(Compiler, WorkingDirectory, CompileFile, CompilerOptions);
86
87 { now use libtool to create a static library .a }
88
89 CompilationOutput := CompilationOutputPath(Compiler, OS, CPU, WorkingDirectory);
90
91 // will raise exception if not found, or ambiguous
92 LinkRes := FindLinkRes(CompilationOutput);
93
94 OutputLibrary := CompilationOutput + IOSPartialLibraryName;
95
96 { grep '\.o$' link.res > lib_cge_project_object_files.txt }
97 LinkResContents := TCastleStringList.Create;
98 try
99 LinkResContents.LoadFromFile(LinkRes);
100
101 ObjectFiles := TCastleStringList.Create;
102 try
103 for I := 0 to LinkResContents.Count - 1 do
104 if IsSuffix('.o', LinkResContents[I]) then
105 ObjectFiles.Add(LinkResContents[I]);
106 ObjectFiles.SaveToFile(CompilationOutput + 'lib_cge_project_object_files.txt');
107 finally FreeAndNil(ObjectFiles) end;
108 finally FreeAndNil(LinkResContents) end;
109
110 DeleteFile(LinkRes); // delete it, to allow later FindLinkRes to work
111
112 RunCommandSimple('libtool', ['-static', '-o', OutputLibrary, '-filelist',
113 CompilationOutput + 'lib_cge_project_object_files.txt']);
114 if not RegularFileExists(OutputLibrary) then
115 raise Exception.CreateFmt('Creating library "%s" failed', [OutputLibrary]);
116 end;
117
118 begin
119 { To compile CastleInternalVorbisFile properly.
120 Later PackageIOS will actually add the static tremolo files to the project. }
121 CompilerOptions.ExtraOptions.Add('-dCASTLE_TREMOLO_STATIC');
122
123 if IosSimulatorSupport then
124 begin
125 { iPhoneSimulator for i386 is not useful, since
126 - macOS on i386 is no longer supported
127 - fpcupdeluxe seems to not even allow making FPC cross-compiler for iPhoneSimulator on i386 }
128 //CompileLibrary(iphonesim, i386);
129 CompileLibrary(iphonesim, x86_64);
130 end;
131 CompileLibrary(iOS, arm);
132 CompileLibrary(iOS, aarch64);
133 end;
134
135 procedure LinkIOSLibrary(const Compiler: TCompiler; const CompilationWorkingDirectory, OutputFile: string);
136 var
137 Options: TCastleStringList;
138 begin
139 Options := TCastleStringList.Create;
140 try
141 Options.Add('-static');
142 Options.Add('-o');
143 Options.Add(OutputFile);
144 if IosSimulatorSupport then
145 begin
146 { iPhoneSimulator for i386 is not useful, since
147 - macOS on i386 is no longer supported
148 - fpcupdeluxe seems to not even allow making FPC cross-compiler for iPhoneSimulator on i386 }
149 //Options.Add(CompilationOutputPath(Compiler, iphonesim, i386 , CompilationWorkingDirectory) + IOSPartialLibraryName);
150 Options.Add(CompilationOutputPath(Compiler, iphonesim, x86_64 , CompilationWorkingDirectory) + IOSPartialLibraryName);
151 end;
152 Options.Add(CompilationOutputPath(Compiler, iOS , arm , CompilationWorkingDirectory) + IOSPartialLibraryName);
153 Options.Add(CompilationOutputPath(Compiler, iOS , aarch64, CompilationWorkingDirectory) + IOSPartialLibraryName);
154 RunCommandSimple('libtool', Options.ToArray);
155 finally FreeAndNil(Options) end;
156 end;
157
158 procedure PackageIOS(const Project: TCastleProject;
159 const UpdateOnlyCode: Boolean);
160 var
161 XcodeProject: string;
162 UsesCocoaPods: boolean;
163
164 { Generate files for iOS project from templates. }
165 procedure GenerateFromTemplates;
166 begin
167 Project.ExtractTemplate('ios/xcode_project/', XcodeProject);
168 end;
169
170 { Generate files for iOS project from templates, adding services. }
171 procedure GenerateServicesFromTemplates;
172
173 procedure ExtractService(const ServiceName: string);
174 var
175 TemplatePath: string;
176 begin
177 TemplatePath := 'ios/services/' + ServiceName + '/';
178 Project.ExtractTemplate(TemplatePath, XcodeProject);
179
180 if URIFileExists('castle-data:/' + TemplatePath + 'Podfile') then
181 begin
182 if Verbose then
183 Writeln(Format('Service "%s" requires using CocoaPods. Make sure you have CocoaPods ( https://cocoapods.org/ ) installed.',
184 [ServiceName]));
185 UsesCocoaPods := true;
186 end;
187 end;
188
189 var
190 S: TService;
191 begin
192 for S in Project.IOSServices do
193 ExtractService(S.Name);
194
195 // Since right now we always compile with CASTLE_TREMOLO_STATIC,
196 // we just always add ogg_vorbis service, otherwise it would not link.
197 if {(depOggVorbis in Project.Dependencies) and}
198 not Project.IOSServices.HasService('ogg_vorbis') then
199 ExtractService('ogg_vorbis');
200 // Since right now we always compile with CASTLE_FREETYPE_STATIC,
201 // we just always add freetype service, otherwise it would not link.
202 if {(depFreeType in Project.Dependencies) and}
203 not Project.IOSServices.HasService('freetype') then
204 ExtractService('freetype');
205 end;
206
207 { Generate icons, in various sizes, from the base icon. }
208 procedure GenerateIcons;
209 var
210 Icon: TCastleImage;
211
212 procedure SaveResized(const Size: Integer);
213 var
214 OutputFile: string;
215 R: TCastleImage;
216 begin
217 R := Icon.MakeResized(Size, Size, BestInterpolation);
218 try
219 OutputFile := Project.Name + PathDelim +
220 'Images.xcassets' + PathDelim +
221 'AppIcon.appiconset' + PathDelim +
222 'icon-' + IntToStr(Size) + '.png';
223 SaveImage(R, FilenameToUriSafe(XcodeProject + OutputFile));
224 if Verbose then
225 Writeln('Packaging generated icon file: ' + OutputFile);
226 finally FreeAndNil(R) end;
227 end;
228
229 begin
230 Icon := Project.Icons.FindReadable;
231 if Icon = nil then
232 begin
233 WritelnWarning('Icon', 'No icon in a format readable by our engine (for example, png or jpg) is specified in CastleEngineManifest.xml. Using default icon.');
234 { Use DefaultIconSquare, not DefaultIcon for iOS, since we cannot have
235 transparency on iOS icon (it's replaced by an ugly blackness).
236 See
237 https://stackoverflow.com/questions/959864/is-is-possible-to-use-transparency-in-an-iphone-app-icon
238 https://stackoverflow.com/questions/22858501/ios-app-icon-with-transparent-background-showing-black-background-on-device }
239 Icon := DefaultIconSquare;
240 end;
241 try
242 SaveResized(57);
243 SaveResized(72);
244 SaveResized(76);
245 SaveResized(114);
246 SaveResized(120);
247 SaveResized(144);
248 SaveResized(152);
249 SaveResized(167);
250 SaveResized(1024);
251 finally
252 if Icon = DefaultIconSquare then
253 Icon := nil else
254 FreeAndNil(Icon);
255 end;
256 end;
257
258 { Generate "Launch Screen.storyboard" and LaunchScreenImage.png it references. }
259 procedure GenerateLaunchImageStoryboard;
260 var
261 Storyboard, ProjectOutputUrl, ImageUrl: String;
262 begin
263 if Project.IOSHasLaunchImageStoryboard then
264 begin
265 ProjectOutputUrl := FilenameToUriSafe(XcodeProject + Project.Name + PathDelim);
266
267 Storyboard := FileToString('castle-data:/ios/Launch%20Screen.storyboard');
268 Storyboard := Project.ReplaceMacros(Storyboard);
269 StringToFile(ProjectOutputUrl + 'Launch%20Screen.storyboard', Storyboard);
270
271 ImageUrl := CombineURI(
272 Project.LaunchImageStoryboard.BaseUrl,
273 Project.LaunchImageStoryboard.Path);
274 CheckCopyFile(
275 UriToFilenameSafe(ImageUrl),
276 UriToFilenameSafe(ProjectOutputUrl + 'LaunchScreenImage.png'));
277 end;
278 end;
279
280 { Generate launch images, in various sizes,
281 from the most suitable launch images specified. }
282 procedure GenerateLaunchImages;
283 var
284 LaunchImages: TCastleImageList;
285
286 function FindBestMatching(const Width, Height: Integer;
287 const DefaultImage: TCastleImage): TCastleImage;
288 var
289 I: Integer;
290 ResultIndex: Integer;
291 begin
292 ResultIndex := -1;
293 Result := nil;
294
295 for I := 0 to LaunchImages.Count - 1 do
296 if (Result = nil) or
297 (Abs(LaunchImages[I].Width / LaunchImages[I].Height - Width / Height) <
298 Abs( Result.Width / Result.Height - Width / Height)) then
299 begin
300 ResultIndex := I;
301 Result := LaunchImages[ResultIndex];
302 end;
303
304 if Result = nil then
305 begin
306 Result := DefaultImage;
307 if Verbose then
308 Writeln('iOS lauch image: No custom launch image, using the default for size ', Width, ' x ', Height);
309 end else
310 begin
311 if Verbose then
312 Writeln('iOS lauch image: Using the (resized) launch image "' + Project.LaunchImages[ResultIndex] + '" as it has the best aspect ratio for size ', Width, ' x ', Height);
313 end;
314 end;
315
316 procedure SaveResized(const Width, Height: Integer;
317 const DefaultImage: TCastleImage);
318 var
319 OutputFile: string;
320 ImageSource, R: TCastleImage;
321 begin
322 ImageSource := FindBestMatching(Width, Height, DefaultImage);
323 R := ImageSource.MakeResized(Width, Height, BestInterpolation);
324 try
325 OutputFile := Project.Name + PathDelim +
326 'Images.xcassets' + PathDelim +
327 'LaunchImage.launchimage' + PathDelim +
328 'launch-image-' + IntToStr(Width) + 'x' + IntToStr(Height) + '.png';
329 SaveImage(R, FilenameToUriSafe(XcodeProject + OutputFile));
330 // it's already reported by FindBestMatching
331 // if Verbose then
332 // Writeln('Packaging generated launch icon file: ' + OutputFile);
333 finally FreeAndNil(R) end;
334 end;
335
336 var
337 I: Integer;
338 Default640x1136, Default1536x2048, Default2048x1536: TCastleImage;
339 begin
340 Default640x1136 := nil;
341 Default1536x2048 := nil;
342 Default2048x1536 := nil;
343 LaunchImages := TCastleImageList.Create(true);
344 try
345 Default640x1136 := LoadImage('castle-data:/default_launch_images/DefaultLaunchImage640x1136.png');
346 Default1536x2048 := LoadImage('castle-data:/default_launch_images/DefaultLaunchImage1536x2048.png');
347 Default2048x1536 := LoadImage('castle-data:/default_launch_images/DefaultLaunchImage2048x1536.png');
348
349 for I := 0 to Project.LaunchImages.Count - 1 do
350 LaunchImages.Add(LoadImage(Project.LaunchImages[I]));
351 // iPhone Portrait
352 SaveResized(640, 1136, Default640x1136);
353 // iPad Landscape
354 SaveResized(1024, 768, Default2048x1536);
355 // iPad Landscape x2
356 SaveResized(1024 * 2, 768 * 2, Default2048x1536);
357 // iPad Portrait
358 SaveResized(768, 1024, Default1536x2048);
359 // iPad Portrait x2
360 SaveResized(768 * 2, 1024 * 2, Default1536x2048);
361 finally FreeAndNil(LaunchImages) end;
362 end;
363
364 { Copy project data into Xcode project. }
365 procedure GenerateData;
366 begin
367 Project.CopyData(XcodeProject + Project.Name + PathDelim + 'data', cpIOS);
368 end;
369
370 (* Add a large auto-generated chunk into the pbx file, replacing a special macro
371 ${PBX_CONTENTS_GENERATED} inside the pbx file. *)
372 procedure FixPbxProjectFile;
373 var
374 PbxProject: TXcodeProject;
375 PBXContentsGenerated, PBX, PBXFileUrl: String;
376 begin
377 PbxProject := TXcodeProject.Create;
378 try
379 PbxProject.AddTopLevelDir(XcodeProject, Project.Name);
380
381 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('Foundation.framework'));
382 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('CoreGraphics.framework'));
383 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('UIKit.framework'));
384 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('OpenGLES.framework'));
385 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('GLKit.framework'));
386 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('OpenAL.framework'));
387
388 // TODO: These service-specific things should be defined in respective service CastleEngineService.xml
389 if Project.IOSServices.HasService('apple_game_center') then
390 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('GameKit.framework'));
391 if Project.IOSServices.HasService('in_app_purchases') then
392 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('StoreKit.framework'));
393 if Project.IOSServices.HasService('fmod') then
394 begin
395 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('libfmod_iphoneos.a'));
396 PbxProject.Frameworks.Add(TXcodeProjectFramework.Create('libc++.tbd'));
397 end;
398
399 PBXContentsGenerated := PbxProject.PBXContents;
400 // process macros inside PBXContentsGenerated, to replace ${NAME} etc. inside
401 PBXContentsGenerated := Project.ReplaceMacros(PBXContentsGenerated);
402
403 PBXFileUrl := FilenameToUriSafe(
404 XcodeProject + Project.Name + '.xcodeproj' + PathDelim + 'project.pbxproj');
405 PBX := FileToString(PBXFileUrl);
406 StringReplaceAllVar(PBX, '${PBX_CONTENTS_GENERATED}', PBXContentsGenerated, false);
407 StringToFile(PBXFileUrl, PBX);
408 finally FreeAndNil(PbxProject) end;
409 end;
410
411 { Copy compiled library into Xcode project. }
412 procedure GenerateLibrary;
413 var
414 OutputFileBase: string;
415 begin
416 OutputFileBase := ExtractFileName(Project.IOSLibraryFile);
417 SmartCopyFile(Project.IOSLibraryFile, XcodeProject + OutputFileBase);
418 if Verbose then
419 Writeln('Packaging library file: ' + OutputFileBase);
420 end;
421
422 procedure GenerateCocoaPods;
423 begin
424 if UsesCocoaPods then
425 begin
426 { If current binary architecture is x86_64, use CocoaPods native binaries
427 also with x86_64 architecture. }
428 if DefaultCPU = x86_64 then
429 RunCommandSimple(XcodeProject, 'arch', ['-x86_64', 'pod', 'install'])
430 else
431 RunCommandSimple(XcodeProject, 'pod', ['install']);
432 end;
433 end;
434
435 begin
436 UsesCocoaPods := false;
437 XcodeProject := TempOutputPath(Project.Path) +
438 'ios' + PathDelim + 'xcode_project' + PathDelim;
439
440 if UpdateOnlyCode then
441 begin
442 if not DirectoryExists(XcodeProject) then
443 raise Exception.CreateFmt('Project directory "%s" doesn''t exist. Run "package" without the --update-only-code option', [
444 XcodeProject
445 ]);
446 GenerateLibrary;
447 end else
448 begin
449 if DirectoryExists(XcodeProject) then
450 RemoveNonEmptyDir(XcodeProject);
451
452 GenerateFromTemplates;
453 GenerateServicesFromTemplates;
454 PackageServices(Project, Project.IOSServices,
455 'castle-data:/ios/services/', XcodeProject);
456 GenerateLaunchImageStoryboard;
457 FixPbxProjectFile; // must be done *after* all files that have to be in PBX are in place, so after PackageServices and GenerateLaunchImageStoryboard
458 GenerateIcons;
459 GenerateLaunchImages;
460 GenerateData;
461 GenerateLibrary;
462 GenerateCocoaPods; // should be at the end, to allow CocoaPods to see our existing project
463
464 Writeln('Xcode project has been created in:');
465 Writeln(' ', XcodeProject);
466 Writeln('You can open it now on macOS with Xcode and compile, run and publish.');
467 Writeln('The generated project should compile and work out-of-the-box.');
468 end;
469 end;
470
471 function PackageFormatWantsIOSArchive(const PackageFormat: TPackageFormatNoDefault;
472 out ArchiveType: TIosArchiveType; out ExportMethod: String): Boolean;
473 begin
474 case PackageFormat of
475 pfIosArchiveDevelopment:
476 begin
477 ArchiveType := atDevelopment;
478 ExportMethod := 'development';
479 Result := true;
480 end;
481 pfIosArchiveAdHoc:
482 begin
483 ArchiveType := atAdHoc;
484 ExportMethod := 'ad-hoc';
485 Result := true;
486 end;
487 pfIosArchiveAppStore:
488 begin
489 ArchiveType := atAppStore;
490 ExportMethod := 'app-store';
491 Result := true;
492 end;
493 else Result := false;
494 end;
495 end;
496
497 procedure ArchiveIOS(const Project: TCastleProject; const ArchiveType: TIosArchiveType);
498 var
499 XcodeProject: String;
500 XcodeSelectExe, XcodeBuildExe: String;
501 OutputString, ArchivePath, ExportPath: String;
502 ExitStatus: Integer;
503 begin
504 XcodeProject := TempOutputPath(Project.Path) +
505 'ios' + PathDelim + 'xcode_project' + PathDelim; // same as in PackageIOS
506 ArchivePath := TempOutputPath(Project.Path) +
507 'ios' + PathDelim + 'App.xcarchive';
508 ExportPath := TempOutputPath(Project.Path) +
509 'ios' + PathDelim + 'build' + PathDelim;
510
511 if not DirectoryExists(XcodeProject) then
512 raise Exception.CreateFmt('Cannot read created Xcode project in "%s"', [XcodeProject]);
513
514 XcodeSelectExe := FindExe('xcode-select');
515 if XcodeSelectExe = '' then
516 raise Exception.Create('Cannot find "xcode-select". Make sure that Xcode with command-line utilities is installed.');
517
518 MyRunCommandIndir(XcodeProject, XcodeSelectExe, ['--print-path'], OutputString, ExitStatus);
519
520 if ExitStatus <> 0 then
521 raise Exception.CreateFmt('Running "xcode-select" failed, exit status %d, output "%s".', [
522 ExitStatus,
523 OutputString
524 ]);
525
526 if Trim(OutputString) = '/Library/Developer/CommandLineTools' then
527 WritelnWarning('xcode-select points to only command-line utilities, but not Xcode path. In new Xcode versions, you should do something like "sudo xcode-select -switch /Applications/Xcode.app".');
528
529 Writeln('Using Xcode from: ' + Trim(OutputString));
530
531 { See
532 https://developer.apple.com/library/archive/technotes/tn2339/_index.html
533 https://stackoverflow.com/questions/25678372/xcodebuild-cant-build-when-no-physical-ios
534 about these commands.
535
536 xcodebuild -list -workspace castle-engine-output/ios/xcode_project/PROJ_NAME.xcworkspace
537 }
538
539 XcodeBuildExe := FindExe('xcodebuild');
540 if XcodeBuildExe = '' then
541 raise Exception.Create('Cannot find "xcodebuild". Make sure that Xcode with command-line utilities is installed.');
542
543 if DirectoryExists(ArchivePath) then
544 RemoveNonEmptyDir(ArchivePath);
545 // do not create the archive path, it would be malformed archive to Xcode then
546
547 if DirectoryExists(ExportPath) then
548 RemoveNonEmptyDir(ExportPath);
549 CheckForceDirectories(ExportPath);
550
551 RunCommandSimple(XcodeProject, XcodeBuildExe, [
552 '-allowProvisioningUpdates',
553 '-workspace', Project.Name + '.xcworkspace',
554 '-scheme', Project.Caption,
555 '-destination', 'generic/platform=iOS',
556 '-quiet',
557 '-archivePath', ArchivePath,
558 'archive'
559 ]);
560 RunCommandSimple(XcodeProject, XcodeBuildExe, [
561 '-allowProvisioningUpdates',
562 '-archivePath', ArchivePath,
563 '-exportOptionsPlist', XcodeProject + 'export_options.plist',
564 '-exportArchive',
565 '-exportPath', ExportPath
566 ]);
567
568 // TODO: It could be a bit cleaner to keep export_options.plist outside of Xcode project dir,
569 // and copy it here to the final place,
570 // replacing IOS_EXPORT_METHOD by a special code in this unit.
571 // This would allow to simplify PackageFormatWantsIOSArchive?
572 end;
573
574 procedure RunIOS(const Project: TCastleProject);
575 begin
576 // TODO
577 raise Exception.Create('The "run" command is not implemented for iOS right now');
578 end;
579
580 type
581 ECannotMergeTemplate = class(Exception);
582
583 procedure MergeIOSAppDelegate(const Source, Destination: string;
584 const ReplaceMacros: TReplaceMacros);
585 const
586 MarkerImport = '/* IOS-SERVICES-IMPORT */';
587 MarkerCreate = '/* IOS-SERVICES-CREATE */';
588 CreateTemplate =
589 '{' + NL +
590 '%s* serviceInstance;' + NL +
591 'serviceInstance = [[%0:s alloc] init];' + NL +
592 'serviceInstance.mainController = viewController;' + NL +
593 'serviceInstance.window = self.window;' + NL +
594 '[services addObject: serviceInstance];' + NL +
595 '}';
596
597 var
598 DestinationContents: string;
599
600 procedure InsertAtMarker(const Marker, Insertion: string);
601 var
602 MarkerPos: Integer;
603 begin
604 MarkerPos := Pos(Marker, DestinationContents);
605 if MarkerPos = 0 then
606 raise ECannotMergeTemplate.CreateFmt('Cannot find marker "%s" in AppDelegate.m', [Marker]);
607 Insert(Trim(Insertion) + NL, DestinationContents, MarkerPos);
608 end;
609
610 var
611 SourceDocument: TXMLDocument;
612 Import, CreateClass, CreateCode: string;
613 begin
614 SourceDocument := URLReadXML(Source);
615 try
616 if SourceDocument.DocumentElement.TagName <> 'app_delegate_patch' then
617 raise ECannotMergeTemplate.Create('The source file from which to merge AppDelegate.m must be XML with root <app_delegate_patch>');
618 Import := SourceDocument.DocumentElement.ChildElement('import').TextData;
619 CreateClass := SourceDocument.DocumentElement.ChildElement('class').TextData;
620 finally FreeAndNil(SourceDocument) end;
621
622 CreateCode := Format(CreateTemplate, [CreateClass]);
623
624 DestinationContents := FileToString(FilenameToUriSafe(Destination));
625 InsertAtMarker(MarkerImport, Import);
626 InsertAtMarker(MarkerCreate, CreateCode);
627 StringToFile(Destination, DestinationContents);
628 end;
629
630 procedure MergeIOSPodfile(const Source, Destination: string;
631 const ReplaceMacros: TReplaceMacros);
632 var
633 DestinationContents: string;
634
635 procedure InsertAtMarker(const Marker, Insertion: string);
636 var
637 MarkerPos: Integer;
638 begin
639 MarkerPos := Pos(Marker, DestinationContents);
640 if MarkerPos = 0 then
641 raise ECannotMergeTemplate.CreateFmt('Cannot find marker "%s" in Podfile', [Marker]);
642 Insert(Insertion, DestinationContents, MarkerPos);
643 end;
644
645 const
646 Marker = '### SERVICES-PODFILES ###';
647 var
648 SourceContents: string;
649 begin
650 SourceContents := NL +
651 '# ---- Inserted contents of ' + Source + NL +
652 Trim(ReplaceMacros(FileToString(FilenameToUriSafe(Source)))) + NL +
653 '# ---- End of inserted contents of ' + Source + NL + NL;
654
655 DestinationContents := FileToString(FilenameToUriSafe(Destination));
656 InsertAtMarker(Marker, SourceContents);
657 StringToFile(Destination, DestinationContents);
658 end;
659
660 procedure MergeIOSInfoPlist(const Source, Destination: string;
661 const ReplaceMacros: TReplaceMacros);
662 var
663 DestinationContents: string;
664
665 procedure InsertAtMarker(const Marker, Insertion: string);
666 var
667 MarkerPos: Integer;
668 begin
669 MarkerPos := Pos(Marker, DestinationContents);
670 if MarkerPos = 0 then
671 raise ECannotMergeTemplate.CreateFmt('Cannot find marker "%s" in xxx-Info.plist', [Marker]);
672 Insert(Insertion, DestinationContents, MarkerPos);
673 end;
674
675 const
676 Marker = '<!-- IOS-SERVICES-PLIST -->';
677 var
678 SourceContents: string;
679 begin
680 SourceContents := NL +
681 '<!-- Inserted contents of ' + Source + ' -->' + NL +
682 Trim(ReplaceMacros(FileToString(FilenameToUriSafe(Source)))) + NL +
683 '<!-- End of inserted contents of ' + Source + ' -->' + NL + NL;
684
685 DestinationContents := FileToString(FilenameToUriSafe(Destination));
686 InsertAtMarker(Marker, SourceContents);
687 StringToFile(Destination, DestinationContents);
688 end;
689
690 end.