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.

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