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.

3111 lines
141KB

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