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.

3609 lines
168KB

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