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.

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