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.

3610 lines
169KB

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