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.

3506 lines
169KB

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