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.

1529 lines
63KB

  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. namespace
  18. {
  19. const char* const osxVersionDefault = "default";
  20. const int oldestSDKVersion = 5;
  21. const int currentSDKVersion = 10;
  22. const char* const osxArch_Default = "default";
  23. const char* const osxArch_Native = "Native";
  24. const char* const osxArch_32BitUniversal = "32BitUniversal";
  25. const char* const osxArch_64BitUniversal = "64BitUniversal";
  26. const char* const osxArch_64Bit = "64BitIntel";
  27. }
  28. //==============================================================================
  29. class XCodeProjectExporter : public ProjectExporter
  30. {
  31. public:
  32. //==============================================================================
  33. static const char* getNameMac() { return "Xcode (MacOSX)"; }
  34. static const char* getNameiOS() { return "Xcode (iOS)"; }
  35. static const char* getValueTreeTypeName (bool iOS) { return iOS ? "XCODE_IPHONE" : "XCODE_MAC"; }
  36. //==============================================================================
  37. XCodeProjectExporter (Project& p, const ValueTree& t, const bool isIOS)
  38. : ProjectExporter (p, t),
  39. iOS (isIOS)
  40. {
  41. name = iOS ? getNameiOS() : getNameMac();
  42. if (getTargetLocationString().isEmpty())
  43. getTargetLocationValue() = getDefaultBuildsRootFolder() + (iOS ? "iOS" : "MacOSX");
  44. initialiseDependencyPathValues();
  45. }
  46. static XCodeProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  47. {
  48. if (settings.hasType (getValueTreeTypeName (false))) return new XCodeProjectExporter (project, settings, false);
  49. if (settings.hasType (getValueTreeTypeName (true))) return new XCodeProjectExporter (project, settings, true);
  50. return nullptr;
  51. }
  52. //==============================================================================
  53. Value getPListToMergeValue() { return getSetting ("customPList"); }
  54. String getPListToMergeString() const { return settings ["customPList"]; }
  55. Value getExtraFrameworksValue() { return getSetting (Ids::extraFrameworks); }
  56. String getExtraFrameworksString() const { return settings [Ids::extraFrameworks]; }
  57. Value getPostBuildScriptValue() { return getSetting (Ids::postbuildCommand); }
  58. String getPostBuildScript() const { return settings [Ids::postbuildCommand]; }
  59. Value getPreBuildScriptValue() { return getSetting (Ids::prebuildCommand); }
  60. String getPreBuildScript() const { return settings [Ids::prebuildCommand]; }
  61. bool usesMMFiles() const override { return true; }
  62. bool isXcode() const override { return true; }
  63. bool isOSX() const override { return ! iOS; }
  64. bool canCopeWithDuplicateFiles() override { return true; }
  65. void createExporterProperties (PropertyListBuilder& props) override
  66. {
  67. if (projectType.isGUIApplication() && ! iOS)
  68. {
  69. props.add (new TextPropertyComponent (getSetting ("documentExtensions"), "Document file extensions", 128, false),
  70. "A comma-separated list of file extensions for documents that your app can open. "
  71. "Using a leading '.' is optional, and the extensions are not case-sensitive.");
  72. }
  73. else if (iOS)
  74. {
  75. props.add (new BooleanPropertyComponent (getSetting ("UIFileSharingEnabled"), "File Sharing Enabled", "Enabled"),
  76. "Enable this to expose your app's files to iTunes.");
  77. props.add (new BooleanPropertyComponent (getSetting ("UIStatusBarHidden"), "Status Bar Hidden", "Enabled"),
  78. "Enable this to disable the status bar in your app.");
  79. }
  80. props.add (new TextPropertyComponent (getPListToMergeValue(), "Custom PList", 8192, true),
  81. "You can paste the contents of an XML PList file in here, and the settings that it contains will override any "
  82. "settings that the Introjucer creates. BEWARE! When doing this, be careful to remove from the XML any "
  83. "values that you DO want the introjucer to change!");
  84. props.add (new TextPropertyComponent (getExtraFrameworksValue(), "Extra Frameworks", 2048, false),
  85. "A comma-separated list of extra frameworks that should be added to the build. "
  86. "(Don't include the .framework extension in the name)");
  87. props.add (new TextPropertyComponent (getPreBuildScriptValue(), "Pre-build shell script", 32768, true),
  88. "Some shell-script that will be run before a build starts.");
  89. props.add (new TextPropertyComponent (getPostBuildScriptValue(), "Post-build shell script", 32768, true),
  90. "Some shell-script that will be run after a build completes.");
  91. }
  92. bool launchProject() override
  93. {
  94. #if JUCE_MAC
  95. return getProjectBundle().startAsProcess();
  96. #else
  97. return false;
  98. #endif
  99. }
  100. bool canLaunchProject() override
  101. {
  102. #if JUCE_MAC
  103. return true;
  104. #else
  105. return false;
  106. #endif
  107. }
  108. //==============================================================================
  109. void create (const OwnedArray<LibraryModule>&) const override
  110. {
  111. infoPlistFile = getTargetFolder().getChildFile ("Info.plist");
  112. menuNibFile = getTargetFolder().getChildFile ("RecentFilesMenuTemplate.nib");
  113. createIconFile();
  114. File projectBundle (getProjectBundle());
  115. createDirectoryOrThrow (projectBundle);
  116. createObjects();
  117. File projectFile (projectBundle.getChildFile ("project.pbxproj"));
  118. {
  119. MemoryOutputStream mo;
  120. writeProjectFile (mo);
  121. overwriteFileIfDifferentOrThrow (projectFile, mo);
  122. }
  123. writeInfoPlistFile();
  124. // Deleting the .rsrc files can be needed to force Xcode to update the version number.
  125. deleteRsrcFiles();
  126. }
  127. protected:
  128. //==============================================================================
  129. class XcodeBuildConfiguration : public BuildConfiguration
  130. {
  131. public:
  132. XcodeBuildConfiguration (Project& p, const ValueTree& t, const bool isIOS)
  133. : BuildConfiguration (p, t), iOS (isIOS)
  134. {
  135. if (iOS)
  136. {
  137. if (getiOSCompatibilityVersion().isEmpty())
  138. getiOSCompatibilityVersionValue() = osxVersionDefault;
  139. }
  140. else
  141. {
  142. if (getMacSDKVersion().isEmpty())
  143. getMacSDKVersionValue() = osxVersionDefault;
  144. if (getMacCompatibilityVersion().isEmpty())
  145. getMacCompatibilityVersionValue() = osxVersionDefault;
  146. if (getMacArchitecture().isEmpty())
  147. getMacArchitectureValue() = osxArch_Default;
  148. }
  149. }
  150. Value getMacSDKVersionValue() { return getValue (Ids::osxSDK); }
  151. String getMacSDKVersion() const { return config [Ids::osxSDK]; }
  152. Value getMacCompatibilityVersionValue() { return getValue (Ids::osxCompatibility); }
  153. String getMacCompatibilityVersion() const { return config [Ids::osxCompatibility]; }
  154. Value getiOSCompatibilityVersionValue() { return getValue (Ids::iosCompatibility); }
  155. String getiOSCompatibilityVersion() const { return config [Ids::iosCompatibility]; }
  156. Value getMacArchitectureValue() { return getValue (Ids::osxArchitecture); }
  157. String getMacArchitecture() const { return config [Ids::osxArchitecture]; }
  158. Value getCustomXcodeFlagsValue() { return getValue (Ids::customXcodeFlags); }
  159. String getCustomXcodeFlags() const { return config [Ids::customXcodeFlags]; }
  160. Value getCppLanguageStandardValue() { return getValue (Ids::cppLanguageStandard); }
  161. String getCppLanguageStandard() const { return config [Ids::cppLanguageStandard]; }
  162. Value getCppLibTypeValue() { return getValue (Ids::cppLibType); }
  163. String getCppLibType() const { return config [Ids::cppLibType]; }
  164. Value getCodeSignIdentityValue() { return getValue (Ids::codeSigningIdentity); }
  165. String getCodeSignIdentity() const { return config [Ids::codeSigningIdentity]; }
  166. Value getFastMathValue() { return getValue (Ids::fastMath); }
  167. bool isFastMathEnabled() const { return config [Ids::fastMath]; }
  168. Value getLinkTimeOptimisationValue() { return getValue (Ids::linkTimeOptimisation); }
  169. bool isLinkTimeOptimisationEnabled() const { return config [Ids::linkTimeOptimisation]; }
  170. var getDefaultOptimisationLevel() const override { return var ((int) (isDebug() ? gccO0 : gccO3)); }
  171. void createConfigProperties (PropertyListBuilder& props) override
  172. {
  173. addGCCOptimisationProperty (props);
  174. if (iOS)
  175. {
  176. const char* iosVersions[] = { "Use Default", "4.3", "5.0", "5.1", "6.0", "6.1", "7.0", "7.1", "8.0", "8.1", "8.2", "8.3", "8.4", 0 };
  177. const char* iosVersionValues[] = { osxVersionDefault, "4.3", "5.0", "5.1", "6.0", "6.1", "7.0", "7.1", "8.0", "8.1", "8.2", "8.3", "8.4", 0 };
  178. props.add (new ChoicePropertyComponent (getiOSCompatibilityVersionValue(), "iOS Deployment Target",
  179. StringArray (iosVersions), Array<var> (iosVersionValues)),
  180. "The minimum version of iOS that the target binary will run on.");
  181. }
  182. else
  183. {
  184. StringArray sdkVersionNames, osxVersionNames;
  185. Array<var> versionValues;
  186. sdkVersionNames.add ("Use Default");
  187. osxVersionNames.add ("Use Default");
  188. versionValues.add (osxVersionDefault);
  189. for (int ver = oldestSDKVersion; ver <= currentSDKVersion; ++ver)
  190. {
  191. sdkVersionNames.add (getSDKName (ver));
  192. osxVersionNames.add (getOSXVersionName (ver));
  193. versionValues.add (getSDKName (ver));
  194. }
  195. props.add (new ChoicePropertyComponent (getMacSDKVersionValue(), "OSX Base SDK Version", sdkVersionNames, versionValues),
  196. "The version of OSX to link against in the XCode build.");
  197. props.add (new ChoicePropertyComponent (getMacCompatibilityVersionValue(), "OSX Deployment Target", osxVersionNames, versionValues),
  198. "The minimum version of OSX that the target binary will be compatible with.");
  199. const char* osxArch[] = { "Use Default", "Native architecture of build machine",
  200. "Universal Binary (32-bit)", "Universal Binary (32/64-bit)", "64-bit Intel", 0 };
  201. const char* osxArchValues[] = { osxArch_Default, osxArch_Native, osxArch_32BitUniversal,
  202. osxArch_64BitUniversal, osxArch_64Bit, 0 };
  203. props.add (new ChoicePropertyComponent (getMacArchitectureValue(), "OSX Architecture",
  204. StringArray (osxArch), Array<var> (osxArchValues)),
  205. "The type of OSX binary that will be produced.");
  206. }
  207. props.add (new TextPropertyComponent (getCustomXcodeFlagsValue(), "Custom Xcode flags", 8192, false),
  208. "A comma-separated list of custom Xcode setting flags which will be appended to the list of generated flags, "
  209. "e.g. MACOSX_DEPLOYMENT_TARGET_i386 = 10.5, VALID_ARCHS = \"ppc i386 x86_64\"");
  210. const char* cppLanguageStandardNames[] = { "Use Default", "C++98", "GNU++98", "C++11", "GNU++11", "C++14", "GNU++14", nullptr };
  211. Array<var> cppLanguageStandardValues;
  212. cppLanguageStandardValues.add (var::null);
  213. cppLanguageStandardValues.add ("c++98");
  214. cppLanguageStandardValues.add ("gnu++98");
  215. cppLanguageStandardValues.add ("c++11");
  216. cppLanguageStandardValues.add ("gnu++11");
  217. cppLanguageStandardValues.add ("c++14");
  218. cppLanguageStandardValues.add ("gnu++14");
  219. props.add (new ChoicePropertyComponent (getCppLanguageStandardValue(), "C++ Language Standard", StringArray (cppLanguageStandardNames), cppLanguageStandardValues),
  220. "The standard of the C++ language that will be used for compilation.");
  221. const char* cppLibNames[] = { "Use Default", "LLVM libc++", "GNU libstdc++", nullptr };
  222. Array<var> cppLibValues;
  223. cppLibValues.add (var::null);
  224. cppLibValues.add ("libc++");
  225. cppLibValues.add ("libstdc++");
  226. props.add (new ChoicePropertyComponent (getCppLibTypeValue(), "C++ Library", StringArray (cppLibNames), cppLibValues),
  227. "The type of C++ std lib that will be linked.");
  228. props.add (new TextPropertyComponent (getCodeSignIdentityValue(), "Code-signing Identity", 8192, false),
  229. "The name of a code-signing identity for Xcode to apply.");
  230. props.add (new BooleanPropertyComponent (getFastMathValue(), "Relax IEEE compliance", "Enabled"),
  231. "Enable this to use FAST_MATH non-IEEE mode. (Warning: this can have unexpected results!)");
  232. props.add (new BooleanPropertyComponent (getLinkTimeOptimisationValue(), "Link-Time Optimisation", "Enabled"),
  233. "Enable this to perform link-time code generation. This is recommended for release builds.");
  234. }
  235. bool iOS;
  236. };
  237. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  238. {
  239. return new XcodeBuildConfiguration (project, v, iOS);
  240. }
  241. private:
  242. mutable OwnedArray<ValueTree> pbxBuildFiles, pbxFileReferences, pbxGroups, misc, projectConfigs, targetConfigs;
  243. mutable StringArray buildPhaseIDs, resourceIDs, sourceIDs, frameworkIDs;
  244. mutable StringArray frameworkFileIDs, rezFileIDs, resourceFileRefs;
  245. mutable File infoPlistFile, menuNibFile, iconFile;
  246. const bool iOS;
  247. static String sanitisePath (const String& path)
  248. {
  249. if (path.startsWithChar ('~'))
  250. return "$(HOME)" + path.substring (1);
  251. return path;
  252. }
  253. static String addQuotesIfContainsSpace (const String& s)
  254. {
  255. return s.containsChar (' ') ? s.quoted() : s;
  256. }
  257. File getProjectBundle() const { return getTargetFolder().getChildFile (project.getProjectFilenameRoot()).withFileExtension (".xcodeproj"); }
  258. //==============================================================================
  259. void createObjects() const
  260. {
  261. addFrameworks();
  262. addMainBuildProduct();
  263. if (xcodeCreatePList)
  264. {
  265. RelativePath plistPath (infoPlistFile, getTargetFolder(), RelativePath::buildTargetFolder);
  266. addFileReference (plistPath.toUnixStyle());
  267. resourceFileRefs.add (createFileRefID (plistPath));
  268. }
  269. if (iOS)
  270. {
  271. if (! projectType.isStaticLibrary())
  272. createiOSAssetsFolder();
  273. }
  274. else
  275. {
  276. MemoryOutputStream nib;
  277. nib.write (BinaryData::RecentFilesMenuTemplate_nib, BinaryData::RecentFilesMenuTemplate_nibSize);
  278. overwriteFileIfDifferentOrThrow (menuNibFile, nib);
  279. RelativePath menuNibPath (menuNibFile, getTargetFolder(), RelativePath::buildTargetFolder);
  280. addFileReference (menuNibPath.toUnixStyle());
  281. resourceIDs.add (addBuildFile (menuNibPath, false, false));
  282. resourceFileRefs.add (createFileRefID (menuNibPath));
  283. }
  284. if (iconFile.exists())
  285. {
  286. RelativePath iconPath (iconFile, getTargetFolder(), RelativePath::buildTargetFolder);
  287. addFileReference (iconPath.toUnixStyle());
  288. resourceIDs.add (addBuildFile (iconPath, false, false));
  289. resourceFileRefs.add (createFileRefID (iconPath));
  290. }
  291. {
  292. StringArray topLevelGroupIDs;
  293. for (int i = 0; i < getAllGroups().size(); ++i)
  294. {
  295. const Project::Item& group = getAllGroups().getReference(i);
  296. if (group.getNumChildren() > 0)
  297. topLevelGroupIDs.add (addProjectItem (group));
  298. }
  299. { // Add 'resources' group
  300. String resourcesGroupID (createID ("__resources"));
  301. addGroup (resourcesGroupID, "Resources", resourceFileRefs);
  302. topLevelGroupIDs.add (resourcesGroupID);
  303. }
  304. { // Add 'frameworks' group
  305. String frameworksGroupID (createID ("__frameworks"));
  306. addGroup (frameworksGroupID, "Frameworks", frameworkFileIDs);
  307. topLevelGroupIDs.add (frameworksGroupID);
  308. }
  309. { // Add 'products' group
  310. String productsGroupID (createID ("__products"));
  311. StringArray products;
  312. products.add (createID ("__productFileID"));
  313. addGroup (productsGroupID, "Products", products);
  314. topLevelGroupIDs.add (productsGroupID);
  315. }
  316. addGroup (createID ("__mainsourcegroup"), "Source", topLevelGroupIDs);
  317. }
  318. for (ConstConfigIterator config (*this); config.next();)
  319. {
  320. const XcodeBuildConfiguration& xcodeConfig = dynamic_cast <const XcodeBuildConfiguration&> (*config);
  321. addProjectConfig (config->getName(), getProjectSettings (xcodeConfig));
  322. addTargetConfig (config->getName(), getTargetSettings (xcodeConfig));
  323. }
  324. addConfigList (projectConfigs, createID ("__projList"));
  325. addConfigList (targetConfigs, createID ("__configList"));
  326. addShellScriptBuildPhase ("Pre-build script", getPreBuildScript());
  327. if (! projectType.isStaticLibrary())
  328. addBuildPhase ("PBXResourcesBuildPhase", resourceIDs);
  329. if (rezFileIDs.size() > 0)
  330. addBuildPhase ("PBXRezBuildPhase", rezFileIDs);
  331. addBuildPhase ("PBXSourcesBuildPhase", sourceIDs);
  332. if (! projectType.isStaticLibrary())
  333. addBuildPhase ("PBXFrameworksBuildPhase", frameworkIDs);
  334. addShellScriptBuildPhase ("Post-build script", getPostBuildScript());
  335. addTargetObject();
  336. addProjectObject();
  337. }
  338. static Image fixMacIconImageSize (Drawable& image)
  339. {
  340. const int validSizes[] = { 16, 32, 48, 128, 256, 512, 1024 };
  341. const int w = image.getWidth();
  342. const int h = image.getHeight();
  343. int bestSize = 16;
  344. for (int i = 0; i < numElementsInArray (validSizes); ++i)
  345. {
  346. if (w == h && w == validSizes[i])
  347. {
  348. bestSize = w;
  349. break;
  350. }
  351. if (jmax (w, h) > validSizes[i])
  352. bestSize = validSizes[i];
  353. }
  354. return rescaleImageForIcon (image, bestSize);
  355. }
  356. static void writeOldIconFormat (MemoryOutputStream& out, const Image& image, const char* type, const char* maskType)
  357. {
  358. const int w = image.getWidth();
  359. const int h = image.getHeight();
  360. out.write (type, 4);
  361. out.writeIntBigEndian (8 + 4 * w * h);
  362. const Image::BitmapData bitmap (image, Image::BitmapData::readOnly);
  363. for (int y = 0; y < h; ++y)
  364. {
  365. for (int x = 0; x < w; ++x)
  366. {
  367. const Colour pixel (bitmap.getPixelColour (x, y));
  368. out.writeByte ((char) pixel.getAlpha());
  369. out.writeByte ((char) pixel.getRed());
  370. out.writeByte ((char) pixel.getGreen());
  371. out.writeByte ((char) pixel.getBlue());
  372. }
  373. }
  374. out.write (maskType, 4);
  375. out.writeIntBigEndian (8 + w * h);
  376. for (int y = 0; y < h; ++y)
  377. {
  378. for (int x = 0; x < w; ++x)
  379. {
  380. const Colour pixel (bitmap.getPixelColour (x, y));
  381. out.writeByte ((char) pixel.getAlpha());
  382. }
  383. }
  384. }
  385. static void writeNewIconFormat (MemoryOutputStream& out, const Image& image, const char* type)
  386. {
  387. MemoryOutputStream pngData;
  388. PNGImageFormat pngFormat;
  389. pngFormat.writeImageToStream (image, pngData);
  390. out.write (type, 4);
  391. out.writeIntBigEndian (8 + (int) pngData.getDataSize());
  392. out << pngData;
  393. }
  394. void writeIcnsFile (const OwnedArray<Drawable>& images, OutputStream& out) const
  395. {
  396. MemoryOutputStream data;
  397. int smallest = 0x7fffffff;
  398. Drawable* smallestImage = nullptr;
  399. for (int i = 0; i < images.size(); ++i)
  400. {
  401. const Image image (fixMacIconImageSize (*images.getUnchecked(i)));
  402. jassert (image.getWidth() == image.getHeight());
  403. if (image.getWidth() < smallest)
  404. {
  405. smallest = image.getWidth();
  406. smallestImage = images.getUnchecked(i);
  407. }
  408. switch (image.getWidth())
  409. {
  410. case 16: writeOldIconFormat (data, image, "is32", "s8mk"); break;
  411. case 32: writeOldIconFormat (data, image, "il32", "l8mk"); break;
  412. case 48: writeOldIconFormat (data, image, "ih32", "h8mk"); break;
  413. case 128: writeOldIconFormat (data, image, "it32", "t8mk"); break;
  414. case 256: writeNewIconFormat (data, image, "ic08"); break;
  415. case 512: writeNewIconFormat (data, image, "ic09"); break;
  416. case 1024: writeNewIconFormat (data, image, "ic10"); break;
  417. default: break;
  418. }
  419. }
  420. jassert (data.getDataSize() > 0); // no suitable sized images?
  421. // If you only supply a 1024 image, the file doesn't work on 10.8, so we need
  422. // to force a smaller one in there too..
  423. if (smallest > 512 && smallestImage != nullptr)
  424. writeNewIconFormat (data, rescaleImageForIcon (*smallestImage, 512), "ic09");
  425. out.write ("icns", 4);
  426. out.writeIntBigEndian ((int) data.getDataSize() + 8);
  427. out << data;
  428. }
  429. void getIconImages (OwnedArray<Drawable>& images) const
  430. {
  431. ScopedPointer<Drawable> bigIcon (getBigIcon());
  432. if (bigIcon != nullptr)
  433. images.add (bigIcon.release());
  434. ScopedPointer<Drawable> smallIcon (getSmallIcon());
  435. if (smallIcon != nullptr)
  436. images.add (smallIcon.release());
  437. }
  438. void createiOSIconFiles (File appIconSet) const
  439. {
  440. const Array<AppIconType> types (getiOSAppIconTypes());
  441. OwnedArray<Drawable> images;
  442. getIconImages (images);
  443. if (images.size() > 0)
  444. {
  445. for (int i = 0; i < types.size(); ++i)
  446. {
  447. const AppIconType type = types.getUnchecked(i);
  448. const Image image (rescaleImageForIcon (*images.getFirst(), type.size));
  449. MemoryOutputStream pngData;
  450. PNGImageFormat pngFormat;
  451. pngFormat.writeImageToStream (image, pngData);
  452. overwriteFileIfDifferentOrThrow (appIconSet.getChildFile (type.filename), pngData);
  453. }
  454. }
  455. }
  456. void createIconFile() const
  457. {
  458. OwnedArray<Drawable> images;
  459. getIconImages (images);
  460. if (images.size() > 0)
  461. {
  462. MemoryOutputStream mo;
  463. writeIcnsFile (images, mo);
  464. iconFile = getTargetFolder().getChildFile ("Icon.icns");
  465. overwriteFileIfDifferentOrThrow (iconFile, mo);
  466. }
  467. }
  468. void writeInfoPlistFile() const
  469. {
  470. if (! xcodeCreatePList)
  471. return;
  472. ScopedPointer<XmlElement> plist (XmlDocument::parse (getPListToMergeString()));
  473. if (plist == nullptr || ! plist->hasTagName ("plist"))
  474. plist = new XmlElement ("plist");
  475. XmlElement* dict = plist->getChildByName ("dict");
  476. if (dict == nullptr)
  477. dict = plist->createNewChildElement ("dict");
  478. if (iOS)
  479. {
  480. addPlistDictionaryKeyBool (dict, "LSRequiresIPhoneOS", true);
  481. addPlistDictionaryKeyBool (dict, "UIViewControllerBasedStatusBarAppearance", false);
  482. }
  483. addPlistDictionaryKey (dict, "CFBundleExecutable", "${EXECUTABLE_NAME}");
  484. addPlistDictionaryKey (dict, "CFBundleIconFile", iconFile.exists() ? iconFile.getFileName() : String());
  485. addPlistDictionaryKey (dict, "CFBundleIdentifier", project.getBundleIdentifier().toString());
  486. addPlistDictionaryKey (dict, "CFBundleName", projectName);
  487. addPlistDictionaryKey (dict, "CFBundlePackageType", xcodePackageType);
  488. addPlistDictionaryKey (dict, "CFBundleSignature", xcodeBundleSignature);
  489. addPlistDictionaryKey (dict, "CFBundleShortVersionString", project.getVersionString());
  490. addPlistDictionaryKey (dict, "CFBundleVersion", project.getVersionString());
  491. addPlistDictionaryKey (dict, "NSHumanReadableCopyright", project.getCompanyName().toString());
  492. addPlistDictionaryKeyBool (dict, "NSHighResolutionCapable", true);
  493. StringArray documentExtensions;
  494. documentExtensions.addTokens (replacePreprocessorDefs (getAllPreprocessorDefs(), settings ["documentExtensions"]),
  495. ",", StringRef());
  496. documentExtensions.trim();
  497. documentExtensions.removeEmptyStrings (true);
  498. if (documentExtensions.size() > 0)
  499. {
  500. dict->createNewChildElement ("key")->addTextElement ("CFBundleDocumentTypes");
  501. XmlElement* dict2 = dict->createNewChildElement ("array")->createNewChildElement ("dict");
  502. XmlElement* arrayTag = nullptr;
  503. for (int i = 0; i < documentExtensions.size(); ++i)
  504. {
  505. String ex (documentExtensions[i]);
  506. if (ex.startsWithChar ('.'))
  507. ex = ex.substring (1);
  508. if (arrayTag == nullptr)
  509. {
  510. dict2->createNewChildElement ("key")->addTextElement ("CFBundleTypeExtensions");
  511. arrayTag = dict2->createNewChildElement ("array");
  512. addPlistDictionaryKey (dict2, "CFBundleTypeName", ex);
  513. addPlistDictionaryKey (dict2, "CFBundleTypeRole", "Editor");
  514. addPlistDictionaryKey (dict2, "NSPersistentStoreTypeKey", "XML");
  515. }
  516. arrayTag->createNewChildElement ("string")->addTextElement (ex);
  517. }
  518. }
  519. if (settings ["UIFileSharingEnabled"])
  520. addPlistDictionaryKeyBool (dict, "UIFileSharingEnabled", true);
  521. if (settings ["UIStatusBarHidden"])
  522. addPlistDictionaryKeyBool (dict, "UIStatusBarHidden", true);
  523. if (iOS)
  524. {
  525. static const char* kDefaultiOSOrientationStrings[] =
  526. {
  527. "UIInterfaceOrientationPortrait",
  528. "UIInterfaceOrientationPortraitUpsideDown",
  529. "UIInterfaceOrientationLandscapeLeft",
  530. "UIInterfaceOrientationLandscapeRight",
  531. nullptr
  532. };
  533. StringArray iOSOrientations (kDefaultiOSOrientationStrings);
  534. dict->createNewChildElement ("key")->addTextElement ("UISupportedInterfaceOrientations");
  535. XmlElement* plistStringArray = dict->createNewChildElement ("array");
  536. for (int i = 0; i < iOSOrientations.size(); ++i)
  537. plistStringArray->createNewChildElement ("string")->addTextElement (iOSOrientations[i]);
  538. }
  539. for (int i = 0; i < xcodeExtraPListEntries.size(); ++i)
  540. dict->addChildElement (new XmlElement (xcodeExtraPListEntries.getReference(i)));
  541. MemoryOutputStream mo;
  542. plist->writeToStream (mo, "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
  543. overwriteFileIfDifferentOrThrow (infoPlistFile, mo);
  544. }
  545. void deleteRsrcFiles() const
  546. {
  547. for (DirectoryIterator di (getTargetFolder().getChildFile ("build"), true, "*.rsrc", File::findFiles); di.next();)
  548. di.getFile().deleteFile();
  549. }
  550. String getHeaderSearchPaths (const BuildConfiguration& config) const
  551. {
  552. StringArray paths (extraSearchPaths);
  553. paths.addArray (config.getHeaderSearchPaths());
  554. paths.add ("$(inherited)");
  555. paths = getCleanedStringArray (paths);
  556. for (int i = 0; i < paths.size(); ++i)
  557. {
  558. String& s = paths.getReference(i);
  559. s = replacePreprocessorTokens (config, s);
  560. if (s.containsChar (' '))
  561. s = "\"\\\"" + s + "\\\"\""; // crazy double quotes required when there are spaces..
  562. else
  563. s = "\"" + s + "\"";
  564. }
  565. return "(" + paths.joinIntoString (", ") + ")";
  566. }
  567. static String getLinkerFlagForLib (String library)
  568. {
  569. if (library.substring (0, 3) == "lib")
  570. library = library.substring (3);
  571. return "-l" + library.upToLastOccurrenceOf (".", false, false);
  572. }
  573. void getLinkerFlagsForStaticLibrary (const RelativePath& library, StringArray& flags, StringArray& librarySearchPaths) const
  574. {
  575. flags.add (getLinkerFlagForLib (library.getFileNameWithoutExtension()));
  576. String searchPath (library.toUnixStyle().upToLastOccurrenceOf ("/", false, false));
  577. if (! library.isAbsolute())
  578. {
  579. String srcRoot (rebaseFromProjectFolderToBuildTarget (RelativePath (".", RelativePath::projectFolder)).toUnixStyle());
  580. if (srcRoot.endsWith ("/.")) srcRoot = srcRoot.dropLastCharacters (2);
  581. if (! srcRoot.endsWithChar ('/')) srcRoot << '/';
  582. searchPath = srcRoot + searchPath;
  583. }
  584. librarySearchPaths.add (sanitisePath (searchPath));
  585. }
  586. void getLinkerFlags (const BuildConfiguration& config, StringArray& flags, StringArray& librarySearchPaths) const
  587. {
  588. if (xcodeIsBundle)
  589. flags.add ("-bundle");
  590. const Array<RelativePath>& extraLibs = config.isDebug() ? xcodeExtraLibrariesDebug
  591. : xcodeExtraLibrariesRelease;
  592. for (int i = 0; i < extraLibs.size(); ++i)
  593. getLinkerFlagsForStaticLibrary (extraLibs.getReference(i), flags, librarySearchPaths);
  594. flags.add (replacePreprocessorTokens (config, getExtraLinkerFlagsString()));
  595. flags.add (getExternalLibraryFlags (config));
  596. for (int i = 0; i < xcodeLibs.size(); ++i)
  597. flags.add (getLinkerFlagForLib (xcodeLibs[i]));
  598. flags = getCleanedStringArray (flags);
  599. }
  600. StringArray getProjectSettings (const XcodeBuildConfiguration& config) const
  601. {
  602. StringArray s;
  603. s.add ("ALWAYS_SEARCH_USER_PATHS = NO");
  604. s.add ("GCC_C_LANGUAGE_STANDARD = c99");
  605. s.add ("GCC_WARN_ABOUT_RETURN_TYPE = YES");
  606. s.add ("GCC_WARN_CHECK_SWITCH_STATEMENTS = YES");
  607. s.add ("GCC_WARN_UNUSED_VARIABLE = YES");
  608. s.add ("GCC_WARN_MISSING_PARENTHESES = YES");
  609. s.add ("GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES");
  610. s.add ("GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES");
  611. s.add ("WARNING_CFLAGS = -Wreorder");
  612. s.add ("GCC_MODEL_TUNING = G5");
  613. if (projectType.isStaticLibrary())
  614. {
  615. s.add ("GCC_INLINES_ARE_PRIVATE_EXTERN = NO");
  616. s.add ("GCC_SYMBOLS_PRIVATE_EXTERN = NO");
  617. }
  618. else
  619. {
  620. s.add ("GCC_INLINES_ARE_PRIVATE_EXTERN = YES");
  621. }
  622. if (config.isDebug())
  623. if (config.getMacArchitecture() == osxArch_Default || config.getMacArchitecture().isEmpty())
  624. s.add ("ONLY_ACTIVE_ARCH = YES");
  625. if (iOS)
  626. {
  627. s.add ("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\"");
  628. s.add ("SDKROOT = iphoneos");
  629. s.add ("TARGETED_DEVICE_FAMILY = \"1,2\"");
  630. const String iosVersion (config.getiOSCompatibilityVersion());
  631. if (iosVersion.isNotEmpty() && iosVersion != osxVersionDefault)
  632. s.add ("IPHONEOS_DEPLOYMENT_TARGET = " + iosVersion);
  633. }
  634. s.add ("ZERO_LINK = NO");
  635. if (xcodeCanUseDwarf)
  636. s.add ("DEBUG_INFORMATION_FORMAT = \"dwarf\"");
  637. s.add ("PRODUCT_NAME = \"" + replacePreprocessorTokens (config, config.getTargetBinaryNameString()) + "\"");
  638. return s;
  639. }
  640. StringArray getTargetSettings (const XcodeBuildConfiguration& config) const
  641. {
  642. StringArray s;
  643. const String arch (config.getMacArchitecture());
  644. if (arch == osxArch_Native) s.add ("ARCHS = \"$(NATIVE_ARCH_ACTUAL)\"");
  645. else if (arch == osxArch_32BitUniversal) s.add ("ARCHS = \"$(ARCHS_STANDARD_32_BIT)\"");
  646. else if (arch == osxArch_64BitUniversal) s.add ("ARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\"");
  647. else if (arch == osxArch_64Bit) s.add ("ARCHS = \"$(ARCHS_STANDARD_64_BIT)\"");
  648. s.add ("HEADER_SEARCH_PATHS = " + getHeaderSearchPaths (config));
  649. s.add ("GCC_OPTIMIZATION_LEVEL = " + config.getGCCOptimisationFlag());
  650. s.add ("INFOPLIST_FILE = " + infoPlistFile.getFileName());
  651. if (config.isLinkTimeOptimisationEnabled())
  652. s.add ("LLVM_LTO = YES");
  653. if (config.isFastMathEnabled())
  654. s.add ("GCC_FAST_MATH = YES");
  655. const String extraFlags (replacePreprocessorTokens (config, getExtraCompilerFlagsString()).trim());
  656. if (extraFlags.isNotEmpty())
  657. s.add ("OTHER_CPLUSPLUSFLAGS = \"" + extraFlags + "\"");
  658. if (xcodeProductInstallPath.isNotEmpty())
  659. s.add ("INSTALL_PATH = \"" + xcodeProductInstallPath + "\"");
  660. if (xcodeIsBundle)
  661. {
  662. s.add ("LIBRARY_STYLE = Bundle");
  663. s.add ("WRAPPER_EXTENSION = " + xcodeBundleExtension.substring (1));
  664. s.add ("GENERATE_PKGINFO_FILE = YES");
  665. }
  666. if (xcodeOtherRezFlags.isNotEmpty())
  667. s.add ("OTHER_REZFLAGS = \"" + xcodeOtherRezFlags + "\"");
  668. if (config.getTargetBinaryRelativePathString().isNotEmpty())
  669. {
  670. RelativePath binaryPath (config.getTargetBinaryRelativePathString(), RelativePath::projectFolder);
  671. binaryPath = binaryPath.rebased (projectFolder, getTargetFolder(), RelativePath::buildTargetFolder);
  672. s.add ("DSTROOT = " + addQuotesIfContainsSpace (sanitisePath (binaryPath.toUnixStyle())));
  673. s.add ("SYMROOT = " + addQuotesIfContainsSpace (sanitisePath (binaryPath.toUnixStyle())));
  674. }
  675. else
  676. {
  677. s.add ("CONFIGURATION_BUILD_DIR = \"$(PROJECT_DIR)/build/$(CONFIGURATION)\"");
  678. }
  679. String gccVersion ("com.apple.compilers.llvm.clang.1_0");
  680. if (iOS)
  681. {
  682. s.add ("ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon");
  683. s.add ("ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage");
  684. }
  685. else
  686. {
  687. const String sdk (config.getMacSDKVersion());
  688. const String sdkCompat (config.getMacCompatibilityVersion());
  689. for (int ver = oldestSDKVersion; ver <= currentSDKVersion; ++ver)
  690. {
  691. if (sdk == getSDKName (ver)) s.add ("SDKROOT = macosx10." + String (ver));
  692. if (sdkCompat == getSDKName (ver)) s.add ("MACOSX_DEPLOYMENT_TARGET = 10." + String (ver));
  693. }
  694. s.add ("MACOSX_DEPLOYMENT_TARGET_ppc = 10.4");
  695. s.add ("SDKROOT_ppc = macosx10.5");
  696. if (xcodeExcludedFiles64Bit.isNotEmpty())
  697. {
  698. s.add ("EXCLUDED_SOURCE_FILE_NAMES = \"$(EXCLUDED_SOURCE_FILE_NAMES_$(CURRENT_ARCH))\"");
  699. s.add ("EXCLUDED_SOURCE_FILE_NAMES_x86_64 = " + xcodeExcludedFiles64Bit);
  700. }
  701. }
  702. s.add ("GCC_VERSION = " + gccVersion);
  703. s.add ("CLANG_CXX_LANGUAGE_STANDARD = \"c++0x\"");
  704. s.add ("CLANG_LINK_OBJC_RUNTIME = NO");
  705. if (config.getCodeSignIdentity().isNotEmpty())
  706. s.add ("CODE_SIGN_IDENTITY = " + config.getCodeSignIdentity().quoted());
  707. if (config.getCppLanguageStandard().isNotEmpty())
  708. s.add ("CLANG_CXX_LANGUAGE_STANDARD = " + config.getCppLanguageStandard().quoted());
  709. if (config.getCppLibType().isNotEmpty())
  710. s.add ("CLANG_CXX_LIBRARY = " + config.getCppLibType().quoted());
  711. s.add ("COMBINE_HIDPI_IMAGES = YES");
  712. {
  713. StringArray linkerFlags, librarySearchPaths;
  714. getLinkerFlags (config, linkerFlags, librarySearchPaths);
  715. if (linkerFlags.size() > 0)
  716. s.add ("OTHER_LDFLAGS = \"" + linkerFlags.joinIntoString (" ") + "\"");
  717. librarySearchPaths.addArray (config.getLibrarySearchPaths());
  718. librarySearchPaths = getCleanedStringArray (librarySearchPaths);
  719. if (librarySearchPaths.size() > 0)
  720. {
  721. String libPaths ("LIBRARY_SEARCH_PATHS = (\"$(inherited)\"");
  722. for (int i = 0; i < librarySearchPaths.size(); ++i)
  723. libPaths += ", \"\\\"" + librarySearchPaths[i] + "\\\"\"";
  724. s.add (libPaths + ")");
  725. }
  726. }
  727. StringPairArray defines;
  728. if (config.isDebug())
  729. {
  730. defines.set ("_DEBUG", "1");
  731. defines.set ("DEBUG", "1");
  732. s.add ("COPY_PHASE_STRIP = NO");
  733. s.add ("GCC_DYNAMIC_NO_PIC = NO");
  734. }
  735. else
  736. {
  737. defines.set ("_NDEBUG", "1");
  738. defines.set ("NDEBUG", "1");
  739. s.add ("GCC_GENERATE_DEBUGGING_SYMBOLS = NO");
  740. s.add ("GCC_SYMBOLS_PRIVATE_EXTERN = YES");
  741. s.add ("DEAD_CODE_STRIPPING = YES");
  742. }
  743. {
  744. defines = mergePreprocessorDefs (defines, getAllPreprocessorDefs (config));
  745. StringArray defsList;
  746. for (int i = 0; i < defines.size(); ++i)
  747. {
  748. String def (defines.getAllKeys()[i]);
  749. const String value (defines.getAllValues()[i]);
  750. if (value.isNotEmpty())
  751. def << "=" << value.replace ("\"", "\\\"");
  752. defsList.add ("\"" + def + "\"");
  753. }
  754. s.add ("GCC_PREPROCESSOR_DEFINITIONS = " + indentParenthesisedList (defsList));
  755. }
  756. s.addTokens (config.getCustomXcodeFlags(), ",", "\"'");
  757. return getCleanedStringArray (s);
  758. }
  759. void addFrameworks() const
  760. {
  761. if (! projectType.isStaticLibrary())
  762. {
  763. StringArray s (xcodeFrameworks);
  764. s.addTokens (getExtraFrameworksString(), ",;", "\"'");
  765. if (project.getConfigFlag ("JUCE_QUICKTIME") == Project::configFlagDisabled)
  766. s.removeString ("QuickTime");
  767. s.trim();
  768. s.removeDuplicates (true);
  769. s.sort (true);
  770. for (int i = 0; i < s.size(); ++i)
  771. addFramework (s[i]);
  772. }
  773. }
  774. //==============================================================================
  775. void writeProjectFile (OutputStream& output) const
  776. {
  777. output << "// !$*UTF8*$!\n{\n"
  778. "\tarchiveVersion = 1;\n"
  779. "\tclasses = {\n\t};\n"
  780. "\tobjectVersion = 46;\n"
  781. "\tobjects = {\n\n";
  782. Array <ValueTree*> objects;
  783. objects.addArray (pbxBuildFiles);
  784. objects.addArray (pbxFileReferences);
  785. objects.addArray (pbxGroups);
  786. objects.addArray (targetConfigs);
  787. objects.addArray (projectConfigs);
  788. objects.addArray (misc);
  789. for (int i = 0; i < objects.size(); ++i)
  790. {
  791. ValueTree& o = *objects.getUnchecked(i);
  792. output << "\t\t" << o.getType().toString() << " = {";
  793. for (int j = 0; j < o.getNumProperties(); ++j)
  794. {
  795. const Identifier propertyName (o.getPropertyName(j));
  796. String val (o.getProperty (propertyName).toString());
  797. if (val.isEmpty() || (val.containsAnyOf (" \t;<>()=,&+-_@~\r\n\\#%^`*")
  798. && ! (val.trimStart().startsWithChar ('(')
  799. || val.trimStart().startsWithChar ('{'))))
  800. val = "\"" + val + "\"";
  801. output << propertyName.toString() << " = " << val << "; ";
  802. }
  803. output << "};\n";
  804. }
  805. output << "\t};\n\trootObject = " << createID ("__root") << ";\n}\n";
  806. }
  807. String addBuildFile (const String& path, const String& fileRefID, bool addToSourceBuildPhase, bool inhibitWarnings) const
  808. {
  809. String fileID (createID (path + "buildref"));
  810. if (addToSourceBuildPhase)
  811. sourceIDs.add (fileID);
  812. ValueTree* v = new ValueTree (fileID);
  813. v->setProperty ("isa", "PBXBuildFile", nullptr);
  814. v->setProperty ("fileRef", fileRefID, nullptr);
  815. if (inhibitWarnings)
  816. v->setProperty ("settings", "{COMPILER_FLAGS = \"-w\"; }", nullptr);
  817. pbxBuildFiles.add (v);
  818. return fileID;
  819. }
  820. String addBuildFile (const RelativePath& path, bool addToSourceBuildPhase, bool inhibitWarnings) const
  821. {
  822. return addBuildFile (path.toUnixStyle(), createFileRefID (path), addToSourceBuildPhase, inhibitWarnings);
  823. }
  824. String addFileReference (String pathString) const
  825. {
  826. String sourceTree ("SOURCE_ROOT");
  827. RelativePath path (pathString, RelativePath::unknown);
  828. if (pathString.startsWith ("${"))
  829. {
  830. sourceTree = pathString.substring (2).upToFirstOccurrenceOf ("}", false, false);
  831. pathString = pathString.fromFirstOccurrenceOf ("}/", false, false);
  832. }
  833. else if (path.isAbsolute())
  834. {
  835. sourceTree = "<absolute>";
  836. }
  837. const String fileRefID (createFileRefID (pathString));
  838. ScopedPointer<ValueTree> v (new ValueTree (fileRefID));
  839. v->setProperty ("isa", "PBXFileReference", nullptr);
  840. v->setProperty ("lastKnownFileType", getFileType (path), nullptr);
  841. v->setProperty (Ids::name, pathString.fromLastOccurrenceOf ("/", false, false), nullptr);
  842. v->setProperty ("path", sanitisePath (pathString), nullptr);
  843. v->setProperty ("sourceTree", sourceTree, nullptr);
  844. const int existing = pbxFileReferences.indexOfSorted (*this, v);
  845. if (existing >= 0)
  846. {
  847. // If this fails, there's either a string hash collision, or the same file is being added twice (incorrectly)
  848. jassert (pbxFileReferences.getUnchecked (existing)->isEquivalentTo (*v));
  849. }
  850. else
  851. {
  852. pbxFileReferences.addSorted (*this, v.release());
  853. }
  854. return fileRefID;
  855. }
  856. public:
  857. static int compareElements (const ValueTree* first, const ValueTree* second)
  858. {
  859. return first->getType().getCharPointer().compare (second->getType().getCharPointer());
  860. }
  861. private:
  862. static String getFileType (const RelativePath& file)
  863. {
  864. if (file.hasFileExtension (cppFileExtensions)) return "sourcecode.cpp.cpp";
  865. if (file.hasFileExtension (".mm")) return "sourcecode.cpp.objcpp";
  866. if (file.hasFileExtension (".m")) return "sourcecode.c.objc";
  867. if (file.hasFileExtension (".c")) return "sourcecode.c.c";
  868. if (file.hasFileExtension (headerFileExtensions)) return "sourcecode.c.h";
  869. if (file.hasFileExtension (asmFileExtensions)) return "sourcecode.c.asm";
  870. if (file.hasFileExtension (".framework")) return "wrapper.framework";
  871. if (file.hasFileExtension (".jpeg;.jpg")) return "image.jpeg";
  872. if (file.hasFileExtension ("png;gif")) return "image" + file.getFileExtension();
  873. if (file.hasFileExtension ("html;htm")) return "text.html";
  874. if (file.hasFileExtension ("xml;zip;wav")) return "file" + file.getFileExtension();
  875. if (file.hasFileExtension ("txt;rtf")) return "text" + file.getFileExtension();
  876. if (file.hasFileExtension ("plist")) return "text.plist.xml";
  877. if (file.hasFileExtension ("app")) return "wrapper.application";
  878. if (file.hasFileExtension ("component;vst;plugin")) return "wrapper.cfbundle";
  879. if (file.hasFileExtension ("xcodeproj")) return "wrapper.pb-project";
  880. if (file.hasFileExtension ("a")) return "archive.ar";
  881. if (file.hasFileExtension ("xcassets")) return "folder.assetcatalog";
  882. return "file" + file.getFileExtension();
  883. }
  884. String addFile (const RelativePath& path, bool shouldBeCompiled, bool shouldBeAddedToBinaryResources, bool inhibitWarnings) const
  885. {
  886. const String pathAsString (path.toUnixStyle());
  887. const String refID (addFileReference (path.toUnixStyle()));
  888. if (shouldBeCompiled)
  889. {
  890. if (path.hasFileExtension (".r"))
  891. rezFileIDs.add (addBuildFile (pathAsString, refID, false, inhibitWarnings));
  892. else
  893. addBuildFile (pathAsString, refID, true, inhibitWarnings);
  894. }
  895. else if (! shouldBeAddedToBinaryResources)
  896. {
  897. const String fileType (getFileType (path));
  898. if (fileType.startsWith ("image.") || fileType.startsWith ("text.") || fileType.startsWith ("file."))
  899. {
  900. resourceIDs.add (addBuildFile (pathAsString, refID, false, false));
  901. resourceFileRefs.add (refID);
  902. }
  903. }
  904. return refID;
  905. }
  906. String addProjectItem (const Project::Item& projectItem) const
  907. {
  908. if (projectItem.isGroup())
  909. {
  910. StringArray childIDs;
  911. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  912. {
  913. const String childID (addProjectItem (projectItem.getChild(i)));
  914. if (childID.isNotEmpty())
  915. childIDs.add (childID);
  916. }
  917. return addGroup (projectItem, childIDs);
  918. }
  919. if (projectItem.shouldBeAddedToTargetProject())
  920. {
  921. const String itemPath (projectItem.getFilePath());
  922. RelativePath path;
  923. if (itemPath.startsWith ("${"))
  924. path = RelativePath (itemPath, RelativePath::unknown);
  925. else
  926. path = RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder);
  927. return addFile (path, projectItem.shouldBeCompiled(),
  928. projectItem.shouldBeAddedToBinaryResources(),
  929. projectItem.shouldInhibitWarnings());
  930. }
  931. return String();
  932. }
  933. void addFramework (const String& frameworkName) const
  934. {
  935. String path (frameworkName);
  936. if (! File::isAbsolutePath (path))
  937. path = "System/Library/Frameworks/" + path;
  938. if (! path.endsWithIgnoreCase (".framework"))
  939. path << ".framework";
  940. const String fileRefID (createFileRefID (path));
  941. addFileReference ((File::isAbsolutePath (frameworkName) ? "" : "${SDKROOT}/") + path);
  942. frameworkIDs.add (addBuildFile (path, fileRefID, false, false));
  943. frameworkFileIDs.add (fileRefID);
  944. }
  945. void addGroup (const String& groupID, const String& groupName, const StringArray& childIDs) const
  946. {
  947. ValueTree* v = new ValueTree (groupID);
  948. v->setProperty ("isa", "PBXGroup", nullptr);
  949. v->setProperty ("children", indentParenthesisedList (childIDs), nullptr);
  950. v->setProperty (Ids::name, groupName, nullptr);
  951. v->setProperty ("sourceTree", "<group>", nullptr);
  952. pbxGroups.add (v);
  953. }
  954. String addGroup (const Project::Item& item, StringArray& childIDs) const
  955. {
  956. const String groupName (item.getName());
  957. const String groupID (getIDForGroup (item));
  958. addGroup (groupID, groupName, childIDs);
  959. return groupID;
  960. }
  961. void addMainBuildProduct() const
  962. {
  963. jassert (xcodeFileType.isNotEmpty());
  964. jassert (xcodeBundleExtension.isEmpty() || xcodeBundleExtension.startsWithChar ('.'));
  965. if (ProjectExporter::BuildConfiguration::Ptr config = getConfiguration(0))
  966. {
  967. String productName (replacePreprocessorTokens (*config, config->getTargetBinaryNameString()));
  968. if (xcodeFileType == "archive.ar")
  969. productName = getLibbedFilename (productName);
  970. else
  971. productName += xcodeBundleExtension;
  972. addBuildProduct (xcodeFileType, productName);
  973. }
  974. }
  975. void addBuildProduct (const String& fileType, const String& binaryName) const
  976. {
  977. ValueTree* v = new ValueTree (createID ("__productFileID"));
  978. v->setProperty ("isa", "PBXFileReference", nullptr);
  979. v->setProperty ("explicitFileType", fileType, nullptr);
  980. v->setProperty ("includeInIndex", (int) 0, nullptr);
  981. v->setProperty ("path", sanitisePath (binaryName), nullptr);
  982. v->setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);
  983. pbxFileReferences.add (v);
  984. }
  985. void addTargetConfig (const String& configName, const StringArray& buildSettings) const
  986. {
  987. ValueTree* v = new ValueTree (createID ("targetconfigid_" + configName));
  988. v->setProperty ("isa", "XCBuildConfiguration", nullptr);
  989. v->setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
  990. v->setProperty (Ids::name, configName, nullptr);
  991. targetConfigs.add (v);
  992. }
  993. void addProjectConfig (const String& configName, const StringArray& buildSettings) const
  994. {
  995. ValueTree* v = new ValueTree (createID ("projectconfigid_" + configName));
  996. v->setProperty ("isa", "XCBuildConfiguration", nullptr);
  997. v->setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
  998. v->setProperty (Ids::name, configName, nullptr);
  999. projectConfigs.add (v);
  1000. }
  1001. void addConfigList (const OwnedArray <ValueTree>& configsToUse, const String& listID) const
  1002. {
  1003. StringArray configIDs;
  1004. for (int i = 0; i < configsToUse.size(); ++i)
  1005. configIDs.add (configsToUse[i]->getType().toString());
  1006. ValueTree* v = new ValueTree (listID);
  1007. v->setProperty ("isa", "XCConfigurationList", nullptr);
  1008. v->setProperty ("buildConfigurations", indentParenthesisedList (configIDs), nullptr);
  1009. v->setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
  1010. if (configsToUse[0] != nullptr)
  1011. v->setProperty ("defaultConfigurationName", configsToUse[0]->getProperty (Ids::name), nullptr);
  1012. misc.add (v);
  1013. }
  1014. ValueTree& addBuildPhase (const String& phaseType, const StringArray& fileIds) const
  1015. {
  1016. String phaseId (createID (phaseType + "resbuildphase"));
  1017. int n = 0;
  1018. while (buildPhaseIDs.contains (phaseId))
  1019. phaseId = createID (phaseType + "resbuildphase" + String (++n));
  1020. buildPhaseIDs.add (phaseId);
  1021. ValueTree* v = new ValueTree (phaseId);
  1022. v->setProperty ("isa", phaseType, nullptr);
  1023. v->setProperty ("buildActionMask", "2147483647", nullptr);
  1024. v->setProperty ("files", indentParenthesisedList (fileIds), nullptr);
  1025. v->setProperty ("runOnlyForDeploymentPostprocessing", (int) 0, nullptr);
  1026. misc.add (v);
  1027. return *v;
  1028. }
  1029. void addTargetObject() const
  1030. {
  1031. ValueTree* const v = new ValueTree (createID ("__target"));
  1032. v->setProperty ("isa", "PBXNativeTarget", nullptr);
  1033. v->setProperty ("buildConfigurationList", createID ("__configList"), nullptr);
  1034. v->setProperty ("buildPhases", indentParenthesisedList (buildPhaseIDs), nullptr);
  1035. v->setProperty ("buildRules", "( )", nullptr);
  1036. v->setProperty ("dependencies", "( )", nullptr);
  1037. v->setProperty (Ids::name, projectName, nullptr);
  1038. v->setProperty ("productName", projectName, nullptr);
  1039. v->setProperty ("productReference", createID ("__productFileID"), nullptr);
  1040. if (xcodeProductInstallPath.isNotEmpty())
  1041. v->setProperty ("productInstallPath", xcodeProductInstallPath, nullptr);
  1042. jassert (xcodeProductType.isNotEmpty());
  1043. v->setProperty ("productType", xcodeProductType, nullptr);
  1044. misc.add (v);
  1045. }
  1046. void addProjectObject() const
  1047. {
  1048. ValueTree* const v = new ValueTree (createID ("__root"));
  1049. v->setProperty ("isa", "PBXProject", nullptr);
  1050. v->setProperty ("buildConfigurationList", createID ("__projList"), nullptr);
  1051. v->setProperty ("attributes", "{ LastUpgradeCheck = 0440; }", nullptr);
  1052. v->setProperty ("compatibilityVersion", "Xcode 3.2", nullptr);
  1053. v->setProperty ("hasScannedForEncodings", (int) 0, nullptr);
  1054. v->setProperty ("mainGroup", createID ("__mainsourcegroup"), nullptr);
  1055. v->setProperty ("projectDirPath", "\"\"", nullptr);
  1056. v->setProperty ("projectRoot", "\"\"", nullptr);
  1057. v->setProperty ("targets", "( " + createID ("__target") + " )", nullptr);
  1058. misc.add (v);
  1059. }
  1060. void addShellScriptBuildPhase (const String& phaseName, const String& script) const
  1061. {
  1062. if (script.trim().isNotEmpty())
  1063. {
  1064. ValueTree& v = addBuildPhase ("PBXShellScriptBuildPhase", StringArray());
  1065. v.setProperty (Ids::name, phaseName, nullptr);
  1066. v.setProperty ("shellPath", "/bin/sh", nullptr);
  1067. v.setProperty ("shellScript", script.replace ("\\", "\\\\")
  1068. .replace ("\"", "\\\"")
  1069. .replace ("\r\n", "\\n")
  1070. .replace ("\n", "\\n"), nullptr);
  1071. }
  1072. }
  1073. String getiOSAssetContents (var images) const
  1074. {
  1075. DynamicObject::Ptr v (new DynamicObject());
  1076. var info (new DynamicObject());
  1077. info.getDynamicObject()->setProperty ("version", 1);
  1078. info.getDynamicObject()->setProperty ("author", "xcode");
  1079. v->setProperty ("images", images);
  1080. v->setProperty ("info", info);
  1081. return JSON::toString (var (v));
  1082. }
  1083. struct AppIconType
  1084. {
  1085. const char* idiom;
  1086. const char* sizeString;
  1087. const char* filename;
  1088. const char* scale;
  1089. int size;
  1090. };
  1091. static Array<AppIconType> getiOSAppIconTypes()
  1092. {
  1093. AppIconType types[] =
  1094. {
  1095. { "iphone", "29x29", "Icon-Small.png", "1x", 29 },
  1096. { "iphone", "29x29", "Icon-Small@2x.png", "2x", 58 },
  1097. { "iphone", "40x40", "Icon-Spotlight-40@2x.png", "2x", 80 },
  1098. { "iphone", "57x57", "Icon.png", "1x", 57 },
  1099. { "iphone", "57x57", "Icon@2x.png", "2x", 114 },
  1100. { "iphone", "60x60", "Icon-60@2x.png", "2x", 120 },
  1101. { "iphone", "60x60", "Icon-@3x.png", "3x", 180 },
  1102. { "ipad", "29x29", "Icon-Small-1.png", "1x", 29 },
  1103. { "ipad", "29x29", "Icon-Small@2x-1.png", "2x", 58 },
  1104. { "ipad", "40x40", "Icon-Spotlight-40.png", "1x", 40 },
  1105. { "ipad", "40x40", "Icon-Spotlight-40@2x-1.png", "2x", 80 },
  1106. { "ipad", "50x50", "Icon-Small-50.png", "1x", 50 },
  1107. { "ipad", "50x50", "Icon-Small-50@2x.png", "2x", 100 },
  1108. { "ipad", "72x72", "Icon-72.png", "1x", 72 },
  1109. { "ipad", "72x72", "Icon-72@2x.png", "2x", 144 },
  1110. { "ipad", "76x76", "Icon-76.png", "1x", 76 },
  1111. { "ipad", "76x76", "Icon-76@2x.png", "2x", 152 }
  1112. };
  1113. return Array<AppIconType> (types, numElementsInArray (types));
  1114. }
  1115. String getiOSAppIconContents() const
  1116. {
  1117. const Array<AppIconType> types = getiOSAppIconTypes();
  1118. var images;
  1119. for (int i = 0; i < types.size(); ++i)
  1120. {
  1121. AppIconType type = types.getUnchecked(i);
  1122. DynamicObject::Ptr d = new DynamicObject();
  1123. d->setProperty ("idiom", type.idiom);
  1124. d->setProperty ("size", type.sizeString);
  1125. d->setProperty ("filename", type.filename);
  1126. d->setProperty ("scale", type.scale);
  1127. images.append (var (d));
  1128. }
  1129. return getiOSAssetContents (images);
  1130. }
  1131. String getiOSLaunchImageContents() const
  1132. {
  1133. struct ImageType
  1134. {
  1135. const char* orientation;
  1136. const char* idiom;
  1137. const char* extent;
  1138. const char* scale;
  1139. };
  1140. const ImageType types[] = { { "portrait", "iphone", "full-screen", "2x" },
  1141. { "landscape", "iphone", "full-screen", "2x" },
  1142. { "portrait", "ipad", "full-screen", "1x" },
  1143. { "landscape", "ipad", "full-screen", "1x" },
  1144. { "portrait", "ipad", "full-screen", "2x" },
  1145. { "landscape", "ipad", "full-screen", "2x" } };
  1146. var images;
  1147. for (size_t i = 0; i < sizeof (types) / sizeof (types[0]); ++i)
  1148. {
  1149. DynamicObject::Ptr d = new DynamicObject();
  1150. d->setProperty ("orientation", types[i].orientation);
  1151. d->setProperty ("idiom", types[i].idiom);
  1152. d->setProperty ("extent", types[i].extent);
  1153. d->setProperty ("minimum-system-version", "7.0");
  1154. d->setProperty ("scale", types[i].scale);
  1155. images.append (var (d));
  1156. }
  1157. return getiOSAssetContents (images);
  1158. }
  1159. void createiOSAssetsFolder() const
  1160. {
  1161. File assets (getTargetFolder().getChildFile (project.getProjectFilenameRoot()).getChildFile ("Images.xcassets"));
  1162. overwriteFileIfDifferentOrThrow (assets.getChildFile ("AppIcon.appiconset").getChildFile ("Contents.json"), getiOSAppIconContents());
  1163. createiOSIconFiles (assets.getChildFile ("AppIcon.appiconset"));
  1164. overwriteFileIfDifferentOrThrow (assets.getChildFile ("LaunchImage.launchimage").getChildFile ("Contents.json"), getiOSLaunchImageContents());
  1165. RelativePath assetsPath (assets, getTargetFolder(), RelativePath::buildTargetFolder);
  1166. addFileReference (assetsPath.toUnixStyle());
  1167. resourceIDs.add (addBuildFile (assetsPath, false, false));
  1168. resourceFileRefs.add (createFileRefID (assetsPath));
  1169. }
  1170. //==============================================================================
  1171. static String indentBracedList (const StringArray& list) { return "{" + indentList (list, ";", 0, true) + " }"; }
  1172. static String indentParenthesisedList (const StringArray& list) { return "(" + indentList (list, ",", 1, false) + " )"; }
  1173. static String indentList (const StringArray& list, const String& separator, int extraTabs, bool shouldSort)
  1174. {
  1175. if (list.size() == 0)
  1176. return " ";
  1177. const String tabs ("\n" + String::repeatedString ("\t", extraTabs + 4));
  1178. if (shouldSort)
  1179. {
  1180. StringArray sorted (list);
  1181. sorted.sort (true);
  1182. return tabs + sorted.joinIntoString (separator + tabs) + separator;
  1183. }
  1184. return tabs + list.joinIntoString (separator + tabs) + separator;
  1185. }
  1186. String createID (String rootString) const
  1187. {
  1188. if (rootString.startsWith ("${"))
  1189. rootString = rootString.fromFirstOccurrenceOf ("}/", false, false);
  1190. rootString += project.getProjectUID();
  1191. return MD5 (rootString.toUTF8()).toHexString().substring (0, 24).toUpperCase();
  1192. }
  1193. String createFileRefID (const RelativePath& path) const { return createFileRefID (path.toUnixStyle()); }
  1194. String createFileRefID (const String& path) const { return createID ("__fileref_" + path); }
  1195. String getIDForGroup (const Project::Item& item) const { return createID (item.getID()); }
  1196. bool shouldFileBeCompiledByDefault (const RelativePath& file) const override
  1197. {
  1198. return file.hasFileExtension (sourceFileExtensions) || file.hasFileExtension ("swift");
  1199. }
  1200. static String getOSXVersionName (int version)
  1201. {
  1202. jassert (version >= 4);
  1203. return "10." + String (version);
  1204. }
  1205. static String getSDKName (int version)
  1206. {
  1207. return getOSXVersionName (version) + " SDK";
  1208. }
  1209. void initialiseDependencyPathValues()
  1210. {
  1211. vst2Path.referTo (Value (new DependencyPathValueSource (getSetting (Ids::vstFolder),
  1212. Ids::vst2Path, TargetOS::osx)));
  1213. vst3Path.referTo (Value (new DependencyPathValueSource (getSetting (Ids::vst3Folder),
  1214. Ids::vst3Path, TargetOS::osx)));
  1215. aaxPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::aaxFolder),
  1216. Ids::aaxPath, TargetOS::osx)));
  1217. rtasPath.referTo (Value (new DependencyPathValueSource (getSetting (Ids::rtasFolder),
  1218. Ids::rtasPath, TargetOS::osx)));
  1219. }
  1220. };