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.

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