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.

1393 lines
57KB

  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. void getLinkerFlagsForStaticLibrary (const RelativePath& library, StringArray& flags, StringArray& librarySearchPaths) const
  505. {
  506. jassert (library.getFileNameWithoutExtension().substring (0, 3) == "lib");
  507. flags.add ("-l" + library.getFileNameWithoutExtension().substring (3));
  508. String searchPath (library.toUnixStyle().upToLastOccurrenceOf ("/", false, false));
  509. if (! library.isAbsolute())
  510. {
  511. String srcRoot (rebaseFromProjectFolderToBuildTarget (RelativePath (".", RelativePath::projectFolder)).toUnixStyle());
  512. if (srcRoot.endsWith ("/.")) srcRoot = srcRoot.dropLastCharacters (2);
  513. if (! srcRoot.endsWithChar ('/')) srcRoot << '/';
  514. searchPath = srcRoot + searchPath;
  515. }
  516. librarySearchPaths.add (sanitisePath (searchPath));
  517. }
  518. void getLinkerFlags (const BuildConfiguration& config, StringArray& flags, StringArray& librarySearchPaths) const
  519. {
  520. if (xcodeIsBundle)
  521. flags.add ("-bundle");
  522. const Array<RelativePath>& extraLibs = config.isDebug() ? xcodeExtraLibrariesDebug
  523. : xcodeExtraLibrariesRelease;
  524. for (int i = 0; i < extraLibs.size(); ++i)
  525. getLinkerFlagsForStaticLibrary (extraLibs.getReference(i), flags, librarySearchPaths);
  526. flags.add (replacePreprocessorTokens (config, getExtraLinkerFlagsString()));
  527. flags.add (getExternalLibraryFlags (config));
  528. flags.removeEmptyStrings (true);
  529. }
  530. StringArray getProjectSettings (const XcodeBuildConfiguration& config) const
  531. {
  532. StringArray s;
  533. s.add ("ALWAYS_SEARCH_USER_PATHS = NO");
  534. s.add ("GCC_C_LANGUAGE_STANDARD = c99");
  535. s.add ("GCC_WARN_ABOUT_RETURN_TYPE = YES");
  536. s.add ("GCC_WARN_CHECK_SWITCH_STATEMENTS = YES");
  537. s.add ("GCC_WARN_UNUSED_VARIABLE = YES");
  538. s.add ("GCC_WARN_MISSING_PARENTHESES = YES");
  539. s.add ("GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES");
  540. s.add ("GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES");
  541. s.add ("WARNING_CFLAGS = -Wreorder");
  542. s.add ("GCC_MODEL_TUNING = G5");
  543. if (projectType.isStaticLibrary())
  544. {
  545. s.add ("GCC_INLINES_ARE_PRIVATE_EXTERN = NO");
  546. s.add ("GCC_SYMBOLS_PRIVATE_EXTERN = NO");
  547. }
  548. else
  549. {
  550. s.add ("GCC_INLINES_ARE_PRIVATE_EXTERN = YES");
  551. }
  552. if (config.isDebug())
  553. if (config.getMacArchitecture() == osxArch_Default || config.getMacArchitecture().isEmpty())
  554. s.add ("ONLY_ACTIVE_ARCH = YES");
  555. if (iOS)
  556. {
  557. s.add ("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\"");
  558. s.add ("SDKROOT = iphoneos");
  559. s.add ("TARGETED_DEVICE_FAMILY = \"1,2\"");
  560. const String iosVersion (config.getiOSCompatibilityVersion());
  561. if (iosVersion.isNotEmpty() && iosVersion != osxVersionDefault)
  562. s.add ("IPHONEOS_DEPLOYMENT_TARGET = " + iosVersion);
  563. }
  564. s.add ("ZERO_LINK = NO");
  565. if (xcodeCanUseDwarf)
  566. s.add ("DEBUG_INFORMATION_FORMAT = \"dwarf\"");
  567. s.add ("PRODUCT_NAME = \"" + replacePreprocessorTokens (config, config.getTargetBinaryNameString()) + "\"");
  568. return s;
  569. }
  570. StringArray getTargetSettings (const XcodeBuildConfiguration& config) const
  571. {
  572. StringArray s;
  573. const String arch (config.getMacArchitecture());
  574. if (arch == osxArch_Native) s.add ("ARCHS = \"$(NATIVE_ARCH_ACTUAL)\"");
  575. else if (arch == osxArch_32BitUniversal) s.add ("ARCHS = \"$(ARCHS_STANDARD_32_BIT)\"");
  576. else if (arch == osxArch_64BitUniversal) s.add ("ARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\"");
  577. else if (arch == osxArch_64Bit) s.add ("ARCHS = \"$(ARCHS_STANDARD_64_BIT)\"");
  578. s.add ("HEADER_SEARCH_PATHS = " + getHeaderSearchPaths (config));
  579. s.add ("GCC_OPTIMIZATION_LEVEL = " + config.getGCCOptimisationFlag());
  580. s.add ("INFOPLIST_FILE = " + infoPlistFile.getFileName());
  581. if (config.isLinkTimeOptimisationEnabled())
  582. s.add ("LLVM_LTO = YES");
  583. if (config.isFastMathEnabled())
  584. s.add ("GCC_FAST_MATH = YES");
  585. const String extraFlags (replacePreprocessorTokens (config, getExtraCompilerFlagsString()).trim());
  586. if (extraFlags.isNotEmpty())
  587. s.add ("OTHER_CPLUSPLUSFLAGS = \"" + extraFlags + "\"");
  588. if (xcodeProductInstallPath.isNotEmpty())
  589. s.add ("INSTALL_PATH = \"" + xcodeProductInstallPath + "\"");
  590. if (xcodeIsBundle)
  591. {
  592. s.add ("LIBRARY_STYLE = Bundle");
  593. s.add ("WRAPPER_EXTENSION = " + xcodeBundleExtension.substring (1));
  594. s.add ("GENERATE_PKGINFO_FILE = YES");
  595. }
  596. if (xcodeOtherRezFlags.isNotEmpty())
  597. s.add ("OTHER_REZFLAGS = \"" + xcodeOtherRezFlags + "\"");
  598. if (config.getTargetBinaryRelativePathString().isNotEmpty())
  599. {
  600. RelativePath binaryPath (config.getTargetBinaryRelativePathString(), RelativePath::projectFolder);
  601. binaryPath = binaryPath.rebased (projectFolder, getTargetFolder(), RelativePath::buildTargetFolder);
  602. s.add ("DSTROOT = " + addQuotesIfContainsSpace (sanitisePath (binaryPath.toUnixStyle())));
  603. s.add ("SYMROOT = " + addQuotesIfContainsSpace (sanitisePath (binaryPath.toUnixStyle())));
  604. }
  605. else
  606. {
  607. s.add ("CONFIGURATION_BUILD_DIR = \"$(PROJECT_DIR)/build/$(CONFIGURATION)\"");
  608. }
  609. String gccVersion ("com.apple.compilers.llvm.clang.1_0");
  610. if (iOS)
  611. {
  612. s.add ("ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon");
  613. s.add ("ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage");
  614. }
  615. else
  616. {
  617. const String sdk (config.getMacSDKVersion());
  618. const String sdkCompat (config.getMacCompatibilityVersion());
  619. for (int ver = oldestSDKVersion; ver <= currentSDKVersion; ++ver)
  620. {
  621. if (sdk == getSDKName (ver)) s.add ("SDKROOT = macosx10." + String (ver));
  622. if (sdkCompat == getSDKName (ver)) s.add ("MACOSX_DEPLOYMENT_TARGET = 10." + String (ver));
  623. }
  624. s.add ("MACOSX_DEPLOYMENT_TARGET_ppc = 10.4");
  625. s.add ("SDKROOT_ppc = macosx10.5");
  626. if (xcodeExcludedFiles64Bit.isNotEmpty())
  627. {
  628. s.add ("EXCLUDED_SOURCE_FILE_NAMES = \"$(EXCLUDED_SOURCE_FILE_NAMES_$(CURRENT_ARCH))\"");
  629. s.add ("EXCLUDED_SOURCE_FILE_NAMES_x86_64 = " + xcodeExcludedFiles64Bit);
  630. }
  631. }
  632. s.add ("GCC_VERSION = " + gccVersion);
  633. s.add ("CLANG_CXX_LANGUAGE_STANDARD = \"c++0x\"");
  634. s.add ("CLANG_LINK_OBJC_RUNTIME = NO");
  635. if (config.getCodeSignIdentity().isNotEmpty())
  636. s.add ("CODE_SIGN_IDENTITY = " + config.getCodeSignIdentity().quoted());
  637. if (config.getCppLibType().isNotEmpty())
  638. s.add ("CLANG_CXX_LIBRARY = " + config.getCppLibType().quoted());
  639. s.add ("COMBINE_HIDPI_IMAGES = YES");
  640. {
  641. StringArray linkerFlags, librarySearchPaths;
  642. getLinkerFlags (config, linkerFlags, librarySearchPaths);
  643. if (linkerFlags.size() > 0)
  644. s.add ("OTHER_LDFLAGS = \"" + linkerFlags.joinIntoString (" ") + "\"");
  645. librarySearchPaths.addArray (config.getLibrarySearchPaths());
  646. librarySearchPaths.removeDuplicates (false);
  647. if (librarySearchPaths.size() > 0)
  648. {
  649. String libPaths ("LIBRARY_SEARCH_PATHS = (\"$(inherited)\"");
  650. for (int i = 0; i < librarySearchPaths.size(); ++i)
  651. libPaths += ", \"\\\"" + librarySearchPaths[i] + "\\\"\"";
  652. s.add (libPaths + ")");
  653. }
  654. }
  655. StringPairArray defines;
  656. if (config.isDebug())
  657. {
  658. defines.set ("_DEBUG", "1");
  659. defines.set ("DEBUG", "1");
  660. s.add ("COPY_PHASE_STRIP = NO");
  661. s.add ("GCC_DYNAMIC_NO_PIC = NO");
  662. }
  663. else
  664. {
  665. defines.set ("_NDEBUG", "1");
  666. defines.set ("NDEBUG", "1");
  667. s.add ("GCC_GENERATE_DEBUGGING_SYMBOLS = NO");
  668. s.add ("GCC_SYMBOLS_PRIVATE_EXTERN = YES");
  669. s.add ("DEAD_CODE_STRIPPING = YES");
  670. }
  671. {
  672. defines = mergePreprocessorDefs (defines, getAllPreprocessorDefs (config));
  673. StringArray defsList;
  674. for (int i = 0; i < defines.size(); ++i)
  675. {
  676. String def (defines.getAllKeys()[i]);
  677. const String value (defines.getAllValues()[i]);
  678. if (value.isNotEmpty())
  679. def << "=" << value.replace ("\"", "\\\"");
  680. defsList.add ("\"" + def + "\"");
  681. }
  682. s.add ("GCC_PREPROCESSOR_DEFINITIONS = " + indentParenthesisedList (defsList));
  683. }
  684. s.addTokens (config.getCustomXcodeFlags(), ",", "\"'");
  685. s.trim();
  686. s.removeEmptyStrings();
  687. s.removeDuplicates (false);
  688. return s;
  689. }
  690. void addFrameworks() const
  691. {
  692. if (! projectType.isStaticLibrary())
  693. {
  694. StringArray s (xcodeFrameworks);
  695. s.addTokens (getExtraFrameworksString(), ",;", "\"'");
  696. if (project.getConfigFlag ("JUCE_QUICKTIME") == Project::configFlagDisabled)
  697. s.removeString ("QuickTime");
  698. s.trim();
  699. s.removeDuplicates (true);
  700. s.sort (true);
  701. for (int i = 0; i < s.size(); ++i)
  702. addFramework (s[i]);
  703. }
  704. }
  705. //==============================================================================
  706. void writeProjectFile (OutputStream& output) const
  707. {
  708. output << "// !$*UTF8*$!\n{\n"
  709. "\tarchiveVersion = 1;\n"
  710. "\tclasses = {\n\t};\n"
  711. "\tobjectVersion = 46;\n"
  712. "\tobjects = {\n\n";
  713. Array <ValueTree*> objects;
  714. objects.addArray (pbxBuildFiles);
  715. objects.addArray (pbxFileReferences);
  716. objects.addArray (pbxGroups);
  717. objects.addArray (targetConfigs);
  718. objects.addArray (projectConfigs);
  719. objects.addArray (misc);
  720. for (int i = 0; i < objects.size(); ++i)
  721. {
  722. ValueTree& o = *objects.getUnchecked(i);
  723. output << "\t\t" << o.getType().toString() << " = {";
  724. for (int j = 0; j < o.getNumProperties(); ++j)
  725. {
  726. const Identifier propertyName (o.getPropertyName(j));
  727. String val (o.getProperty (propertyName).toString());
  728. if (val.isEmpty() || (val.containsAnyOf (" \t;<>()=,&+-_@~\r\n\\#%^`*")
  729. && ! (val.trimStart().startsWithChar ('(')
  730. || val.trimStart().startsWithChar ('{'))))
  731. val = "\"" + val + "\"";
  732. output << propertyName.toString() << " = " << val << "; ";
  733. }
  734. output << "};\n";
  735. }
  736. output << "\t};\n\trootObject = " << createID ("__root") << ";\n}\n";
  737. }
  738. String addBuildFile (const String& path, const String& fileRefID, bool addToSourceBuildPhase, bool inhibitWarnings) const
  739. {
  740. String fileID (createID (path + "buildref"));
  741. if (addToSourceBuildPhase)
  742. sourceIDs.add (fileID);
  743. ValueTree* v = new ValueTree (fileID);
  744. v->setProperty ("isa", "PBXBuildFile", nullptr);
  745. v->setProperty ("fileRef", fileRefID, nullptr);
  746. if (inhibitWarnings)
  747. v->setProperty ("settings", "{COMPILER_FLAGS = \"-w\"; }", nullptr);
  748. pbxBuildFiles.add (v);
  749. return fileID;
  750. }
  751. String addBuildFile (const RelativePath& path, bool addToSourceBuildPhase, bool inhibitWarnings) const
  752. {
  753. return addBuildFile (path.toUnixStyle(), createFileRefID (path), addToSourceBuildPhase, inhibitWarnings);
  754. }
  755. String addFileReference (String pathString) const
  756. {
  757. String sourceTree ("SOURCE_ROOT");
  758. RelativePath path (pathString, RelativePath::unknown);
  759. if (pathString.startsWith ("${"))
  760. {
  761. sourceTree = pathString.substring (2).upToFirstOccurrenceOf ("}", false, false);
  762. pathString = pathString.fromFirstOccurrenceOf ("}/", false, false);
  763. }
  764. else if (path.isAbsolute())
  765. {
  766. sourceTree = "<absolute>";
  767. }
  768. const String fileRefID (createFileRefID (pathString));
  769. ScopedPointer<ValueTree> v (new ValueTree (fileRefID));
  770. v->setProperty ("isa", "PBXFileReference", nullptr);
  771. v->setProperty ("lastKnownFileType", getFileType (path), nullptr);
  772. v->setProperty (Ids::name, pathString.fromLastOccurrenceOf ("/", false, false), nullptr);
  773. v->setProperty ("path", sanitisePath (pathString), nullptr);
  774. v->setProperty ("sourceTree", sourceTree, nullptr);
  775. const int existing = pbxFileReferences.indexOfSorted (*this, v);
  776. if (existing >= 0)
  777. {
  778. // If this fails, there's either a string hash collision, or the same file is being added twice (incorrectly)
  779. jassert (pbxFileReferences.getUnchecked (existing)->isEquivalentTo (*v));
  780. }
  781. else
  782. {
  783. pbxFileReferences.addSorted (*this, v.release());
  784. }
  785. return fileRefID;
  786. }
  787. public:
  788. static int compareElements (const ValueTree* first, const ValueTree* second)
  789. {
  790. return first->getType().getCharPointer().compare (second->getType().getCharPointer());
  791. }
  792. private:
  793. static String getFileType (const RelativePath& file)
  794. {
  795. if (file.hasFileExtension (cppFileExtensions)) return "sourcecode.cpp.cpp";
  796. if (file.hasFileExtension (".mm")) return "sourcecode.cpp.objcpp";
  797. if (file.hasFileExtension (".m")) return "sourcecode.c.objc";
  798. if (file.hasFileExtension (".c")) return "sourcecode.c.c";
  799. if (file.hasFileExtension (headerFileExtensions)) return "sourcecode.c.h";
  800. if (file.hasFileExtension (asmFileExtensions)) return "sourcecode.c.asm";
  801. if (file.hasFileExtension (".framework")) return "wrapper.framework";
  802. if (file.hasFileExtension (".jpeg;.jpg")) return "image.jpeg";
  803. if (file.hasFileExtension ("png;gif")) return "image" + file.getFileExtension();
  804. if (file.hasFileExtension ("html;htm")) return "text.html";
  805. if (file.hasFileExtension ("xml;zip;wav")) return "file" + file.getFileExtension();
  806. if (file.hasFileExtension ("txt;rtf")) return "text" + file.getFileExtension();
  807. if (file.hasFileExtension ("plist")) return "text.plist.xml";
  808. if (file.hasFileExtension ("app")) return "wrapper.application";
  809. if (file.hasFileExtension ("component;vst;plugin")) return "wrapper.cfbundle";
  810. if (file.hasFileExtension ("xcodeproj")) return "wrapper.pb-project";
  811. if (file.hasFileExtension ("a")) return "archive.ar";
  812. if (file.hasFileExtension ("xcassets")) return "folder.assetcatalog";
  813. return "file" + file.getFileExtension();
  814. }
  815. String addFile (const RelativePath& path, bool shouldBeCompiled, bool shouldBeAddedToBinaryResources, bool inhibitWarnings) const
  816. {
  817. const String pathAsString (path.toUnixStyle());
  818. const String refID (addFileReference (path.toUnixStyle()));
  819. if (shouldBeCompiled)
  820. {
  821. if (path.hasFileExtension (".r"))
  822. rezFileIDs.add (addBuildFile (pathAsString, refID, false, inhibitWarnings));
  823. else
  824. addBuildFile (pathAsString, refID, true, inhibitWarnings);
  825. }
  826. else if (! shouldBeAddedToBinaryResources)
  827. {
  828. const String fileType (getFileType (path));
  829. if (fileType.startsWith ("image.") || fileType.startsWith ("text.") || fileType.startsWith ("file."))
  830. {
  831. resourceIDs.add (addBuildFile (pathAsString, refID, false, false));
  832. resourceFileRefs.add (refID);
  833. }
  834. }
  835. return refID;
  836. }
  837. String addProjectItem (const Project::Item& projectItem) const
  838. {
  839. if (projectItem.isGroup())
  840. {
  841. StringArray childIDs;
  842. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  843. {
  844. const String childID (addProjectItem (projectItem.getChild(i)));
  845. if (childID.isNotEmpty())
  846. childIDs.add (childID);
  847. }
  848. return addGroup (projectItem, childIDs);
  849. }
  850. if (projectItem.shouldBeAddedToTargetProject())
  851. {
  852. const String itemPath (projectItem.getFilePath());
  853. RelativePath path;
  854. if (itemPath.startsWith ("${"))
  855. path = RelativePath (itemPath, RelativePath::unknown);
  856. else
  857. path = RelativePath (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder);
  858. return addFile (path, projectItem.shouldBeCompiled(),
  859. projectItem.shouldBeAddedToBinaryResources(),
  860. projectItem.shouldInhibitWarnings());
  861. }
  862. return String::empty;
  863. }
  864. void addFramework (const String& frameworkName) const
  865. {
  866. String path (frameworkName);
  867. if (! File::isAbsolutePath (path))
  868. path = "System/Library/Frameworks/" + path;
  869. if (! path.endsWithIgnoreCase (".framework"))
  870. path << ".framework";
  871. const String fileRefID (createFileRefID (path));
  872. addFileReference ((File::isAbsolutePath (frameworkName) ? "" : "${SDKROOT}/") + path);
  873. frameworkIDs.add (addBuildFile (path, fileRefID, false, false));
  874. frameworkFileIDs.add (fileRefID);
  875. }
  876. void addGroup (const String& groupID, const String& groupName, const StringArray& childIDs) const
  877. {
  878. ValueTree* v = new ValueTree (groupID);
  879. v->setProperty ("isa", "PBXGroup", nullptr);
  880. v->setProperty ("children", indentParenthesisedList (childIDs), nullptr);
  881. v->setProperty (Ids::name, groupName, nullptr);
  882. v->setProperty ("sourceTree", "<group>", nullptr);
  883. pbxGroups.add (v);
  884. }
  885. String addGroup (const Project::Item& item, StringArray& childIDs) const
  886. {
  887. const String groupName (item.getName());
  888. const String groupID (getIDForGroup (item));
  889. addGroup (groupID, groupName, childIDs);
  890. return groupID;
  891. }
  892. void addMainBuildProduct() const
  893. {
  894. jassert (xcodeFileType.isNotEmpty());
  895. jassert (xcodeBundleExtension.isEmpty() || xcodeBundleExtension.startsWithChar('.'));
  896. ProjectExporter::BuildConfiguration::Ptr config = getConfiguration(0);
  897. jassert (config != nullptr);
  898. String productName (replacePreprocessorTokens (*config, config->getTargetBinaryNameString()));
  899. if (xcodeFileType == "archive.ar")
  900. productName = getLibbedFilename (productName);
  901. else
  902. productName += xcodeBundleExtension;
  903. addBuildProduct (xcodeFileType, productName);
  904. }
  905. void addBuildProduct (const String& fileType, const String& binaryName) const
  906. {
  907. ValueTree* v = new ValueTree (createID ("__productFileID"));
  908. v->setProperty ("isa", "PBXFileReference", nullptr);
  909. v->setProperty ("explicitFileType", fileType, nullptr);
  910. v->setProperty ("includeInIndex", (int) 0, nullptr);
  911. v->setProperty ("path", sanitisePath (binaryName), nullptr);
  912. v->setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", nullptr);
  913. pbxFileReferences.add (v);
  914. }
  915. void addTargetConfig (const String& configName, const StringArray& buildSettings) const
  916. {
  917. ValueTree* v = new ValueTree (createID ("targetconfigid_" + configName));
  918. v->setProperty ("isa", "XCBuildConfiguration", nullptr);
  919. v->setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
  920. v->setProperty (Ids::name, configName, nullptr);
  921. targetConfigs.add (v);
  922. }
  923. void addProjectConfig (const String& configName, const StringArray& buildSettings) const
  924. {
  925. ValueTree* v = new ValueTree (createID ("projectconfigid_" + configName));
  926. v->setProperty ("isa", "XCBuildConfiguration", nullptr);
  927. v->setProperty ("buildSettings", indentBracedList (buildSettings), nullptr);
  928. v->setProperty (Ids::name, configName, nullptr);
  929. projectConfigs.add (v);
  930. }
  931. void addConfigList (const OwnedArray <ValueTree>& configsToUse, const String& listID) const
  932. {
  933. StringArray configIDs;
  934. for (int i = 0; i < configsToUse.size(); ++i)
  935. configIDs.add (configsToUse[i]->getType().toString());
  936. ValueTree* v = new ValueTree (listID);
  937. v->setProperty ("isa", "XCConfigurationList", nullptr);
  938. v->setProperty ("buildConfigurations", indentParenthesisedList (configIDs), nullptr);
  939. v->setProperty ("defaultConfigurationIsVisible", (int) 0, nullptr);
  940. if (configsToUse[0] != nullptr)
  941. v->setProperty ("defaultConfigurationName", configsToUse[0]->getProperty (Ids::name), nullptr);
  942. misc.add (v);
  943. }
  944. ValueTree& addBuildPhase (const String& phaseType, const StringArray& fileIds) const
  945. {
  946. String phaseId (createID (phaseType + "resbuildphase"));
  947. int n = 0;
  948. while (buildPhaseIDs.contains (phaseId))
  949. phaseId = createID (phaseType + "resbuildphase" + String (++n));
  950. buildPhaseIDs.add (phaseId);
  951. ValueTree* v = new ValueTree (phaseId);
  952. v->setProperty ("isa", phaseType, nullptr);
  953. v->setProperty ("buildActionMask", "2147483647", nullptr);
  954. v->setProperty ("files", indentParenthesisedList (fileIds), nullptr);
  955. v->setProperty ("runOnlyForDeploymentPostprocessing", (int) 0, nullptr);
  956. misc.add (v);
  957. return *v;
  958. }
  959. void addTargetObject() const
  960. {
  961. ValueTree* const v = new ValueTree (createID ("__target"));
  962. v->setProperty ("isa", "PBXNativeTarget", nullptr);
  963. v->setProperty ("buildConfigurationList", createID ("__configList"), nullptr);
  964. v->setProperty ("buildPhases", indentParenthesisedList (buildPhaseIDs), nullptr);
  965. v->setProperty ("buildRules", "( )", nullptr);
  966. v->setProperty ("dependencies", "( )", nullptr);
  967. v->setProperty (Ids::name, projectName, nullptr);
  968. v->setProperty ("productName", projectName, nullptr);
  969. v->setProperty ("productReference", createID ("__productFileID"), nullptr);
  970. if (xcodeProductInstallPath.isNotEmpty())
  971. v->setProperty ("productInstallPath", xcodeProductInstallPath, nullptr);
  972. jassert (xcodeProductType.isNotEmpty());
  973. v->setProperty ("productType", xcodeProductType, nullptr);
  974. misc.add (v);
  975. }
  976. void addProjectObject() const
  977. {
  978. ValueTree* const v = new ValueTree (createID ("__root"));
  979. v->setProperty ("isa", "PBXProject", nullptr);
  980. v->setProperty ("buildConfigurationList", createID ("__projList"), nullptr);
  981. v->setProperty ("attributes", "{ LastUpgradeCheck = 0440; }", nullptr);
  982. v->setProperty ("compatibilityVersion", "Xcode 3.2", nullptr);
  983. v->setProperty ("hasScannedForEncodings", (int) 0, nullptr);
  984. v->setProperty ("mainGroup", createID ("__mainsourcegroup"), nullptr);
  985. v->setProperty ("projectDirPath", "\"\"", nullptr);
  986. v->setProperty ("projectRoot", "\"\"", nullptr);
  987. v->setProperty ("targets", "( " + createID ("__target") + " )", nullptr);
  988. misc.add (v);
  989. }
  990. void addShellScriptBuildPhase (const String& phaseName, const String& script) const
  991. {
  992. if (script.trim().isNotEmpty())
  993. {
  994. ValueTree& v = addBuildPhase ("PBXShellScriptBuildPhase", StringArray());
  995. v.setProperty (Ids::name, phaseName, nullptr);
  996. v.setProperty ("shellPath", "/bin/sh", nullptr);
  997. v.setProperty ("shellScript", script.replace ("\\", "\\\\")
  998. .replace ("\"", "\\\"")
  999. .replace ("\r\n", "\\n")
  1000. .replace ("\n", "\\n"), nullptr);
  1001. }
  1002. }
  1003. String getiOSAssetContents (var images) const
  1004. {
  1005. DynamicObject::Ptr v (new DynamicObject());
  1006. var info (new DynamicObject());
  1007. info.getDynamicObject()->setProperty ("version", 1);
  1008. info.getDynamicObject()->setProperty ("author", "xcode");
  1009. v->setProperty ("images", images);
  1010. v->setProperty ("info", info);
  1011. return JSON::toString (var (v));
  1012. }
  1013. String getiOSAppIconContents() const
  1014. {
  1015. struct ImageType
  1016. {
  1017. const char* idiom;
  1018. const char* size;
  1019. const char* scale;
  1020. };
  1021. const ImageType types[] = { { "iphone", "29x29", "2x" },
  1022. { "iphone", "40x40", "2x" },
  1023. { "iphone", "60x60", "2x" },
  1024. { "iphone", "60x60", "3x" },
  1025. { "ipad", "29x29", "1x" },
  1026. { "ipad", "29x29", "2x" },
  1027. { "ipad", "40x40", "1x" },
  1028. { "ipad", "40x40", "2x" },
  1029. { "ipad", "76x76", "1x" },
  1030. { "ipad", "76x76", "2x" } };
  1031. var images;
  1032. for (size_t i = 0; i < sizeof (types) / sizeof (types[0]); ++i)
  1033. {
  1034. DynamicObject::Ptr d = new DynamicObject();
  1035. d->setProperty ("idiom", types[i].idiom);
  1036. d->setProperty ("size", types[i].size);
  1037. d->setProperty ("scale", types[i].scale);
  1038. images.append (var (d));
  1039. }
  1040. return getiOSAssetContents (images);
  1041. }
  1042. String getiOSLaunchImageContents() const
  1043. {
  1044. struct ImageType
  1045. {
  1046. const char* orientation;
  1047. const char* idiom;
  1048. const char* extent;
  1049. const char* scale;
  1050. };
  1051. const ImageType types[] = { { "portrait", "iphone", "full-screen", "2x" },
  1052. { "landscape", "iphone", "full-screen", "2x" },
  1053. { "portrait", "ipad", "full-screen", "1x" },
  1054. { "landscape", "ipad", "full-screen", "1x" },
  1055. { "portrait", "ipad", "full-screen", "2x" },
  1056. { "landscape", "ipad", "full-screen", "2x" } };
  1057. var images;
  1058. for (size_t i = 0; i < sizeof (types) / sizeof (types[0]); ++i)
  1059. {
  1060. DynamicObject::Ptr d = new DynamicObject();
  1061. d->setProperty ("orientation", types[i].orientation);
  1062. d->setProperty ("idiom", types[i].idiom);
  1063. d->setProperty ("extent", types[i].extent);
  1064. d->setProperty ("minimum-system-version", "7.0");
  1065. d->setProperty ("scale", types[i].scale);
  1066. images.append (var (d));
  1067. }
  1068. return getiOSAssetContents (images);
  1069. }
  1070. void createiOSAssetsFolder() const
  1071. {
  1072. File assets (getTargetFolder().getChildFile (project.getProjectFilenameRoot()).getChildFile ("Images.xcassets"));
  1073. overwriteFileIfDifferentOrThrow (assets.getChildFile ("AppIcon.appiconset") .getChildFile ("Contents.json"), getiOSAppIconContents());
  1074. overwriteFileIfDifferentOrThrow (assets.getChildFile ("LaunchImage.launchimage").getChildFile ("Contents.json"), getiOSLaunchImageContents());
  1075. RelativePath assetsPath (assets, getTargetFolder(), RelativePath::buildTargetFolder);
  1076. addFileReference (assetsPath.toUnixStyle());
  1077. resourceIDs.add (addBuildFile (assetsPath, false, false));
  1078. resourceFileRefs.add (createFileRefID (assetsPath));
  1079. }
  1080. //==============================================================================
  1081. static String indentBracedList (const StringArray& list) { return "{" + indentList (list, ";", 0, true) + " }"; }
  1082. static String indentParenthesisedList (const StringArray& list) { return "(" + indentList (list, ",", 1, false) + " )"; }
  1083. static String indentList (const StringArray& list, const String& separator, int extraTabs, bool shouldSort)
  1084. {
  1085. if (list.size() == 0)
  1086. return " ";
  1087. const String tabs ("\n" + String::repeatedString ("\t", extraTabs + 4));
  1088. if (shouldSort)
  1089. {
  1090. StringArray sorted (list);
  1091. sorted.sort (true);
  1092. return tabs + sorted.joinIntoString (separator + tabs) + separator;
  1093. }
  1094. return tabs + list.joinIntoString (separator + tabs) + separator;
  1095. }
  1096. String createID (String rootString) const
  1097. {
  1098. if (rootString.startsWith ("${"))
  1099. rootString = rootString.fromFirstOccurrenceOf ("}/", false, false);
  1100. rootString += project.getProjectUID();
  1101. return MD5 (rootString.toUTF8()).toHexString().substring (0, 24).toUpperCase();
  1102. }
  1103. String createFileRefID (const RelativePath& path) const { return createFileRefID (path.toUnixStyle()); }
  1104. String createFileRefID (const String& path) const { return createID ("__fileref_" + path); }
  1105. String getIDForGroup (const Project::Item& item) const { return createID (item.getID()); }
  1106. bool shouldFileBeCompiledByDefault (const RelativePath& file) const
  1107. {
  1108. return file.hasFileExtension (sourceFileExtensions);
  1109. }
  1110. static String getSDKName (int version)
  1111. {
  1112. jassert (version >= 4);
  1113. return "10." + String (version) + " SDK";
  1114. }
  1115. };