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.

3618 lines
176KB

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