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.

1502 lines
62KB

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