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.

1116 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCER_PROJECTEXPORT_XCODE_JUCEHEADER__
  19. #define __JUCER_PROJECTEXPORT_XCODE_JUCEHEADER__
  20. #include "jucer_ProjectExporter.h"
  21. namespace
  22. {
  23. const char* const osxVersionDefault = "default";
  24. const char* const osxVersion10_4 = "10.4 SDK";
  25. const char* const osxVersion10_5 = "10.5 SDK";
  26. const char* const osxVersion10_6 = "10.6 SDK";
  27. const char* const osxArch_Default = "default";
  28. const char* const osxArch_Native = "Native";
  29. const char* const osxArch_32BitUniversal = "32BitUniversal";
  30. const char* const osxArch_64BitUniversal = "64BitUniversal";
  31. const char* const osxArch_64Bit = "64BitIntel";
  32. }
  33. //==============================================================================
  34. class XCodeProjectExporter : public ProjectExporter
  35. {
  36. public:
  37. //==============================================================================
  38. static const char* getNameMac() { return "XCode (MacOSX)"; }
  39. static const char* getNameiOS() { return "XCode (iOS)"; }
  40. static const char* getValueTreeTypeName (bool iOS) { return iOS ? "XCODE_IPHONE" : "XCODE_MAC"; }
  41. //==============================================================================
  42. XCodeProjectExporter (Project& project_, const ValueTree& settings_, const bool iOS_)
  43. : ProjectExporter (project_, settings_),
  44. iOS (iOS_)
  45. {
  46. name = iOS ? getNameiOS() : getNameMac();
  47. if (getTargetLocation().toString().isEmpty())
  48. getTargetLocation() = getDefaultBuildsRootFolder() + (iOS ? "iOS" : "MacOSX");
  49. if (getSettings() ["objCExtraSuffix"].isVoid())
  50. getObjCSuffix() = createAlphaNumericUID();
  51. }
  52. static XCodeProjectExporter* createForSettings (Project& project, const ValueTree& settings)
  53. {
  54. if (settings.hasType (getValueTreeTypeName (false)))
  55. return new XCodeProjectExporter (project, settings, false);
  56. else if (settings.hasType (getValueTreeTypeName (true)))
  57. return new XCodeProjectExporter (project, settings, true);
  58. return 0;
  59. }
  60. //==============================================================================
  61. Value getObjCSuffix() { return getSetting ("objCExtraSuffix"); }
  62. Value getPListToMerge() { return getSetting ("customPList"); }
  63. int getLaunchPreferenceOrderForCurrentOS()
  64. {
  65. #if JUCE_MAC
  66. return iOS ? 1 : 2;
  67. #else
  68. return 0;
  69. #endif
  70. }
  71. bool isAvailableOnCurrentOS()
  72. {
  73. #if JUCE_MAC
  74. return true;
  75. #else
  76. return false;
  77. #endif
  78. }
  79. bool isPossibleForCurrentProject() { return projectType.isGUIApplication() || ! iOS; }
  80. bool usesMMFiles() const { return true; }
  81. bool isXcode() const { return true; }
  82. bool isOSX() const { return ! iOS; }
  83. bool canCopeWithDuplicateFiles() { return true; }
  84. void createPropertyEditors (PropertyListBuilder& props)
  85. {
  86. ProjectExporter::createPropertyEditors (props);
  87. props.add (new TextPropertyComponent (getObjCSuffix(), "Objective-C class name suffix", 64, false),
  88. "Because objective-C linkage is done by string-matching, you can get horrible linkage mix-ups when different modules containing the "
  89. "same class-names are loaded simultaneously. This setting lets you provide a unique string that will be used in naming "
  90. "the obj-C classes in your executable to avoid this.");
  91. if (projectType.isGUIApplication() && ! iOS)
  92. {
  93. props.add (new TextPropertyComponent (getSetting ("documentExtensions"), "Document file extensions", 128, false),
  94. "A comma-separated list of file extensions for documents that your app can open.");
  95. }
  96. else if (iOS)
  97. {
  98. props.add (new BooleanPropertyComponent (getSetting ("UIFileSharingEnabled"), "File Sharing Enabled", "Enabled"),
  99. "Enable this to expose your app's files to iTunes.");
  100. props.add (new BooleanPropertyComponent (getSetting ("UIStatusBarHidden"), "Status Bar Hidden", "Enabled"),
  101. "Enable this to disable the status bar in your app.");
  102. }
  103. props.add (new TextPropertyComponent (getPListToMerge(), "Custom PList", 8192, true),
  104. "You can paste the contents of an XML PList file in here, and the settings that it contains will override any "
  105. "settings that the Introjucer creates. BEWARE! When doing this, be careful to remove from the XML any "
  106. "values that you DO want the introjucer to change!");
  107. }
  108. void launchProject()
  109. {
  110. getProjectBundle().startAsProcess();
  111. }
  112. //==============================================================================
  113. void create()
  114. {
  115. infoPlistFile = getTargetFolder().getChildFile ("Info.plist");
  116. createIconFile();
  117. File projectBundle (getProjectBundle());
  118. createDirectoryOrThrow (projectBundle);
  119. createObjects();
  120. File projectFile (projectBundle.getChildFile ("project.pbxproj"));
  121. {
  122. MemoryOutputStream mo;
  123. writeProjectFile (mo);
  124. overwriteFileIfDifferentOrThrow (projectFile, mo);
  125. }
  126. writeInfoPlistFile();
  127. }
  128. protected:
  129. //==============================================================================
  130. class XcodeBuildConfiguration : public BuildConfiguration
  131. {
  132. public:
  133. XcodeBuildConfiguration (Project& project, const ValueTree& settings)
  134. : BuildConfiguration (project, settings)
  135. {
  136. }
  137. Value getMacSDKVersion() const { return getValue (Ids::osxSDK); }
  138. Value getMacCompatibilityVersion() const { return getValue (Ids::osxCompatibility); }
  139. Value getMacArchitecture() const { return getValue (Ids::osxArchitecture); }
  140. void createPropertyEditors (PropertyListBuilder& props)
  141. {
  142. createBasicPropertyEditors (props);
  143. if (getMacSDKVersion().toString().isEmpty())
  144. getMacSDKVersion() = osxVersionDefault;
  145. const char* osxVersions[] = { "Use Default", osxVersion10_4, osxVersion10_5, osxVersion10_6, 0 };
  146. const char* osxVersionValues[] = { osxVersionDefault, osxVersion10_4, osxVersion10_5, osxVersion10_6, 0 };
  147. props.add (new ChoicePropertyComponent (getMacSDKVersion(), "OSX Base SDK Version", StringArray (osxVersions), Array<var> (osxVersionValues)),
  148. "The version of OSX to link against in the XCode build.");
  149. if (getMacCompatibilityVersion().toString().isEmpty())
  150. getMacCompatibilityVersion() = osxVersionDefault;
  151. props.add (new ChoicePropertyComponent (getMacCompatibilityVersion(), "OSX Compatibility Version", StringArray (osxVersions), Array<var> (osxVersionValues)),
  152. "The minimum version of OSX that the target binary will be compatible with.");
  153. const char* osxArch[] = { "Use Default", "Native architecture of build machine", "Universal Binary (32-bit)", "Universal Binary (64-bit)", "64-bit Intel", 0 };
  154. const char* osxArchValues[] = { osxArch_Default, osxArch_Native, osxArch_32BitUniversal, osxArch_64BitUniversal, osxArch_64Bit, 0 };
  155. if (getMacArchitecture().toString().isEmpty())
  156. getMacArchitecture() = osxArch_Default;
  157. props.add (new ChoicePropertyComponent (getMacArchitecture(), "OSX Architecture", StringArray (osxArch), Array<var> (osxArchValues)),
  158. "The type of OSX binary that will be produced.");
  159. }
  160. };
  161. BuildConfiguration::Ptr createBuildConfig (const ValueTree& settings) const
  162. {
  163. return new XcodeBuildConfiguration (project, settings);
  164. }
  165. private:
  166. OwnedArray<ValueTree> pbxBuildFiles, pbxFileReferences, pbxGroups, misc, projectConfigs, targetConfigs;
  167. StringArray buildPhaseIDs, resourceIDs, sourceIDs, frameworkIDs;
  168. StringArray frameworkFileIDs, rezFileIDs, resourceFileRefs;
  169. File infoPlistFile, iconFile;
  170. const bool iOS;
  171. static String sanitisePath (const String& path)
  172. {
  173. if (path.startsWithChar ('~'))
  174. return "$(HOME)" + path.substring (1);
  175. return path;
  176. }
  177. File getProjectBundle() const { return getTargetFolder().getChildFile (project.getProjectFilenameRoot()).withFileExtension (".xcodeproj"); }
  178. //==============================================================================
  179. void createObjects()
  180. {
  181. addFrameworks();
  182. addMainBuildProduct();
  183. if (xcodeCreatePList)
  184. {
  185. RelativePath plistPath (infoPlistFile, getTargetFolder(), RelativePath::buildTargetFolder);
  186. addFileReference (plistPath.toUnixStyle());
  187. resourceFileRefs.add (createFileRefID (plistPath));
  188. }
  189. if (iconFile.exists())
  190. {
  191. RelativePath iconPath (iconFile, getTargetFolder(), RelativePath::buildTargetFolder);
  192. addFileReference (iconPath.toUnixStyle());
  193. resourceIDs.add (addBuildFile (iconPath, false, false));
  194. resourceFileRefs.add (createFileRefID (iconPath));
  195. }
  196. {
  197. StringArray topLevelGroupIDs;
  198. for (int i = 0; i < groups.size(); ++i)
  199. if (groups.getReference(i).getNumChildren() > 0)
  200. topLevelGroupIDs.add (addProjectItem (groups.getReference(i)));
  201. { // Add 'resources' group
  202. String resourcesGroupID (createID ("__resources"));
  203. addGroup (resourcesGroupID, "Resources", resourceFileRefs);
  204. topLevelGroupIDs.add (resourcesGroupID);
  205. }
  206. { // Add 'frameworks' group
  207. String frameworksGroupID (createID ("__frameworks"));
  208. addGroup (frameworksGroupID, "Frameworks", frameworkFileIDs);
  209. topLevelGroupIDs.add (frameworksGroupID);
  210. }
  211. { // Add 'products' group
  212. String productsGroupID (createID ("__products"));
  213. StringArray products;
  214. products.add (createID ("__productFileID"));
  215. addGroup (productsGroupID, "Products", products);
  216. topLevelGroupIDs.add (productsGroupID);
  217. }
  218. addGroup (createID ("__mainsourcegroup"), "Source", topLevelGroupIDs);
  219. }
  220. for (int i = 0; i < getNumConfigurations(); ++i)
  221. {
  222. const BuildConfiguration::Ptr config (getConfiguration (i));
  223. addProjectConfig (config->getName().getValue(), getProjectSettings (*config));
  224. addTargetConfig (config->getName().getValue(), getTargetSettings (dynamic_cast <XcodeBuildConfiguration&> (*config)));
  225. }
  226. addConfigList (projectConfigs, createID ("__projList"));
  227. addConfigList (targetConfigs, createID ("__configList"));
  228. if (! projectType.isLibrary())
  229. addBuildPhase ("PBXResourcesBuildPhase", resourceIDs);
  230. if (rezFileIDs.size() > 0)
  231. addBuildPhase ("PBXRezBuildPhase", rezFileIDs);
  232. addBuildPhase ("PBXSourcesBuildPhase", sourceIDs);
  233. if (! projectType.isLibrary())
  234. addBuildPhase ("PBXFrameworksBuildPhase", frameworkIDs);
  235. addShellScriptPhase();
  236. addTargetObject();
  237. addProjectObject();
  238. }
  239. static Image fixMacIconImageSize (Image& image)
  240. {
  241. const int w = image.getWidth();
  242. const int h = image.getHeight();
  243. if (w != h || (w != 16 && w != 32 && w != 48 && w != 64))
  244. {
  245. const int newSize = w >= 128 ? 128 : (w >= 64 ? 64 : (w >= 32 ? 32 : 16));
  246. Image newIm (Image::ARGB, newSize, newSize, true, SoftwareImageType());
  247. Graphics g (newIm);
  248. g.drawImageWithin (image, 0, 0, newSize, newSize,
  249. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  250. return newIm;
  251. }
  252. return image;
  253. }
  254. void writeIcnsFile (const Array<Image>& images, OutputStream& out)
  255. {
  256. MemoryOutputStream data;
  257. for (int i = 0; i < images.size(); ++i)
  258. {
  259. Image image (fixMacIconImageSize (images.getReference (i)));
  260. const int w = image.getWidth();
  261. const int h = image.getHeight();
  262. const char* type = nullptr;
  263. const char* maskType = nullptr;
  264. if (w == h)
  265. {
  266. if (w == 16) { type = "is32"; maskType = "s8mk"; }
  267. if (w == 32) { type = "il32"; maskType = "l8mk"; }
  268. if (w == 48) { type = "ih32"; maskType = "h8mk"; }
  269. if (w == 128) { type = "it32"; maskType = "t8mk"; }
  270. }
  271. if (type != nullptr)
  272. {
  273. data.write (type, 4);
  274. data.writeIntBigEndian (8 + 4 * w * h);
  275. const Image::BitmapData bitmap (image, Image::BitmapData::readOnly);
  276. int y;
  277. for (y = 0; y < h; ++y)
  278. {
  279. for (int x = 0; x < w; ++x)
  280. {
  281. const Colour pixel (bitmap.getPixelColour (x, y));
  282. data.writeByte ((char) pixel.getAlpha());
  283. data.writeByte ((char) pixel.getRed());
  284. data.writeByte ((char) pixel.getGreen());
  285. data.writeByte ((char) pixel.getBlue());
  286. }
  287. }
  288. data.write (maskType, 4);
  289. data.writeIntBigEndian (8 + w * h);
  290. for (y = 0; y < h; ++y)
  291. {
  292. for (int x = 0; x < w; ++x)
  293. {
  294. const Colour pixel (bitmap.getPixelColour (x, y));
  295. data.writeByte ((char) pixel.getAlpha());
  296. }
  297. }
  298. }
  299. }
  300. jassert (data.getDataSize() > 0); // no suitable sized images?
  301. out.write ("icns", 4);
  302. out.writeIntBigEndian (data.getDataSize() + 8);
  303. out << data;
  304. }
  305. void createIconFile()
  306. {
  307. Array<Image> images;
  308. Image bigIcon (project.getBigIcon());
  309. if (bigIcon.isValid())
  310. images.add (bigIcon);
  311. Image smallIcon (project.getSmallIcon());
  312. if (smallIcon.isValid())
  313. images.add (smallIcon);
  314. if (images.size() > 0)
  315. {
  316. MemoryOutputStream mo;
  317. writeIcnsFile (images, mo);
  318. iconFile = getTargetFolder().getChildFile ("Icon.icns");
  319. overwriteFileIfDifferentOrThrow (iconFile, mo);
  320. }
  321. }
  322. void writeInfoPlistFile()
  323. {
  324. if (! xcodeCreatePList)
  325. return;
  326. ScopedPointer<XmlElement> plist (XmlDocument::parse (getPListToMerge().toString()));
  327. if (plist == nullptr || ! plist->hasTagName ("plist"))
  328. plist = new XmlElement ("plist");
  329. XmlElement* dict = plist->getChildByName ("dict");
  330. if (dict == nullptr)
  331. dict = plist->createNewChildElement ("dict");
  332. if (iOS)
  333. addPlistDictionaryKeyBool (dict, "LSRequiresIPhoneOS", true);
  334. addPlistDictionaryKey (dict, "CFBundleExecutable", "${EXECUTABLE_NAME}");
  335. addPlistDictionaryKey (dict, "CFBundleIconFile", iconFile.exists() ? iconFile.getFileName() : String::empty);
  336. addPlistDictionaryKey (dict, "CFBundleIdentifier", project.getBundleIdentifier().toString());
  337. addPlistDictionaryKey (dict, "CFBundleName", projectName);
  338. addPlistDictionaryKey (dict, "CFBundlePackageType", xcodePackageType);
  339. addPlistDictionaryKey (dict, "CFBundleSignature", xcodeBundleSignature);
  340. addPlistDictionaryKey (dict, "CFBundleShortVersionString", project.getVersion().toString());
  341. addPlistDictionaryKey (dict, "CFBundleVersion", project.getVersion().toString());
  342. StringArray documentExtensions;
  343. documentExtensions.addTokens (replacePreprocessorDefs (getAllPreprocessorDefs(), getSetting ("documentExtensions").toString()),
  344. ",", String::empty);
  345. documentExtensions.trim();
  346. documentExtensions.removeEmptyStrings (true);
  347. if (documentExtensions.size() > 0)
  348. {
  349. dict->createNewChildElement ("key")->addTextElement ("CFBundleDocumentTypes");
  350. XmlElement* dict2 = dict->createNewChildElement ("array")->createNewChildElement ("dict");
  351. for (int i = 0; i < documentExtensions.size(); ++i)
  352. {
  353. String ex (documentExtensions[i]);
  354. if (ex.startsWithChar ('.'))
  355. ex = ex.substring (1);
  356. dict2->createNewChildElement ("key")->addTextElement ("CFBundleTypeExtensions");
  357. dict2->createNewChildElement ("array")->createNewChildElement ("string")->addTextElement (ex);
  358. addPlistDictionaryKey (dict2, "CFBundleTypeName", ex);
  359. addPlistDictionaryKey (dict2, "CFBundleTypeRole", "Editor");
  360. addPlistDictionaryKey (dict2, "NSPersistentStoreTypeKey", "XML");
  361. }
  362. }
  363. if (getSetting ("UIFileSharingEnabled").getValue())
  364. addPlistDictionaryKeyBool (dict, "UIFileSharingEnabled", true);
  365. if (getSetting ("UIStatusBarHidden").getValue())
  366. addPlistDictionaryKeyBool (dict, "UIStatusBarHidden", true);
  367. for (int i = 0; i < xcodeExtraPListEntries.size(); ++i)
  368. dict->addChildElement (new XmlElement (xcodeExtraPListEntries.getReference(i)));
  369. MemoryOutputStream mo;
  370. plist->writeToStream (mo, "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">");
  371. overwriteFileIfDifferentOrThrow (infoPlistFile, mo);
  372. }
  373. StringArray getHeaderSearchPaths (const BuildConfiguration& config)
  374. {
  375. StringArray searchPaths (extraSearchPaths);
  376. searchPaths.addArray (config.getHeaderSearchPaths());
  377. searchPaths.removeDuplicates (false);
  378. return searchPaths;
  379. }
  380. static void getLinkerFlagsForStaticLibrary (const RelativePath& library, StringArray& flags, StringArray& librarySearchPaths)
  381. {
  382. jassert (library.getFileNameWithoutExtension().substring (0, 3) == "lib");
  383. flags.add ("-l" + library.getFileNameWithoutExtension().substring (3));
  384. String searchPath (library.toUnixStyle().upToLastOccurrenceOf ("/", false, false));
  385. if (! library.isAbsolute())
  386. searchPath = "$(SRCROOT)/" + searchPath;
  387. librarySearchPaths.add (sanitisePath (searchPath));
  388. }
  389. void getLinkerFlags (const BuildConfiguration& config, StringArray& flags, StringArray& librarySearchPaths)
  390. {
  391. if (xcodeIsBundle)
  392. flags.add ("-bundle");
  393. const Array<RelativePath>& extraLibs = config.isDebug().getValue() ? xcodeExtraLibrariesDebug
  394. : xcodeExtraLibrariesRelease;
  395. for (int i = 0; i < extraLibs.size(); ++i)
  396. getLinkerFlagsForStaticLibrary (extraLibs.getReference(i), flags, librarySearchPaths);
  397. flags.add (replacePreprocessorTokens (config, getExtraLinkerFlags().toString()));
  398. flags.removeEmptyStrings (true);
  399. }
  400. StringArray getProjectSettings (const BuildConfiguration& config)
  401. {
  402. StringArray s;
  403. s.add ("ALWAYS_SEARCH_USER_PATHS = NO");
  404. s.add ("GCC_C_LANGUAGE_STANDARD = c99");
  405. s.add ("GCC_WARN_ABOUT_RETURN_TYPE = YES");
  406. s.add ("GCC_WARN_CHECK_SWITCH_STATEMENTS = YES");
  407. s.add ("GCC_WARN_UNUSED_VARIABLE = YES");
  408. s.add ("GCC_WARN_MISSING_PARENTHESES = YES");
  409. s.add ("GCC_WARN_NON_VIRTUAL_DESTRUCTOR = YES");
  410. s.add ("GCC_WARN_TYPECHECK_CALLS_TO_PRINTF = YES");
  411. s.add ("WARNING_CFLAGS = -Wreorder");
  412. s.add ("GCC_MODEL_TUNING = G5");
  413. if (projectType.isLibrary())
  414. {
  415. s.add ("GCC_INLINES_ARE_PRIVATE_EXTERN = NO");
  416. s.add ("GCC_SYMBOLS_PRIVATE_EXTERN = NO");
  417. }
  418. else
  419. {
  420. s.add ("GCC_INLINES_ARE_PRIVATE_EXTERN = YES");
  421. }
  422. if (iOS)
  423. {
  424. s.add ("\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\"");
  425. s.add ("SDKROOT = iphoneos");
  426. s.add ("TARGETED_DEVICE_FAMILY = \"1,2\"");
  427. }
  428. s.add ("ZERO_LINK = NO");
  429. if (xcodeCanUseDwarf)
  430. s.add ("DEBUG_INFORMATION_FORMAT = \"dwarf\"");
  431. s.add ("PRODUCT_NAME = \"" + config.getTargetBinaryName().toString() + "\"");
  432. return s;
  433. }
  434. StringArray getTargetSettings (const XcodeBuildConfiguration& config)
  435. {
  436. StringArray s;
  437. const String arch (config.getMacArchitecture().toString());
  438. if (arch == osxArch_Native) s.add ("ARCHS = \"$(ARCHS_NATIVE)\"");
  439. else if (arch == osxArch_32BitUniversal) s.add ("ARCHS = \"$(ARCHS_STANDARD_32_BIT)\"");
  440. else if (arch == osxArch_64BitUniversal) s.add ("ARCHS = \"$(ARCHS_STANDARD_32_64_BIT)\"");
  441. else if (arch == osxArch_64Bit) s.add ("ARCHS = \"$(ARCHS_STANDARD_64_BIT)\"");
  442. s.add ("HEADER_SEARCH_PATHS = \"" + replacePreprocessorTokens (config, getHeaderSearchPaths (config).joinIntoString (" ")) + " $(inherited)\"");
  443. s.add ("GCC_OPTIMIZATION_LEVEL = " + config.getGCCOptimisationFlag());
  444. s.add ("INFOPLIST_FILE = " + infoPlistFile.getFileName());
  445. const String extraFlags (replacePreprocessorTokens (config, getExtraCompilerFlags().toString()).trim());
  446. if (extraFlags.isNotEmpty())
  447. s.add ("OTHER_CPLUSPLUSFLAGS = \"" + extraFlags + "\"");
  448. if (xcodeProductInstallPath.isNotEmpty())
  449. s.add ("INSTALL_PATH = \"" + xcodeProductInstallPath + "\"");
  450. if (xcodeIsBundle)
  451. {
  452. s.add ("LIBRARY_STYLE = Bundle");
  453. s.add ("WRAPPER_EXTENSION = " + xcodeBundleExtension.substring (1));
  454. s.add ("GENERATE_PKGINFO_FILE = YES");
  455. }
  456. if (xcodeOtherRezFlags.isNotEmpty())
  457. s.add ("OTHER_REZFLAGS = \"" + xcodeOtherRezFlags + "\"");
  458. if (projectType.isLibrary())
  459. {
  460. if (config.getTargetBinaryRelativePath().toString().isNotEmpty())
  461. {
  462. RelativePath binaryPath (config.getTargetBinaryRelativePath().toString(), RelativePath::projectFolder);
  463. binaryPath = binaryPath.rebased (projectFolder, getTargetFolder(), RelativePath::buildTargetFolder);
  464. s.add ("DSTROOT = " + sanitisePath (binaryPath.toUnixStyle()));
  465. s.add ("SYMROOT = " + sanitisePath (binaryPath.toUnixStyle()));
  466. }
  467. s.add ("CONFIGURATION_BUILD_DIR = \"$(BUILD_DIR)\"");
  468. s.add ("DEPLOYMENT_LOCATION = YES");
  469. }
  470. String gccVersion ("com.apple.compilers.llvm.clang.1_0");
  471. if (! iOS)
  472. {
  473. const String sdk (config.getMacSDKVersion().toString());
  474. const String sdkCompat (config.getMacCompatibilityVersion().toString());
  475. if (sdk == osxVersion10_4)
  476. {
  477. s.add ("SDKROOT = macosx10.4");
  478. gccVersion = "4.0";
  479. }
  480. else if (sdk == osxVersion10_5)
  481. {
  482. s.add ("SDKROOT = macosx10.5");
  483. }
  484. else if (sdk == osxVersion10_6)
  485. {
  486. s.add ("SDKROOT = macosx10.6");
  487. }
  488. if (sdkCompat == osxVersion10_4) s.add ("MACOSX_DEPLOYMENT_TARGET = 10.4");
  489. else if (sdkCompat == osxVersion10_5) s.add ("MACOSX_DEPLOYMENT_TARGET = 10.5");
  490. else if (sdkCompat == osxVersion10_6) s.add ("MACOSX_DEPLOYMENT_TARGET = 10.6");
  491. s.add ("MACOSX_DEPLOYMENT_TARGET_ppc = 10.4");
  492. }
  493. s.add ("GCC_VERSION = " + gccVersion);
  494. s.add ("CLANG_CXX_LANGUAGE_STANDARD = \"c++0x\"");
  495. {
  496. StringArray linkerFlags, librarySearchPaths;
  497. getLinkerFlags (config, linkerFlags, librarySearchPaths);
  498. if (linkerFlags.size() > 0)
  499. s.add ("OTHER_LDFLAGS = \"" + linkerFlags.joinIntoString (" ") + "\"");
  500. if (librarySearchPaths.size() > 0)
  501. {
  502. String libPaths ("LIBRARY_SEARCH_PATHS = (\"$(inherited)\"");
  503. for (int i = 0; i < librarySearchPaths.size(); ++i)
  504. libPaths += ", \"\\\"" + librarySearchPaths[i] + "\\\"\"";
  505. s.add (libPaths + ")");
  506. }
  507. }
  508. StringPairArray defines;
  509. if (config.isDebug().getValue())
  510. {
  511. defines.set ("_DEBUG", "1");
  512. defines.set ("DEBUG", "1");
  513. s.add ("ONLY_ACTIVE_ARCH = YES");
  514. s.add ("COPY_PHASE_STRIP = NO");
  515. s.add ("GCC_DYNAMIC_NO_PIC = NO");
  516. }
  517. else
  518. {
  519. defines.set ("_NDEBUG", "1");
  520. defines.set ("NDEBUG", "1");
  521. s.add ("GCC_GENERATE_DEBUGGING_SYMBOLS = NO");
  522. s.add ("GCC_SYMBOLS_PRIVATE_EXTERN = YES");
  523. }
  524. {
  525. const String objCSuffix (getObjCSuffix().toString().trim());
  526. if (objCSuffix.isNotEmpty())
  527. defines.set ("JUCE_ObjCExtraSuffix", replacePreprocessorTokens (config, objCSuffix));
  528. }
  529. {
  530. defines = mergePreprocessorDefs (defines, getAllPreprocessorDefs (config));
  531. StringArray defsList;
  532. for (int i = 0; i < defines.size(); ++i)
  533. {
  534. String def (defines.getAllKeys()[i]);
  535. const String value (defines.getAllValues()[i]);
  536. if (value.isNotEmpty())
  537. def << "=" << value;
  538. defsList.add (def.quoted());
  539. }
  540. s.add ("GCC_PREPROCESSOR_DEFINITIONS = (" + indentList (defsList, ",") + ")");
  541. }
  542. return s;
  543. }
  544. void addFrameworks()
  545. {
  546. if (! projectType.isLibrary())
  547. {
  548. StringArray s (xcodeFrameworks);
  549. s.trim();
  550. s.removeDuplicates (true);
  551. s.sort (true);
  552. for (int i = 0; i < s.size(); ++i)
  553. addFramework (s[i]);
  554. }
  555. }
  556. //==============================================================================
  557. void writeProjectFile (OutputStream& output)
  558. {
  559. output << "// !$*UTF8*$!\n{\n"
  560. "\tarchiveVersion = 1;\n"
  561. "\tclasses = {\n\t};\n"
  562. "\tobjectVersion = 46;\n"
  563. "\tobjects = {\n\n";
  564. Array <ValueTree*> objects;
  565. objects.addArray (pbxBuildFiles);
  566. objects.addArray (pbxFileReferences);
  567. objects.addArray (pbxGroups);
  568. objects.addArray (targetConfigs);
  569. objects.addArray (projectConfigs);
  570. objects.addArray (misc);
  571. for (int i = 0; i < objects.size(); ++i)
  572. {
  573. ValueTree& o = *objects.getUnchecked(i);
  574. output << "\t\t" << o.getType().toString() << " = { ";
  575. for (int j = 0; j < o.getNumProperties(); ++j)
  576. {
  577. const Identifier propertyName (o.getPropertyName(j));
  578. String val (o.getProperty (propertyName).toString());
  579. if (val.isEmpty() || (val.containsAnyOf (" \t;<>()=,&+-_\r\n")
  580. && ! (val.trimStart().startsWithChar ('(')
  581. || val.trimStart().startsWithChar ('{'))))
  582. val = val.quoted();
  583. output << propertyName.toString() << " = " << val << "; ";
  584. }
  585. output << "};\n";
  586. }
  587. output << "\t};\n\trootObject = " << createID ("__root") << ";\n}\n";
  588. }
  589. static void addPlistDictionaryKey (XmlElement* xml, const String& key, const String& value)
  590. {
  591. forEachXmlChildElementWithTagName (*xml, e, "key")
  592. {
  593. if (e->getAllSubText().trim().equalsIgnoreCase (key))
  594. {
  595. if (e->getNextElement() != nullptr && e->getNextElement()->hasTagName ("key"))
  596. {
  597. // try to fix broken plist format..
  598. xml->removeChildElement (e, true);
  599. break;
  600. }
  601. else
  602. {
  603. return; // (value already exists)
  604. }
  605. }
  606. }
  607. xml->createNewChildElement ("key") ->addTextElement (key);
  608. xml->createNewChildElement ("string")->addTextElement (value);
  609. }
  610. static void addPlistDictionaryKeyBool (XmlElement* xml, const String& key, const bool value)
  611. {
  612. xml->createNewChildElement ("key")->addTextElement (key);
  613. xml->createNewChildElement (value ? "true" : "false");
  614. }
  615. String addBuildFile (const String& path, const String& fileRefID, bool addToSourceBuildPhase, bool inhibitWarnings)
  616. {
  617. String fileID (createID (path + "buildref"));
  618. if (addToSourceBuildPhase)
  619. sourceIDs.add (fileID);
  620. ValueTree* v = new ValueTree (fileID);
  621. v->setProperty ("isa", "PBXBuildFile", 0);
  622. v->setProperty ("fileRef", fileRefID, 0);
  623. if (inhibitWarnings)
  624. v->setProperty ("settings", "{COMPILER_FLAGS = \"-w\"; }", 0);
  625. pbxBuildFiles.add (v);
  626. return fileID;
  627. }
  628. String addBuildFile (const RelativePath& path, bool addToSourceBuildPhase, bool inhibitWarnings)
  629. {
  630. return addBuildFile (path.toUnixStyle(), createFileRefID (path), addToSourceBuildPhase, inhibitWarnings);
  631. }
  632. String addFileReference (String pathString)
  633. {
  634. String sourceTree ("SOURCE_ROOT");
  635. RelativePath path (pathString, RelativePath::unknown);
  636. if (pathString.startsWith ("${"))
  637. {
  638. sourceTree = pathString.substring (2).upToFirstOccurrenceOf ("}", false, false);
  639. pathString = pathString.fromFirstOccurrenceOf ("}/", false, false);
  640. }
  641. else if (path.isAbsolute())
  642. {
  643. sourceTree = "<absolute>";
  644. }
  645. const String fileRefID (createFileRefID (pathString));
  646. ScopedPointer<ValueTree> v (new ValueTree (fileRefID));
  647. v->setProperty ("isa", "PBXFileReference", 0);
  648. v->setProperty ("lastKnownFileType", getFileType (path), 0);
  649. v->setProperty (Ids::name, pathString.fromLastOccurrenceOf ("/", false, false), 0);
  650. v->setProperty ("path", sanitisePath (pathString), 0);
  651. v->setProperty ("sourceTree", sourceTree, 0);
  652. const int existing = pbxFileReferences.indexOfSorted (*this, v);
  653. if (existing >= 0)
  654. {
  655. // If this fails, there's either a string hash collision, or the same file is being added twice (incorrectly)
  656. jassert (pbxFileReferences.getUnchecked (existing)->isEquivalentTo (*v));
  657. }
  658. else
  659. {
  660. pbxFileReferences.addSorted (*this, v.release());
  661. }
  662. return fileRefID;
  663. }
  664. public:
  665. static int compareElements (const ValueTree* first, const ValueTree* second)
  666. {
  667. return first->getType().toString().compare (second->getType().toString());
  668. }
  669. private:
  670. static String getFileType (const RelativePath& file)
  671. {
  672. if (file.hasFileExtension ("cpp;cc;cxx")) return "sourcecode.cpp.cpp";
  673. else if (file.hasFileExtension (".mm")) return "sourcecode.cpp.objcpp";
  674. else if (file.hasFileExtension (".m")) return "sourcecode.c.objc";
  675. else if (file.hasFileExtension (headerFileExtensions)) return "sourcecode.c.h";
  676. else if (file.hasFileExtension (".framework")) return "wrapper.framework";
  677. else if (file.hasFileExtension (".jpeg;.jpg")) return "image.jpeg";
  678. else if (file.hasFileExtension ("png;gif")) return "image" + file.getFileExtension();
  679. else if (file.hasFileExtension ("html;htm")) return "text.html";
  680. else if (file.hasFileExtension ("xml;zip;wav")) return "file" + file.getFileExtension();
  681. else if (file.hasFileExtension ("txt;rtf")) return "text" + file.getFileExtension();
  682. else if (file.hasFileExtension ("plist")) return "text.plist.xml";
  683. else if (file.hasFileExtension ("app")) return "wrapper.application";
  684. else if (file.hasFileExtension ("component;vst;plugin")) return "wrapper.cfbundle";
  685. else if (file.hasFileExtension ("xcodeproj")) return "wrapper.pb-project";
  686. else if (file.hasFileExtension ("a")) return "archive.ar";
  687. return "file" + file.getFileExtension();
  688. }
  689. String addFile (const RelativePath& path, bool shouldBeCompiled, bool inhibitWarnings)
  690. {
  691. const String pathAsString (path.toUnixStyle());
  692. const String refID (addFileReference (path.toUnixStyle()));
  693. if (shouldBeCompiled)
  694. {
  695. if (path.hasFileExtension (".r"))
  696. rezFileIDs.add (addBuildFile (pathAsString, refID, false, inhibitWarnings));
  697. else
  698. addBuildFile (pathAsString, refID, true, inhibitWarnings);
  699. }
  700. return refID;
  701. }
  702. String addProjectItem (const Project::Item& projectItem)
  703. {
  704. if (projectItem.isGroup())
  705. {
  706. StringArray childIDs;
  707. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  708. {
  709. const String childID (addProjectItem (projectItem.getChild(i)));
  710. if (childID.isNotEmpty())
  711. childIDs.add (childID);
  712. }
  713. return addGroup (projectItem, childIDs);
  714. }
  715. else
  716. {
  717. if (projectItem.shouldBeAddedToTargetProject())
  718. {
  719. String itemPath (projectItem.getFilePath());
  720. bool inhibitWarnings = projectItem.getShouldInhibitWarningsValue().getValue();
  721. if (itemPath.startsWith ("${"))
  722. {
  723. const RelativePath path (itemPath, RelativePath::unknown);
  724. return addFile (path, projectItem.shouldBeCompiled(), inhibitWarnings);
  725. }
  726. else
  727. {
  728. const RelativePath path (projectItem.getFile(), getTargetFolder(), RelativePath::buildTargetFolder);
  729. return addFile (path, projectItem.shouldBeCompiled(), inhibitWarnings);
  730. }
  731. }
  732. }
  733. return String::empty;
  734. }
  735. void addFramework (const String& frameworkName)
  736. {
  737. const String path ("System/Library/Frameworks/" + frameworkName + ".framework");
  738. const String fileRefID (createFileRefID (path));
  739. addFileReference ("${SDKROOT}/" + path);
  740. frameworkIDs.add (addBuildFile (path, fileRefID, false, false));
  741. frameworkFileIDs.add (fileRefID);
  742. }
  743. void addGroup (const String& groupID, const String& groupName, const StringArray& childIDs)
  744. {
  745. ValueTree* v = new ValueTree (groupID);
  746. v->setProperty ("isa", "PBXGroup", 0);
  747. v->setProperty ("children", "(" + indentList (childIDs, ",") + " )", 0);
  748. v->setProperty (Ids::name, groupName, 0);
  749. v->setProperty ("sourceTree", "<group>", 0);
  750. pbxGroups.add (v);
  751. }
  752. String addGroup (const Project::Item& item, StringArray& childIDs)
  753. {
  754. const String groupName (item.getName().toString());
  755. const String groupID (getIDForGroup (item));
  756. addGroup (groupID, groupName, childIDs);
  757. return groupID;
  758. }
  759. void addMainBuildProduct()
  760. {
  761. jassert (xcodeFileType.isNotEmpty());
  762. jassert (xcodeBundleExtension.isEmpty() || xcodeBundleExtension.startsWithChar('.'));
  763. String productName (getConfiguration(0)->getTargetBinaryName().toString());
  764. if (xcodeFileType == "archive.ar")
  765. productName = getLibbedFilename (productName);
  766. else
  767. productName += xcodeBundleExtension;
  768. addBuildProduct (xcodeFileType, productName);
  769. }
  770. void addBuildProduct (const String& fileType, const String& binaryName)
  771. {
  772. ValueTree* v = new ValueTree (createID ("__productFileID"));
  773. v->setProperty ("isa", "PBXFileReference", 0);
  774. v->setProperty ("explicitFileType", fileType, 0);
  775. v->setProperty ("includeInIndex", (int) 0, 0);
  776. v->setProperty ("path", sanitisePath (binaryName), 0);
  777. v->setProperty ("sourceTree", "BUILT_PRODUCTS_DIR", 0);
  778. pbxFileReferences.add (v);
  779. }
  780. void addTargetConfig (const String& configName, const StringArray& buildSettings)
  781. {
  782. ValueTree* v = new ValueTree (createID ("targetconfigid_" + configName));
  783. v->setProperty ("isa", "XCBuildConfiguration", 0);
  784. v->setProperty ("buildSettings", "{" + indentList (buildSettings, ";") + " }", 0);
  785. v->setProperty (Ids::name, configName, 0);
  786. targetConfigs.add (v);
  787. }
  788. void addProjectConfig (const String& configName, const StringArray& buildSettings)
  789. {
  790. ValueTree* v = new ValueTree (createID ("projectconfigid_" + configName));
  791. v->setProperty ("isa", "XCBuildConfiguration", 0);
  792. v->setProperty ("buildSettings", "{" + indentList (buildSettings, ";") + " }", 0);
  793. v->setProperty (Ids::name, configName, 0);
  794. projectConfigs.add (v);
  795. }
  796. void addConfigList (const OwnedArray <ValueTree>& configsToUse, const String& listID)
  797. {
  798. StringArray configIDs;
  799. for (int i = 0; i < configsToUse.size(); ++i)
  800. configIDs.add (configsToUse[i]->getType().toString());
  801. ValueTree* v = new ValueTree (listID);
  802. v->setProperty ("isa", "XCConfigurationList", 0);
  803. v->setProperty ("buildConfigurations", "(" + indentList (configIDs, ",") + " )", 0);
  804. v->setProperty ("defaultConfigurationIsVisible", (int) 0, 0);
  805. if (configsToUse[0] != nullptr)
  806. v->setProperty ("defaultConfigurationName", configsToUse[0]->getProperty (Ids::name), 0);
  807. misc.add (v);
  808. }
  809. ValueTree* addBuildPhase (const String& phaseType, const StringArray& fileIds)
  810. {
  811. String phaseId (createID (phaseType + "resbuildphase"));
  812. buildPhaseIDs.add (phaseId);
  813. ValueTree* v = new ValueTree (phaseId);
  814. v->setProperty ("isa", phaseType, 0);
  815. v->setProperty ("buildActionMask", "2147483647", 0);
  816. v->setProperty ("files", "(" + indentList (fileIds, ",") + " )", 0);
  817. v->setProperty ("runOnlyForDeploymentPostprocessing", (int) 0, 0);
  818. misc.add (v);
  819. return v;
  820. }
  821. void addTargetObject()
  822. {
  823. ValueTree* const v = new ValueTree (createID ("__target"));
  824. v->setProperty ("isa", "PBXNativeTarget", 0);
  825. v->setProperty ("buildConfigurationList", createID ("__configList"), 0);
  826. v->setProperty ("buildPhases", "(" + indentList (buildPhaseIDs, ",") + " )", 0);
  827. v->setProperty ("buildRules", "( )", 0);
  828. v->setProperty ("dependencies", "( )", 0);
  829. v->setProperty (Ids::name, projectName, 0);
  830. v->setProperty ("productName", projectName, 0);
  831. v->setProperty ("productReference", createID ("__productFileID"), 0);
  832. if (xcodeProductInstallPath.isNotEmpty())
  833. v->setProperty ("productInstallPath", xcodeProductInstallPath, 0);
  834. jassert (xcodeProductType.isNotEmpty());
  835. v->setProperty ("productType", xcodeProductType, 0);
  836. misc.add (v);
  837. }
  838. void addProjectObject()
  839. {
  840. ValueTree* const v = new ValueTree (createID ("__root"));
  841. v->setProperty ("isa", "PBXProject", 0);
  842. v->setProperty ("buildConfigurationList", createID ("__projList"), 0);
  843. v->setProperty ("compatibilityVersion", "Xcode 3.2", 0);
  844. v->setProperty ("hasScannedForEncodings", (int) 0, 0);
  845. v->setProperty ("mainGroup", createID ("__mainsourcegroup"), 0);
  846. v->setProperty ("projectDirPath", "\"\"", 0);
  847. v->setProperty ("projectRoot", "\"\"", 0);
  848. v->setProperty ("targets", "( " + createID ("__target") + " )", 0);
  849. misc.add (v);
  850. }
  851. void addShellScriptPhase()
  852. {
  853. if (xcodeShellScript.isNotEmpty())
  854. {
  855. ValueTree* const v = addBuildPhase ("PBXShellScriptBuildPhase", StringArray());
  856. v->setProperty (Ids::name, xcodeShellScriptTitle, 0);
  857. v->setProperty ("shellPath", "/bin/sh", 0);
  858. v->setProperty ("shellScript", xcodeShellScript.replace ("\\", "\\\\")
  859. .replace ("\"", "\\\"")
  860. .replace ("\r\n", "\\n")
  861. .replace ("\n", "\\n"), 0);
  862. }
  863. }
  864. //==============================================================================
  865. static String indentList (const StringArray& list, const String& separator)
  866. {
  867. if (list.size() == 0)
  868. return " ";
  869. return "\n\t\t\t\t" + list.joinIntoString (separator + "\n\t\t\t\t")
  870. + (separator == ";" ? separator : String::empty);
  871. }
  872. String createID (String rootString) const
  873. {
  874. if (rootString.startsWith ("${"))
  875. rootString = rootString.fromFirstOccurrenceOf ("}/", false, false);
  876. rootString += project.getProjectUID();
  877. return MD5 (rootString.toUTF8()).toHexString().substring (0, 24).toUpperCase();
  878. }
  879. String createFileRefID (const RelativePath& path) const
  880. {
  881. return createFileRefID (path.toUnixStyle());
  882. }
  883. String createFileRefID (const String& path) const
  884. {
  885. return createID ("__fileref_" + path);
  886. }
  887. String getIDForGroup (const Project::Item& item) const
  888. {
  889. return createID (item.getID());
  890. }
  891. bool shouldFileBeCompiledByDefault (const RelativePath& file) const
  892. {
  893. return file.hasFileExtension (sourceFileExtensions);
  894. }
  895. };
  896. #endif // __JUCER_PROJECTEXPORT_XCODE_JUCEHEADER__