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.

1403 lines
58KB

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