The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3624 lines
170KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #pragma once
  20. #include "jucer_XcodeProjectParser.h"
  21. //==============================================================================
  22. namespace
  23. {
  24. const char* const osxVersionDefault = "10.11";
  25. const char* const iosVersionDefault = "9.3";
  26. const int oldestSDKVersion = 7;
  27. const int currentSDKVersion = 14;
  28. const int minimumAUv3SDKVersion = 11;
  29. const char* const osxArch_Default = "default";
  30. const char* const osxArch_Native = "Native";
  31. const char* const osxArch_32BitUniversal = "32BitUniversal";
  32. const char* const osxArch_64BitUniversal = "64BitUniversal";
  33. const char* const osxArch_64Bit = "64BitIntel";
  34. }
  35. //==============================================================================
  36. class XcodeProjectExporter : public ProjectExporter
  37. {
  38. public:
  39. //==============================================================================
  40. static const char* getNameMac() { return "Xcode (MacOSX)"; }
  41. static const char* getNameiOS() { return "Xcode (iOS)"; }
  42. static const char* getValueTreeTypeName (bool iOS) { return iOS ? "XCODE_IPHONE" : "XCODE_MAC"; }
  43. //==============================================================================
  44. XcodeProjectExporter (Project& p, const ValueTree& t, const bool isIOS)
  45. : ProjectExporter (p, t),
  46. xcodeCanUseDwarf (true),
  47. iOS (isIOS),
  48. customPListValue (settings, Ids::customPList, getUndoManager()),
  49. pListPrefixHeaderValue (settings, Ids::pListPrefixHeader, getUndoManager()),
  50. pListPreprocessValue (settings, Ids::pListPreprocess, getUndoManager()),
  51. subprojectsValue (settings, Ids::xcodeSubprojects, getUndoManager()),
  52. extraFrameworksValue (settings, Ids::extraFrameworks, getUndoManager()),
  53. frameworkSearchPathsValue (settings, Ids::frameworkSearchPaths, getUndoManager()),
  54. extraCustomFrameworksValue (settings, Ids::extraCustomFrameworks, getUndoManager()),
  55. embeddedFrameworksValue (settings, Ids::embeddedFrameworks, getUndoManager()),
  56. postbuildCommandValue (settings, Ids::postbuildCommand, getUndoManager()),
  57. prebuildCommandValue (settings, Ids::prebuildCommand, getUndoManager()),
  58. duplicateAppExResourcesFolderValue (settings, Ids::duplicateAppExResourcesFolder, getUndoManager(), true),
  59. iosDeviceFamilyValue (settings, Ids::iosDeviceFamily, getUndoManager(), "1,2"),
  60. iPhoneScreenOrientationValue (settings, Ids::iPhoneScreenOrientation, getUndoManager(), "portraitlandscape"),
  61. iPadScreenOrientationValue (settings, Ids::iPadScreenOrientation, getUndoManager(), "portraitlandscape"),
  62. customXcodeResourceFoldersValue (settings, Ids::customXcodeResourceFolders, getUndoManager()),
  63. customXcassetsFolderValue (settings, Ids::customXcassetsFolder, getUndoManager()),
  64. hardenedRuntimeValue (settings, Ids::hardenedRuntime, getUndoManager()),
  65. hardenedRuntimeOptionsValue (settings, Ids::hardenedRuntimeOptions, getUndoManager(), Array<var>(), ","),
  66. microphonePermissionNeededValue (settings, Ids::microphonePermissionNeeded, getUndoManager()),
  67. microphonePermissionsTextValue (settings, Ids::microphonePermissionsText, getUndoManager(),
  68. "This app requires audio input. If you do not have an audio interface connected it will use the built-in microphone."),
  69. cameraPermissionNeededValue (settings, Ids::cameraPermissionNeeded, getUndoManager()),
  70. cameraPermissionTextValue (settings, Ids::cameraPermissionText, getUndoManager(),
  71. "This app requires access to the camera to function correctly."),
  72. uiFileSharingEnabledValue (settings, Ids::UIFileSharingEnabled, getUndoManager()),
  73. uiSupportsDocumentBrowserValue (settings, Ids::UISupportsDocumentBrowser, getUndoManager()),
  74. uiStatusBarHiddenValue (settings, Ids::UIStatusBarHidden, getUndoManager()),
  75. documentExtensionsValue (settings, Ids::documentExtensions, getUndoManager()),
  76. iosInAppPurchasesValue (settings, Ids::iosInAppPurchases, getUndoManager()),
  77. iosBackgroundAudioValue (settings, Ids::iosBackgroundAudio, getUndoManager()),
  78. iosBackgroundBleValue (settings, Ids::iosBackgroundBle, getUndoManager()),
  79. iosPushNotificationsValue (settings, Ids::iosPushNotifications, getUndoManager()),
  80. iosAppGroupsValue (settings, Ids::iosAppGroups, getUndoManager()),
  81. iCloudPermissionsValue (settings, Ids::iCloudPermissions, getUndoManager()),
  82. iosDevelopmentTeamIDValue (settings, Ids::iosDevelopmentTeamID, getUndoManager()),
  83. iosAppGroupsIDValue (settings, Ids::iosAppGroupsId, getUndoManager()),
  84. keepCustomXcodeSchemesValue (settings, Ids::keepCustomXcodeSchemes, getUndoManager()),
  85. useHeaderMapValue (settings, Ids::useHeaderMap, getUndoManager()),
  86. customLaunchStoryboardValue (settings, Ids::customLaunchStoryboard, getUndoManager()),
  87. exporterBundleIdentifierValue (settings, Ids::bundleIdentifier, getUndoManager())
  88. {
  89. name = iOS ? getNameiOS() : getNameMac();
  90. targetLocationValue.setDefault (getDefaultBuildsRootFolder() + getTargetFolderForExporter (getValueTreeTypeName (isIOS)));
  91. }
  92. static XcodeProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  93. {
  94. if (settings.hasType (getValueTreeTypeName (false))) return new XcodeProjectExporter (project, settings, false);
  95. if (settings.hasType (getValueTreeTypeName (true))) return new XcodeProjectExporter (project, settings, true);
  96. return nullptr;
  97. }
  98. //==============================================================================
  99. String getPListToMergeString() const { return customPListValue.get(); }
  100. String getPListPrefixHeaderString() const { return pListPrefixHeaderValue.get(); }
  101. bool isPListPreprocessEnabled() const { return pListPreprocessValue.get(); }
  102. String getSubprojectsString() const { return subprojectsValue.get(); }
  103. String getExtraFrameworksString() const { return extraFrameworksValue.get(); }
  104. String getFrameworkSearchPathsString() const { return frameworkSearchPathsValue.get(); }
  105. String getExtraCustomFrameworksString() const { return extraCustomFrameworksValue.get(); }
  106. String getEmbeddedFrameworksString() const { return embeddedFrameworksValue.get(); }
  107. String getPostBuildScript() const { return postbuildCommandValue.get(); }
  108. String getPreBuildScript() const { return prebuildCommandValue.get(); }
  109. bool shouldDuplicateAppExResourcesFolder() const { return duplicateAppExResourcesFolderValue.get(); }
  110. String getDeviceFamilyString() const { return iosDeviceFamilyValue.get(); }
  111. String getiPhoneScreenOrientationString() const { return iPhoneScreenOrientationValue.get(); }
  112. String getiPadScreenOrientationString() const { return iPadScreenOrientationValue.get(); }
  113. String getCustomResourceFoldersString() const { return customXcodeResourceFoldersValue.get().toString().replaceCharacters ("\r\n", "::"); }
  114. String getCustomXcassetsFolderString() const { return customXcassetsFolderValue.get(); }
  115. String getCustomLaunchStoryboardString() const { return customLaunchStoryboardValue.get(); }
  116. bool shouldAddStoryboardToProject() const { return getCustomLaunchStoryboardString().isNotEmpty() || getCustomXcassetsFolderString().isEmpty(); }
  117. bool isHardenedRuntimeEnabled() const { return hardenedRuntimeValue.get(); }
  118. Array<var> getHardenedRuntimeOptions() const { return *hardenedRuntimeOptionsValue.get().getArray(); }
  119. bool isMicrophonePermissionEnabled() const { return microphonePermissionNeededValue.get(); }
  120. String getMicrophonePermissionsTextString() const { return microphonePermissionsTextValue.get(); }
  121. bool isCameraPermissionEnabled() const { return cameraPermissionNeededValue.get(); }
  122. String getCameraPermissionTextString() const { return cameraPermissionTextValue.get(); }
  123. bool isInAppPurchasesEnabled() const { return iosInAppPurchasesValue.get(); }
  124. bool isBackgroundAudioEnabled() const { return iosBackgroundAudioValue.get(); }
  125. bool isBackgroundBleEnabled() const { return iosBackgroundBleValue.get(); }
  126. bool isPushNotificationsEnabled() const { return iosPushNotificationsValue.get(); }
  127. bool isAppGroupsEnabled() const { return iosAppGroupsValue.get(); }
  128. bool isiCloudPermissionsEnabled() const { return iCloudPermissionsValue.get(); }
  129. bool isFileSharingEnabled() const { return uiFileSharingEnabledValue.get(); }
  130. bool isDocumentBrowserEnabled() const { return uiSupportsDocumentBrowserValue.get(); }
  131. bool isStatusBarHidden() const { return uiStatusBarHiddenValue.get(); }
  132. String getDocumentExtensionsString() const { return documentExtensionsValue.get(); }
  133. bool shouldKeepCustomXcodeSchemes() const { return keepCustomXcodeSchemesValue.get(); }
  134. String getIosDevelopmentTeamIDString() const { return iosDevelopmentTeamIDValue.get(); }
  135. String getAppGroupIdString() const { return iosAppGroupsIDValue.get(); }
  136. String getDefaultLaunchStoryboardName() const { jassert (iOS); return "LaunchScreen"; }
  137. //==============================================================================
  138. bool usesMMFiles() const override { return true; }
  139. bool canCopeWithDuplicateFiles() override { return true; }
  140. bool supportsUserDefinedConfigurations() const override { return true; }
  141. bool isXcode() const override { return true; }
  142. bool isVisualStudio() const override { return false; }
  143. bool isCodeBlocks() const override { return false; }
  144. bool isMakefile() const override { return false; }
  145. bool isAndroidStudio() const override { return false; }
  146. bool isCLion() const override { return false; }
  147. bool isAndroid() const override { return false; }
  148. bool isWindows() const override { return false; }
  149. bool isLinux() const override { return false; }
  150. bool isOSX() const override { return ! iOS; }
  151. bool isiOS() const override { return iOS; }
  152. bool supportsTargetType (ProjectType::Target::Type type) const override
  153. {
  154. switch (type)
  155. {
  156. case ProjectType::Target::AudioUnitv3PlugIn:
  157. case ProjectType::Target::StandalonePlugIn:
  158. case ProjectType::Target::GUIApp:
  159. case ProjectType::Target::StaticLibrary:
  160. case ProjectType::Target::DynamicLibrary:
  161. case ProjectType::Target::SharedCodeTarget:
  162. case ProjectType::Target::AggregateTarget:
  163. return true;
  164. case ProjectType::Target::ConsoleApp:
  165. case ProjectType::Target::VSTPlugIn:
  166. case ProjectType::Target::VST3PlugIn:
  167. case ProjectType::Target::AAXPlugIn:
  168. case ProjectType::Target::RTASPlugIn:
  169. case ProjectType::Target::AudioUnitPlugIn:
  170. case ProjectType::Target::UnityPlugIn:
  171. return ! iOS;
  172. default:
  173. break;
  174. }
  175. return false;
  176. }
  177. void createExporterProperties (PropertyListBuilder& props) override
  178. {
  179. if (iOS)
  180. {
  181. props.add (new TextPropertyComponent (customXcassetsFolderValue, "Custom Xcassets Folder", 128, false),
  182. "If this field is not empty, your Xcode project will use the custom xcassets folder specified here "
  183. "for the app icons and launchimages, and will ignore the Icon files specified above. This will also prevent "
  184. "a launch storyboard from being used.");
  185. props.add (new TextPropertyComponent (customLaunchStoryboardValue, "Custom Launch Storyboard", 256, false),
  186. "If this field is not empty then the specified launch storyboard file will be added to the project as an Xcode "
  187. "resource and will be used for the app's launch screen, otherwise a default blank launch storyboard will be used. "
  188. "The file path should be relative to the project folder.");
  189. }
  190. props.add (new TextPropertyComponent (customXcodeResourceFoldersValue, "Custom Xcode Resource Folders", 8192, true),
  191. "You can specify a list of custom resource folders here (separated by newlines or whitespace). "
  192. "References to these folders will then be added to the Xcode resources. "
  193. "This way you can specify them for OS X and iOS separately, and modify the content of the resource folders "
  194. "without re-saving the Projucer project.");
  195. if (getProject().getProjectType().isAudioPlugin())
  196. props.add (new ChoicePropertyComponent (duplicateAppExResourcesFolderValue, "Add Duplicate Resources Folder to App Extension"),
  197. "Disable this to prevent the Projucer from creating a duplicate resources folder for AUv3 app extensions.");
  198. if (iOS)
  199. {
  200. props.add (new ChoicePropertyComponent (iosDeviceFamilyValue, "Device Family",
  201. { "iPhone", "iPad", "Universal" },
  202. { "1", "2", "1,2" }),
  203. "The device family to target.");
  204. {
  205. StringArray orientationStrings { "Portrait and Landscape", "Portrait", "Landscape" };
  206. Array<var> orientationValues { "portraitlandscape", "portrait", "landscape"};
  207. props.add (new ChoicePropertyComponent (iPhoneScreenOrientationValue, "iPhone Screen Orientation",
  208. orientationStrings, orientationValues),
  209. "The screen orientations that this app should support on iPhones.");
  210. props.add (new ChoicePropertyComponent (iPadScreenOrientationValue, "iPad Screen Orientation",
  211. orientationStrings, orientationValues),
  212. "The screen orientations that this app should support on iPads.");
  213. }
  214. props.add (new ChoicePropertyComponent (uiFileSharingEnabledValue, "File Sharing Enabled"),
  215. "Enable this to expose your app's files to iTunes.");
  216. props.add (new ChoicePropertyComponent (uiSupportsDocumentBrowserValue, "Support Document Browser"),
  217. "Enable this to allow the user to access your app documents from a native file chooser.");
  218. props.add (new ChoicePropertyComponent (uiStatusBarHiddenValue, "Status Bar Hidden"),
  219. "Enable this to disable the status bar in your app.");
  220. }
  221. else if (projectType.isGUIApplication())
  222. {
  223. props.add (new TextPropertyComponent (documentExtensionsValue, "Document File Extensions", 128, false),
  224. "A comma-separated list of file extensions for documents that your app can open. "
  225. "Using a leading '.' is optional, and the extensions are not case-sensitive.");
  226. }
  227. if (isOSX())
  228. {
  229. props.add (new ChoicePropertyComponent (hardenedRuntimeValue, "Use Hardened Runtime"),
  230. "Enable this to use the hardened runtime required for app notarization.");
  231. std::vector<std::pair<String, String>> options
  232. {
  233. { "Allow Execution of JIT-compiled Code", "cs.allow-jit" },
  234. { "Allow Unsigned Executable Memory", "cs.allow-unsigned-executable-memory" },
  235. { "Allow DYLD Environment Variables", "cs.allow-dyld-environment-variables" },
  236. { "Disable Library Validation", "cs.disable-library-validation" },
  237. { "Disable Executable Memory Protection", "cs.disable-executable-page-protection" },
  238. { "Debugging Tool", "cs.debugger" },
  239. { "Audio Input", "device.audio-input" },
  240. { "Camera", "device.camera" },
  241. { "Location", "personal-information.location" },
  242. { "Address Book", "personal-information.addressbook" },
  243. { "Calendar", "personal-information.calendars" },
  244. { "Photos Library", "personal-information.photos-library" },
  245. { "Apple Events", "automation.apple-events" },
  246. };
  247. StringArray keys;
  248. Array<var> values;
  249. for (auto& opt : options)
  250. {
  251. keys.add (opt.first);
  252. values.add ("com.apple.security." + opt.second);
  253. }
  254. props.add (new MultiChoicePropertyComponentWithEnablement (hardenedRuntimeOptionsValue,
  255. hardenedRuntimeValue,
  256. "Hardened Runtime Options",
  257. keys,
  258. values));
  259. }
  260. props.add (new ChoicePropertyComponent (microphonePermissionNeededValue, "Microphone Access"),
  261. "Enable this to allow your app to use the microphone. "
  262. "The user of your app will be prompted to grant microphone access permissions.");
  263. props.add (new TextPropertyComponentWithEnablement (microphonePermissionsTextValue, microphonePermissionNeededValue,
  264. "Microphone Access Text", 1024, false),
  265. "A short description of why your app requires microphone access.");
  266. props.add (new ChoicePropertyComponent (cameraPermissionNeededValue, "Camera Access"),
  267. "Enable this to allow your app to use the camera. "
  268. "The user of your app will be prompted to grant camera access permissions.");
  269. props.add (new TextPropertyComponentWithEnablement (cameraPermissionTextValue, cameraPermissionNeededValue,
  270. "Camera Access Text", 1024, false),
  271. "A short description of why your app requires camera access.");
  272. props.add (new ChoicePropertyComponent (iosInAppPurchasesValue, "In-App Purchases Capability"),
  273. "Enable this to grant your app the capability for in-app purchases. "
  274. "This option requires that you specify a valid Development Team ID.");
  275. if (iOS)
  276. {
  277. props.add (new ChoicePropertyComponent (iosBackgroundAudioValue, "Audio Background Capability"),
  278. "Enable this to grant your app the capability to access audio when in background mode. "
  279. "This permission is required if your app creates a MIDI input or output device.");
  280. props.add (new ChoicePropertyComponent (iosBackgroundBleValue, "Bluetooth MIDI Background Capability"),
  281. "Enable this to grant your app the capability to connect to Bluetooth LE devices when in background mode.");
  282. props.add (new ChoicePropertyComponent (iosAppGroupsValue, "App Groups Capability"),
  283. "Enable this to grant your app the capability to share resources between apps using the same app group ID.");
  284. props.add (new ChoicePropertyComponent (iCloudPermissionsValue, "iCloud Permissions"),
  285. "Enable this to grant your app the capability to use native file load/save browser windows on iOS.");
  286. }
  287. props.add (new ChoicePropertyComponent (iosPushNotificationsValue, "Push Notifications Capability"),
  288. "Enable this to grant your app the capability to receive push notifications.");
  289. props.add (new TextPropertyComponent (customPListValue, "Custom PList", 8192, true),
  290. "You can paste the contents of an XML PList file in here, and the settings that it contains will override any "
  291. "settings that the Projucer creates. BEWARE! When doing this, be careful to remove from the XML any "
  292. "values that you DO want the Projucer to change!");
  293. props.add (new ChoicePropertyComponent (pListPreprocessValue, "PList Preprocess"),
  294. "Enable this to preprocess PList file. This will allow you to set values to preprocessor defines,"
  295. " for instance if you define: #define MY_FLAG 1 in a prefix header file (see PList prefix header), you can have"
  296. " a key with MY_FLAG value and it will be replaced with 1.");
  297. props.add (new TextPropertyComponent (pListPrefixHeaderValue, "PList Prefix Header", 512, false),
  298. "Header file containing definitions used in plist file (see PList Preprocess).");
  299. props.add (new TextPropertyComponent (extraFrameworksValue, "Extra System Frameworks", 2048, false),
  300. "A comma-separated list of extra system frameworks that should be added to the build. "
  301. "(Don't include the .framework extension in the name)"
  302. " The frameworks are expected to be located in /System/Library/Frameworks");
  303. props.add (new TextPropertyComponent (frameworkSearchPathsValue, "Framework Search Paths", 8192, true),
  304. "A set of paths to search for custom frameworks (one per line).");
  305. props.add (new TextPropertyComponent (extraCustomFrameworksValue, "Extra Custom Frameworks", 8192, true),
  306. "Paths to custom frameworks that should be added to the build (one per line). "
  307. "You will probably need to add an entry to the Framework Search Paths for each unique directory.");
  308. props.add (new TextPropertyComponent (embeddedFrameworksValue, "Embedded Frameworks", 8192, true),
  309. "Paths to frameworks to be embedded with the app (one per line). "
  310. "If you are adding a framework here then you do not need to specify it in Extra Custom Frameworks too. "
  311. "You will probably need to add an entry to the Framework Search Paths for each unique directory.");
  312. props.add (new TextPropertyComponent (subprojectsValue, "Xcode Subprojects", 8192, true),
  313. "Paths to Xcode projects that should be added to the build (one per line). "
  314. "The names of the required build products can be specified after a colon, comma seperated, "
  315. "e.g. \"path/to/MySubProject.xcodeproj: MySubProject, OtherTarget\". "
  316. "If no build products are specified, all build products associated with a subproject will be added.");
  317. props.add (new TextPropertyComponent (prebuildCommandValue, "Pre-Build Shell Script", 32768, true),
  318. "Some shell-script that will be run before a build starts.");
  319. props.add (new TextPropertyComponent (postbuildCommandValue, "Post-Build Shell Script", 32768, true),
  320. "Some shell-script that will be run after a build completes.");
  321. props.add (new TextPropertyComponent (exporterBundleIdentifierValue, "Exporter Bundle Identifier", 256, false),
  322. "Use this to override the project bundle identifier for this exporter. "
  323. "This is useful if you want to use different bundle identifiers for Mac and iOS exporters in the same project.");
  324. props.add (new TextPropertyComponent (iosDevelopmentTeamIDValue, "Development Team ID", 10, false),
  325. "The Development Team ID to be used for setting up code-signing your iOS app. This is a ten-character "
  326. "string (for example, \"S7B6T5XJ2Q\") that describes the distribution certificate Apple issued to you. "
  327. "You can find this string in the OS X app Keychain Access under \"Certificates\".");
  328. if (iOS)
  329. props.add (new TextPropertyComponentWithEnablement (iosAppGroupsIDValue, iosAppGroupsValue, "App Group ID", 256, false),
  330. "The App Group ID to be used for allowing multiple apps to access a shared resource folder. Multiple IDs can be "
  331. "added separated by a semicolon.");
  332. props.add (new ChoicePropertyComponent (keepCustomXcodeSchemesValue, "Keep Custom Xcode Schemes"),
  333. "Enable this to keep any Xcode schemes you have created for debugging or running, e.g. to launch a plug-in in"
  334. "various hosts. If disabled, all schemes are replaced by a default set.");
  335. props.add (new ChoicePropertyComponent (useHeaderMapValue, "USE_HEADERMAP"),
  336. "Enable this to make Xcode search all the projects folders for include files. This means you can be lazy "
  337. "and not bother using relative paths to include your headers, but it means your code won't be "
  338. "compatible with other build systems");
  339. }
  340. bool launchProject() override
  341. {
  342. #if JUCE_MAC
  343. return getProjectBundle().startAsProcess();
  344. #else
  345. return false;
  346. #endif
  347. }
  348. bool canLaunchProject() override
  349. {
  350. #if JUCE_MAC
  351. return true;
  352. #else
  353. return false;
  354. #endif
  355. }
  356. //==============================================================================
  357. void create (const OwnedArray<LibraryModule>&) const override
  358. {
  359. for (auto& target : targets)
  360. if (target->shouldCreatePList())
  361. target->infoPlistFile = getTargetFolder().getChildFile (target->getInfoPlistName());
  362. menuNibFile = getTargetFolder().getChildFile ("RecentFilesMenuTemplate.nib");
  363. createIconFile();
  364. auto projectBundle = getProjectBundle();
  365. createDirectoryOrThrow (projectBundle);
  366. createObjects();
  367. auto projectFile = projectBundle.getChildFile ("project.pbxproj");
  368. {
  369. MemoryOutputStream mo;
  370. writeProjectFile (mo);
  371. overwriteFileIfDifferentOrThrow (projectFile, mo);
  372. }
  373. writeInfoPlistFiles();
  374. // This forces the project to use the legacy build system to workaround Xcode 10 issues,
  375. // hopefully these will be fixed in the future and this can be removed...
  376. writeWorkspaceSettings();
  377. // Deleting the .rsrc files can be needed to force Xcode to update the version number.
  378. deleteRsrcFiles (getTargetFolder().getChildFile ("build"));
  379. }
  380. //==============================================================================
  381. void addPlatformSpecificSettingsForProjectType (const ProjectType&) override
  382. {
  383. callForAllSupportedTargets ([this] (ProjectType::Target::Type targetType)
  384. {
  385. if (auto* target = new XcodeTarget (targetType, *this))
  386. {
  387. if (targetType == ProjectType::Target::AggregateTarget)
  388. targets.insert (0, target);
  389. else
  390. targets.add (target);
  391. }
  392. });
  393. // If you hit this assert, you tried to generate a project for an exporter
  394. // that does not support any of your targets!
  395. jassert (targets.size() > 0);
  396. }
  397. void updateDeprecatedProjectSettingsInteractively() override
  398. {
  399. if (hasInvalidPostBuildScript())
  400. {
  401. String alertWindowText = iOS ? "Your Xcode (iOS) Exporter settings use an invalid post-build script. Click 'Update' to remove it."
  402. : "Your Xcode (OSX) Exporter settings use a pre-JUCE 4.2 post-build script to move the plug-in binaries to their plug-in install folders.\n\n"
  403. "Since JUCE 4.2, this is instead done using \"AU/VST/VST2/AAX/RTAS Binary Location\" in the Xcode (OS X) configuration settings.\n\n"
  404. "Click 'Update' to remove the script (otherwise your plug-in may not compile correctly).";
  405. if (AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  406. "Project settings: " + project.getDocumentTitle(),
  407. alertWindowText, "Update", "Cancel", nullptr, nullptr))
  408. postbuildCommandValue.resetToDefault();
  409. }
  410. }
  411. bool hasInvalidPostBuildScript() const
  412. {
  413. // check whether the script is identical to the old one that the Introjucer used to auto-generate
  414. return (MD5 (getPostBuildScript().toUTF8()).toHexString() == "265ac212a7e734c5bbd6150e1eae18a1");
  415. }
  416. //==============================================================================
  417. void initialiseDependencyPathValues() override
  418. {
  419. vstLegacyPathValueWrapper.init ({ settings, Ids::vstLegacyFolder, nullptr },
  420. getAppSettings().getStoredPath (Ids::vstLegacyPath, TargetOS::osx), TargetOS::osx);
  421. vst3PathValueWrapper.init ({ settings, Ids::vst3Folder, nullptr },
  422. getAppSettings().getStoredPath (Ids::vst3Path, TargetOS::osx), TargetOS::osx);
  423. aaxPathValueWrapper.init ({ settings, Ids::aaxFolder, nullptr },
  424. getAppSettings().getStoredPath (Ids::aaxPath, TargetOS::osx), TargetOS::osx);
  425. rtasPathValueWrapper.init ({ settings, Ids::rtasFolder, nullptr },
  426. getAppSettings().getStoredPath (Ids::rtasPath, TargetOS::osx), TargetOS::osx);
  427. }
  428. protected:
  429. //==============================================================================
  430. class XcodeBuildConfiguration : public BuildConfiguration
  431. {
  432. public:
  433. XcodeBuildConfiguration (Project& p, const ValueTree& t, const bool isIOS, const ProjectExporter& e)
  434. : BuildConfiguration (p, t, e),
  435. iOS (isIOS),
  436. osxSDKVersion (config, Ids::osxSDK, getUndoManager()),
  437. osxDeploymentTarget (config, Ids::osxCompatibility, getUndoManager(), String (osxVersionDefault) + " SDK"),
  438. iosDeploymentTarget (config, Ids::iosCompatibility, getUndoManager(), iosVersionDefault),
  439. osxArchitecture (config, Ids::osxArchitecture, getUndoManager(), osxArch_Default),
  440. customXcodeFlags (config, Ids::customXcodeFlags, getUndoManager()),
  441. plistPreprocessorDefinitions (config, Ids::plistPreprocessorDefinitions, getUndoManager()),
  442. codeSignIdentity (config, Ids::codeSigningIdentity, getUndoManager(), iOS ? "iPhone Developer" : "Mac Developer"),
  443. fastMathEnabled (config, Ids::fastMath, getUndoManager()),
  444. stripLocalSymbolsEnabled (config, Ids::stripLocalSymbols, getUndoManager()),
  445. pluginBinaryCopyStepEnabled (config, Ids::enablePluginBinaryCopyStep, getUndoManager(), true),
  446. vstBinaryLocation (config, Ids::vstBinaryLocation, getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/VST/"),
  447. vst3BinaryLocation (config, Ids::vst3BinaryLocation, getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/VST3/"),
  448. auBinaryLocation (config, Ids::auBinaryLocation, getUndoManager(), "$(HOME)/Library/Audio/Plug-Ins/Components/"),
  449. rtasBinaryLocation (config, Ids::rtasBinaryLocation, getUndoManager(), "/Library/Application Support/Digidesign/Plug-Ins/"),
  450. aaxBinaryLocation (config, Ids::aaxBinaryLocation, getUndoManager(), "/Library/Application Support/Avid/Audio/Plug-Ins/"),
  451. unityPluginBinaryLocation (config, Ids::unityPluginBinaryLocation, getUndoManager())
  452. {
  453. updateOldPluginBinaryLocations();
  454. updateOldSDKDefaults();
  455. optimisationLevelValue.setDefault (isDebug() ? gccO0 : gccO3);
  456. }
  457. //==========================================================================
  458. void createConfigProperties (PropertyListBuilder& props) override
  459. {
  460. addXcodePluginInstallPathProperties (props);
  461. addGCCOptimisationProperty (props);
  462. if (iOS)
  463. {
  464. props.add (new ChoicePropertyComponent (iosDeploymentTarget, "iOS Deployment Target",
  465. { "7.0", "7.1", "8.0", "8.1", "8.2", "8.3", "8.4",
  466. "9.0", "9.1", "9.2", "9.3", "10.0", "10.1", "10.2", "10.3",
  467. "11.0", "12.0" },
  468. { "7.0", "7.1", "8.0", "8.1", "8.2", "8.3", "8.4",
  469. "9.0", "9.1", "9.2", "9.3", "10.0", "10.1", "10.2", "10.3",
  470. "11.0", "12.0" }),
  471. "The minimum version of iOS that the target binary will run on.");
  472. }
  473. else
  474. {
  475. StringArray sdkVersionNames, osxVersionNames;
  476. Array<var> versionValues;
  477. for (int ver = oldestSDKVersion; ver <= currentSDKVersion; ++ver)
  478. {
  479. sdkVersionNames.add (getSDKName (ver));
  480. osxVersionNames.add (getOSXVersionName (ver));
  481. versionValues.add (getSDKName (ver));
  482. }
  483. props.add (new ChoicePropertyComponent (osxSDKVersion, "OSX Base SDK Version", sdkVersionNames, versionValues),
  484. "The version of OSX to link against in the Xcode build. If \"Default\" is selected then the field will be left "
  485. "empty and the Xcode default will be used.");
  486. props.add (new ChoicePropertyComponent (osxDeploymentTarget, "OSX Deployment Target", osxVersionNames, versionValues),
  487. "The minimum version of OSX that the target binary will be compatible with.");
  488. props.add (new ChoicePropertyComponent (osxArchitecture, "OSX Architecture",
  489. { "Native architecture of build machine", "Universal Binary (32-bit)", "Universal Binary (32/64-bit)", "64-bit Intel" },
  490. { osxArch_Native, osxArch_32BitUniversal, osxArch_64BitUniversal, osxArch_64Bit }),
  491. "The type of OSX binary that will be produced.");
  492. }
  493. props.add (new TextPropertyComponent (customXcodeFlags, "Custom Xcode Flags", 8192, true),
  494. "A comma-separated list of custom Xcode setting flags which will be appended to the list of generated flags, "
  495. "e.g. MACOSX_DEPLOYMENT_TARGET_i386 = 10.5, VALID_ARCHS = \"ppc i386 x86_64\"");
  496. props.add (new TextPropertyComponent (plistPreprocessorDefinitions, "PList Preprocessor Definitions", 2048, true),
  497. "Preprocessor definitions used during PList preprocessing (see PList Preprocess).");
  498. props.add (new TextPropertyComponent (codeSignIdentity, "Code-Signing Identity", 1024, false),
  499. "The name of a code-signing identity for Xcode to apply.");
  500. props.add (new ChoicePropertyComponent (fastMathEnabled, "Relax IEEE Compliance"),
  501. "Enable this to use FAST_MATH non-IEEE mode. (Warning: this can have unexpected results!)");
  502. props.add (new ChoicePropertyComponent (stripLocalSymbolsEnabled, "Strip Local Symbols"),
  503. "Enable this to strip any locally defined symbols resulting in a smaller binary size. Enabling this "
  504. "will also remove any function names from crash logs. Must be disabled for static library projects.");
  505. }
  506. String getModuleLibraryArchName() const override
  507. {
  508. return "${CURRENT_ARCH}";
  509. }
  510. //==========================================================================
  511. String getOSXArchitectureString() const { return osxArchitecture.get(); }
  512. String getPListPreprocessorDefinitionsString() const { return plistPreprocessorDefinitions.get(); }
  513. bool isFastMathEnabled() const { return fastMathEnabled.get(); }
  514. bool isStripLocalSymbolsEnabled() const { return stripLocalSymbolsEnabled.get(); }
  515. String getCustomXcodeFlagsString() const { return customXcodeFlags.get(); }
  516. String getOSXSDKVersionString() const { return osxSDKVersion.get(); }
  517. String getOSXDeploymentTargetString() const { return osxDeploymentTarget.get(); }
  518. String getCodeSignIdentityString() const { return codeSignIdentity.get(); }
  519. bool isUsingDefaultCodeSignIdentity() const { return codeSignIdentity.isUsingDefault(); }
  520. String getiOSDeploymentTargetString() const { return iosDeploymentTarget.get(); }
  521. bool isPluginBinaryCopyStepEnabled() const { return pluginBinaryCopyStepEnabled.get(); }
  522. String getVSTBinaryLocationString() const { return vstBinaryLocation.get(); }
  523. String getVST3BinaryLocationString() const { return vst3BinaryLocation.get(); }
  524. String getAUBinaryLocationString() const { return auBinaryLocation.get(); }
  525. String getRTASBinaryLocationString() const { return rtasBinaryLocation.get();}
  526. String getAAXBinaryLocationString() const { return aaxBinaryLocation.get();}
  527. String getUnityPluginBinaryLocationString() const { return unityPluginBinaryLocation.get(); }
  528. private:
  529. //==========================================================================
  530. bool iOS;
  531. ValueWithDefault osxSDKVersion, osxDeploymentTarget, iosDeploymentTarget, osxArchitecture,
  532. customXcodeFlags, plistPreprocessorDefinitions, codeSignIdentity,
  533. fastMathEnabled, stripLocalSymbolsEnabled, pluginBinaryCopyStepEnabled,
  534. vstBinaryLocation, vst3BinaryLocation, auBinaryLocation, rtasBinaryLocation,
  535. aaxBinaryLocation, unityPluginBinaryLocation;
  536. //==========================================================================
  537. void addXcodePluginInstallPathProperties (PropertyListBuilder& props)
  538. {
  539. auto isBuildingAnyPlugins = (project.shouldBuildVST() || project.shouldBuildVST3() || project.shouldBuildAU()
  540. || project.shouldBuildRTAS() || project.shouldBuildAAX() || project.shouldBuildUnityPlugin());
  541. if (isBuildingAnyPlugins)
  542. props.add (new ChoicePropertyComponent (pluginBinaryCopyStepEnabled, "Enable Plugin Copy Step"),
  543. "Enable this to copy plugin binaries to the specified folder after building.");
  544. if (project.shouldBuildVST3())
  545. props.add (new TextPropertyComponentWithEnablement (vst3BinaryLocation, pluginBinaryCopyStepEnabled, "VST3 Binary Location",
  546. 1024, false),
  547. "The folder in which the compiled VST3 binary should be placed.");
  548. if (project.shouldBuildAU())
  549. props.add (new TextPropertyComponentWithEnablement (auBinaryLocation, pluginBinaryCopyStepEnabled, "AU Binary Location",
  550. 1024, false),
  551. "The folder in which the compiled AU binary should be placed.");
  552. if (project.shouldBuildRTAS())
  553. props.add (new TextPropertyComponentWithEnablement (rtasBinaryLocation, pluginBinaryCopyStepEnabled, "RTAS Binary Location",
  554. 1024, false),
  555. "The folder in which the compiled RTAS binary should be placed.");
  556. if (project.shouldBuildAAX())
  557. props.add (new TextPropertyComponentWithEnablement (aaxBinaryLocation, pluginBinaryCopyStepEnabled, "AAX Binary Location",
  558. 1024, false),
  559. "The folder in which the compiled AAX binary should be placed.");
  560. if (project.shouldBuildUnityPlugin())
  561. props.add (new TextPropertyComponentWithEnablement (unityPluginBinaryLocation, pluginBinaryCopyStepEnabled, "Unity Binary Location",
  562. 1024, false),
  563. "The folder in which the compiled Unity plugin binary and associated C# GUI script should be placed.");
  564. if (project.shouldBuildVST())
  565. props.add (new TextPropertyComponentWithEnablement (vstBinaryLocation, pluginBinaryCopyStepEnabled, "VST Binary Location",
  566. 1024, false),
  567. "The folder in which the compiled legacy VST binary should be placed.");
  568. }
  569. void updateOldPluginBinaryLocations()
  570. {
  571. if (! config ["xcodeVstBinaryLocation"].isVoid()) vstBinaryLocation = config ["xcodeVstBinaryLocation"];
  572. if (! config ["xcodeVst3BinaryLocation"].isVoid()) vst3BinaryLocation = config ["xcodeVst3BinaryLocation"];
  573. if (! config ["xcodeAudioUnitBinaryLocation"].isVoid()) auBinaryLocation = config ["xcodeAudioUnitBinaryLocation"];
  574. if (! config ["xcodeRtasBinaryLocation"].isVoid()) rtasBinaryLocation = config ["xcodeRtasBinaryLocation"];
  575. if (! config ["xcodeAaxBinaryLocation"].isVoid()) aaxBinaryLocation = config ["xcodeAaxBinaryLocation"];
  576. }
  577. void updateOldSDKDefaults()
  578. {
  579. if (iosDeploymentTarget.get() == "default") iosDeploymentTarget.resetToDefault();
  580. if (osxArchitecture.get() == "default") osxArchitecture.resetToDefault();
  581. if (osxSDKVersion.get() == "default") osxSDKVersion.resetToDefault();
  582. if (osxDeploymentTarget.get() == "default") osxDeploymentTarget.resetToDefault();
  583. }
  584. };
  585. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  586. {
  587. return *new XcodeBuildConfiguration (project, v, iOS, *this);
  588. }
  589. public:
  590. //==============================================================================
  591. /* The numbers for these enum values are defined by Xcode for the different
  592. possible destinations of a "copy files" post-build step.
  593. */
  594. enum XcodeCopyFilesDestinationIDs
  595. {
  596. kWrapperFolder = 1,
  597. kExecutablesFolder = 6,
  598. kResourcesFolder = 7,
  599. kFrameworksFolder = 10,
  600. kSharedFrameworksFolder = 11,
  601. kSharedSupportFolder = 12,
  602. kPluginsFolder = 13,
  603. kJavaResourcesFolder = 15,
  604. kXPCServicesFolder = 16
  605. };
  606. //==============================================================================
  607. struct XcodeTarget : ProjectType::Target
  608. {
  609. //==============================================================================
  610. XcodeTarget (ProjectType::Target::Type targetType, const XcodeProjectExporter& exporter)
  611. : ProjectType::Target (targetType),
  612. owner (exporter)
  613. {
  614. switch (type)
  615. {
  616. case GUIApp:
  617. xcodePackageType = "APPL";
  618. xcodeBundleSignature = "????";
  619. xcodeFileType = "wrapper.application";
  620. xcodeBundleExtension = ".app";
  621. xcodeProductType = "com.apple.product-type.application";
  622. xcodeCopyToProductInstallPathAfterBuild = false;
  623. break;
  624. case ConsoleApp:
  625. xcodeFileType = "compiled.mach-o.executable";
  626. xcodeBundleExtension = String();
  627. xcodeProductType = "com.apple.product-type.tool";
  628. xcodeCopyToProductInstallPathAfterBuild = false;
  629. break;
  630. case StaticLibrary:
  631. xcodeFileType = "archive.ar";
  632. xcodeBundleExtension = ".a";
  633. xcodeProductType = "com.apple.product-type.library.static";
  634. xcodeCopyToProductInstallPathAfterBuild = false;
  635. break;
  636. case DynamicLibrary:
  637. xcodeFileType = "compiled.mach-o.dylib";
  638. xcodeProductType = "com.apple.product-type.library.dynamic";
  639. xcodeBundleExtension = ".dylib";
  640. xcodeCopyToProductInstallPathAfterBuild = false;
  641. break;
  642. case VSTPlugIn:
  643. xcodePackageType = "BNDL";
  644. xcodeBundleSignature = "????";
  645. xcodeFileType = "wrapper.cfbundle";
  646. xcodeBundleExtension = ".vst";
  647. xcodeProductType = "com.apple.product-type.bundle";
  648. xcodeCopyToProductInstallPathAfterBuild = true;
  649. break;
  650. case VST3PlugIn:
  651. xcodePackageType = "BNDL";
  652. xcodeBundleSignature = "????";
  653. xcodeFileType = "wrapper.cfbundle";
  654. xcodeBundleExtension = ".vst3";
  655. xcodeProductType = "com.apple.product-type.bundle";
  656. xcodeCopyToProductInstallPathAfterBuild = true;
  657. break;
  658. case AudioUnitPlugIn:
  659. xcodePackageType = "BNDL";
  660. xcodeBundleSignature = "????";
  661. xcodeFileType = "wrapper.cfbundle";
  662. xcodeBundleExtension = ".component";
  663. xcodeProductType = "com.apple.product-type.bundle";
  664. xcodeCopyToProductInstallPathAfterBuild = true;
  665. addExtraAudioUnitTargetSettings();
  666. break;
  667. case StandalonePlugIn:
  668. xcodePackageType = "APPL";
  669. xcodeBundleSignature = "????";
  670. xcodeFileType = "wrapper.application";
  671. xcodeBundleExtension = ".app";
  672. xcodeProductType = "com.apple.product-type.application";
  673. xcodeCopyToProductInstallPathAfterBuild = false;
  674. break;
  675. case AudioUnitv3PlugIn:
  676. xcodePackageType = "XPC!";
  677. xcodeBundleSignature = "????";
  678. xcodeFileType = "wrapper.app-extension";
  679. xcodeBundleExtension = ".appex";
  680. xcodeBundleIDSubPath = "AUv3";
  681. xcodeProductType = "com.apple.product-type.app-extension";
  682. xcodeCopyToProductInstallPathAfterBuild = false;
  683. addExtraAudioUnitv3PlugInTargetSettings();
  684. break;
  685. case AAXPlugIn:
  686. xcodePackageType = "TDMw";
  687. xcodeBundleSignature = "PTul";
  688. xcodeFileType = "wrapper.cfbundle";
  689. xcodeBundleExtension = ".aaxplugin";
  690. xcodeProductType = "com.apple.product-type.bundle";
  691. xcodeCopyToProductInstallPathAfterBuild = true;
  692. break;
  693. case RTASPlugIn:
  694. xcodePackageType = "TDMw";
  695. xcodeBundleSignature = "PTul";
  696. xcodeFileType = "wrapper.cfbundle";
  697. xcodeBundleExtension = ".dpm";
  698. xcodeProductType = "com.apple.product-type.bundle";
  699. xcodeCopyToProductInstallPathAfterBuild = true;
  700. break;
  701. case UnityPlugIn:
  702. xcodePackageType = "BNDL";
  703. xcodeBundleSignature = "????";
  704. xcodeFileType = "wrapper.cfbundle";
  705. xcodeBundleExtension = ".bundle";
  706. xcodeProductType = "com.apple.product-type.bundle";
  707. xcodeCopyToProductInstallPathAfterBuild = true;
  708. break;
  709. case SharedCodeTarget:
  710. xcodeFileType = "archive.ar";
  711. xcodeBundleExtension = ".a";
  712. xcodeProductType = "com.apple.product-type.library.static";
  713. xcodeCopyToProductInstallPathAfterBuild = false;
  714. break;
  715. case AggregateTarget:
  716. xcodeCopyToProductInstallPathAfterBuild = false;
  717. break;
  718. default:
  719. // unknown target type!
  720. jassertfalse;
  721. break;
  722. }
  723. }
  724. String getXcodeSchemeName() const
  725. {
  726. return owner.projectName + " - " + getName();
  727. }
  728. String getID() const
  729. {
  730. return owner.createID (String ("__target") + getName());
  731. }
  732. String getInfoPlistName() const
  733. {
  734. return String ("Info-") + String (getName()).replace (" ", "_") + String (".plist");
  735. }
  736. String xcodePackageType, xcodeBundleSignature, xcodeBundleExtension;
  737. String xcodeProductType, xcodeFileType;
  738. String xcodeOtherRezFlags, xcodeBundleIDSubPath;
  739. bool xcodeCopyToProductInstallPathAfterBuild;
  740. StringArray xcodeFrameworks, xcodeLibs;
  741. Array<XmlElement> xcodeExtraPListEntries;
  742. StringArray frameworkIDs, buildPhaseIDs, configIDs, sourceIDs, rezFileIDs;
  743. StringArray frameworkNames;
  744. String dependencyID, mainBuildProductID;
  745. File infoPlistFile;
  746. struct SourceFileInfo
  747. {
  748. RelativePath path;
  749. bool shouldBeCompiled = false;
  750. };
  751. Array<SourceFileInfo> getSourceFilesInfo (const Project::Item& projectItem) const
  752. {
  753. Array<SourceFileInfo> result;
  754. auto targetType = (owner.getProject().getProjectType().isAudioPlugin() ? type : SharedCodeTarget);
  755. if (projectItem.isGroup())
  756. {
  757. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  758. result.addArray (getSourceFilesInfo (projectItem.getChild (i)));
  759. }
  760. else if (projectItem.shouldBeAddedToTargetProject()
  761. && owner.getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
  762. {
  763. SourceFileInfo info;
  764. info.path = RelativePath (projectItem.getFile(), owner.getTargetFolder(), RelativePath::buildTargetFolder);
  765. jassert (info.path.getRoot() == RelativePath::buildTargetFolder);
  766. if (targetType == SharedCodeTarget || projectItem.shouldBeCompiled())
  767. info.shouldBeCompiled = projectItem.shouldBeCompiled();
  768. result.add (info);
  769. }
  770. return result;
  771. }
  772. //==============================================================================
  773. void addMainBuildProduct() const
  774. {
  775. jassert (xcodeFileType.isNotEmpty());
  776. jassert (xcodeBundleExtension.isEmpty() || xcodeBundleExtension.startsWithChar ('.'));
  777. if (ProjectExporter::BuildConfiguration::Ptr config = owner.getConfiguration(0))
  778. {
  779. auto productName = owner.replacePreprocessorTokens (*config, config->getTargetBinaryNameString (type == UnityPlugIn));
  780. if (xcodeFileType == "archive.ar")
  781. productName = getStaticLibbedFilename (productName);
  782. else
  783. productName += xcodeBundleExtension;
  784. addBuildProduct (xcodeFileType, productName);
  785. }
  786. }
  787. //==============================================================================
  788. void addBuildProduct (const String& fileType, const String& binaryName) const
  789. {
  790. auto* v = new ValueTree (owner.createID (String ("__productFileID") + getName()));
  791. v->setProperty ("isa", "PBXFileReference", nullptr);
  792. v->setProperty ("explicitFileType", fileType, nullptr);
  793. v->setProperty ("includeInIndex", (int) 0, nullptr);
  794. v->setProperty ("path", sanitisePath (binaryName), nullptr);
  795. v->setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);
  796. owner.pbxFileReferences.add (v);
  797. }
  798. //==============================================================================
  799. void addDependency()
  800. {
  801. jassert (dependencyID.isEmpty());
  802. dependencyID = owner.createID (String ("__dependency") + getName());
  803. auto* v = new ValueTree (dependencyID);
  804. v->setProperty ("isa", "PBXTargetDependency", nullptr);
  805. v->setProperty ("target", getID(), nullptr);
  806. owner.misc.add (v);
  807. }
  808. String getDependencyID() const
  809. {
  810. jassert (dependencyID.isNotEmpty());
  811. return dependencyID;
  812. }
  813. //==============================================================================
  814. void addTargetConfig (const String& configName, const StringArray& buildSettings)
  815. {
  816. auto configID = owner.createID (String ("targetconfigid_") + getName() + String ("_") + configName);
  817. auto* v = new ValueTree (configID);
  818. v->setProperty ("isa", "XCBuildConfiguration", nullptr);
  819. v->setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
  820. v->setProperty (Ids::name, configName, nullptr);
  821. configIDs.add (configID);
  822. owner.targetConfigs.add (v);
  823. }
  824. //==============================================================================
  825. String getTargetAttributes() const
  826. {
  827. auto attributes = getID() + " = { ";
  828. auto developmentTeamID = owner.getIosDevelopmentTeamIDString();
  829. if (developmentTeamID.isNotEmpty())
  830. {
  831. attributes << "DevelopmentTeam = " << developmentTeamID << "; ";
  832. attributes << "ProvisioningStyle = Automatic; ";
  833. }
  834. auto appGroupsEnabled = (owner.iOS && owner.isAppGroupsEnabled() ? 1 : 0);
  835. auto inAppPurchasesEnabled = owner.isInAppPurchasesEnabled() ? 1 : 0;
  836. auto interAppAudioEnabled = (owner.iOS
  837. && type == Target::StandalonePlugIn
  838. && owner.getProject().shouldEnableIAA()) ? 1 : 0;
  839. auto pushNotificationsEnabled = owner.isPushNotificationsEnabled() ? 1 : 0;
  840. auto sandboxEnabled = (type == Target::AudioUnitv3PlugIn ? 1 : 0);
  841. auto hardendedRuntimeEnabled = owner.isHardenedRuntimeEnabled() ? 1 : 0;
  842. attributes << "SystemCapabilities = {";
  843. attributes << "com.apple.ApplicationGroups.iOS = { enabled = " << appGroupsEnabled << "; }; ";
  844. attributes << "com.apple.InAppPurchase = { enabled = " << inAppPurchasesEnabled << "; }; ";
  845. attributes << "com.apple.InterAppAudio = { enabled = " << interAppAudioEnabled << "; }; ";
  846. attributes << "com.apple.Push = { enabled = " << pushNotificationsEnabled << "; }; ";
  847. attributes << "com.apple.Sandbox = { enabled = " << sandboxEnabled << "; }; ";
  848. attributes << "com.apple.HardenedRuntime = { enabled = " << hardendedRuntimeEnabled << "; }; ";
  849. if (owner.iOS && owner.isiCloudPermissionsEnabled())
  850. attributes << "com.apple.iCloud = { enabled = 1; }; ";
  851. attributes << "}; };";
  852. return attributes;
  853. }
  854. //==============================================================================
  855. ValueTree& addBuildPhase (const String& buildPhaseType, const StringArray& fileIds, const StringRef humanReadableName = StringRef())
  856. {
  857. auto buildPhaseName = buildPhaseType + "_" + getName() + "_" + (humanReadableName.isNotEmpty() ? String (humanReadableName) : String ("resbuildphase"));
  858. auto buildPhaseId (owner.createID (buildPhaseName));
  859. int n = 0;
  860. while (buildPhaseIDs.contains (buildPhaseId))
  861. buildPhaseId = owner.createID (buildPhaseName + String (++n));
  862. buildPhaseIDs.add (buildPhaseId);
  863. auto* v = new ValueTree (buildPhaseId);
  864. v->setProperty ("isa", buildPhaseType, nullptr);
  865. v->setProperty ("buildActionMask", "2147483647", nullptr);
  866. v->setProperty ("files", indentParenthesisedList (fileIds), nullptr);
  867. v->setProperty ("runOnlyForDeploymentPostprocessing", (int) 0, nullptr);
  868. if (humanReadableName.isNotEmpty())
  869. v->setProperty ("name", String (humanReadableName), nullptr);
  870. owner.misc.add (v);
  871. return *v;
  872. }
  873. bool shouldCreatePList() const
  874. {
  875. auto fileType = getTargetFileType();
  876. return (fileType == executable && type != ConsoleApp) || fileType == pluginBundle || fileType == macOSAppex;
  877. }
  878. //==============================================================================
  879. bool shouldAddEntitlements() const
  880. {
  881. if (owner.isPushNotificationsEnabled()
  882. || owner.isAppGroupsEnabled()
  883. || owner.isHardenedRuntimeEnabled()
  884. || (owner.isiOS() && owner.isiCloudPermissionsEnabled()))
  885. return true;
  886. if (owner.project.getProjectType().isAudioPlugin()
  887. && ( (owner.isOSX() && type == Target::AudioUnitv3PlugIn)
  888. || (owner.isiOS() && type == Target::StandalonePlugIn && owner.getProject().shouldEnableIAA())))
  889. return true;
  890. return false;
  891. }
  892. String getBundleIdentifier() const
  893. {
  894. auto exporterBundleIdentifier = owner.exporterBundleIdentifierValue.get().toString();
  895. auto bundleIdentifier = exporterBundleIdentifier.isNotEmpty() ? exporterBundleIdentifier
  896. : owner.project.getBundleIdentifierString();
  897. if (xcodeBundleIDSubPath.isNotEmpty())
  898. {
  899. auto bundleIdSegments = StringArray::fromTokens (bundleIdentifier, ".", StringRef());
  900. jassert (bundleIdSegments.size() > 0);
  901. bundleIdentifier += String (".") + bundleIdSegments[bundleIdSegments.size() - 1] + xcodeBundleIDSubPath;
  902. }
  903. return bundleIdentifier;
  904. }
  905. //==============================================================================
  906. StringPairArray getTargetSettings (const XcodeBuildConfiguration& config) const
  907. {
  908. StringPairArray s;
  909. if (type == AggregateTarget && ! owner.isiOS())
  910. {
  911. // the aggregate target needs to have the deployment target set for
  912. // pre-/post-build scripts
  913. String sdkRoot;
  914. s.set ("MACOSX_DEPLOYMENT_TARGET", getOSXDeploymentTarget (config, &sdkRoot));
  915. if (sdkRoot.isNotEmpty())
  916. s.set ("SDKROOT", sdkRoot);
  917. return s;
  918. }
  919. s.set ("PRODUCT_NAME", owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString (type == UnityPlugIn)).quoted());
  920. s.set ("PRODUCT_BUNDLE_IDENTIFIER", getBundleIdentifier());
  921. auto arch = (! owner.isiOS() && type == Target::AudioUnitv3PlugIn) ? osxArch_64Bit
  922. : config.getOSXArchitectureString();
  923. if (arch == osxArch_Native) s.set ("ARCHS", "\"$(NATIVE_ARCH_ACTUAL)\"");
  924. else if (arch == osxArch_32BitUniversal) s.set ("ARCHS", "\"$(ARCHS_STANDARD_32_BIT)\"");
  925. else if (arch == osxArch_64BitUniversal) s.set ("ARCHS", "\"$(ARCHS_STANDARD_32_64_BIT)\"");
  926. else if (arch == osxArch_64Bit) s.set ("ARCHS", "\"$(ARCHS_STANDARD_64_BIT)\"");
  927. StringArray headerPaths (getHeaderSearchPaths (config));
  928. headerPaths.add ("\"$(inherited)\"");
  929. s.set ("HEADER_SEARCH_PATHS", indentParenthesisedList (headerPaths, 1));
  930. s.set ("USE_HEADERMAP", String (static_cast<bool> (config.exporter.settings.getProperty ("useHeaderMap")) ? "YES" : "NO"));
  931. auto frameworkSearchPaths = getFrameworkSearchPaths (config);
  932. if (! frameworkSearchPaths.isEmpty())
  933. s.set ("FRAMEWORK_SEARCH_PATHS", String ("(") + frameworkSearchPaths.joinIntoString (", ") + ", \"$(inherited)\")");
  934. s.set ("GCC_OPTIMIZATION_LEVEL", config.getGCCOptimisationFlag());
  935. if (shouldCreatePList())
  936. {
  937. s.set ("INFOPLIST_FILE", infoPlistFile.getFileName());
  938. if (owner.getPListPrefixHeaderString().isNotEmpty())
  939. s.set ("INFOPLIST_PREFIX_HEADER", owner.getPListPrefixHeaderString());
  940. s.set ("INFOPLIST_PREPROCESS", (owner.isPListPreprocessEnabled() ? String ("YES") : String ("NO")));
  941. auto plistDefs = parsePreprocessorDefs (config.getPListPreprocessorDefinitionsString());
  942. StringArray defsList;
  943. for (int i = 0; i < plistDefs.size(); ++i)
  944. {
  945. auto def = plistDefs.getAllKeys()[i];
  946. auto value = plistDefs.getAllValues()[i];
  947. if (value.isNotEmpty())
  948. def << "=" << value.replace ("\"", "\\\\\\\"");
  949. defsList.add ("\"" + def + "\"");
  950. }
  951. if (defsList.size() > 0)
  952. s.set ("INFOPLIST_PREPROCESSOR_DEFINITIONS", indentParenthesisedList (defsList, 1));
  953. }
  954. if (config.isLinkTimeOptimisationEnabled())
  955. s.set ("LLVM_LTO", "YES");
  956. if (config.isFastMathEnabled())
  957. s.set ("GCC_FAST_MATH", "YES");
  958. auto extraFlags = owner.replacePreprocessorTokens (config, owner.getExtraCompilerFlagsString()).trim();
  959. if (extraFlags.isNotEmpty())
  960. s.set ("OTHER_CPLUSPLUSFLAGS", extraFlags.quoted());
  961. auto installPath = getInstallPathForConfiguration (config);
  962. if (installPath.startsWith ("~"))
  963. installPath = installPath.replace ("~", "$(HOME)");
  964. if (installPath.isNotEmpty())
  965. {
  966. s.set ("INSTALL_PATH", installPath.quoted());
  967. if (type == Target::SharedCodeTarget)
  968. s.set ("SKIP_INSTALL", "YES");
  969. if (! owner.embeddedFrameworkIDs.isEmpty())
  970. s.set ("LD_RUNPATH_SEARCH_PATHS", "\"$(inherited) @executable_path/Frameworks @executable_path/../Frameworks\"");
  971. if (xcodeCopyToProductInstallPathAfterBuild)
  972. {
  973. s.set ("DEPLOYMENT_LOCATION", "YES");
  974. s.set ("DSTROOT", "/");
  975. }
  976. }
  977. if (getTargetFileType() == pluginBundle)
  978. {
  979. s.set ("LIBRARY_STYLE", "Bundle");
  980. s.set ("WRAPPER_EXTENSION", xcodeBundleExtension.substring (1));
  981. s.set ("GENERATE_PKGINFO_FILE", "YES");
  982. }
  983. if (xcodeOtherRezFlags.isNotEmpty())
  984. s.set ("OTHER_REZFLAGS", "\"" + xcodeOtherRezFlags + "\"");
  985. String configurationBuildDir ("$(PROJECT_DIR)/build/$(CONFIGURATION)");
  986. if (config.getTargetBinaryRelativePathString().isNotEmpty())
  987. {
  988. // a target's position can either be defined via installPath + xcodeCopyToProductInstallPathAfterBuild
  989. // (= for audio plug-ins) or using a custom binary path (for everything else), but not both (= conflict!)
  990. jassert (! xcodeCopyToProductInstallPathAfterBuild);
  991. RelativePath binaryPath (config.getTargetBinaryRelativePathString(), RelativePath::projectFolder);
  992. configurationBuildDir = sanitisePath (binaryPath.rebased (owner.projectFolder, owner.getTargetFolder(), RelativePath::buildTargetFolder)
  993. .toUnixStyle());
  994. }
  995. s.set ("CONFIGURATION_BUILD_DIR", addQuotesIfRequired (configurationBuildDir));
  996. if (owner.isHardenedRuntimeEnabled())
  997. s.set ("ENABLE_HARDENED_RUNTIME", "YES");
  998. String gccVersion ("com.apple.compilers.llvm.clang.1_0");
  999. if (owner.iOS)
  1000. {
  1001. s.set ("ASSETCATALOG_COMPILER_APPICON_NAME", "AppIcon");
  1002. s.set ("ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME", "LaunchImage");
  1003. }
  1004. else
  1005. {
  1006. String sdkRoot;
  1007. s.set ("MACOSX_DEPLOYMENT_TARGET", getOSXDeploymentTarget (config, &sdkRoot));
  1008. if (sdkRoot.isNotEmpty())
  1009. s.set ("SDKROOT", sdkRoot);
  1010. }
  1011. s.set ("GCC_VERSION", gccVersion);
  1012. s.set ("CLANG_LINK_OBJC_RUNTIME", "NO");
  1013. if (isUsingCodeSigning (config))
  1014. {
  1015. s.set (owner.iOS ? "\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"" : "CODE_SIGN_IDENTITY",
  1016. config.getCodeSignIdentityString().quoted());
  1017. s.set ("PROVISIONING_PROFILE_SPECIFIER", "\"\"");
  1018. }
  1019. if (owner.getIosDevelopmentTeamIDString().isNotEmpty())
  1020. s.set ("DEVELOPMENT_TEAM", owner.getIosDevelopmentTeamIDString());
  1021. if (shouldAddEntitlements())
  1022. s.set ("CODE_SIGN_ENTITLEMENTS", owner.getEntitlementsFileName().quoted());
  1023. {
  1024. auto cppStandard = owner.project.getCppStandardString();
  1025. if (cppStandard == "latest")
  1026. cppStandard = "17";
  1027. s.set ("CLANG_CXX_LANGUAGE_STANDARD", (String (owner.shouldUseGNUExtensions() ? "gnu++"
  1028. : "c++") + cppStandard).quoted());
  1029. }
  1030. s.set ("CLANG_CXX_LIBRARY", "\"libc++\"");
  1031. s.set ("COMBINE_HIDPI_IMAGES", "YES");
  1032. {
  1033. StringArray linkerFlags, librarySearchPaths;
  1034. getLinkerSettings (config, linkerFlags, librarySearchPaths);
  1035. if (linkerFlags.size() > 0)
  1036. s.set ("OTHER_LDFLAGS", linkerFlags.joinIntoString (" ").quoted());
  1037. librarySearchPaths.addArray (config.getLibrarySearchPaths());
  1038. librarySearchPaths = getCleanedStringArray (librarySearchPaths);
  1039. if (librarySearchPaths.size() > 0)
  1040. {
  1041. StringArray libPaths;
  1042. libPaths.add ("\"$(inherited)\"");
  1043. for (auto& p : librarySearchPaths)
  1044. libPaths.add ("\"\\\"" + p + "\\\"\"");
  1045. s.set ("LIBRARY_SEARCH_PATHS", indentParenthesisedList (libPaths, 1));
  1046. }
  1047. }
  1048. StringPairArray defines;
  1049. if (config.isDebug())
  1050. {
  1051. defines.set ("_DEBUG", "1");
  1052. defines.set ("DEBUG", "1");
  1053. s.set ("COPY_PHASE_STRIP", "NO");
  1054. s.set ("GCC_DYNAMIC_NO_PIC", "NO");
  1055. }
  1056. else
  1057. {
  1058. defines.set ("_NDEBUG", "1");
  1059. defines.set ("NDEBUG", "1");
  1060. s.set ("GCC_GENERATE_DEBUGGING_SYMBOLS", "NO");
  1061. s.set ("GCC_SYMBOLS_PRIVATE_EXTERN", "YES");
  1062. s.set ("DEAD_CODE_STRIPPING", "YES");
  1063. }
  1064. if (type != Target::SharedCodeTarget && type != Target::StaticLibrary && type != Target::DynamicLibrary
  1065. && config.isStripLocalSymbolsEnabled())
  1066. {
  1067. s.set ("STRIPFLAGS", "\"-x\"");
  1068. s.set ("DEPLOYMENT_POSTPROCESSING", "YES");
  1069. s.set ("SEPARATE_STRIP", "YES");
  1070. }
  1071. if (owner.isInAppPurchasesEnabled())
  1072. defines.set ("JUCE_IN_APP_PURCHASES", "1");
  1073. if (owner.isPushNotificationsEnabled())
  1074. defines.set ("JUCE_PUSH_NOTIFICATIONS", "1");
  1075. defines = mergePreprocessorDefs (defines, owner.getAllPreprocessorDefs (config, type));
  1076. StringArray defsList;
  1077. for (int i = 0; i < defines.size(); ++i)
  1078. {
  1079. auto def = defines.getAllKeys()[i];
  1080. auto value = defines.getAllValues()[i];
  1081. if (value.isNotEmpty())
  1082. def << "=" << value.replace ("\"", "\\\\\\\"");
  1083. defsList.add ("\"" + def + "\"");
  1084. }
  1085. s.set ("GCC_PREPROCESSOR_DEFINITIONS", indentParenthesisedList (defsList, 1));
  1086. StringArray customFlags;
  1087. customFlags.addTokens (config.getCustomXcodeFlagsString(), ",", "\"'");
  1088. customFlags.removeEmptyStrings();
  1089. for (auto flag : customFlags)
  1090. {
  1091. s.set (flag.upToFirstOccurrenceOf ("=", false, false).trim(),
  1092. flag.fromFirstOccurrenceOf ("=", false, false).trim().quoted());
  1093. }
  1094. return s;
  1095. }
  1096. String getInstallPathForConfiguration (const XcodeBuildConfiguration& config) const
  1097. {
  1098. switch (type)
  1099. {
  1100. case GUIApp: return "$(HOME)/Applications";
  1101. case ConsoleApp: return "/usr/bin";
  1102. case VSTPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getVSTBinaryLocationString() : String();
  1103. case VST3PlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getVST3BinaryLocationString() : String();
  1104. case AudioUnitPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getAUBinaryLocationString() : String();
  1105. case RTASPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getRTASBinaryLocationString() : String();
  1106. case AAXPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getAAXBinaryLocationString() : String();
  1107. case UnityPlugIn: return config.isPluginBinaryCopyStepEnabled() ? config.getUnityPluginBinaryLocationString() : String();
  1108. case SharedCodeTarget: return owner.isiOS() ? "@executable_path/Frameworks" : "@executable_path/../Frameworks";
  1109. default: return {};
  1110. }
  1111. }
  1112. //==============================================================================
  1113. void getLinkerSettings (const BuildConfiguration& config, StringArray& flags, StringArray& librarySearchPaths) const
  1114. {
  1115. if (getTargetFileType() == pluginBundle)
  1116. flags.add (owner.isiOS() ? "-bitcode_bundle" : "-bundle");
  1117. Array<RelativePath> extraLibs;
  1118. addExtraLibsForTargetType (config, extraLibs);
  1119. for (auto& lib : extraLibs)
  1120. {
  1121. flags.add (getLinkerFlagForLib (lib.getFileNameWithoutExtension()));
  1122. librarySearchPaths.add (owner.getSearchPathForStaticLibrary (lib));
  1123. }
  1124. if (owner.project.getProjectType().isAudioPlugin() && type != Target::SharedCodeTarget)
  1125. {
  1126. if (owner.getTargetOfType (Target::SharedCodeTarget) != nullptr)
  1127. {
  1128. auto productName = getStaticLibbedFilename (owner.replacePreprocessorTokens (config, config.getTargetBinaryNameString()));
  1129. RelativePath sharedCodelib (productName, RelativePath::buildTargetFolder);
  1130. flags.add (getLinkerFlagForLib (sharedCodelib.getFileNameWithoutExtension()));
  1131. }
  1132. }
  1133. flags.add (owner.replacePreprocessorTokens (config, owner.getExtraLinkerFlagsString()));
  1134. flags.add (owner.getExternalLibraryFlags (config));
  1135. auto libs = owner.xcodeLibs;
  1136. libs.addArray (xcodeLibs);
  1137. for (auto& l : libs)
  1138. flags.add (getLinkerFlagForLib (l));
  1139. flags = getCleanedStringArray (flags);
  1140. }
  1141. //========================================================================== c
  1142. void writeInfoPlistFile() const
  1143. {
  1144. if (! shouldCreatePList())
  1145. return;
  1146. auto plist = parseXML (owner.getPListToMergeString());
  1147. if (plist == nullptr || ! plist->hasTagName ("plist"))
  1148. plist.reset (new XmlElement ("plist"));
  1149. auto* dict = plist->getChildByName ("dict");
  1150. if (dict == nullptr)
  1151. dict = plist->createNewChildElement ("dict");
  1152. if (owner.isMicrophonePermissionEnabled())
  1153. addPlistDictionaryKey (dict, "NSMicrophoneUsageDescription", owner.getMicrophonePermissionsTextString());
  1154. if (owner.isCameraPermissionEnabled())
  1155. addPlistDictionaryKey (dict, "NSCameraUsageDescription", owner.getCameraPermissionTextString());
  1156. if (owner.iOS)
  1157. {
  1158. addPlistDictionaryKeyBool (dict, "LSRequiresIPhoneOS", true);
  1159. if (type != AudioUnitv3PlugIn)
  1160. addPlistDictionaryKeyBool (dict, "UIViewControllerBasedStatusBarAppearance", false);
  1161. if (owner.shouldAddStoryboardToProject())
  1162. {
  1163. auto customStoryboard = owner.getCustomLaunchStoryboardString();
  1164. addPlistDictionaryKey (dict, "UILaunchStoryboardName", customStoryboard.isNotEmpty() ? customStoryboard.fromLastOccurrenceOf ("/", false, false)
  1165. .upToLastOccurrenceOf (".storyboard", false, false)
  1166. : owner.getDefaultLaunchStoryboardName());
  1167. }
  1168. }
  1169. addPlistDictionaryKey (dict, "CFBundleExecutable", "${EXECUTABLE_NAME}");
  1170. if (! owner.iOS) // (NB: on iOS this causes error ITMS-90032 during publishing)
  1171. addPlistDictionaryKey (dict, "CFBundleIconFile", owner.iconFile.exists() ? owner.iconFile.getFileName() : String());
  1172. addPlistDictionaryKey (dict, "CFBundleIdentifier", getBundleIdentifier());
  1173. addPlistDictionaryKey (dict, "CFBundleName", owner.projectName);
  1174. // needed by NSExtension on iOS
  1175. addPlistDictionaryKey (dict, "CFBundleDisplayName", owner.projectName);
  1176. addPlistDictionaryKey (dict, "CFBundlePackageType", xcodePackageType);
  1177. addPlistDictionaryKey (dict, "CFBundleSignature", xcodeBundleSignature);
  1178. addPlistDictionaryKey (dict, "CFBundleShortVersionString", owner.project.getVersionString());
  1179. addPlistDictionaryKey (dict, "CFBundleVersion", owner.project.getVersionString());
  1180. addPlistDictionaryKey (dict, "NSHumanReadableCopyright", owner.project.getCompanyCopyrightString());
  1181. addPlistDictionaryKeyBool (dict, "NSHighResolutionCapable", true);
  1182. auto documentExtensions = StringArray::fromTokens (replacePreprocessorDefs (owner.getAllPreprocessorDefs(),
  1183. owner.getDocumentExtensionsString()), ",", {});
  1184. documentExtensions.trim();
  1185. documentExtensions.removeEmptyStrings (true);
  1186. if (documentExtensions.size() > 0 && type != AudioUnitv3PlugIn)
  1187. {
  1188. dict->createNewChildElement ("key")->addTextElement ("CFBundleDocumentTypes");
  1189. auto* dict2 = dict->createNewChildElement ("array")->createNewChildElement ("dict");
  1190. XmlElement* arrayTag = nullptr;
  1191. for (auto ex : documentExtensions)
  1192. {
  1193. if (ex.startsWithChar ('.'))
  1194. ex = ex.substring (1);
  1195. if (arrayTag == nullptr)
  1196. {
  1197. dict2->createNewChildElement ("key")->addTextElement ("CFBundleTypeExtensions");
  1198. arrayTag = dict2->createNewChildElement ("array");
  1199. addPlistDictionaryKey (dict2, "CFBundleTypeName", ex);
  1200. addPlistDictionaryKey (dict2, "CFBundleTypeRole", "Editor");
  1201. addPlistDictionaryKey (dict2, "CFBundleTypeIconFile", "Icon");
  1202. addPlistDictionaryKey (dict2, "NSPersistentStoreTypeKey", "XML");
  1203. }
  1204. arrayTag->createNewChildElement ("string")->addTextElement (ex);
  1205. }
  1206. }
  1207. if (owner.isFileSharingEnabled() && type != AudioUnitv3PlugIn)
  1208. addPlistDictionaryKeyBool (dict, "UIFileSharingEnabled", true);
  1209. if (owner.isDocumentBrowserEnabled())
  1210. addPlistDictionaryKeyBool (dict, "UISupportsDocumentBrowser", true);
  1211. if (owner.isStatusBarHidden() && type != AudioUnitv3PlugIn)
  1212. addPlistDictionaryKeyBool (dict, "UIStatusBarHidden", true);
  1213. if (owner.iOS)
  1214. {
  1215. if (type != AudioUnitv3PlugIn)
  1216. {
  1217. // Forcing full screen disables the split screen feature and prevents error ITMS-90475
  1218. addPlistDictionaryKeyBool (dict, "UIRequiresFullScreen", true);
  1219. addPlistDictionaryKeyBool (dict, "UIStatusBarHidden", true);
  1220. addIosScreenOrientations (dict);
  1221. addIosBackgroundModes (dict);
  1222. }
  1223. if (type == StandalonePlugIn && owner.getProject().shouldEnableIAA())
  1224. {
  1225. XmlElement audioComponentsPlistKey ("key");
  1226. audioComponentsPlistKey.addTextElement ("AudioComponents");
  1227. dict->addChildElement (new XmlElement (audioComponentsPlistKey));
  1228. XmlElement audioComponentsPlistEntry ("array");
  1229. auto* audioComponentsDict = audioComponentsPlistEntry.createNewChildElement ("dict");
  1230. addPlistDictionaryKey (audioComponentsDict, "name", owner.project.getIAAPluginName());
  1231. addPlistDictionaryKey (audioComponentsDict, "manufacturer", owner.project.getPluginManufacturerCodeString().substring (0, 4));
  1232. addPlistDictionaryKey (audioComponentsDict, "type", owner.project.getIAATypeCode());
  1233. addPlistDictionaryKey (audioComponentsDict, "subtype", owner.project.getPluginCodeString().substring (0, 4));
  1234. addPlistDictionaryKeyInt (audioComponentsDict, "version", owner.project.getVersionAsHexInteger());
  1235. dict->addChildElement (new XmlElement (audioComponentsPlistEntry));
  1236. }
  1237. }
  1238. for (auto& e : xcodeExtraPListEntries)
  1239. dict->addChildElement (new XmlElement (e));
  1240. MemoryOutputStream mo;
  1241. plist->writeToStream (mo, "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
  1242. overwriteFileIfDifferentOrThrow (infoPlistFile, mo);
  1243. }
  1244. //==============================================================================
  1245. void addIosScreenOrientations (XmlElement* dict) const
  1246. {
  1247. String screenOrientations[2] = { owner.getiPhoneScreenOrientationString(), owner.getiPadScreenOrientationString() };
  1248. String plistSuffix[2] = { "", "~ipad" };
  1249. auto orientationsAreTheSame = ( screenOrientations[0] == screenOrientations[1] );
  1250. for (int i = 0; i < (orientationsAreTheSame ? 1 : 2); ++i)
  1251. {
  1252. StringArray iOSOrientations;
  1253. if (screenOrientations[i].contains ("portrait")) { iOSOrientations.add ("UIInterfaceOrientationPortrait"); }
  1254. if (screenOrientations[i].contains ("landscape")) { iOSOrientations.add ("UIInterfaceOrientationLandscapeLeft"); iOSOrientations.add ("UIInterfaceOrientationLandscapeRight"); }
  1255. addArrayToPlist (dict, String ("UISupportedInterfaceOrientations") + plistSuffix[i], iOSOrientations);
  1256. }
  1257. }
  1258. //==============================================================================
  1259. void addIosBackgroundModes (XmlElement* dict) const
  1260. {
  1261. StringArray iosBackgroundModes;
  1262. if (owner.isBackgroundAudioEnabled()) iosBackgroundModes.add ("audio");
  1263. if (owner.isBackgroundBleEnabled()) iosBackgroundModes.add ("bluetooth-central");
  1264. if (owner.isPushNotificationsEnabled()) iosBackgroundModes.add ("remote-notification");
  1265. addArrayToPlist (dict, "UIBackgroundModes", iosBackgroundModes);
  1266. }
  1267. //==============================================================================
  1268. static void addArrayToPlist (XmlElement* dict, String arrayKey, const StringArray& arrayElements)
  1269. {
  1270. dict->createNewChildElement ("key")->addTextElement (arrayKey);
  1271. auto* plistStringArray = dict->createNewChildElement ("array");
  1272. for (auto& e : arrayElements)
  1273. plistStringArray->createNewChildElement ("string")->addTextElement (e);
  1274. }
  1275. //==============================================================================
  1276. void addShellScriptBuildPhase (const String& phaseName, const String& script)
  1277. {
  1278. if (script.trim().isNotEmpty())
  1279. {
  1280. auto& v = addBuildPhase ("PBXShellScriptBuildPhase", {});
  1281. v.setProperty (Ids::name, phaseName, nullptr);
  1282. v.setProperty ("shellPath", "/bin/sh", nullptr);
  1283. v.setProperty ("shellScript", script.replace ("\\", "\\\\")
  1284. .replace ("\"", "\\\"")
  1285. .replace ("\r\n", "\\n")
  1286. .replace ("\n", "\\n"), nullptr);
  1287. }
  1288. }
  1289. void addCopyFilesPhase (const String& phaseName, const StringArray& files, XcodeCopyFilesDestinationIDs dst)
  1290. {
  1291. auto& v = addBuildPhase ("PBXCopyFilesBuildPhase", files, phaseName);
  1292. v.setProperty ("dstPath", "", nullptr);
  1293. v.setProperty ("dstSubfolderSpec", (int) dst, nullptr);
  1294. }
  1295. //==============================================================================
  1296. void sanitiseAndEscapeSearchPaths (const BuildConfiguration& config, StringArray& paths) const
  1297. {
  1298. paths = getCleanedStringArray (paths);
  1299. for (auto& path : paths)
  1300. {
  1301. // Xcode 10 can't deal with search paths starting with "~" so we need to replace them here...
  1302. path = owner.replacePreprocessorTokens (config, sanitisePath (path));
  1303. if (path.containsChar (' '))
  1304. path = "\"\\\"" + path + "\\\"\""; // crazy double quotes required when there are spaces..
  1305. else
  1306. path = "\"" + path + "\"";
  1307. }
  1308. }
  1309. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  1310. {
  1311. StringArray paths (owner.extraSearchPaths);
  1312. paths.addArray (config.getHeaderSearchPaths());
  1313. paths.addArray (getTargetExtraHeaderSearchPaths());
  1314. if (owner.project.getEnabledModules().isModuleEnabled ("juce_audio_plugin_client"))
  1315. {
  1316. // Needed to compile .r files
  1317. paths.add (owner.getModuleFolderRelativeToProject ("juce_audio_plugin_client")
  1318. .rebased (owner.projectFolder, owner.getTargetFolder(), RelativePath::buildTargetFolder)
  1319. .toUnixStyle());
  1320. }
  1321. sanitiseAndEscapeSearchPaths (config, paths);
  1322. return paths;
  1323. }
  1324. StringArray getFrameworkSearchPaths (const BuildConfiguration& config) const
  1325. {
  1326. auto paths = getSearchPathsFromString (owner.getFrameworkSearchPathsString());
  1327. sanitiseAndEscapeSearchPaths (config, paths);
  1328. return paths;
  1329. }
  1330. private:
  1331. //==============================================================================
  1332. void addExtraAudioUnitTargetSettings()
  1333. {
  1334. xcodeOtherRezFlags = "-d ppc_$ppc -d i386_$i386 -d ppc64_$ppc64 -d x86_64_$x86_64"
  1335. " -I /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Versions/A/Headers"
  1336. " -I \\\"$(DEVELOPER_DIR)/Extras/CoreAudio/AudioUnits/AUPublic/AUBase\\\"";
  1337. xcodeFrameworks.addTokens ("AudioUnit CoreAudioKit", false);
  1338. XmlElement plistKey ("key");
  1339. plistKey.addTextElement ("AudioComponents");
  1340. XmlElement plistEntry ("array");
  1341. auto* dict = plistEntry.createNewChildElement ("dict");
  1342. auto pluginManufacturerCode = owner.project.getPluginManufacturerCodeString().substring (0, 4);
  1343. auto pluginSubType = owner.project.getPluginCodeString().substring (0, 4);
  1344. if (pluginManufacturerCode.toLowerCase() == pluginManufacturerCode)
  1345. {
  1346. throw SaveError ("AudioUnit plugin code identifiers invalid!\n\n"
  1347. "You have used only lower case letters in your AU plugin manufacturer identifier. "
  1348. "You must have at least one uppercase letter in your AU plugin manufacturer "
  1349. "identifier code.");
  1350. }
  1351. addPlistDictionaryKey (dict, "name", owner.project.getPluginManufacturerString()
  1352. + ": " + owner.project.getPluginNameString());
  1353. addPlistDictionaryKey (dict, "description", owner.project.getPluginDescriptionString());
  1354. addPlistDictionaryKey (dict, "factoryFunction", owner.project.getPluginAUExportPrefixString() + "Factory");
  1355. addPlistDictionaryKey (dict, "manufacturer", pluginManufacturerCode);
  1356. addPlistDictionaryKey (dict, "type", owner.project.getAUMainTypeString().removeCharacters ("'"));
  1357. addPlistDictionaryKey (dict, "subtype", pluginSubType);
  1358. addPlistDictionaryKeyInt (dict, "version", owner.project.getVersionAsHexInteger());
  1359. if (owner.project.isAUSandBoxSafe())
  1360. {
  1361. addPlistDictionaryKeyBool (dict, "sandboxSafe", true);
  1362. }
  1363. else
  1364. {
  1365. dict->createNewChildElement ("key")->addTextElement ("resourceUsage");
  1366. auto* resourceUsageDict = dict->createNewChildElement ("dict");
  1367. addPlistDictionaryKeyBool (resourceUsageDict, "network.client", true);
  1368. addPlistDictionaryKeyBool (resourceUsageDict, "temporary-exception.files.all.read-write", true);
  1369. }
  1370. xcodeExtraPListEntries.add (plistKey);
  1371. xcodeExtraPListEntries.add (plistEntry);
  1372. }
  1373. void addExtraAudioUnitv3PlugInTargetSettings()
  1374. {
  1375. if (owner.isiOS())
  1376. xcodeFrameworks.addTokens ("CoreAudioKit AVFoundation", false);
  1377. else
  1378. xcodeFrameworks.addTokens ("AudioUnit CoreAudioKit AVFoundation", false);
  1379. XmlElement plistKey ("key");
  1380. plistKey.addTextElement ("NSExtension");
  1381. XmlElement plistEntry ("dict");
  1382. addPlistDictionaryKey (&plistEntry, "NSExtensionPrincipalClass", owner.project.getPluginAUExportPrefixString() + "FactoryAUv3");
  1383. addPlistDictionaryKey (&plistEntry, "NSExtensionPointIdentifier", "com.apple.AudioUnit-UI");
  1384. plistEntry.createNewChildElement ("key")->addTextElement ("NSExtensionAttributes");
  1385. auto* dict = plistEntry.createNewChildElement ("dict");
  1386. dict->createNewChildElement ("key")->addTextElement ("AudioComponents");
  1387. auto* componentArray = dict->createNewChildElement ("array");
  1388. auto* componentDict = componentArray->createNewChildElement ("dict");
  1389. addPlistDictionaryKey (componentDict, "name", owner.project.getPluginManufacturerString()
  1390. + ": " + owner.project.getPluginNameString());
  1391. addPlistDictionaryKey (componentDict, "description", owner.project.getPluginDescriptionString());
  1392. addPlistDictionaryKey (componentDict, "factoryFunction",owner.project. getPluginAUExportPrefixString() + "FactoryAUv3");
  1393. addPlistDictionaryKey (componentDict, "manufacturer", owner.project.getPluginManufacturerCodeString().substring (0, 4));
  1394. addPlistDictionaryKey (componentDict, "type", owner.project.getAUMainTypeString().removeCharacters ("'"));
  1395. addPlistDictionaryKey (componentDict, "subtype", owner.project.getPluginCodeString().substring (0, 4));
  1396. addPlistDictionaryKeyInt (componentDict, "version", owner.project.getVersionAsHexInteger());
  1397. addPlistDictionaryKeyBool (componentDict, "sandboxSafe", true);
  1398. componentDict->createNewChildElement ("key")->addTextElement ("tags");
  1399. auto* tagsArray = componentDict->createNewChildElement ("array");
  1400. tagsArray->createNewChildElement ("string")
  1401. ->addTextElement (static_cast<bool> (owner.project.isPluginSynth()) ? "Synth" : "Effects");
  1402. xcodeExtraPListEntries.add (plistKey);
  1403. xcodeExtraPListEntries.add (plistEntry);
  1404. }
  1405. void addExtraLibsForTargetType (const BuildConfiguration& config, Array<RelativePath>& extraLibs) const
  1406. {
  1407. if (type == AAXPlugIn)
  1408. {
  1409. auto aaxLibsFolder = RelativePath (owner.getAAXPathString(), RelativePath::projectFolder).getChildFile ("Libs");
  1410. String libraryPath (config.isDebug() ? "Debug" : "Release");
  1411. libraryPath += "/libAAXLibrary_libcpp.a";
  1412. extraLibs.add (aaxLibsFolder.getChildFile (libraryPath));
  1413. }
  1414. else if (type == RTASPlugIn)
  1415. {
  1416. RelativePath rtasFolder (owner.getRTASPathString(), RelativePath::projectFolder);
  1417. extraLibs.add (rtasFolder.getChildFile ("MacBag/Libs/Debug/libPluginLibrary.a"));
  1418. extraLibs.add (rtasFolder.getChildFile ("MacBag/Libs/Release/libPluginLibrary.a"));
  1419. }
  1420. }
  1421. StringArray getTargetExtraHeaderSearchPaths() const
  1422. {
  1423. StringArray targetExtraSearchPaths;
  1424. if (type == RTASPlugIn)
  1425. {
  1426. RelativePath rtasFolder (owner.getRTASPathString(), RelativePath::projectFolder);
  1427. targetExtraSearchPaths.add ("$(DEVELOPER_DIR)/Headers/FlatCarbon");
  1428. targetExtraSearchPaths.add ("$(SDKROOT)/Developer/Headers/FlatCarbon");
  1429. static const char* p[] = { "AlturaPorts/TDMPlugIns/PlugInLibrary/Controls",
  1430. "AlturaPorts/TDMPlugIns/PlugInLibrary/CoreClasses",
  1431. "AlturaPorts/TDMPlugIns/PlugInLibrary/DSPClasses",
  1432. "AlturaPorts/TDMPlugIns/PlugInLibrary/EffectClasses",
  1433. "AlturaPorts/TDMPlugIns/PlugInLibrary/MacBuild",
  1434. "AlturaPorts/TDMPlugIns/PlugInLibrary/Meters",
  1435. "AlturaPorts/TDMPlugIns/PlugInLibrary/ProcessClasses",
  1436. "AlturaPorts/TDMPlugIns/PlugInLibrary/ProcessClasses/Interfaces",
  1437. "AlturaPorts/TDMPlugIns/PlugInLibrary/RTASP_Adapt",
  1438. "AlturaPorts/TDMPlugIns/PlugInLibrary/Utilities",
  1439. "AlturaPorts/TDMPlugIns/PlugInLibrary/ViewClasses",
  1440. "AlturaPorts/TDMPlugIns/DSPManager/**",
  1441. "AlturaPorts/TDMPlugIns/SupplementalPlugInLib/Encryption",
  1442. "AlturaPorts/TDMPlugIns/SupplementalPlugInLib/GraphicsExtensions",
  1443. "AlturaPorts/TDMPlugIns/common/**",
  1444. "AlturaPorts/TDMPlugIns/common/PI_LibInterface",
  1445. "AlturaPorts/TDMPlugIns/PACEProtection/**",
  1446. "AlturaPorts/TDMPlugIns/SignalProcessing/**",
  1447. "AlturaPorts/OMS/Headers",
  1448. "AlturaPorts/Fic/Interfaces/**",
  1449. "AlturaPorts/Fic/Source/SignalNets",
  1450. "AlturaPorts/DSIPublicInterface/PublicHeaders",
  1451. "DAEWin/Include",
  1452. "AlturaPorts/DigiPublic/Interfaces",
  1453. "AlturaPorts/DigiPublic",
  1454. "AlturaPorts/NewFileLibs/DOA",
  1455. "AlturaPorts/NewFileLibs/Cmn",
  1456. "xplat/AVX/avx2/avx2sdk/inc",
  1457. "xplat/AVX/avx2/avx2sdk/utils" };
  1458. for (auto* path : p)
  1459. owner.addProjectPathToBuildPathList (targetExtraSearchPaths, rtasFolder.getChildFile (path));
  1460. }
  1461. return targetExtraSearchPaths;
  1462. }
  1463. String getOSXDeploymentTarget (const XcodeBuildConfiguration& config, String* sdkRoot = nullptr) const
  1464. {
  1465. auto sdk = config.getOSXSDKVersionString();
  1466. auto sdkCompat = config.getOSXDeploymentTargetString();
  1467. // The AUv3 target always needs to be at least 10.11
  1468. int oldestAllowedDeploymentTarget = (type == Target::AudioUnitv3PlugIn ? minimumAUv3SDKVersion
  1469. : oldestSDKVersion);
  1470. // if the user doesn't set it, then use the last known version that works well with JUCE
  1471. String deploymentTarget (osxVersionDefault);
  1472. for (int ver = oldestAllowedDeploymentTarget; ver <= currentSDKVersion; ++ver)
  1473. {
  1474. if (sdk.isNotEmpty() && (sdk == getSDKName (ver) && sdkRoot != nullptr)) *sdkRoot = String ("macosx10." + String (ver));
  1475. if (sdkCompat == getSDKName (ver)) deploymentTarget = "10." + String (ver);
  1476. }
  1477. return deploymentTarget;
  1478. }
  1479. bool isUsingCodeSigning (const XcodeBuildConfiguration& config) const
  1480. {
  1481. return (! config.isUsingDefaultCodeSignIdentity())
  1482. || owner.getIosDevelopmentTeamIDString().isNotEmpty();
  1483. }
  1484. //==============================================================================
  1485. const XcodeProjectExporter& owner;
  1486. Target& operator= (const Target&) = delete;
  1487. };
  1488. mutable StringArray xcodeFrameworks;
  1489. StringArray xcodeLibs;
  1490. private:
  1491. //==============================================================================
  1492. friend class CLionProjectExporter;
  1493. bool xcodeCanUseDwarf;
  1494. OwnedArray<XcodeTarget> targets;
  1495. mutable OwnedArray<ValueTree> pbxBuildFiles, pbxFileReferences, pbxGroups, misc, projectConfigs, targetConfigs;
  1496. mutable StringArray resourceIDs, sourceIDs, targetIDs;
  1497. mutable StringArray frameworkFileIDs, embeddedFrameworkIDs, rezFileIDs, resourceFileRefs, subprojectFileIDs;
  1498. mutable Array<std::pair<String, String>> subprojectReferences;
  1499. mutable File menuNibFile, iconFile;
  1500. mutable StringArray buildProducts;
  1501. const bool iOS;
  1502. ValueWithDefault customPListValue, pListPrefixHeaderValue, pListPreprocessValue,
  1503. subprojectsValue,
  1504. extraFrameworksValue, frameworkSearchPathsValue, extraCustomFrameworksValue, embeddedFrameworksValue,
  1505. postbuildCommandValue, prebuildCommandValue,
  1506. duplicateAppExResourcesFolderValue, iosDeviceFamilyValue, iPhoneScreenOrientationValue,
  1507. iPadScreenOrientationValue, customXcodeResourceFoldersValue, customXcassetsFolderValue,
  1508. hardenedRuntimeValue, hardenedRuntimeOptionsValue,
  1509. microphonePermissionNeededValue, microphonePermissionsTextValue, cameraPermissionNeededValue, cameraPermissionTextValue,
  1510. uiFileSharingEnabledValue, uiSupportsDocumentBrowserValue, uiStatusBarHiddenValue, documentExtensionsValue, iosInAppPurchasesValue,
  1511. iosBackgroundAudioValue, iosBackgroundBleValue, iosPushNotificationsValue, iosAppGroupsValue, iCloudPermissionsValue,
  1512. iosDevelopmentTeamIDValue, iosAppGroupsIDValue, keepCustomXcodeSchemesValue, useHeaderMapValue, customLaunchStoryboardValue,
  1513. exporterBundleIdentifierValue;
  1514. static String sanitisePath (const String& path)
  1515. {
  1516. if (path.startsWithChar ('~'))
  1517. return "$(HOME)" + path.substring (1);
  1518. return path;
  1519. }
  1520. static String addQuotesIfRequired (const String& s)
  1521. {
  1522. return s.containsAnyOf (" $") ? s.quoted() : s;
  1523. }
  1524. File getProjectBundle() const { return getTargetFolder().getChildFile (project.getProjectFilenameRootString()).withFileExtension (".xcodeproj"); }
  1525. //==============================================================================
  1526. void createObjects() const
  1527. {
  1528. prepareTargets();
  1529. // Must be called before adding embedded frameworks, as we want to
  1530. // embed any frameworks found in subprojects.
  1531. addSubprojects();
  1532. addFrameworks();
  1533. addCustomFrameworks();
  1534. addEmbeddedFrameworks();
  1535. addCustomResourceFolders();
  1536. addPlistFileReferences();
  1537. if (iOS && ! projectType.isStaticLibrary())
  1538. {
  1539. addXcassets();
  1540. if (shouldAddStoryboardToProject())
  1541. {
  1542. auto customLaunchStoryboard = getCustomLaunchStoryboardString();
  1543. if (customLaunchStoryboard.isEmpty())
  1544. writeDefaultLaunchStoryboardFile();
  1545. else if (getProject().getProjectFolder().getChildFile (customLaunchStoryboard).existsAsFile())
  1546. addLaunchStoryboardFileReference (RelativePath (customLaunchStoryboard, RelativePath::projectFolder)
  1547. .rebased (getProject().getProjectFolder(), getTargetFolder(), RelativePath::buildTargetFolder)
  1548. .toUnixStyle());
  1549. }
  1550. }
  1551. else
  1552. {
  1553. addNibFiles();
  1554. }
  1555. addIcons();
  1556. addBuildConfigurations();
  1557. addProjectConfigList (projectConfigs, createID ("__projList"));
  1558. {
  1559. StringArray topLevelGroupIDs;
  1560. addFilesAndGroupsToProject (topLevelGroupIDs);
  1561. addBuildPhases();
  1562. addExtraGroupsToProject (topLevelGroupIDs);
  1563. addGroup (createID ("__mainsourcegroup"), "Source", topLevelGroupIDs);
  1564. }
  1565. addProjectObject();
  1566. removeMismatchedXcuserdata();
  1567. }
  1568. void prepareTargets() const
  1569. {
  1570. for (auto* target : targets)
  1571. {
  1572. if (target->type == XcodeTarget::AggregateTarget)
  1573. continue;
  1574. target->addMainBuildProduct();
  1575. auto targetName = target->getName();
  1576. auto fileID = createID (targetName + String ("__targetbuildref"));
  1577. auto fileRefID = createID (String ("__productFileID") + targetName);
  1578. auto* v = new ValueTree (fileID);
  1579. v->setProperty ("isa", "PBXBuildFile", nullptr);
  1580. v->setProperty ("fileRef", fileRefID, nullptr);
  1581. target->mainBuildProductID = fileID;
  1582. pbxBuildFiles.add (v);
  1583. target->addDependency();
  1584. }
  1585. }
  1586. void addPlistFileReferences() const
  1587. {
  1588. for (auto* target : targets)
  1589. {
  1590. if (target->type == XcodeTarget::AggregateTarget)
  1591. continue;
  1592. if (target->shouldCreatePList())
  1593. {
  1594. RelativePath plistPath (target->infoPlistFile, getTargetFolder(), RelativePath::buildTargetFolder);
  1595. addFileReference (plistPath.toUnixStyle());
  1596. resourceFileRefs.add (createFileRefID (plistPath));
  1597. }
  1598. }
  1599. }
  1600. void addNibFiles() const
  1601. {
  1602. MemoryOutputStream nib;
  1603. nib.write (BinaryData::RecentFilesMenuTemplate_nib, BinaryData::RecentFilesMenuTemplate_nibSize);
  1604. overwriteFileIfDifferentOrThrow (menuNibFile, nib);
  1605. RelativePath menuNibPath (menuNibFile, getTargetFolder(), RelativePath::buildTargetFolder);
  1606. addFileReference (menuNibPath.toUnixStyle());
  1607. resourceIDs.add (addBuildFile (menuNibPath, false, false));
  1608. resourceFileRefs.add (createFileRefID (menuNibPath));
  1609. }
  1610. void addIcons() const
  1611. {
  1612. if (iconFile.exists())
  1613. {
  1614. RelativePath iconPath (iconFile, getTargetFolder(), RelativePath::buildTargetFolder);
  1615. addFileReference (iconPath.toUnixStyle());
  1616. resourceIDs.add (addBuildFile (iconPath, false, false));
  1617. resourceFileRefs.add (createFileRefID (iconPath));
  1618. }
  1619. }
  1620. void addBuildConfigurations() const
  1621. {
  1622. for (ConstConfigIterator config (*this); config.next();)
  1623. {
  1624. auto& xcodeConfig = dynamic_cast<const XcodeBuildConfiguration&> (*config);
  1625. StringArray settingsLines;
  1626. auto configSettings = getProjectSettings (xcodeConfig);
  1627. for (auto& key : configSettings.getAllKeys())
  1628. settingsLines.add (key + " = " + configSettings[key]);
  1629. addProjectConfig (config->getName(), settingsLines);
  1630. }
  1631. }
  1632. void addFilesAndGroupsToProject (StringArray& topLevelGroupIDs) const
  1633. {
  1634. auto entitlements = getEntitlements();
  1635. if (entitlements.size() > 0)
  1636. topLevelGroupIDs.add (addEntitlementsFile (entitlements));
  1637. for (auto& group : getAllGroups())
  1638. {
  1639. if (group.getNumChildren() > 0)
  1640. {
  1641. auto groupID = addProjectItem (group);
  1642. if (groupID.isNotEmpty())
  1643. topLevelGroupIDs.add (groupID);
  1644. }
  1645. }
  1646. }
  1647. void addExtraGroupsToProject (StringArray& topLevelGroupIDs) const
  1648. {
  1649. {
  1650. auto resourcesGroupID = createID ("__resources");
  1651. addGroup (resourcesGroupID, "Resources", resourceFileRefs);
  1652. topLevelGroupIDs.add (resourcesGroupID);
  1653. }
  1654. {
  1655. auto frameworksGroupID = createID ("__frameworks");
  1656. addGroup (frameworksGroupID, "Frameworks", frameworkFileIDs);
  1657. topLevelGroupIDs.add (frameworksGroupID);
  1658. }
  1659. {
  1660. auto productsGroupID = createID ("__products");
  1661. addGroup (productsGroupID, "Products", buildProducts);
  1662. topLevelGroupIDs.add (productsGroupID);
  1663. }
  1664. if (! subprojectFileIDs.isEmpty())
  1665. {
  1666. auto subprojectLibrariesGroupID = createID ("__subprojects");
  1667. addGroup (subprojectLibrariesGroupID, "Subprojects", subprojectFileIDs);
  1668. topLevelGroupIDs.add (subprojectLibrariesGroupID);
  1669. }
  1670. }
  1671. void addBuildPhases() const
  1672. {
  1673. // add build phases
  1674. for (auto* target : targets)
  1675. {
  1676. if (target->type != XcodeTarget::AggregateTarget)
  1677. buildProducts.add (createID (String ("__productFileID") + String (target->getName())));
  1678. for (ConstConfigIterator config (*this); config.next();)
  1679. {
  1680. auto& xcodeConfig = dynamic_cast<const XcodeBuildConfiguration&> (*config);
  1681. auto configSettings = target->getTargetSettings (xcodeConfig);
  1682. StringArray settingsLines;
  1683. for (auto& key : configSettings.getAllKeys())
  1684. settingsLines.add (key + " = " + configSettings.getValue (key, "\"\""));
  1685. target->addTargetConfig (config->getName(), settingsLines);
  1686. }
  1687. addConfigList (*target, targetConfigs, createID (String ("__configList") + target->getName()));
  1688. target->addShellScriptBuildPhase ("Pre-build script", getPreBuildScript());
  1689. if (target->type != XcodeTarget::AggregateTarget)
  1690. {
  1691. auto skipAUv3 = (target->type == XcodeTarget::AudioUnitv3PlugIn && ! shouldDuplicateAppExResourcesFolder());
  1692. if (! projectType.isStaticLibrary() && target->type != XcodeTarget::SharedCodeTarget && ! skipAUv3)
  1693. target->addBuildPhase ("PBXResourcesBuildPhase", resourceIDs);
  1694. auto rezFiles = rezFileIDs;
  1695. rezFiles.addArray (target->rezFileIDs);
  1696. if (rezFiles.size() > 0)
  1697. target->addBuildPhase ("PBXRezBuildPhase", rezFiles);
  1698. auto sourceFiles = target->sourceIDs;
  1699. if (target->type == XcodeTarget::SharedCodeTarget
  1700. || (! project.getProjectType().isAudioPlugin()))
  1701. sourceFiles.addArray (sourceIDs);
  1702. target->addBuildPhase ("PBXSourcesBuildPhase", sourceFiles);
  1703. if (! projectType.isStaticLibrary() && target->type != XcodeTarget::SharedCodeTarget)
  1704. target->addBuildPhase ("PBXFrameworksBuildPhase", target->frameworkIDs);
  1705. }
  1706. target->addShellScriptBuildPhase ("Post-build script", getPostBuildScript());
  1707. if (project.getProjectType().isAudioPlugin() && project.shouldBuildAUv3()
  1708. && project.shouldBuildStandalonePlugin() && target->type == XcodeTarget::StandalonePlugIn)
  1709. embedAppExtension();
  1710. if (project.getProjectType().isAudioPlugin() && project.shouldBuildUnityPlugin()
  1711. && target->type == XcodeTarget::UnityPlugIn)
  1712. embedUnityScript();
  1713. addTargetObject (*target);
  1714. }
  1715. }
  1716. void embedAppExtension() const
  1717. {
  1718. if (auto* standaloneTarget = getTargetOfType (XcodeTarget::StandalonePlugIn))
  1719. {
  1720. if (auto* auv3Target = getTargetOfType (XcodeTarget::AudioUnitv3PlugIn))
  1721. {
  1722. StringArray files;
  1723. files.add (auv3Target->mainBuildProductID);
  1724. standaloneTarget->addCopyFilesPhase ("Embed App Extensions", files, kPluginsFolder);
  1725. }
  1726. }
  1727. }
  1728. void embedUnityScript() const
  1729. {
  1730. if (auto* unityTarget = getTargetOfType (XcodeTarget::UnityPlugIn))
  1731. {
  1732. RelativePath scriptPath (getProject().getGeneratedCodeFolder().getChildFile (getProject().getUnityScriptName()),
  1733. getTargetFolder(),
  1734. RelativePath::buildTargetFolder);
  1735. auto path = scriptPath.toUnixStyle();
  1736. auto refID = addFileReference (path);
  1737. auto fileID = addBuildFile (path, refID, false, false);
  1738. resourceIDs.add (fileID);
  1739. resourceFileRefs.add (refID);
  1740. unityTarget->addCopyFilesPhase ("Embed Unity Script", fileID, kResourcesFolder);
  1741. }
  1742. }
  1743. static Image fixMacIconImageSize (Drawable& image)
  1744. {
  1745. const int validSizes[] = { 16, 32, 64, 128, 256, 512, 1024 };
  1746. auto w = image.getWidth();
  1747. auto h = image.getHeight();
  1748. int bestSize = 16;
  1749. for (int size : validSizes)
  1750. {
  1751. if (w == h && w == size)
  1752. {
  1753. bestSize = w;
  1754. break;
  1755. }
  1756. if (jmax (w, h) > size)
  1757. bestSize = size;
  1758. }
  1759. return rescaleImageForIcon (image, bestSize);
  1760. }
  1761. //==============================================================================
  1762. XcodeTarget* getTargetOfType (ProjectType::Target::Type type) const
  1763. {
  1764. for (auto& target : targets)
  1765. if (target->type == type)
  1766. return target;
  1767. return nullptr;
  1768. }
  1769. void addTargetObject (XcodeTarget& target) const
  1770. {
  1771. auto targetName = target.getName();
  1772. auto targetID = target.getID();
  1773. auto* v = new ValueTree (targetID);
  1774. v->setProperty ("isa", target.type == XcodeTarget::AggregateTarget ? "PBXAggregateTarget" : "PBXNativeTarget", nullptr);
  1775. v->setProperty ("buildConfigurationList", createID (String ("__configList") + targetName), nullptr);
  1776. v->setProperty ("buildPhases", indentParenthesisedList (target.buildPhaseIDs), nullptr);
  1777. v->setProperty ("buildRules", "( )", nullptr);
  1778. v->setProperty ("dependencies", indentParenthesisedList (getTargetDependencies (target)), nullptr);
  1779. v->setProperty (Ids::name, target.getXcodeSchemeName(), nullptr);
  1780. v->setProperty ("productName", projectName, nullptr);
  1781. if (target.type != XcodeTarget::AggregateTarget)
  1782. {
  1783. v->setProperty ("productReference", createID (String ("__productFileID") + targetName), nullptr);
  1784. jassert (target.xcodeProductType.isNotEmpty());
  1785. v->setProperty ("productType", target.xcodeProductType, nullptr);
  1786. }
  1787. targetIDs.add (targetID);
  1788. misc.add (v);
  1789. }
  1790. StringArray getTargetDependencies (const XcodeTarget& target) const
  1791. {
  1792. StringArray dependencies;
  1793. if (project.getProjectType().isAudioPlugin())
  1794. {
  1795. if (target.type == XcodeTarget::StandalonePlugIn) // depends on AUv3 and shared code
  1796. {
  1797. if (auto* auv3Target = getTargetOfType (XcodeTarget::AudioUnitv3PlugIn))
  1798. dependencies.add (auv3Target->getDependencyID());
  1799. if (auto* sharedCodeTarget = getTargetOfType (XcodeTarget::SharedCodeTarget))
  1800. dependencies.add (sharedCodeTarget->getDependencyID());
  1801. }
  1802. else if (target.type == XcodeTarget::AggregateTarget) // depends on all other targets
  1803. {
  1804. for (int i = 1; i < targets.size(); ++i)
  1805. dependencies.add (targets[i]->getDependencyID());
  1806. }
  1807. else if (target.type != XcodeTarget::SharedCodeTarget) // shared code doesn't depend on anything; all other targets depend only on the shared code
  1808. {
  1809. if (auto* sharedCodeTarget = getTargetOfType (XcodeTarget::SharedCodeTarget))
  1810. dependencies.add (sharedCodeTarget->getDependencyID());
  1811. }
  1812. }
  1813. return dependencies;
  1814. }
  1815. static void writeIconData (MemoryOutputStream& out, const Image& image, const char* type)
  1816. {
  1817. MemoryOutputStream pngData;
  1818. PNGImageFormat pngFormat;
  1819. pngFormat.writeImageToStream (image, pngData);
  1820. out.write (type, 4);
  1821. out.writeIntBigEndian (8 + (int) pngData.getDataSize());
  1822. out << pngData;
  1823. }
  1824. void writeIcnsFile (const OwnedArray<Drawable>& images, OutputStream& out) const
  1825. {
  1826. MemoryOutputStream data;
  1827. auto smallest = std::numeric_limits<int>::max();
  1828. Drawable* smallestImage = nullptr;
  1829. for (int i = 0; i < images.size(); ++i)
  1830. {
  1831. auto image = fixMacIconImageSize (*images.getUnchecked (i));
  1832. jassert (image.getWidth() == image.getHeight());
  1833. if (image.getWidth() < smallest)
  1834. {
  1835. smallest = image.getWidth();
  1836. smallestImage = images.getUnchecked(i);
  1837. }
  1838. switch (image.getWidth())
  1839. {
  1840. case 16: writeIconData (data, image, "icp4"); break;
  1841. case 32: writeIconData (data, image, "icp5"); break;
  1842. case 64: writeIconData (data, image, "icp6"); break;
  1843. case 128: writeIconData (data, image, "ic07"); break;
  1844. case 256: writeIconData (data, image, "ic08"); break;
  1845. case 512: writeIconData (data, image, "ic09"); break;
  1846. case 1024: writeIconData (data, image, "ic10"); break;
  1847. default: break;
  1848. }
  1849. }
  1850. jassert (data.getDataSize() > 0); // no suitable sized images?
  1851. // If you only supply a 1024 image, the file doesn't work on 10.8, so we need
  1852. // to force a smaller one in there too..
  1853. if (smallest > 512 && smallestImage != nullptr)
  1854. writeIconData (data, rescaleImageForIcon (*smallestImage, 512), "ic09");
  1855. out.write ("icns", 4);
  1856. out.writeIntBigEndian ((int) data.getDataSize() + 8);
  1857. out << data;
  1858. }
  1859. void getIconImages (OwnedArray<Drawable>& images) const
  1860. {
  1861. std::unique_ptr<Drawable> bigIcon (getBigIcon());
  1862. if (bigIcon != nullptr)
  1863. images.add (bigIcon.release());
  1864. std::unique_ptr<Drawable> smallIcon (getSmallIcon());
  1865. if (smallIcon != nullptr)
  1866. images.add (smallIcon.release());
  1867. }
  1868. void createiOSIconFiles (File appIconSet) const
  1869. {
  1870. OwnedArray<Drawable> images;
  1871. getIconImages (images);
  1872. if (images.size() > 0)
  1873. {
  1874. for (auto& type : getiOSAppIconTypes())
  1875. {
  1876. auto image = rescaleImageForIcon (*images.getFirst(), type.size);
  1877. if (image.hasAlphaChannel())
  1878. {
  1879. Image background (Image::RGB, image.getWidth(), image.getHeight(), false);
  1880. Graphics g (background);
  1881. g.fillAll (Colours::white);
  1882. g.drawImageWithin (image, 0, 0, image.getWidth(), image.getHeight(),
  1883. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize);
  1884. image = background;
  1885. }
  1886. MemoryOutputStream pngData;
  1887. PNGImageFormat pngFormat;
  1888. pngFormat.writeImageToStream (image, pngData);
  1889. overwriteFileIfDifferentOrThrow (appIconSet.getChildFile (type.filename), pngData);
  1890. }
  1891. }
  1892. }
  1893. void createIconFile() const
  1894. {
  1895. OwnedArray<Drawable> images;
  1896. getIconImages (images);
  1897. if (images.size() > 0)
  1898. {
  1899. MemoryOutputStream mo;
  1900. writeIcnsFile (images, mo);
  1901. iconFile = getTargetFolder().getChildFile ("Icon.icns");
  1902. overwriteFileIfDifferentOrThrow (iconFile, mo);
  1903. }
  1904. }
  1905. void writeWorkspaceSettings() const
  1906. {
  1907. auto settingsFile = getProjectBundle().getChildFile ("project.xcworkspace")
  1908. .getChildFile ("xcshareddata")
  1909. .getChildFile ("WorkspaceSettings.xcsettings");
  1910. MemoryOutputStream mo;
  1911. mo.setNewLineString ("\n");
  1912. mo << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << newLine
  1913. << "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" << newLine
  1914. << "<plist version=\"1.0\">" << newLine
  1915. << "<dict>" << newLine
  1916. << "\t" << "<key>BuildSystemType</key>" << newLine
  1917. << "\t" << "<string>Original</string>" << newLine
  1918. << "</dict>" << newLine
  1919. << "</plist>" << newLine;
  1920. overwriteFileIfDifferentOrThrow (settingsFile, mo);
  1921. }
  1922. void writeInfoPlistFiles() const
  1923. {
  1924. for (auto& target : targets)
  1925. target->writeInfoPlistFile();
  1926. }
  1927. // Delete .rsrc files in folder but don't follow sym-links
  1928. void deleteRsrcFiles (const File& folder) const
  1929. {
  1930. for (DirectoryIterator di (folder, false, "*", File::findFilesAndDirectories); di.next();)
  1931. {
  1932. auto& entry = di.getFile();
  1933. if (! entry.isSymbolicLink())
  1934. {
  1935. if (entry.existsAsFile() && entry.getFileExtension().toLowerCase() == ".rsrc")
  1936. entry.deleteFile();
  1937. else if (entry.isDirectory())
  1938. deleteRsrcFiles (entry);
  1939. }
  1940. }
  1941. }
  1942. static String getLinkerFlagForLib (String library)
  1943. {
  1944. if (library.substring (0, 3) == "lib")
  1945. library = library.substring (3);
  1946. return "-l" + library.replace (" ", "\\\\ ").upToLastOccurrenceOf (".", false, false);
  1947. }
  1948. String getSearchPathForStaticLibrary (const RelativePath& library) const
  1949. {
  1950. auto searchPath = library.toUnixStyle().upToLastOccurrenceOf ("/", false, false);
  1951. if (! library.isAbsolute())
  1952. {
  1953. auto srcRoot = rebaseFromProjectFolderToBuildTarget (RelativePath (".", RelativePath::projectFolder)).toUnixStyle();
  1954. if (srcRoot.endsWith ("/.")) srcRoot = srcRoot.dropLastCharacters (2);
  1955. if (! srcRoot.endsWithChar ('/')) srcRoot << '/';
  1956. searchPath = srcRoot + searchPath;
  1957. }
  1958. return sanitisePath (searchPath);
  1959. }
  1960. StringPairArray getProjectSettings (const XcodeBuildConfiguration& config) const
  1961. {
  1962. StringPairArray s;
  1963. s.set ("ALWAYS_SEARCH_USER_PATHS", "NO");
  1964. s.set ("ENABLE_STRICT_OBJC_MSGSEND", "YES");
  1965. s.set ("GCC_C_LANGUAGE_STANDARD", "c11");
  1966. s.set ("GCC_NO_COMMON_BLOCKS", "YES");
  1967. s.set ("GCC_MODEL_TUNING", "G5");
  1968. s.set ("GCC_WARN_ABOUT_RETURN_TYPE", "YES");
  1969. s.set ("GCC_WARN_CHECK_SWITCH_STATEMENTS", "YES");
  1970. s.set ("GCC_WARN_UNUSED_VARIABLE", "YES");
  1971. s.set ("GCC_WARN_MISSING_PARENTHESES", "YES");
  1972. s.set ("GCC_WARN_NON_VIRTUAL_DESTRUCTOR", "YES");
  1973. s.set ("GCC_WARN_TYPECHECK_CALLS_TO_PRINTF", "YES");
  1974. s.set ("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES");
  1975. s.set ("GCC_WARN_UNDECLARED_SELECTOR", "YES");
  1976. s.set ("GCC_WARN_UNINITIALIZED_AUTOS", "YES");
  1977. s.set ("GCC_WARN_UNUSED_FUNCTION", "YES");
  1978. s.set ("CLANG_ENABLE_OBJC_WEAK", "YES");
  1979. s.set ("CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING", "YES");
  1980. s.set ("CLANG_WARN_BOOL_CONVERSION", "YES");
  1981. s.set ("CLANG_WARN_COMMA", "YES");
  1982. s.set ("CLANG_WARN_CONSTANT_CONVERSION", "YES");
  1983. s.set ("CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS", "YES");
  1984. s.set ("CLANG_WARN_EMPTY_BODY", "YES");
  1985. s.set ("CLANG_WARN_ENUM_CONVERSION", "YES");
  1986. s.set ("CLANG_WARN_INFINITE_RECURSION", "YES");
  1987. s.set ("CLANG_WARN_INT_CONVERSION", "YES");
  1988. s.set ("CLANG_WARN_NON_LITERAL_NULL_CONVERSION", "YES");
  1989. s.set ("CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF", "YES");
  1990. s.set ("CLANG_WARN_OBJC_LITERAL_CONVERSION", "YES");
  1991. s.set ("CLANG_WARN_RANGE_LOOP_ANALYSIS", "YES");
  1992. s.set ("CLANG_WARN_STRICT_PROTOTYPES", "YES");
  1993. s.set ("CLANG_WARN_SUSPICIOUS_MOVE", "YES");
  1994. s.set ("CLANG_WARN_UNREACHABLE_CODE", "YES");
  1995. s.set ("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES");
  1996. s.set ("WARNING_CFLAGS", "\"-Wreorder\"");
  1997. if (projectType.isStaticLibrary())
  1998. {
  1999. s.set ("GCC_INLINES_ARE_PRIVATE_EXTERN", "NO");
  2000. s.set ("GCC_SYMBOLS_PRIVATE_EXTERN", "NO");
  2001. }
  2002. else
  2003. {
  2004. s.set ("GCC_INLINES_ARE_PRIVATE_EXTERN", "YES");
  2005. }
  2006. if (config.isDebug())
  2007. {
  2008. s.set ("ENABLE_TESTABILITY", "YES");
  2009. if (config.getOSXArchitectureString() == osxArch_Default)
  2010. s.set ("ONLY_ACTIVE_ARCH", "YES");
  2011. }
  2012. if (iOS)
  2013. {
  2014. s.set ("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\"", config.getCodeSignIdentityString().quoted());
  2015. s.set ("SDKROOT", "iphoneos");
  2016. s.set ("TARGETED_DEVICE_FAMILY", getDeviceFamilyString().quoted());
  2017. s.set ("IPHONEOS_DEPLOYMENT_TARGET", config.getiOSDeploymentTargetString());
  2018. }
  2019. else
  2020. {
  2021. if (! config.isUsingDefaultCodeSignIdentity() || getIosDevelopmentTeamIDString().isNotEmpty())
  2022. s.set ("CODE_SIGN_IDENTITY", config.getCodeSignIdentityString().quoted());
  2023. }
  2024. s.set ("ZERO_LINK", "NO");
  2025. if (xcodeCanUseDwarf)
  2026. s.set ("DEBUG_INFORMATION_FORMAT", "dwarf");
  2027. s.set ("PRODUCT_NAME", replacePreprocessorTokens (config, config.getTargetBinaryNameString()).quoted());
  2028. return s;
  2029. }
  2030. void addFrameworks() const
  2031. {
  2032. if (! projectType.isStaticLibrary())
  2033. {
  2034. if (isInAppPurchasesEnabled())
  2035. xcodeFrameworks.addIfNotAlreadyThere ("StoreKit");
  2036. if (iOS && isPushNotificationsEnabled())
  2037. xcodeFrameworks.addIfNotAlreadyThere ("UserNotifications");
  2038. if (isiOS() && project.getConfigFlag ("JUCE_USE_CAMERA").get())
  2039. xcodeFrameworks.addIfNotAlreadyThere ("ImageIO");
  2040. xcodeFrameworks.addTokens (getExtraFrameworksString(), ",;", "\"'");
  2041. xcodeFrameworks.trim();
  2042. auto s = xcodeFrameworks;
  2043. for (auto& target : targets)
  2044. s.addArray (target->xcodeFrameworks);
  2045. if (! project.getConfigFlag ("JUCE_QUICKTIME").get())
  2046. s.removeString ("QuickTime");
  2047. s.trim();
  2048. s.removeDuplicates (true);
  2049. s.sort (true);
  2050. for (auto& framework : s)
  2051. {
  2052. auto frameworkID = addFramework (framework);
  2053. // find all the targets that are referring to this object
  2054. for (auto& target : targets)
  2055. {
  2056. if (xcodeFrameworks.contains (framework) || target->xcodeFrameworks.contains (framework))
  2057. {
  2058. target->frameworkIDs.add (frameworkID);
  2059. target->frameworkNames.add (framework);
  2060. }
  2061. }
  2062. }
  2063. }
  2064. }
  2065. void addCustomFrameworks() const
  2066. {
  2067. StringArray customFrameworks;
  2068. customFrameworks.addTokens (getExtraCustomFrameworksString(), true);
  2069. customFrameworks.trim();
  2070. for (auto& framework : customFrameworks)
  2071. {
  2072. auto frameworkID = addCustomFramework (framework);
  2073. for (auto& target : targets)
  2074. {
  2075. target->frameworkIDs.add (frameworkID);
  2076. target->frameworkNames.add (framework);
  2077. }
  2078. }
  2079. }
  2080. void addEmbeddedFrameworks() const
  2081. {
  2082. StringArray frameworks;
  2083. frameworks.addTokens (getEmbeddedFrameworksString(), true);
  2084. frameworks.trim();
  2085. for (auto& framework : frameworks)
  2086. {
  2087. auto frameworkID = addEmbeddedFramework (framework);
  2088. embeddedFrameworkIDs.add (frameworkID);
  2089. for (auto& target : targets)
  2090. {
  2091. target->frameworkIDs.add (frameworkID);
  2092. target->frameworkNames.add (framework);
  2093. }
  2094. }
  2095. if (! embeddedFrameworkIDs.isEmpty())
  2096. for (auto& target : targets)
  2097. target->addCopyFilesPhase ("Embed Frameworks", embeddedFrameworkIDs, kFrameworksFolder);
  2098. }
  2099. void addCustomResourceFolders() const
  2100. {
  2101. StringArray folders;
  2102. folders.addTokens (getCustomResourceFoldersString(), ":", "");
  2103. folders.trim();
  2104. folders.removeEmptyStrings();
  2105. for (auto& crf : folders)
  2106. addCustomResourceFolder (crf);
  2107. }
  2108. void addSubprojects() const
  2109. {
  2110. auto subprojectLines = StringArray::fromLines (getSubprojectsString());
  2111. subprojectLines.removeEmptyStrings (true);
  2112. Array<std::pair<String, StringArray>> subprojects;
  2113. for (auto& line : subprojectLines)
  2114. {
  2115. String subprojectName (line.upToFirstOccurrenceOf (":", false, false));
  2116. StringArray requestedBuildProducts (StringArray::fromTokens (line.fromFirstOccurrenceOf (":", false, false), ",;|", "\"'"));
  2117. requestedBuildProducts.trim();
  2118. subprojects.add ({ subprojectName, requestedBuildProducts });
  2119. }
  2120. for (const auto& subprojectInfo : subprojects)
  2121. {
  2122. String subprojectPath (subprojectInfo.first);
  2123. if (! subprojectPath.endsWith (".xcodeproj"))
  2124. subprojectPath += ".xcodeproj";
  2125. File subprojectFile;
  2126. if (File::isAbsolutePath (subprojectPath))
  2127. {
  2128. subprojectFile = subprojectPath;
  2129. }
  2130. else
  2131. {
  2132. subprojectFile = getProject().getProjectFolder().getChildFile (subprojectPath);
  2133. RelativePath p (subprojectPath, RelativePath::projectFolder);
  2134. subprojectPath = p.rebased (getProject().getProjectFolder(), getTargetFolder(), RelativePath::buildTargetFolder).toUnixStyle();
  2135. }
  2136. if (! subprojectFile.isDirectory())
  2137. continue;
  2138. auto availableBuildProducts = XcodeProjectParser::parseBuildProducts (subprojectFile);
  2139. // If no build products have been specified then we'll take everything
  2140. if (! subprojectInfo.second.isEmpty())
  2141. {
  2142. auto newEnd = std::remove_if (availableBuildProducts.begin(), availableBuildProducts.end(),
  2143. [&subprojectInfo](const std::pair<String, String> &item)
  2144. {
  2145. return ! subprojectInfo.second.contains (item.first);
  2146. });
  2147. availableBuildProducts.erase (newEnd, availableBuildProducts.end());
  2148. }
  2149. if (availableBuildProducts.empty())
  2150. continue;
  2151. auto subprojectFileType = getFileType (RelativePath (subprojectPath, RelativePath::projectFolder));
  2152. auto subprojectFileID = addFileOrFolderReference (subprojectPath, "<group>", subprojectFileType);
  2153. subprojectFileIDs.add (subprojectFileID);
  2154. StringArray proxyIDs;
  2155. for (auto& buildProduct : availableBuildProducts)
  2156. {
  2157. auto buildProductFileType = getFileType (RelativePath (buildProduct.second, RelativePath::projectFolder));
  2158. auto containerID = addContainerItemProxy (subprojectFileID, buildProduct.first);
  2159. auto proxyID = addReferenceProxy (containerID, buildProduct.second, buildProductFileType);
  2160. proxyIDs.add (proxyID);
  2161. if (buildProductFileType == "archive.ar" || buildProductFileType == "wrapper.framework")
  2162. {
  2163. auto buildFileID = addBuildFile (buildProduct.second, proxyID, false, true);
  2164. for (auto& target : targets)
  2165. target->frameworkIDs.add (buildFileID);
  2166. if (buildProductFileType == "wrapper.framework")
  2167. {
  2168. auto fileID = createID (buildProduct.second + "buildref");
  2169. auto* v = new ValueTree (fileID);
  2170. v->setProperty ("isa", "PBXBuildFile", nullptr);
  2171. v->setProperty ("fileRef", proxyID, nullptr);
  2172. v->setProperty ("settings", "{ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }", nullptr);
  2173. pbxBuildFiles.add (v);
  2174. embeddedFrameworkIDs.add (fileID);
  2175. }
  2176. }
  2177. }
  2178. auto productGroupID = createFileRefID (subprojectPath + "_products");
  2179. addGroup (productGroupID, "Products", proxyIDs);
  2180. subprojectReferences.add ({ productGroupID, subprojectFileID });
  2181. }
  2182. }
  2183. void addXcassets() const
  2184. {
  2185. auto customXcassetsPath = getCustomXcassetsFolderString();
  2186. if (customXcassetsPath.isEmpty())
  2187. createXcassetsFolderFromIcons();
  2188. else
  2189. addCustomResourceFolder (customXcassetsPath, "folder.assetcatalog");
  2190. }
  2191. void addCustomResourceFolder (String folderPathRelativeToProjectFolder, const String fileType = "folder") const
  2192. {
  2193. auto folderPath = RelativePath (folderPathRelativeToProjectFolder, RelativePath::projectFolder)
  2194. .rebased (projectFolder, getTargetFolder(), RelativePath::buildTargetFolder)
  2195. .toUnixStyle();
  2196. auto fileRefID = createFileRefID (folderPath);
  2197. addFileOrFolderReference (folderPath, "<group>", fileType);
  2198. resourceIDs.add (addBuildFile (folderPath, fileRefID, false, false));
  2199. resourceFileRefs.add (createFileRefID (folderPath));
  2200. }
  2201. //==============================================================================
  2202. void writeProjectFile (OutputStream& output) const
  2203. {
  2204. output << "// !$*UTF8*$!\n{\n"
  2205. "\tarchiveVersion = 1;\n"
  2206. "\tclasses = {\n\t};\n"
  2207. "\tobjectVersion = 46;\n"
  2208. "\tobjects = {\n";
  2209. Array<ValueTree*> objects;
  2210. objects.addArray (pbxBuildFiles);
  2211. objects.addArray (pbxFileReferences);
  2212. objects.addArray (pbxGroups);
  2213. objects.addArray (targetConfigs);
  2214. objects.addArray (projectConfigs);
  2215. objects.addArray (misc);
  2216. for (auto* o : objects)
  2217. {
  2218. output << "\t\t" << o->getType().toString() << " = {\n";
  2219. for (int j = 0; j < o->getNumProperties(); ++j)
  2220. {
  2221. auto propertyName = o->getPropertyName(j);
  2222. auto val = o->getProperty (propertyName).toString();
  2223. if (val.isEmpty() || (val.containsAnyOf (" \t;<>()=,&+-_@~\r\n\\#%^`*")
  2224. && ! (val.trimStart().startsWithChar ('(')
  2225. || val.trimStart().startsWithChar ('{'))))
  2226. val = "\"" + val + "\"";
  2227. output << "\t\t\t" << propertyName.toString() << " = " << val << ";\n";
  2228. }
  2229. output << "\t\t};\n";
  2230. }
  2231. output << "\t};\n\trootObject = " << createID ("__root") << ";\n}\n";
  2232. }
  2233. String addBuildFile (const String& path, const String& fileRefID, bool addToSourceBuildPhase, bool inhibitWarnings,
  2234. XcodeTarget* xcodeTarget = nullptr, String compilerFlags = {}) const
  2235. {
  2236. auto fileID = createID (path + "buildref");
  2237. if (addToSourceBuildPhase)
  2238. {
  2239. if (xcodeTarget != nullptr)
  2240. xcodeTarget->sourceIDs.add (fileID);
  2241. else
  2242. sourceIDs.add (fileID);
  2243. }
  2244. auto* v = new ValueTree (fileID);
  2245. v->setProperty ("isa", "PBXBuildFile", nullptr);
  2246. v->setProperty ("fileRef", fileRefID, nullptr);
  2247. if (inhibitWarnings)
  2248. compilerFlags += " -w";
  2249. if (compilerFlags.isNotEmpty())
  2250. v->setProperty ("settings", "{ COMPILER_FLAGS = \"" + compilerFlags.trim() + "\"; }", nullptr);
  2251. pbxBuildFiles.add (v);
  2252. return fileID;
  2253. }
  2254. String addBuildFile (const RelativePath& path, bool addToSourceBuildPhase, bool inhibitWarnings, XcodeTarget* xcodeTarget = nullptr) const
  2255. {
  2256. return addBuildFile (path.toUnixStyle(), createFileRefID (path), addToSourceBuildPhase, inhibitWarnings, xcodeTarget);
  2257. }
  2258. String addFileReference (String pathString) const
  2259. {
  2260. String sourceTree ("SOURCE_ROOT");
  2261. RelativePath path (pathString, RelativePath::unknown);
  2262. if (pathString.startsWith ("${"))
  2263. {
  2264. sourceTree = pathString.substring (2).upToFirstOccurrenceOf ("}", false, false);
  2265. pathString = pathString.fromFirstOccurrenceOf ("}/", false, false);
  2266. }
  2267. else if (path.isAbsolute())
  2268. {
  2269. sourceTree = "<absolute>";
  2270. }
  2271. auto fileType = getFileType (path);
  2272. return addFileOrFolderReference (pathString, sourceTree, fileType);
  2273. }
  2274. void checkAndAddFileReference (std::unique_ptr<ValueTree> v) const
  2275. {
  2276. auto existing = pbxFileReferences.indexOfSorted (*this, v.get());
  2277. if (existing >= 0)
  2278. {
  2279. // If this fails, there's either a string hash collision, or the same file is being added twice (incorrectly)
  2280. jassert (pbxFileReferences.getUnchecked (existing)->isEquivalentTo (*v));
  2281. }
  2282. else
  2283. {
  2284. pbxFileReferences.addSorted (*this, v.release());
  2285. }
  2286. }
  2287. String addFileOrFolderReference (const String& pathString, String sourceTree, String fileType) const
  2288. {
  2289. auto fileRefID = createFileRefID (pathString);
  2290. std::unique_ptr<ValueTree> v (new ValueTree (fileRefID));
  2291. v->setProperty ("isa", "PBXFileReference", nullptr);
  2292. v->setProperty ("lastKnownFileType", fileType, nullptr);
  2293. v->setProperty (Ids::name, pathString.fromLastOccurrenceOf ("/", false, false), nullptr);
  2294. v->setProperty ("path", pathString, nullptr);
  2295. v->setProperty ("sourceTree", sourceTree, nullptr);
  2296. checkAndAddFileReference (std::move (v));
  2297. return fileRefID;
  2298. }
  2299. String addContainerItemProxy (const String& subprojectID, const String& itemName) const
  2300. {
  2301. auto uniqueString = subprojectID + "_" + itemName;
  2302. auto fileRefID = createFileRefID (uniqueString);
  2303. std::unique_ptr<ValueTree> v (new ValueTree (fileRefID));
  2304. v->setProperty ("isa", "PBXContainerItemProxy", nullptr);
  2305. v->setProperty ("containerPortal", subprojectID, nullptr);
  2306. v->setProperty ("proxyType", 2, nullptr);
  2307. v->setProperty ("remoteGlobalIDString", createFileRefID (uniqueString + "_global"), nullptr);
  2308. v->setProperty ("remoteInfo", itemName, nullptr);
  2309. checkAndAddFileReference (std::move (v));
  2310. return fileRefID;
  2311. }
  2312. String addReferenceProxy (const String& containerItemID, const String& proxyPath, const String& fileType) const
  2313. {
  2314. auto fileRefID = createFileRefID (containerItemID + "_" + proxyPath);
  2315. std::unique_ptr<ValueTree> v (new ValueTree (fileRefID));
  2316. v->setProperty ("isa", "PBXReferenceProxy", nullptr);
  2317. v->setProperty ("fileType", fileType, nullptr);
  2318. v->setProperty ("path", proxyPath, nullptr);
  2319. v->setProperty ("remoteRef", containerItemID, nullptr);
  2320. v->setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);
  2321. checkAndAddFileReference (std::move (v));
  2322. return fileRefID;
  2323. }
  2324. public:
  2325. static int compareElements (const ValueTree* first, const ValueTree* second)
  2326. {
  2327. return first->getType().getCharPointer().compare (second->getType().getCharPointer());
  2328. }
  2329. private:
  2330. static String getFileType (const RelativePath& file)
  2331. {
  2332. if (file.hasFileExtension (cppFileExtensions)) return "sourcecode.cpp.cpp";
  2333. if (file.hasFileExtension (".mm")) return "sourcecode.cpp.objcpp";
  2334. if (file.hasFileExtension (".m")) return "sourcecode.c.objc";
  2335. if (file.hasFileExtension (".c")) return "sourcecode.c.c";
  2336. if (file.hasFileExtension (headerFileExtensions)) return "sourcecode.c.h";
  2337. if (file.hasFileExtension (asmFileExtensions)) return "sourcecode.c.asm";
  2338. if (file.hasFileExtension (".framework")) return "wrapper.framework";
  2339. if (file.hasFileExtension (".jpeg;.jpg")) return "image.jpeg";
  2340. if (file.hasFileExtension ("png;gif")) return "image" + file.getFileExtension();
  2341. if (file.hasFileExtension ("html;htm")) return "text.html";
  2342. if (file.hasFileExtension ("xml;zip;wav")) return "file" + file.getFileExtension();
  2343. if (file.hasFileExtension ("txt;rtf")) return "text" + file.getFileExtension();
  2344. if (file.hasFileExtension ("plist")) return "text.plist.xml";
  2345. if (file.hasFileExtension ("entitlements")) return "text.plist.xml";
  2346. if (file.hasFileExtension ("app")) return "wrapper.application";
  2347. if (file.hasFileExtension ("component;vst;plugin")) return "wrapper.cfbundle";
  2348. if (file.hasFileExtension ("xcodeproj")) return "wrapper.pb-project";
  2349. if (file.hasFileExtension ("a")) return "archive.ar";
  2350. if (file.hasFileExtension ("xcassets")) return "folder.assetcatalog";
  2351. return "file" + file.getFileExtension();
  2352. }
  2353. String addFile (const RelativePath& path, bool shouldBeCompiled, bool shouldBeAddedToBinaryResources,
  2354. bool shouldBeAddedToXcodeResources, bool inhibitWarnings, XcodeTarget* xcodeTarget, const String& compilerFlags) const
  2355. {
  2356. auto pathAsString = path.toUnixStyle();
  2357. auto refID = addFileReference (path.toUnixStyle());
  2358. if (shouldBeCompiled)
  2359. {
  2360. addBuildFile (pathAsString, refID, true, inhibitWarnings, xcodeTarget, compilerFlags);
  2361. }
  2362. else if (! shouldBeAddedToBinaryResources || shouldBeAddedToXcodeResources)
  2363. {
  2364. auto fileType = getFileType (path);
  2365. if (shouldBeAddedToXcodeResources)
  2366. {
  2367. resourceIDs.add (addBuildFile (pathAsString, refID, false, false));
  2368. resourceFileRefs.add (refID);
  2369. }
  2370. }
  2371. return refID;
  2372. }
  2373. String addRezFile (const Project::Item& projectItem, const RelativePath& path) const
  2374. {
  2375. auto pathAsString = path.toUnixStyle();
  2376. auto refID = addFileReference (path.toUnixStyle());
  2377. if (projectItem.isModuleCode())
  2378. {
  2379. if (auto* xcodeTarget = getTargetOfType (getProject().getTargetTypeFromFilePath (projectItem.getFile(), false)))
  2380. {
  2381. auto rezFileID = addBuildFile (pathAsString, refID, false, false, xcodeTarget);
  2382. xcodeTarget->rezFileIDs.add (rezFileID);
  2383. return refID;
  2384. }
  2385. }
  2386. return {};
  2387. }
  2388. String getEntitlementsFileName() const
  2389. {
  2390. return project.getProjectFilenameRootString() + String (".entitlements");
  2391. }
  2392. StringPairArray getEntitlements() const
  2393. {
  2394. StringPairArray entitlements;
  2395. if (project.getProjectType().isAudioPlugin())
  2396. {
  2397. if (isiOS())
  2398. {
  2399. if (project.shouldEnableIAA())
  2400. entitlements.set ("inter-app-audio", "<true/>");
  2401. }
  2402. else
  2403. {
  2404. entitlements.set ("com.apple.security.app-sandbox", "<true/>");
  2405. }
  2406. }
  2407. else
  2408. {
  2409. if (isPushNotificationsEnabled())
  2410. entitlements.set (isiOS() ? "aps-environment"
  2411. : "com.apple.developer.aps-environment",
  2412. "<string>development</string>");
  2413. }
  2414. if (isAppGroupsEnabled())
  2415. {
  2416. auto appGroups = StringArray::fromTokens (getAppGroupIdString(), ";", {});
  2417. auto groups = String ("<array>");
  2418. for (auto group : appGroups)
  2419. groups += "\n\t\t<string>" + group.trim() + "</string>";
  2420. groups += "\n\t</array>";
  2421. entitlements.set ("com.apple.security.application-groups", groups);
  2422. }
  2423. if (isHardenedRuntimeEnabled())
  2424. for (auto& option : getHardenedRuntimeOptions())
  2425. entitlements.set (option, "<true/>");
  2426. if (isiOS() && isiCloudPermissionsEnabled())
  2427. {
  2428. entitlements.set ("com.apple.developer.icloud-container-identifiers",
  2429. "<array>\n"
  2430. " <string>iCloud.$(CFBundleIdentifier)</string>\n"
  2431. " </array>");
  2432. entitlements.set ("com.apple.developer.icloud-services",
  2433. "<array>\n"
  2434. " <string>CloudDocuments</string>\n"
  2435. " </array>");
  2436. entitlements.set ("com.apple.developer.ubiquity-container-identifiers",
  2437. "<array>\n"
  2438. " <string>iCloud.$(CFBundleIdentifier)</string>\n"
  2439. " </array>");
  2440. }
  2441. return entitlements;
  2442. }
  2443. String addEntitlementsFile (StringPairArray entitlements) const
  2444. {
  2445. String content =
  2446. "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
  2447. "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
  2448. "<plist version=\"1.0\">\n"
  2449. "<dict>\n";
  2450. auto keys = entitlements.getAllKeys();
  2451. for (auto& key : keys)
  2452. {
  2453. content += "\t<key>" + key + "</key>\n"
  2454. "\t" + entitlements[key] + "\n";
  2455. }
  2456. content += "</dict>\n"
  2457. "</plist>\n";
  2458. auto entitlementsFile = getTargetFolder().getChildFile (getEntitlementsFileName());
  2459. overwriteFileIfDifferentOrThrow (entitlementsFile, content);
  2460. RelativePath plistPath (entitlementsFile, getTargetFolder(), RelativePath::buildTargetFolder);
  2461. return addFile (plistPath, false, false, false, false, nullptr, {});
  2462. }
  2463. String addProjectItem (const Project::Item& projectItem) const
  2464. {
  2465. if (modulesGroup != nullptr && projectItem.getParent() == *modulesGroup)
  2466. return addFileReference (rebaseFromProjectFolderToBuildTarget (getModuleFolderRelativeToProject (projectItem.getName())).toUnixStyle());
  2467. if (projectItem.isGroup())
  2468. {
  2469. StringArray childIDs;
  2470. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  2471. {
  2472. auto child = projectItem.getChild (i);
  2473. auto childID = addProjectItem (child);
  2474. if (childID.isNotEmpty() && ! child.shouldBeAddedToXcodeResources())
  2475. childIDs.add (childID);
  2476. }
  2477. if (childIDs.isEmpty())
  2478. return {};
  2479. return addGroup (projectItem, childIDs);
  2480. }
  2481. if (projectItem.shouldBeAddedToTargetProject())
  2482. {
  2483. auto itemPath = projectItem.getFilePath();
  2484. RelativePath path;
  2485. if (itemPath.startsWith ("${"))
  2486. path = RelativePath (itemPath, RelativePath::unknown);
  2487. else
  2488. path = RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder);
  2489. if (path.hasFileExtension (".r"))
  2490. return addRezFile (projectItem, path);
  2491. XcodeTarget* xcodeTarget = nullptr;
  2492. if (projectItem.isModuleCode() && projectItem.shouldBeCompiled())
  2493. xcodeTarget = getTargetOfType (project.getTargetTypeFromFilePath (projectItem.getFile(), false));
  2494. return addFile (path, projectItem.shouldBeCompiled(),
  2495. projectItem.shouldBeAddedToBinaryResources(),
  2496. projectItem.shouldBeAddedToXcodeResources(),
  2497. projectItem.shouldInhibitWarnings(),
  2498. xcodeTarget,
  2499. compilerFlagSchemesMap[projectItem.getCompilerFlagSchemeString()].get());
  2500. }
  2501. return {};
  2502. }
  2503. String addFramework (const String& frameworkName) const
  2504. {
  2505. auto path = frameworkName;
  2506. auto isRelativePath = path.startsWith ("../");
  2507. if (! File::isAbsolutePath (path) && ! isRelativePath)
  2508. path = "System/Library/Frameworks/" + path;
  2509. if (! path.endsWithIgnoreCase (".framework"))
  2510. path << ".framework";
  2511. auto fileRefID = createFileRefID (path);
  2512. addFileReference (((File::isAbsolutePath (frameworkName) || isRelativePath) ? "" : "${SDKROOT}/") + path);
  2513. frameworkFileIDs.add (fileRefID);
  2514. return addBuildFile (path, fileRefID, false, false);
  2515. }
  2516. String addCustomFramework (String frameworkPath) const
  2517. {
  2518. if (! frameworkPath.endsWithIgnoreCase (".framework"))
  2519. frameworkPath << ".framework";
  2520. auto fileRefID = createFileRefID (frameworkPath);
  2521. auto fileType = getFileType (RelativePath (frameworkPath, RelativePath::projectFolder));
  2522. addFileOrFolderReference (frameworkPath, "<group>", fileType);
  2523. frameworkFileIDs.add (fileRefID);
  2524. return addBuildFile (frameworkPath, fileRefID, false, false);
  2525. }
  2526. String addEmbeddedFramework (const String& path) const
  2527. {
  2528. auto fileRefID = createFileRefID (path);
  2529. auto fileType = getFileType (RelativePath (path, RelativePath::projectFolder));
  2530. addFileOrFolderReference (path, "<group>", fileType);
  2531. auto fileID = createID (path + "buildref");
  2532. auto* v = new ValueTree (fileID);
  2533. v->setProperty ("isa", "PBXBuildFile", nullptr);
  2534. v->setProperty ("fileRef", fileRefID, nullptr);
  2535. v->setProperty ("settings", "{ ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }", nullptr);
  2536. pbxBuildFiles.add (v);
  2537. frameworkFileIDs.add (fileRefID);
  2538. return fileID;
  2539. }
  2540. void addGroup (const String& groupID, const String& groupName, const StringArray& childIDs) const
  2541. {
  2542. auto* v = new ValueTree (groupID);
  2543. v->setProperty ("isa", "PBXGroup", nullptr);
  2544. v->setProperty ("children", indentParenthesisedList (childIDs), nullptr);
  2545. v->setProperty (Ids::name, groupName, nullptr);
  2546. v->setProperty ("sourceTree", "<group>", nullptr);
  2547. pbxGroups.add (v);
  2548. }
  2549. String addGroup (const Project::Item& item, StringArray& childIDs) const
  2550. {
  2551. auto groupName = item.getName();
  2552. auto groupID = getIDForGroup (item);
  2553. addGroup (groupID, groupName, childIDs);
  2554. return groupID;
  2555. }
  2556. void addProjectConfig (const String& configName, const StringArray& buildSettings) const
  2557. {
  2558. auto* v = new ValueTree (createID ("projectconfigid_" + configName));
  2559. v->setProperty ("isa", "XCBuildConfiguration", nullptr);
  2560. v->setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
  2561. v->setProperty (Ids::name, configName, nullptr);
  2562. projectConfigs.add (v);
  2563. }
  2564. void addConfigList (XcodeTarget& target, const OwnedArray <ValueTree>& configsToUse, const String& listID) const
  2565. {
  2566. auto* v = new ValueTree (listID);
  2567. v->setProperty ("isa", "XCConfigurationList", nullptr);
  2568. v->setProperty ("buildConfigurations", indentParenthesisedList (target.configIDs), nullptr);
  2569. v->setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
  2570. if (auto* first = configsToUse.getFirst())
  2571. v->setProperty ("defaultConfigurationName", first->getProperty (Ids::name), nullptr);
  2572. misc.add (v);
  2573. }
  2574. void addProjectConfigList (const OwnedArray <ValueTree>& configsToUse, const String& listID) const
  2575. {
  2576. StringArray configIDs;
  2577. for (auto* c : configsToUse)
  2578. configIDs.add (c->getType().toString());
  2579. auto* v = new ValueTree (listID);
  2580. v->setProperty ("isa", "XCConfigurationList", nullptr);
  2581. v->setProperty ("buildConfigurations", indentParenthesisedList (configIDs), nullptr);
  2582. v->setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
  2583. if (auto* first = configsToUse.getFirst())
  2584. v->setProperty ("defaultConfigurationName", first->getProperty (Ids::name), nullptr);
  2585. misc.add (v);
  2586. }
  2587. void addProjectObject() const
  2588. {
  2589. auto* v = new ValueTree (createID ("__root"));
  2590. v->setProperty ("isa", "PBXProject", nullptr);
  2591. v->setProperty ("buildConfigurationList", createID ("__projList"), nullptr);
  2592. v->setProperty ("attributes", getProjectObjectAttributes(), nullptr);
  2593. v->setProperty ("compatibilityVersion", "Xcode 3.2", nullptr);
  2594. v->setProperty ("hasScannedForEncodings", (int) 0, nullptr);
  2595. v->setProperty ("mainGroup", createID ("__mainsourcegroup"), nullptr);
  2596. v->setProperty ("projectDirPath", "\"\"", nullptr);
  2597. if (! subprojectReferences.isEmpty())
  2598. {
  2599. StringArray projectReferences;
  2600. for (auto& reference : subprojectReferences)
  2601. projectReferences.add (indentBracedList ({ "ProductGroup = " + reference.first, "ProjectRef = " + reference.second }, 1));
  2602. v->setProperty ("projectReferences", indentParenthesisedList (projectReferences), nullptr);
  2603. }
  2604. v->setProperty ("projectRoot", "\"\"", nullptr);
  2605. auto targetString = "(" + targetIDs.joinIntoString (", ") + ")";
  2606. v->setProperty ("targets", targetString, nullptr);
  2607. v->setProperty ("knownRegions", "(en, Base)", nullptr);
  2608. misc.add (v);
  2609. }
  2610. //==============================================================================
  2611. void removeMismatchedXcuserdata() const
  2612. {
  2613. if (shouldKeepCustomXcodeSchemes())
  2614. return;
  2615. auto xcuserdata = getProjectBundle().getChildFile ("xcuserdata");
  2616. if (! xcuserdata.exists())
  2617. return;
  2618. if (! xcuserdataMatchesTargets (xcuserdata))
  2619. {
  2620. xcuserdata.deleteRecursively();
  2621. getProjectBundle().getChildFile ("xcshareddata").getChildFile ("xcschemes").deleteRecursively();
  2622. getProjectBundle().getChildFile ("project.xcworkspace").deleteRecursively();
  2623. }
  2624. }
  2625. bool xcuserdataMatchesTargets (const File& xcuserdata) const
  2626. {
  2627. for (auto& plist : xcuserdata.findChildFiles (File::findFiles, true, "xcschememanagement.plist"))
  2628. if (! xcschemeManagementPlistMatchesTargets (plist))
  2629. return false;
  2630. return true;
  2631. }
  2632. static StringArray parseNamesOfTargetsFromPlist (const XmlElement& dictXML)
  2633. {
  2634. forEachXmlChildElementWithTagName (dictXML, schemesKey, "key")
  2635. {
  2636. if (schemesKey->getAllSubText().trim().equalsIgnoreCase ("SchemeUserState"))
  2637. {
  2638. if (auto* dict = schemesKey->getNextElement())
  2639. {
  2640. if (dict->hasTagName ("dict"))
  2641. {
  2642. StringArray names;
  2643. forEachXmlChildElementWithTagName (*dict, key, "key")
  2644. names.add (key->getAllSubText().upToLastOccurrenceOf (".xcscheme", false, false).trim());
  2645. names.sort (false);
  2646. return names;
  2647. }
  2648. }
  2649. }
  2650. }
  2651. return {};
  2652. }
  2653. StringArray getNamesOfTargets() const
  2654. {
  2655. StringArray names;
  2656. for (auto& target : targets)
  2657. names.add (target->getXcodeSchemeName());
  2658. names.sort (false);
  2659. return names;
  2660. }
  2661. bool xcschemeManagementPlistMatchesTargets (const File& plist) const
  2662. {
  2663. if (auto xml = parseXML (plist))
  2664. if (auto* dict = xml->getChildByName ("dict"))
  2665. return parseNamesOfTargetsFromPlist (*dict) == getNamesOfTargets();
  2666. return false;
  2667. }
  2668. //==============================================================================
  2669. struct AppIconType
  2670. {
  2671. const char* idiom;
  2672. const char* sizeString;
  2673. const char* filename;
  2674. const char* scale;
  2675. int size;
  2676. };
  2677. static Array<AppIconType> getiOSAppIconTypes()
  2678. {
  2679. AppIconType types[] =
  2680. {
  2681. { "iphone", "20x20", "Icon-Notification-20@2x.png", "2x", 40 },
  2682. { "iphone", "20x20", "Icon-Notification-20@3x.png", "3x", 60 },
  2683. { "iphone", "29x29", "Icon-29.png", "1x", 29 },
  2684. { "iphone", "29x29", "Icon-29@2x.png", "2x", 58 },
  2685. { "iphone", "29x29", "Icon-29@3x.png", "3x", 87 },
  2686. { "iphone", "40x40", "Icon-Spotlight-40@2x.png", "2x", 80 },
  2687. { "iphone", "40x40", "Icon-Spotlight-40@3x.png", "3x", 120 },
  2688. { "iphone", "57x57", "Icon.png", "1x", 57 },
  2689. { "iphone", "57x57", "Icon@2x.png", "2x", 114 },
  2690. { "iphone", "60x60", "Icon-60@2x.png", "2x", 120 },
  2691. { "iphone", "60x60", "Icon-@3x.png", "3x", 180 },
  2692. { "ipad", "20x20", "Icon-Notifications-20.png", "1x", 20 },
  2693. { "ipad", "20x20", "Icon-Notifications-20@2x.png", "2x", 40 },
  2694. { "ipad", "29x29", "Icon-Small-1.png", "1x", 29 },
  2695. { "ipad", "29x29", "Icon-Small@2x-1.png", "2x", 58 },
  2696. { "ipad", "40x40", "Icon-Spotlight-40.png", "1x", 40 },
  2697. { "ipad", "40x40", "Icon-Spotlight-40@2x-1.png", "2x", 80 },
  2698. { "ipad", "50x50", "Icon-Small-50.png", "1x", 50 },
  2699. { "ipad", "50x50", "Icon-Small-50@2x.png", "2x", 100 },
  2700. { "ipad", "72x72", "Icon-72.png", "1x", 72 },
  2701. { "ipad", "72x72", "Icon-72@2x.png", "2x", 144 },
  2702. { "ipad", "76x76", "Icon-76.png", "1x", 76 },
  2703. { "ipad", "76x76", "Icon-76@2x.png", "2x", 152 },
  2704. { "ipad", "83.5x83.5", "Icon-83.5@2x.png", "2x", 167 },
  2705. { "ios-marketing", "1024x1024", "Icon-AppStore-1024.png", "1x", 1024 }
  2706. };
  2707. return Array<AppIconType> (types, numElementsInArray (types));
  2708. }
  2709. static String getiOSAppIconContents()
  2710. {
  2711. var images;
  2712. for (auto& type : getiOSAppIconTypes())
  2713. {
  2714. DynamicObject::Ptr d (new DynamicObject());
  2715. d->setProperty ("idiom", type.idiom);
  2716. d->setProperty ("size", type.sizeString);
  2717. d->setProperty ("filename", type.filename);
  2718. d->setProperty ("scale", type.scale);
  2719. images.append (var (d.get()));
  2720. }
  2721. return getiOSAssetContents (images);
  2722. }
  2723. String getProjectObjectAttributes() const
  2724. {
  2725. String attributes;
  2726. attributes << "{ LastUpgradeCheck = 1010; "
  2727. << "ORGANIZATIONNAME = " << getProject().getCompanyNameString().quoted()
  2728. <<"; ";
  2729. if (projectType.isGUIApplication() || projectType.isAudioPlugin())
  2730. {
  2731. attributes << "TargetAttributes = { ";
  2732. for (auto& target : targets)
  2733. attributes << target->getTargetAttributes();
  2734. attributes << " }; ";
  2735. }
  2736. attributes << "}";
  2737. return attributes;
  2738. }
  2739. //==============================================================================
  2740. struct ImageType
  2741. {
  2742. const char* orientation;
  2743. const char* idiom;
  2744. const char* subtype;
  2745. const char* extent;
  2746. const char* scale;
  2747. const char* filename;
  2748. int width;
  2749. int height;
  2750. };
  2751. static Array<ImageType> getiOSLaunchImageTypes()
  2752. {
  2753. ImageType types[] =
  2754. {
  2755. { "portrait", "iphone", nullptr, "full-screen", "2x", "LaunchImage-iphone-2x.png", 640, 960 },
  2756. { "portrait", "iphone", "retina4", "full-screen", "2x", "LaunchImage-iphone-retina4.png", 640, 1136 },
  2757. { "portrait", "ipad", nullptr, "full-screen", "1x", "LaunchImage-ipad-portrait-1x.png", 768, 1024 },
  2758. { "landscape","ipad", nullptr, "full-screen", "1x", "LaunchImage-ipad-landscape-1x.png", 1024, 768 },
  2759. { "portrait", "ipad", nullptr, "full-screen", "2x", "LaunchImage-ipad-portrait-2x.png", 1536, 2048 },
  2760. { "landscape","ipad", nullptr, "full-screen", "2x", "LaunchImage-ipad-landscape-2x.png", 2048, 1536 }
  2761. };
  2762. return Array<ImageType> (types, numElementsInArray (types));
  2763. }
  2764. static String getiOSLaunchImageContents()
  2765. {
  2766. var images;
  2767. for (auto& type : getiOSLaunchImageTypes())
  2768. {
  2769. DynamicObject::Ptr d (new DynamicObject());
  2770. d->setProperty ("orientation", type.orientation);
  2771. d->setProperty ("idiom", type.idiom);
  2772. d->setProperty ("extent", type.extent);
  2773. d->setProperty ("minimum-system-version", "7.0");
  2774. d->setProperty ("scale", type.scale);
  2775. d->setProperty ("filename", type.filename);
  2776. if (type.subtype != nullptr)
  2777. d->setProperty ("subtype", type.subtype);
  2778. images.append (var (d.get()));
  2779. }
  2780. return getiOSAssetContents (images);
  2781. }
  2782. static void createiOSLaunchImageFiles (const File& launchImageSet)
  2783. {
  2784. for (auto& type : getiOSLaunchImageTypes())
  2785. {
  2786. Image image (Image::ARGB, type.width, type.height, true); // (empty black image)
  2787. image.clear (image.getBounds(), Colours::black);
  2788. MemoryOutputStream pngData;
  2789. PNGImageFormat pngFormat;
  2790. pngFormat.writeImageToStream (image, pngData);
  2791. overwriteFileIfDifferentOrThrow (launchImageSet.getChildFile (type.filename), pngData);
  2792. }
  2793. }
  2794. //==============================================================================
  2795. static String getiOSAssetContents (var images)
  2796. {
  2797. DynamicObject::Ptr v (new DynamicObject());
  2798. var info (new DynamicObject());
  2799. info.getDynamicObject()->setProperty ("version", 1);
  2800. info.getDynamicObject()->setProperty ("author", "xcode");
  2801. v->setProperty ("images", images);
  2802. v->setProperty ("info", info);
  2803. return JSON::toString (var (v.get()));
  2804. }
  2805. void writeDefaultLaunchStoryboardFile() const
  2806. {
  2807. auto storyboardFile = getTargetFolder().getChildFile (getDefaultLaunchStoryboardName() + ".storyboard");
  2808. MemoryOutputStream mo;
  2809. mo.setNewLineString ("\n");
  2810. mo << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << newLine
  2811. << "<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"14460.31\" "
  2812. << "targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" launchScreen=\"YES\" useTraitCollections=\"YES\" "
  2813. << "useSafeAreas=\"YES\" colorMatched=\"YES\" initialViewController=\"01J-lp-oVM\">" << newLine
  2814. << " <scenes>" << newLine
  2815. << " <scene sceneID=\"EHf-IW-A2E\">" << newLine
  2816. << " <objects>" << newLine
  2817. << " <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"iYj-Kq-Ea1\" userLabel=\"\" sceneMemberID=\"firstResponder\"/>" << newLine
  2818. << " <viewController id=\"01J-lp-oVM\" sceneMemberID=\"viewController\">" << newLine
  2819. << " <view key=\"view\" contentMode=\"scaleToFill\" id=\"Ze5-6b-2t3\">" << newLine
  2820. << " <autoresizingMask key=\"autoresizingMask\"/>" << newLine
  2821. << " <color key=\"backgroundColor\" red=\"0\" green=\"0\" blue=\"0\" alpha=\"1\" colorSpace=\"custom\" customColorSpace=\"sRGB\"/>" << newLine
  2822. << " </view>" << newLine
  2823. << " </viewController>" << newLine
  2824. << " </objects>" << newLine
  2825. << " </scene>" << newLine
  2826. << " </scenes>" << newLine
  2827. << "</document>" << newLine;
  2828. overwriteFileIfDifferentOrThrow (storyboardFile, mo);
  2829. addLaunchStoryboardFileReference (RelativePath (storyboardFile, getTargetFolder(), RelativePath::buildTargetFolder).toUnixStyle());
  2830. }
  2831. void addLaunchStoryboardFileReference (const String& relativePath) const
  2832. {
  2833. auto refID = addFileReference (relativePath);
  2834. auto fileID = addBuildFile (relativePath, refID, false, false);
  2835. resourceIDs.add (fileID);
  2836. resourceFileRefs.add (refID);
  2837. }
  2838. void createXcassetsFolderFromIcons() const
  2839. {
  2840. auto assets = getTargetFolder().getChildFile (project.getProjectFilenameRootString())
  2841. .getChildFile ("Images.xcassets");
  2842. auto iconSet = assets.getChildFile ("AppIcon.appiconset");
  2843. auto launchImage = assets.getChildFile ("LaunchImage.launchimage");
  2844. overwriteFileIfDifferentOrThrow (iconSet.getChildFile ("Contents.json"), getiOSAppIconContents());
  2845. createiOSIconFiles (iconSet);
  2846. overwriteFileIfDifferentOrThrow (launchImage.getChildFile ("Contents.json"), getiOSLaunchImageContents());
  2847. createiOSLaunchImageFiles (launchImage);
  2848. RelativePath assetsPath (assets, getTargetFolder(), RelativePath::buildTargetFolder);
  2849. addFileReference (assetsPath.toUnixStyle());
  2850. resourceIDs.add (addBuildFile (assetsPath, false, false));
  2851. resourceFileRefs.add (createFileRefID (assetsPath));
  2852. }
  2853. //==============================================================================
  2854. static String indentBracedList (const StringArray& list, int depth = 0) { return indentList (list, '{', '}', ";", depth, true); }
  2855. static String indentParenthesisedList (const StringArray& list, int depth = 0) { return indentList (list, '(', ')', ",", depth, false); }
  2856. static String indentList (StringArray list, char openBracket, char closeBracket, const String& separator, int extraTabs, bool shouldSort)
  2857. {
  2858. if (list.size() == 0)
  2859. return openBracket + String (" ") + closeBracket;
  2860. auto tabs = "\n" + String::repeatedString ("\t", extraTabs + 4);
  2861. if (shouldSort)
  2862. list.sort (true);
  2863. return openBracket + tabs + list.joinIntoString (separator + tabs) + separator
  2864. + "\n" + String::repeatedString ("\t", extraTabs + 3) + closeBracket;
  2865. }
  2866. String createID (String rootString) const
  2867. {
  2868. if (rootString.startsWith ("${"))
  2869. rootString = rootString.fromFirstOccurrenceOf ("}/", false, false);
  2870. rootString += project.getProjectUIDString();
  2871. return MD5 (rootString.toUTF8()).toHexString().substring (0, 24).toUpperCase();
  2872. }
  2873. String createFileRefID (const RelativePath& path) const { return createFileRefID (path.toUnixStyle()); }
  2874. String createFileRefID (const String& path) const { return createID ("__fileref_" + path); }
  2875. String getIDForGroup (const Project::Item& item) const { return createID (item.getID()); }
  2876. bool shouldFileBeCompiledByDefault (const File& file) const override
  2877. {
  2878. return file.hasFileExtension (sourceFileExtensions);
  2879. }
  2880. static String getOSXVersionName (int version)
  2881. {
  2882. jassert (version >= 4);
  2883. return "10." + String (version);
  2884. }
  2885. static String getSDKName (int version)
  2886. {
  2887. return getOSXVersionName (version) + " SDK";
  2888. }
  2889. JUCE_DECLARE_NON_COPYABLE (XcodeProjectExporter)
  2890. };