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.

3537 lines
164KB

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