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.

2712 lines
119KB

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