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.

3680 lines
174KB

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