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.

1435 lines
59KB

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