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.

1450 lines
60KB

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