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.

3675 lines
178KB

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