forked from apache/cordova-ios
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprepare.js
1387 lines (1188 loc) · 56.1 KB
/
prepare.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
const fs = require('node:fs');
const path = require('node:path');
const plist = require('plist');
const et = require('elementtree');
const events = require('cordova-common').events;
const xmlHelpers = require('cordova-common').xmlHelpers;
const ConfigParser = require('cordova-common').ConfigParser;
const CordovaError = require('cordova-common').CordovaError;
const PlatformJson = require('cordova-common').PlatformJson;
const PlatformMunger = require('cordova-common').ConfigChanges.PlatformMunger;
const PluginInfoProvider = require('cordova-common').PluginInfoProvider;
const FileUpdater = require('cordova-common').FileUpdater;
const projectFile = require('./projectFile');
const Podfile = require('./Podfile').Podfile;
const check_reqs = require('./check_reqs');
const PlatformConfigParser = require('./PlatformConfigParser');
const versions = require('./versions');
// launch storyboard and related constants
const IMAGESET_COMPACT_SIZE_CLASS = 'compact';
const CDV_ANY_SIZE_CLASS = 'any';
const ASSUMED_XCODE_VERSION = '15.0.0';
function checkOrAssumeXcodeVersion () {
if (process.platform === 'darwin') {
return versions.get_apple_xcode_version();
} else {
return Promise.resolve(ASSUMED_XCODE_VERSION);
}
}
module.exports.prepare = function (cordovaProject, options) {
const platformJson = PlatformJson.load(this.locations.root, 'ios');
const munger = new PlatformMunger('ios', this.locations.root, platformJson, new PluginInfoProvider());
this._config = updateConfigFile(cordovaProject.projectConfig, munger, this.locations);
const parser = new PlatformConfigParser(cordovaProject.projectConfig.path);
try {
const manifest = parser.getPrivacyManifest();
overwritePrivacyManifest(manifest, this.locations);
} catch (err) {
return Promise.reject(new CordovaError(`Could not parse PrivacyManifest in config.xml: ${err}`));
}
// Update own www dir with project's www assets and plugins' assets and js-files
return updateWww(cordovaProject, this.locations)
// update project according to config.xml changes.
.then(() => updateProject(this._config, this.locations))
.then(() => updateIcons(cordovaProject, this.locations))
.then(() => updateLaunchStoryboardImages(cordovaProject, this.locations))
.then(() => updateBackgroundColor(cordovaProject, this.locations))
.then(() => updateFileResources(cordovaProject, this.locations))
.then(() => alertDeprecatedPreference(this._config))
.then(() => {
events.emit('verbose', 'Prepared iOS project successfully');
});
};
module.exports.clean = function (options) {
// A cordovaProject isn't passed into the clean() function, because it might have
// been called from the platform shell script rather than the CLI. Check for the
// noPrepare option passed in by the non-CLI clean script. If that's present, or if
// there's no config.xml found at the project root, then don't clean prepared files.
const projectRoot = path.resolve(this.root, '../..');
const projectConfigFile = path.join(projectRoot, 'config.xml');
if ((options && options.noPrepare) || !fs.existsSync(projectConfigFile) ||
!fs.existsSync(this.locations.configXml)) {
return Promise.resolve();
}
const projectConfig = new ConfigParser(this.locations.configXml);
return Promise.resolve()
.then(() => cleanWww(projectRoot, this.locations))
.then(() => cleanIcons(projectRoot, projectConfig, this.locations))
.then(() => cleanLaunchStoryboardImages(projectRoot, projectConfig, this.locations))
.then(() => cleanBackgroundColor(projectRoot, projectConfig, this.locations))
.then(() => cleanFileResources(projectRoot, projectConfig, this.locations));
};
/**
* Overwrites the privacy manifest file with the provided manifest or sets the default manifest.
* @param {ElementTree} manifest - The manifest to be written to the privacy manifest file.
* @param {Object} locations - The locations object containing the path to the Xcode Cordova project.
*/
function overwritePrivacyManifest (manifest, locations) {
const privacyManifestDest = path.join(locations.xcodeCordovaProj, 'PrivacyInfo.xcprivacy');
if (manifest != null) {
const XML_DECLARATION = '<?xml version="1.0" encoding="UTF-8"?>\n';
const DOCTYPE = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n';
const plistElement = et.Element('plist');
plistElement.set('version', '1.0');
const dictElement = et.SubElement(plistElement, 'dict');
manifest.getchildren().forEach((child) => {
dictElement.append(child);
});
const etree = new et.ElementTree(plistElement);
const xmlString = XML_DECLARATION + DOCTYPE + etree.write({ xml_declaration: false });
fs.writeFileSync(privacyManifestDest, xmlString, 'utf-8');
return;
}
// Set default privacy manifest
const defaultPrivacyManifest = path.join(__dirname, '..', 'templates', 'project', '__PROJECT_NAME__', 'PrivacyInfo.xcprivacy');
const xmlString = fs.readFileSync(defaultPrivacyManifest, 'utf8');
fs.writeFileSync(privacyManifestDest, xmlString, 'utf-8');
}
/**
* Updates config files in project based on app's config.xml and config munge,
* generated by plugins.
*
* @param {ConfigParser} sourceConfig A project's configuration that will
* be merged into platform's config.xml
* @param {ConfigChanges} configMunger An initialized ConfigChanges instance
* for this platform.
* @param {Object} locations A map of locations for this platform
*
* @return {ConfigParser} An instance of ConfigParser, that
* represents current project's configuration. When returned, the
* configuration is already dumped to appropriate config.xml file.
*/
function updateConfigFile (sourceConfig, configMunger, locations) {
events.emit('verbose', `Generating platform-specific config.xml from defaults for iOS at ${locations.configXml}`);
// First cleanup current config and merge project's one into own
// Overwrite platform config.xml with defaults.xml.
fs.cpSync(locations.defaultConfigXml, locations.configXml);
// Then apply config changes from global munge to all config files
// in project (including project's config)
configMunger.reapply_global_munge().save_all();
events.emit('verbose', 'Merging project\'s config.xml into platform-specific iOS config.xml');
// Merge changes from app's config.xml into platform's one
const config = new ConfigParser(locations.configXml);
xmlHelpers.mergeXml(sourceConfig.doc.getroot(),
config.doc.getroot(), 'ios', /* clobber= */true);
config.write();
return config;
}
/**
* Logs all file operations via the verbose event stream, indented.
*/
function logFileOp (message) {
events.emit('verbose', ` ${message}`);
}
/**
* Updates platform 'www' directory by replacing it with contents of
* 'platform_www' and app www. Also copies project's overrides' folder into
* the platform 'www' folder
*
* @param {Object} cordovaProject An object which describes cordova project.
* @param {boolean} destinations An object that contains destinations
* paths for www files.
*/
function updateWww (cordovaProject, destinations) {
const sourceDirs = [
path.relative(cordovaProject.root, cordovaProject.locations.www),
path.relative(cordovaProject.root, destinations.platformWww)
];
// If project contains 'merges' for our platform, use them as another overrides
const merges_path = path.join(cordovaProject.root, 'merges', 'ios');
if (fs.existsSync(merges_path)) {
events.emit('verbose', 'Found "merges/ios" folder. Copying its contents into the iOS project.');
sourceDirs.push(path.join('merges', 'ios'));
}
const targetDir = path.relative(cordovaProject.root, destinations.www);
events.emit(
'verbose', `Merging and updating files from [${sourceDirs.join(', ')}] to ${targetDir}`);
FileUpdater.mergeAndUpdateDir(
sourceDirs, targetDir, { rootDir: cordovaProject.root }, logFileOp);
return Promise.resolve();
}
/**
* Cleans all files from the platform 'www' directory.
*/
function cleanWww (projectRoot, locations) {
const targetDir = path.relative(projectRoot, locations.www);
events.emit('verbose', `Cleaning ${targetDir}`);
// No source paths are specified, so mergeAndUpdateDir() will clear the target directory.
FileUpdater.mergeAndUpdateDir(
[], targetDir, { rootDir: projectRoot, all: true }, logFileOp);
}
/**
* Updates project structure and AndroidManifest according to project's configuration.
*
* @param {ConfigParser} platformConfig A project's configuration that will
* be used to update project
* @param {Object} locations A map of locations for this platform (In/Out)
*/
function updateProject (platformConfig, locations) {
// CB-6992 it is necessary to normalize characters
// because node and shell scripts handles unicode symbols differently
// We need to normalize the name to NFD form since iOS uses NFD unicode form
const name = platformConfig.name().normalize('NFD');
const version = platformConfig.version();
const displayName = platformConfig.shortName && platformConfig.shortName();
const originalName = path.basename(locations.xcodeCordovaProj);
// Update package id (bundle id)
const plistFile = path.join(locations.xcodeCordovaProj, `${originalName}-Info.plist`);
const infoPlist = plist.parse(fs.readFileSync(plistFile, 'utf8'));
// Update version (bundle version)
infoPlist.CFBundleShortVersionString = version;
const CFBundleVersion = platformConfig.getAttribute('ios-CFBundleVersion') || default_CFBundleVersion(version);
infoPlist.CFBundleVersion = CFBundleVersion;
if (platformConfig.getAttribute('defaultlocale')) {
infoPlist.CFBundleDevelopmentRegion = platformConfig.getAttribute('defaultlocale');
}
if (displayName) {
infoPlist.CFBundleDisplayName = displayName;
}
// replace Info.plist ATS entries according to <access> and <allow-navigation> config.xml entries
const ats = writeATSEntries(platformConfig);
if (Object.keys(ats).length > 0) {
infoPlist.NSAppTransportSecurity = ats;
} else {
delete infoPlist.NSAppTransportSecurity;
}
handleOrientationSettings(platformConfig, infoPlist);
/* eslint-disable no-tabs */
// Write out the plist file with the same formatting as Xcode does
let info_contents = plist.build(infoPlist, { indent: '\t', offset: -1 });
/* eslint-enable no-tabs */
info_contents = info_contents.replace(/<string>[\s\r\n]*<\/string>/g, '<string></string>');
fs.writeFileSync(plistFile, info_contents, 'utf-8');
events.emit('verbose', `Wrote out iOS Bundle Version "${version}" to ${plistFile}`);
return handleBuildSettings(platformConfig, locations, infoPlist).then(() => {
if (name === originalName) {
events.emit('verbose', `iOS Product Name has not changed (still "${originalName}")`);
return Promise.resolve();
} else { // CB-11712 <name> was changed, we don't support it'
const errorString =
'The product name change (<name> tag) in config.xml is not supported dynamically.\n' +
'To change your product name, you have to remove, then add your ios platform again.\n' +
'Make sure you save your plugins beforehand using `cordova plugin save`.\n' +
'\tcordova plugin save\n' +
'\tcordova platform rm ios\n' +
'\tcordova platform add ios\n';
return Promise.reject(new CordovaError(errorString));
}
});
}
function handleOrientationSettings (platformConfig, infoPlist) {
switch (getOrientationValue(platformConfig)) {
case 'portrait':
infoPlist.UIInterfaceOrientation = ['UIInterfaceOrientationPortrait'];
infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown'];
infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown'];
break;
case 'landscape':
infoPlist.UIInterfaceOrientation = ['UIInterfaceOrientationLandscapeLeft'];
infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
break;
case 'all':
infoPlist.UIInterfaceOrientation = ['UIInterfaceOrientationPortrait'];
infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
break;
case 'default':
infoPlist.UISupportedInterfaceOrientations = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
infoPlist['UISupportedInterfaceOrientations~ipad'] = ['UIInterfaceOrientationPortrait', 'UIInterfaceOrientationPortraitUpsideDown', 'UIInterfaceOrientationLandscapeLeft', 'UIInterfaceOrientationLandscapeRight'];
delete infoPlist.UIInterfaceOrientation;
}
}
function handleBuildSettings (platformConfig, locations, infoPlist) {
const pkg = platformConfig.getAttribute('ios-CFBundleIdentifier') || platformConfig.packageName();
const targetDevice = parseTargetDevicePreference(platformConfig.getPreference('target-device', 'ios'));
const deploymentTarget = platformConfig.getPreference('deployment-target', 'ios');
const swiftVersion = platformConfig.getPreference('SwiftVersion', 'ios');
let project;
try {
project = projectFile.parse(locations);
} catch (err) {
return Promise.reject(new CordovaError(`Could not parse ${locations.pbxproj}: ${err}`));
}
const origPkg = project.xcode.getBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', undefined, platformConfig.name());
// no build settings provided and we don't need to update build settings for launch storyboards,
// then we don't need to parse and update .pbxproj file
if (origPkg === pkg && !targetDevice && !deploymentTarget && !swiftVersion) {
return Promise.resolve();
}
if (origPkg !== pkg) {
events.emit('verbose', `Set PRODUCT_BUNDLE_IDENTIFIER to ${pkg}.`);
project.xcode.updateBuildProperty('PRODUCT_BUNDLE_IDENTIFIER', pkg, null, platformConfig.name());
}
if (targetDevice) {
events.emit('verbose', `Set TARGETED_DEVICE_FAMILY to ${targetDevice}.`);
project.xcode.updateBuildProperty('TARGETED_DEVICE_FAMILY', targetDevice);
}
if (deploymentTarget) {
events.emit('verbose', `Set IPHONEOS_DEPLOYMENT_TARGET to "${deploymentTarget}".`);
project.xcode.updateBuildProperty('IPHONEOS_DEPLOYMENT_TARGET', deploymentTarget);
}
if (swiftVersion) {
events.emit('verbose', `Set SwiftVersion to "${swiftVersion}".`);
project.xcode.updateBuildProperty('SWIFT_VERSION', swiftVersion);
}
project.write();
// If we have a Podfile, we want to update the deployment target there too
const podPath = path.join(locations.root, Podfile.FILENAME);
if (deploymentTarget && fs.existsSync(podPath)) {
const project_name = locations.xcodeCordovaProj.split(path.sep).pop();
const PodsJson = require('./PodsJson').PodsJson;
const podsjsonFile = new PodsJson(path.join(locations.root, PodsJson.FILENAME));
const podfileFile = new Podfile(podPath, project_name, deploymentTarget);
podfileFile.write();
events.emit('verbose', 'Running `pod install` (to install plugins)');
projectFile.purgeProjectFileCache(locations.root);
return podfileFile.install(check_reqs.check_cocoapods)
.then(() => podsjsonFile.setSwiftVersionForCocoaPodsLibraries(locations.root));
}
return Promise.resolve();
}
function mapIconResources (icons, iconsDir, xcodeversion) {
// Ref: https://developer.apple.com/design/human-interface-guidelines/app-icons
// These are ordered according to how Xcode puts them in the Contents.json file
const platformIcons = [
// iOS fallback icon sizes
{ dest: 'icon-20@2x.png', width: 40, height: 40 },
{ dest: 'icon-20@3x.png', width: 60, height: 60 },
{ dest: 'icon-29@2x.png', width: 58, height: 58 },
{ dest: 'icon-29@3x.png', width: 87, height: 87 },
{ dest: 'icon-38@2x.png', width: 76, height: 76 },
{ dest: 'icon-38@3x.png', width: 114, height: 114 },
{ dest: 'icon-40@2x.png', width: 80, height: 80, target: 'spotlight' },
{ dest: 'icon-40@3x.png', width: 120, height: 120, target: 'spotlight' },
{ dest: 'icon-60@2x.png', width: 120, height: 120 },
{ dest: 'icon-60@3x.png', width: 180, height: 180 },
{ dest: 'icon-64@2x.png', width: 128, height: 128 },
{ dest: 'icon-64@3x.png', width: 192, height: 192 },
{ dest: 'icon-68@2x.png', width: 136, height: 136 },
{ dest: 'icon-76@2x.png', width: 152, height: 152 },
{ dest: 'icon-83.5@2x.png', width: 167, height: 167 },
// Default iOS icon
{ dest: 'icon.png', width: 1024, height: 1024, useDefault: true },
// macOS icon sizes
{ dest: 'mac-16.png', width: 16, height: 16, target: 'mac' },
{ dest: 'mac-16@2x.png', width: 32, height: 32, target: 'mac' },
{ dest: 'mac-32.png', width: 32, height: 32, target: 'mac' },
{ dest: 'mac-32@2x.png', width: 64, height: 64, target: 'mac' },
{ dest: 'mac-128.png', width: 128, height: 128, target: 'mac' },
{ dest: 'mac-128@2x.png', width: 256, height: 256, target: 'mac' },
{ dest: 'mac-256.png', width: 256, height: 256, target: 'mac' },
{ dest: 'mac-256@2x.png', width: 512, height: 512, target: 'mac' },
{ dest: 'mac-512.png', width: 512, height: 512, target: 'mac' },
{ dest: 'mac-512@2x.png', width: 1024, height: 1024, target: 'mac' },
// WatchOS fallback icon sizes
{ dest: 'watchos-22@2x.png', width: 44, height: 44, target: 'watchos' },
{ dest: 'watchos-24@2x.png', width: 48, height: 48, target: 'watchos' },
{ dest: 'watchos-27.5@2x.png', width: 55, height: 55, target: 'watchos' },
{ dest: 'watchos-29@2x.png', width: 58, height: 58, target: 'watchos' },
{ dest: 'watchos-30@2x.png', width: 60, height: 60, target: 'watchos' },
{ dest: 'watchos-32@2x.png', width: 64, height: 64, target: 'watchos' },
{ dest: 'watchos-33@2x.png', width: 66, height: 66, target: 'watchos' },
{ dest: 'watchos-40@2x.png', width: 80, height: 80, target: 'watchos' },
{ dest: 'watchos-43.5@2x.png', width: 87, height: 87, target: 'watchos' },
{ dest: 'watchos-44@2x.png', width: 88, height: 88, target: 'watchos' },
{ dest: 'watchos-46@2x.png', width: 92, height: 92, target: 'watchos' },
{ dest: 'watchos-50@2x.png', width: 100, height: 100, target: 'watchos' },
{ dest: 'watchos-51@2x.png', width: 102, height: 102, target: 'watchos' },
{ dest: 'watchos-54@2x.png', width: 108, height: 108, target: 'watchos' },
{ dest: 'watchos-86@2x.png', width: 172, height: 172, target: 'watchos' },
{ dest: 'watchos-98@2x.png', width: 196, height: 196, target: 'watchos' },
{ dest: 'watchos-108@2x.png', width: 216, height: 216, target: 'watchos' },
{ dest: 'watchos-117@2x.png', width: 234, height: 234, target: 'watchos' },
{ dest: 'watchos-129@2x.png', width: 258, height: 258, target: 'watchos' },
// Allow customizing the watchOS icon with target="watchos"
// This falls back to using the iOS app icon by default
{ dest: 'watchos.png', width: 1024, height: 1024, target: 'watchos', useDefault: true }
];
const pathMap = {};
// We can only support dark mode and tinted icons with Xcode 16
const isAtLeastXcode16 = versions.compareVersions(xcodeversion, '16.0.0') >= 0;
function getDefaultIconForTarget (target) {
const def = icons.filter(res => !res.width && !res.height && !res.target).pop();
if (target) {
return icons
.filter(res => res.target === target)
.filter(res => !res.width && !res.height)
.pop() || def;
}
return def;
}
function getIconBySizeAndTarget (width, height, target) {
return icons
.filter(res => res.target === target)
.find(res =>
(res.width || res.height) &&
(!res.width || (width === res.width)) &&
(!res.height || (height === res.height))
) || null;
}
platformIcons.forEach(item => {
const dest = path.join(iconsDir, item.dest);
let icon = getIconBySizeAndTarget(item.width, item.height, item.target);
if (!icon && item.target === 'spotlight') {
// Fall back to a non-targeted icon
icon = getIconBySizeAndTarget(item.width, item.height);
}
if (!icon && item.useDefault) {
if (item.target) {
icon = getIconBySizeAndTarget(item.width, item.height);
}
const defaultIcon = getDefaultIconForTarget(item.target);
if (!icon && defaultIcon) {
icon = defaultIcon;
}
}
if (icon) {
if (icon.src) {
pathMap[dest] = icon.src;
}
// Only iOS has dark/tinted icon variants
if (isAtLeastXcode16 && (!item.target || item.target === 'spotlight')) {
if (icon.foreground) {
pathMap[dest.replace('.png', '-dark.png')] = icon.foreground;
}
if (icon.monochrome) {
pathMap[dest.replace('.png', '-tinted.png')] = icon.monochrome;
}
}
}
});
return pathMap;
}
function generateAppIconContentsJson (resourceMap) {
const contentsJSON = {
images: [],
info: {
author: 'xcode',
version: 1
}
};
Object.keys(resourceMap).forEach(res => {
const [filename, platform, size, scale, variant] = path.basename(res).match(/([A-Za-z]+)(?:-([0-9.]+)(?:@([0-9.]x))?)?(?:-([a-z]+))?\.png/);
const entry = {
filename,
idiom: 'universal',
platform: (platform === 'icon') ? 'ios' : platform,
size: `${size ?? 1024}x${size ?? 1024}`
};
if (scale) {
entry.scale = scale;
}
if (variant) {
entry.appearances = [
{
appearance: 'luminosity',
value: variant
}
];
}
contentsJSON.images.push(entry);
});
return contentsJSON;
}
function updateIcons (cordovaProject, locations) {
const icons = cordovaProject.projectConfig.getIcons('ios');
if (icons.length === 0) {
events.emit('verbose', 'This app does not have icons defined');
return Promise.resolve();
}
const platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);
const iconsDir = path.join(platformProjDir, 'Assets.xcassets', 'AppIcon.appiconset');
return checkOrAssumeXcodeVersion()
.then((xcodeversion) => {
const resourceMap = mapIconResources(icons, iconsDir, xcodeversion);
events.emit('verbose', `Updating icons at ${iconsDir}`);
FileUpdater.updatePaths(
resourceMap, { rootDir: cordovaProject.root }, logFileOp);
// Now we need to update the AppIcon.appiconset/Contents.json file
const contentsJSON = generateAppIconContentsJson(resourceMap);
events.emit('verbose', 'Updating App Icon image set contents.json');
fs.writeFileSync(path.join(cordovaProject.root, iconsDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2));
});
}
function cleanIcons (projectRoot, projectConfig, locations) {
const icons = projectConfig.getIcons('ios');
if (icons.length === 0) {
return Promise.resolve();
}
const platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);
const iconsDir = path.join(platformProjDir, 'Assets.xcassets', 'AppIcon.appiconset');
return checkOrAssumeXcodeVersion()
.then((xcodeversion) => {
const resourceMap = mapIconResources(icons, iconsDir, xcodeversion);
Object.keys(resourceMap).forEach(targetIconPath => {
resourceMap[targetIconPath] = null;
});
events.emit('verbose', `Cleaning icons at ${iconsDir}`);
// Source paths are removed from the map, so updatePaths() will delete the target files.
FileUpdater.updatePaths(
resourceMap, { rootDir: projectRoot, all: true }, logFileOp);
const contentsJSON = generateAppIconContentsJson(resourceMap);
// delete filename from contents.json
contentsJSON.images.forEach(image => {
image.filename = undefined;
});
events.emit('verbose', 'Updating App Icon image set contents.json');
fs.writeFileSync(path.join(projectRoot, iconsDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2));
});
}
/**
* Returns the directory for the BackgroundColor.colorset asset, or null if no
* xcassets exist.
*
* @param {string} projectRoot The project's root directory
* @param {string} platformProjDir The platform's project directory
*/
function getBackgroundColorDir (projectRoot, platformProjDir) {
if (folderExists(path.join(projectRoot, platformProjDir, 'Assets.xcassets'))) {
return path.join(platformProjDir, 'Assets.xcassets', 'BackgroundColor.colorset');
} else {
return null;
}
}
/**
* Returns the directory for the SplashScreenBackgroundColor.colorset asset, or
* null if no xcassets exist.
*
* @param {string} projectRoot The project's root directory
* @param {string} platformProjDir The platform's project directory
*/
function getSplashScreenBackgroundColorDir (projectRoot, platformProjDir) {
if (folderExists(path.join(projectRoot, platformProjDir, 'Assets.xcassets/'))) {
return path.join(platformProjDir, 'Assets.xcassets', 'SplashScreenBackgroundColor.colorset');
} else {
return null;
}
}
function colorPreferenceToComponents (pref) {
if (!pref || !pref.match(/^(#[0-9A-Fa-f]{3}|(0x|#)([0-9A-Fa-f]{2})?[0-9A-Fa-f]{6})$/)) {
return {
platform: 'ios',
reference: 'systemBackgroundColor'
};
}
let red = 'FF';
let green = 'FF';
let blue = 'FF';
let alpha = 1.0;
if (pref[0] === '#' && pref.length === 4) {
red = pref[1] + pref[1];
green = pref[2] + pref[2];
blue = pref[3] + pref[3];
}
if (pref.length >= 7 && (pref[0] === '#' || pref.substring(0, 2) === '0x')) {
let offset = pref[0] === '#' ? 1 : 2;
if (pref.substring(offset).length === 8) {
alpha = parseInt(pref.substring(offset, offset + 2), 16) / 255.0;
offset += 2;
}
red = pref.substring(offset, offset + 2);
green = pref.substring(offset + 2, offset + 4);
blue = pref.substring(offset + 4, offset + 6);
}
return {
'color-space': 'srgb',
components: {
red: '0x' + red.toUpperCase(),
green: '0x' + green.toUpperCase(),
blue: '0x' + blue.toUpperCase(),
alpha: alpha.toFixed(3)
}
};
}
/**
* Update the background color Contents.json in xcassets.
*
* @param {Object} cordovaProject The cordova project
* @param {Object} locations A dictionary containing useful location paths
*/
function updateBackgroundColor (cordovaProject, locations) {
const platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj);
const pref = cordovaProject.projectConfig.getPreference('BackgroundColor', 'ios') || '';
const splashPref = cordovaProject.projectConfig.getPreference('SplashScreenBackgroundColor', 'ios') || pref;
const backgroundColorDir = getBackgroundColorDir(cordovaProject.root, platformProjDir);
if (backgroundColorDir) {
const contentsJSON = {
colors: [{
idiom: 'universal',
color: colorPreferenceToComponents(pref)
}],
info: {
author: 'Xcode',
version: 1
}
};
events.emit('verbose', 'Updating Background Color color set Contents.json');
fs.writeFileSync(path.join(cordovaProject.root, backgroundColorDir, 'Contents.json'),
JSON.stringify(contentsJSON, null, 2));
}
const splashBackgroundColorDir = getSplashScreenBackgroundColorDir(cordovaProject.root, platformProjDir);
if (splashBackgroundColorDir) {
const contentsJSON = {
colors: [{
idiom: 'universal',
color: colorPreferenceToComponents(splashPref)
}],
info: {
author: 'Xcode',
version: 1
}
};
events.emit('verbose', 'Updating Splash Screen Background Color color set Contents.json');
fs.writeFileSync(path.join(cordovaProject.root, splashBackgroundColorDir, 'Contents.json'),
JSON.stringify(contentsJSON, null, 2));
}
}
/**
* Resets the background color Contents.json in xcassets to default.
*
* @param {string} projectRoot Path to the project root
* @param {Object} projectConfig The project's config.xml
* @param {Object} locations A dictionary containing useful location paths
*/
function cleanBackgroundColor (projectRoot, projectConfig, locations) {
const platformProjDir = path.relative(projectRoot, locations.xcodeCordovaProj);
const contentsJSON = {
colors: [{
idiom: 'universal',
color: colorPreferenceToComponents(null)
}],
info: {
author: 'Xcode',
version: 1
}
};
const backgroundColorDir = getBackgroundColorDir(projectRoot, platformProjDir);
if (backgroundColorDir) {
events.emit('verbose', 'Cleaning Background Color color set Contents.json');
fs.writeFileSync(path.join(projectRoot, backgroundColorDir, 'Contents.json'),
JSON.stringify(contentsJSON, null, 2));
}
const splashBackgroundColorDir = getSplashScreenBackgroundColorDir(projectRoot, platformProjDir);
if (splashBackgroundColorDir) {
events.emit('verbose', 'Cleaning Splash Screen Background Color color set Contents.json');
fs.writeFileSync(path.join(projectRoot, splashBackgroundColorDir, 'Contents.json'),
JSON.stringify(contentsJSON, null, 2));
}
}
function updateFileResources (cordovaProject, locations) {
const platformDir = path.relative(cordovaProject.root, locations.root);
const files = cordovaProject.projectConfig.getFileResources('ios');
const project = projectFile.parse(locations);
// if there are resource-file elements in config.xml
if (files.length === 0) {
events.emit('verbose', 'This app does not have additional resource files defined');
return;
}
const resourceMap = {};
files.forEach(res => {
const src = res.src;
let target = res.target;
if (!target) {
target = src;
}
let targetPath = path.join(project.resources_dir, target);
targetPath = path.relative(cordovaProject.root, targetPath);
if (!fs.existsSync(targetPath)) {
project.xcode.addResourceFile(target);
} else {
events.emit('warn', `Overwriting existing resource file at ${targetPath}`);
}
resourceMap[targetPath] = src;
});
events.emit('verbose', `Updating resource files at ${platformDir}`);
FileUpdater.updatePaths(
resourceMap, { rootDir: cordovaProject.root }, logFileOp);
project.write();
}
function alertDeprecatedPreference (configParser) {
const deprecatedToNewPreferences = {
MediaPlaybackRequiresUserAction: {
newPreference: 'MediaTypesRequiringUserActionForPlayback',
isDeprecated: true
},
MediaPlaybackAllowsAirPlay: {
newPreference: 'AllowsAirPlayForMediaPlayback',
isDeprecated: false
}
};
Object.keys(deprecatedToNewPreferences).forEach(oldKey => {
if (configParser.getPreference(oldKey)) {
const isDeprecated = deprecatedToNewPreferences[oldKey].isDeprecated;
const verb = isDeprecated ? 'has been' : 'is being';
const newPreferenceKey = deprecatedToNewPreferences[oldKey].newPreference;
// Create the Log Message
const log = [`The preference name "${oldKey}" ${verb} deprecated.`];
if (newPreferenceKey) {
log.push(`It is recommended to replace this preference with "${newPreferenceKey}."`);
} else {
log.push('There is no replacement for this preference.');
}
/**
* If the preference has been deprecated, the usage of the old preference is no longer used.
* Therefore, the following line is not appended. It is added only if the old preference is still used.
* We are only keeping the top lines for deprecated items only for an additional major release when
* the pre-warning was not provided in a past major release due to a necessary quick deprecation.
* Typically caused by implementation nature or third-party requirement changes.
*/
if (!isDeprecated) {
log.push('Please note that this preference will be removed in the near future.');
}
events.emit('warn', log.join(' '));
}
});
}
function cleanFileResources (projectRoot, projectConfig, locations) {
const platformDir = path.relative(projectRoot, locations.root);
const files = projectConfig.getFileResources('ios', true);
if (files.length > 0) {
events.emit('verbose', `Cleaning resource files at ${platformDir}`);
const project = projectFile.parse(locations);
const resourceMap = {};
files.forEach(res => {
const src = res.src;
let target = res.target;
if (!target) {
target = src;
}
let targetPath = path.join(project.resources_dir, target);
targetPath = path.relative(projectRoot, targetPath);
const resfile = path.join('Resources', path.basename(targetPath));
project.xcode.removeResourceFile(resfile);
resourceMap[targetPath] = null;
});
FileUpdater.updatePaths(
resourceMap, { rootDir: projectRoot, all: true }, logFileOp);
project.write();
}
}
/**
* Returns an array of images for each possible idiom, scale, and size class. The images themselves are
* located in the platform's splash images by their pattern (@scale~idiom~sizesize). All possible
* combinations are returned, but not all will have a `filename` property. If the latter isn't present,
* the device won't attempt to load an image matching the same traits. If the filename is present,
* the device will try to load the image if it corresponds to the traits.
*
* The resulting return looks like this:
*
* [
* {
* idiom: 'universal|ipad|iphone',
* scale: '1x|2x|3x',
* width: 'any|com',
* height: 'any|com',
* filename: undefined|'Default@scale~idiom~widthheight.png',
* src: undefined|'path/to/original/matched/image/from/splash/screens.png',
* target: undefined|'path/to/asset/library/Default@scale~idiom~widthheight.png',
* appearence: undefined|'dark'|'light'
* }, ...
* ]
*
* @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform
* @param {string} launchStoryboardImagesDir project-root/Assets.xcassets/LaunchStoryboard.imageset/
* @return {Array<Object>}
*/
function mapLaunchStoryboardContents (splashScreens, launchStoryboardImagesDir) {
const platformLaunchStoryboardImages = [];
const idioms = ['universal', 'ipad', 'iphone'];
const scalesForIdiom = {
universal: ['1x', '2x', '3x'],
ipad: ['1x', '2x'],
iphone: ['1x', '2x', '3x']
};
const sizes = ['com', 'any'];
const appearences = ['', 'dark', 'light'];
idioms.forEach(idiom => {
scalesForIdiom[idiom].forEach(scale => {
sizes.forEach(width => {
sizes.forEach(height => {
appearences.forEach(appearence => {
const item = { idiom, scale, width, height };
if (appearence !== '') {
item.appearence = appearence;
}
/* examples of the search pattern:
* scale ~ idiom ~ width height ~ appearence
* @2x ~ universal ~ any any
* @3x ~ iphone ~ com any ~ dark
* @2x ~ ipad ~ com any ~ light
*/
const searchPattern = '@' + scale + '~' + idiom + '~' + width + height + (appearence ? '~' + appearence : '');
/* because old node versions don't have Array.find, the below is
* functionally equivalent to this:
* var launchStoryboardImage = splashScreens.find(function(item) {
* return (item.src.indexOf(searchPattern) >= 0) ? (appearence !== '' ? true : ((item.src.indexOf(searchPattern + '~light') >= 0 || (item.src.indexOf(searchPattern + '~dark') >= 0)) ? false : true)) : false;
* });
*/
const launchStoryboardImage = splashScreens.reduce(
(p, c) => (c.src.indexOf(searchPattern) >= 0) ? (appearence !== '' ? c : ((c.src.indexOf(searchPattern + '~light') >= 0 || (c.src.indexOf(searchPattern + '~dark') >= 0)) ? p : c)) : p,
undefined
);
if (launchStoryboardImage) {
item.filename = `Default${searchPattern}.png`;
item.src = launchStoryboardImage.src;
item.target = path.join(launchStoryboardImagesDir, item.filename);
}
platformLaunchStoryboardImages.push(item);
});
});
});
});
});
return platformLaunchStoryboardImages;
}
/**
* Returns a dictionary representing the source and destination paths for the launch storyboard images
* that need to be copied.
*
* The resulting return looks like this:
*
* {
* 'target-path': 'source-path',
* ...
* }
*
* @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform
* @param {string} launchStoryboardImagesDir project-root/Assets.xcassets/LaunchStoryboard.imageset/
* @return {Object}
*/
function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) {
const platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir);
const pathMap = {};
platformLaunchStoryboardImages.forEach(item => {
if (item.target) {
pathMap[item.target] = item.src;
}
});
return pathMap;
}
/**
* Builds the object that represents the contents.json file for the LaunchStoryboard image set.
*
* The resulting return looks like this:
*
* {
* images: [
* {
* idiom: 'universal|ipad|iphone',
* scale: '1x|2x|3x',
* width-class: undefined|'compact',
* height-class: undefined|'compact'
* ...
* }, ...
* ],
* info: {
* author: 'Xcode',
* version: 1
* }
* }
*
* A bit of minor logic is used to map from the array of images returned from mapLaunchStoryboardContents
* to the format requried by Xcode.