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.

1186 lines
43KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-10 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. #include "jucer_Project.h"
  19. #include "jucer_ProjectType.h"
  20. #include "jucer_ProjectExporter.h"
  21. #include "jucer_ResourceFile.h"
  22. #include "jucer_ProjectSaver.h"
  23. #include "../Application/jucer_OpenDocumentManager.h"
  24. //==============================================================================
  25. namespace Tags
  26. {
  27. const Identifier projectRoot ("JUCERPROJECT");
  28. const Identifier projectMainGroup ("MAINGROUP");
  29. const Identifier group ("GROUP");
  30. const Identifier file ("FILE");
  31. const Identifier configurations ("CONFIGURATIONS");
  32. const Identifier configuration ("CONFIGURATION");
  33. const Identifier exporters ("EXPORTFORMATS");
  34. const Identifier configGroup ("JUCEOPTIONS");
  35. }
  36. const char* Project::projectFileExtension = ".jucer";
  37. //==============================================================================
  38. Project::Project (const File& file_)
  39. : FileBasedDocument (projectFileExtension,
  40. String ("*") + projectFileExtension,
  41. "Choose a Jucer project to load",
  42. "Save Jucer project"),
  43. projectRoot (Tags::projectRoot)
  44. {
  45. setFile (file_);
  46. setMissingDefaultValues();
  47. setChangedFlag (false);
  48. mainProjectIcon.setImage (ImageCache::getFromMemory (BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize));
  49. projectRoot.addListener (this);
  50. }
  51. Project::~Project()
  52. {
  53. projectRoot.removeListener (this);
  54. OpenDocumentManager::getInstance()->closeAllDocumentsUsingProject (*this, false);
  55. }
  56. //==============================================================================
  57. void Project::setTitle (const String& newTitle)
  58. {
  59. projectRoot.setProperty (Ids::name, newTitle, getUndoManagerFor (projectRoot));
  60. getMainGroup().getName() = newTitle;
  61. }
  62. const String Project::getDocumentTitle()
  63. {
  64. return getProjectName().toString();
  65. }
  66. void Project::updateProjectSettings()
  67. {
  68. projectRoot.setProperty (Ids::jucerVersion, ProjectInfo::versionString, 0);
  69. projectRoot.setProperty (Ids::name, getDocumentTitle(), 0);
  70. }
  71. void Project::setMissingDefaultValues()
  72. {
  73. if (! projectRoot.hasProperty (Ids::id_))
  74. projectRoot.setProperty (Ids::id_, createAlphaNumericUID(), nullptr);
  75. // Create main file group if missing
  76. if (! projectRoot.getChildWithName (Tags::projectMainGroup).isValid())
  77. {
  78. Item mainGroup (*this, ValueTree (Tags::projectMainGroup));
  79. projectRoot.addChild (mainGroup.getNode(), 0, 0);
  80. }
  81. getMainGroup().initialiseNodeValues();
  82. if (getDocumentTitle().isEmpty())
  83. setTitle ("Juce Project");
  84. if (! projectRoot.hasProperty (Ids::projectType))
  85. getProjectTypeValue() = ProjectType::getGUIAppTypeName();
  86. if (! projectRoot.hasProperty (Ids::version))
  87. getVersion() = "1.0.0";
  88. if (! projectRoot.hasProperty (Ids::juceLinkage))
  89. getJuceLinkageModeValue() = useAmalgamatedJuceViaMultipleTemplates;
  90. const String juceFolderPath (getRelativePathForFile (StoredSettings::getInstance()->getLastKnownJuceFolder()));
  91. // Create configs group
  92. if (! projectRoot.getChildWithName (Tags::configurations).isValid())
  93. {
  94. projectRoot.addChild (ValueTree (Tags::configurations), 0, 0);
  95. createDefaultConfigs();
  96. }
  97. if (! projectRoot.getChildWithName (Tags::exporters).isValid())
  98. createDefaultExporters();
  99. const String sanitisedProjectName (CodeHelpers::makeValidIdentifier (getProjectName().toString(), false, true, false));
  100. if (! projectRoot.hasProperty (Ids::buildVST))
  101. {
  102. shouldBuildVST() = true;
  103. shouldBuildRTAS() = false;
  104. shouldBuildAU() = true;
  105. getPluginName() = getProjectName().toString();
  106. getPluginDesc() = getProjectName().toString();
  107. getPluginManufacturer() = "yourcompany";
  108. getPluginManufacturerCode() = "Manu";
  109. getPluginCode() = "Plug";
  110. getPluginChannelConfigs() = "{1, 1}, {2, 2}";
  111. getPluginIsSynth() = false;
  112. getPluginWantsMidiInput() = false;
  113. getPluginProducesMidiOut() = false;
  114. getPluginSilenceInProducesSilenceOut() = false;
  115. getPluginTailLengthSeconds() = 0;
  116. getPluginEditorNeedsKeyFocus() = false;
  117. getPluginAUExportPrefix() = sanitisedProjectName + "AU";
  118. getPluginAUCocoaViewClassName() = sanitisedProjectName + "AU_V1";
  119. getPluginRTASCategory() = String::empty;
  120. }
  121. if (! projectRoot.hasProperty (Ids::bundleIdentifier))
  122. setBundleIdentifierToDefault();
  123. }
  124. //==============================================================================
  125. const String Project::loadDocument (const File& file)
  126. {
  127. ScopedPointer <XmlElement> xml (XmlDocument::parse (file));
  128. if (xml == nullptr || ! xml->hasTagName (Tags::projectRoot.toString()))
  129. return "Not a valid Jucer project!";
  130. ValueTree newTree (ValueTree::fromXml (*xml));
  131. if (! newTree.hasType (Tags::projectRoot))
  132. return "The document contains errors and couldn't be parsed!";
  133. StoredSettings::getInstance()->recentFiles.addFile (file);
  134. StoredSettings::getInstance()->flush();
  135. projectRoot = newTree;
  136. setMissingDefaultValues();
  137. return String::empty;
  138. }
  139. const String Project::saveDocument (const File& file)
  140. {
  141. updateProjectSettings();
  142. {
  143. // (getting these forces the values to be sanitised)
  144. OwnedArray <Project::ConfigFlag> flags;
  145. getAllConfigFlags (flags);
  146. }
  147. if (FileHelpers::isJuceFolder (getLocalJuceFolder()))
  148. StoredSettings::getInstance()->setLastKnownJuceFolder (getLocalJuceFolder().getFullPathName());
  149. StoredSettings::getInstance()->recentFiles.addFile (file);
  150. ProjectSaver saver (*this, file);
  151. return saver.save();
  152. }
  153. //==============================================================================
  154. File Project::lastDocumentOpened;
  155. const File Project::getLastDocumentOpened()
  156. {
  157. return lastDocumentOpened;
  158. }
  159. void Project::setLastDocumentOpened (const File& file)
  160. {
  161. lastDocumentOpened = file;
  162. }
  163. //==============================================================================
  164. void Project::valueTreePropertyChanged (ValueTree& tree, const Identifier& property)
  165. {
  166. if (getProjectType().isLibrary())
  167. getJuceLinkageModeValue() = notLinkedToJuce;
  168. changed();
  169. }
  170. void Project::valueTreeChildAdded (ValueTree& parentTree, ValueTree& childWhichHasBeenAdded)
  171. {
  172. changed();
  173. }
  174. void Project::valueTreeChildRemoved (ValueTree& parentTree, ValueTree& childWhichHasBeenRemoved)
  175. {
  176. changed();
  177. }
  178. void Project::valueTreeChildOrderChanged (ValueTree& parentTree)
  179. {
  180. changed();
  181. }
  182. void Project::valueTreeParentChanged (ValueTree& tree)
  183. {
  184. }
  185. //==============================================================================
  186. File Project::resolveFilename (String filename) const
  187. {
  188. if (filename.isEmpty())
  189. return File::nonexistent;
  190. filename = replacePreprocessorDefs (getPreprocessorDefs(), filename)
  191. .replaceCharacter ('\\', '/');
  192. if (File::isAbsolutePath (filename))
  193. return File (filename);
  194. return getFile().getSiblingFile (filename);
  195. }
  196. String Project::getRelativePathForFile (const File& file) const
  197. {
  198. String filename (file.getFullPathName());
  199. File relativePathBase (getFile().getParentDirectory());
  200. String p1 (relativePathBase.getFullPathName());
  201. String p2 (file.getFullPathName());
  202. while (p1.startsWithChar (File::separator))
  203. p1 = p1.substring (1);
  204. while (p2.startsWithChar (File::separator))
  205. p2 = p2.substring (1);
  206. if (p1.upToFirstOccurrenceOf (File::separatorString, true, false)
  207. .equalsIgnoreCase (p2.upToFirstOccurrenceOf (File::separatorString, true, false)))
  208. {
  209. filename = file.getRelativePathFrom (relativePathBase);
  210. }
  211. return filename;
  212. }
  213. //==============================================================================
  214. const ProjectType& Project::getProjectType() const
  215. {
  216. const ProjectType* type = ProjectType::findType (getProjectTypeValue().toString());
  217. jassert (type != nullptr);
  218. if (type == nullptr)
  219. {
  220. type = ProjectType::findType (ProjectType::getGUIAppTypeName());
  221. jassert (type != nullptr);
  222. }
  223. return *type;
  224. }
  225. const char* const Project::notLinkedToJuce = "none";
  226. const char* const Project::useLinkedJuce = "static";
  227. const char* const Project::useAmalgamatedJuce = "amalg_big";
  228. const char* const Project::useAmalgamatedJuceViaSingleTemplate = "amalg_template";
  229. const char* const Project::useAmalgamatedJuceViaMultipleTemplates = "amalg_multi";
  230. File Project::getLocalJuceFolder()
  231. {
  232. ScopedPointer <ProjectExporter> exp (ProjectExporter::createPlatformDefaultExporter (*this));
  233. if (exp != nullptr)
  234. {
  235. File f (resolveFilename (exp->getJuceFolder().toString()));
  236. if (FileHelpers::isJuceFolder (f))
  237. return f;
  238. }
  239. return StoredSettings::getInstance()->getLastKnownJuceFolder();
  240. }
  241. //==============================================================================
  242. void Project::createPropertyEditors (Array <PropertyComponent*>& props)
  243. {
  244. props.add (new TextPropertyComponent (getProjectName(), "Project Name", 256, false));
  245. props.getLast()->setTooltip ("The name of the project.");
  246. props.add (new TextPropertyComponent (getVersion(), "Project Version", 16, false));
  247. props.getLast()->setTooltip ("The project's version number, This should be in the format major.minor.point");
  248. {
  249. StringArray projectTypeNames;
  250. Array<var> projectTypeCodes;
  251. const Array<ProjectType*>& types = ProjectType::getAllTypes();
  252. for (int i = 0; i < types.size(); ++i)
  253. {
  254. projectTypeNames.add (types.getUnchecked(i)->getDescription());
  255. projectTypeCodes.add (types.getUnchecked(i)->getType());
  256. }
  257. props.add (new ChoicePropertyComponent (getProjectTypeValue(), "Project Type", projectTypeNames, projectTypeCodes));
  258. }
  259. const char* linkageTypes[] = { "Not linked to Juce", "Linked to Juce Static Library", "Include Juce Amalgamated Files", "Include Juce Source Code Directly (In a single file)", "Include Juce Source Code Directly (Split across several files)", 0 };
  260. const char* linkageTypeValues[] = { notLinkedToJuce, useLinkedJuce, useAmalgamatedJuce, useAmalgamatedJuceViaSingleTemplate, useAmalgamatedJuceViaMultipleTemplates, 0 };
  261. props.add (new ChoicePropertyComponent (getJuceLinkageModeValue(), "Juce Linkage Method", StringArray (linkageTypes), Array<var> (linkageTypeValues)));
  262. props.getLast()->setTooltip ("The method by which your project will be linked to Juce.");
  263. props.add (new TextPropertyComponent (getBundleIdentifier(), "Bundle Identifier", 256, false));
  264. props.getLast()->setTooltip ("A unique identifier for this product, mainly for use in Mac builds. It should be something like 'com.yourcompanyname.yourproductname'");
  265. {
  266. OwnedArray<Project::Item> images;
  267. findAllImageItems (images);
  268. StringArray choices;
  269. Array<var> ids;
  270. choices.add ("<None>");
  271. ids.add (var::null);
  272. choices.add (String::empty);
  273. ids.add (var::null);
  274. for (int i = 0; i < images.size(); ++i)
  275. {
  276. choices.add (images.getUnchecked(i)->getName().toString());
  277. ids.add (images.getUnchecked(i)->getID());
  278. }
  279. props.add (new ChoicePropertyComponent (getSmallIconImageItemID(), "Icon (small)", choices, ids));
  280. props.getLast()->setTooltip ("Sets an icon to use for the executable.");
  281. props.add (new ChoicePropertyComponent (getBigIconImageItemID(), "Icon (large)", choices, ids));
  282. props.getLast()->setTooltip ("Sets an icon to use for the executable.");
  283. }
  284. if (getProjectType().isAudioPlugin())
  285. {
  286. props.add (new BooleanPropertyComponent (shouldBuildVST(), "Build VST", "Enabled"));
  287. props.getLast()->setTooltip ("Whether the project should produce a VST plugin.");
  288. props.add (new BooleanPropertyComponent (shouldBuildAU(), "Build AudioUnit", "Enabled"));
  289. props.getLast()->setTooltip ("Whether the project should produce an AudioUnit plugin.");
  290. props.add (new BooleanPropertyComponent (shouldBuildRTAS(), "Build RTAS", "Enabled"));
  291. props.getLast()->setTooltip ("Whether the project should produce an RTAS plugin.");
  292. }
  293. if (getProjectType().isAudioPlugin())
  294. {
  295. props.add (new TextPropertyComponent (getPluginName(), "Plugin Name", 128, false));
  296. props.getLast()->setTooltip ("The name of your plugin (keep it short!)");
  297. props.add (new TextPropertyComponent (getPluginDesc(), "Plugin Description", 256, false));
  298. props.getLast()->setTooltip ("A short description of your plugin.");
  299. props.add (new TextPropertyComponent (getPluginManufacturer(), "Plugin Manufacturer", 256, false));
  300. props.getLast()->setTooltip ("The name of your company (cannot be blank).");
  301. props.add (new TextPropertyComponent (getPluginManufacturerCode(), "Plugin Manufacturer Code", 4, false));
  302. props.getLast()->setTooltip ("A four-character unique ID for your company. Note that for AU compatibility, this must contain at least one upper-case letter!");
  303. props.add (new TextPropertyComponent (getPluginCode(), "Plugin Code", 4, false));
  304. props.getLast()->setTooltip ("A four-character unique ID for your plugin. Note that for AU compatibility, this must contain at least one upper-case letter!");
  305. props.add (new TextPropertyComponent (getPluginChannelConfigs(), "Plugin Channel Configurations", 256, false));
  306. props.getLast()->setTooltip ("This is the set of input/output channel configurations that your plugin can handle. The list is a comma-separated set of pairs of values in the form { numInputs, numOutputs }, and each "
  307. "pair indicates a valid configuration that the plugin can handle. So for example, {1, 1}, {2, 2} means that the plugin can be used in just two configurations: either with 1 input "
  308. "and 1 output, or with 2 inputs and 2 outputs.");
  309. props.add (new BooleanPropertyComponent (getPluginIsSynth(), "Plugin is a Synth", "Is a Synth"));
  310. props.getLast()->setTooltip ("Enable this if you want your plugin to be treated as a synth or generator. It doesn't make much difference to the plugin itself, but some hosts treat synths differently to other plugins.");
  311. props.add (new BooleanPropertyComponent (getPluginWantsMidiInput(), "Plugin Midi Input", "Plugin wants midi input"));
  312. props.getLast()->setTooltip ("Enable this if you want your plugin to accept midi messages.");
  313. props.add (new BooleanPropertyComponent (getPluginProducesMidiOut(), "Plugin Midi Output", "Plugin produces midi output"));
  314. props.getLast()->setTooltip ("Enable this if your plugin is going to produce midi messages.");
  315. props.add (new BooleanPropertyComponent (getPluginSilenceInProducesSilenceOut(), "Silence", "Silence in produces silence out"));
  316. props.getLast()->setTooltip ("Enable this if your plugin has no tail - i.e. if passing a silent buffer to it will always result in a silent buffer being produced.");
  317. props.add (new TextPropertyComponent (getPluginTailLengthSeconds(), "Tail Length (in seconds)", 12, false));
  318. props.getLast()->setTooltip ("This indicates the length, in seconds, of the plugin's tail. This information may or may not be used by the host.");
  319. props.add (new BooleanPropertyComponent (getPluginEditorNeedsKeyFocus(), "Key Focus", "Plugin editor requires keyboard focus"));
  320. props.getLast()->setTooltip ("Enable this if your plugin needs keyboard input - some hosts can be a bit funny about keyboard focus..");
  321. props.add (new TextPropertyComponent (getPluginAUExportPrefix(), "Plugin AU Export Prefix", 64, false));
  322. props.getLast()->setTooltip ("A prefix for the names of exported entry-point functions that the component exposes - typically this will be a version of your plugin's name that can be used as part of a C++ token.");
  323. props.add (new TextPropertyComponent (getPluginAUCocoaViewClassName(), "Plugin AU Cocoa View Name", 64, false));
  324. props.getLast()->setTooltip ("In an AU, this is the name of Cocoa class that creates the UI. Some hosts bizarrely display the class-name, so you might want to make it reflect your plugin. But the name must be "
  325. "UNIQUE to this exact version of your plugin, to avoid objective-C linkage mix-ups that happen when different plugins containing the same class-name are loaded simultaneously.");
  326. props.add (new TextPropertyComponent (getPluginRTASCategory(), "Plugin RTAS Category", 64, false));
  327. props.getLast()->setTooltip ("(Leave this blank if your plugin is a synth). This is one of the RTAS categories from FicPluginEnums.h, such as: ePlugInCategory_None, ePlugInCategory_EQ, ePlugInCategory_Dynamics, "
  328. "ePlugInCategory_PitchShift, ePlugInCategory_Reverb, ePlugInCategory_Delay, "
  329. "ePlugInCategory_Modulation, ePlugInCategory_Harmonic, ePlugInCategory_NoiseReduction, "
  330. "ePlugInCategory_Dither, ePlugInCategory_SoundField");
  331. }
  332. props.add (new TextPropertyComponent (getProjectPreprocessorDefs(), "Preprocessor definitions", 32768, false));
  333. props.getLast()->setTooltip ("Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace or commas to separate the items - to include a space or comma in a definition, precede it with a backslash.");
  334. for (int i = props.size(); --i >= 0;)
  335. props.getUnchecked(i)->setPreferredHeight (22);
  336. }
  337. String Project::getVersionAsHex() const
  338. {
  339. StringArray configs;
  340. configs.addTokens (getVersion().toString(), ",.", String::empty);
  341. configs.trim();
  342. configs.removeEmptyStrings();
  343. int value = (configs[0].getIntValue() << 16) + (configs[1].getIntValue() << 8) + configs[2].getIntValue();
  344. if (configs.size() >= 4)
  345. value = (value << 8) + configs[3].getIntValue();
  346. return "0x" + String::toHexString (value);
  347. }
  348. Image Project::getBigIcon()
  349. {
  350. Item icon (getMainGroup().findItemWithID (getBigIconImageItemID().toString()));
  351. if (icon.isValid())
  352. return ImageCache::getFromFile (icon.getFile());
  353. return Image();
  354. }
  355. Image Project::getSmallIcon()
  356. {
  357. Item icon (getMainGroup().findItemWithID (getSmallIconImageItemID().toString()));
  358. if (icon.isValid())
  359. return ImageCache::getFromFile (icon.getFile());
  360. return Image();
  361. }
  362. Image Project::getBestIconForSize (int size, bool returnNullIfNothingBigEnough)
  363. {
  364. Image im;
  365. const Image im1 (getSmallIcon());
  366. const Image im2 (getBigIcon());
  367. if (im1.isValid() && im2.isValid())
  368. {
  369. if (im1.getWidth() >= size && im2.getWidth() >= size)
  370. im = im1.getWidth() < im2.getWidth() ? im1 : im2;
  371. else if (im1.getWidth() >= size)
  372. im = im1;
  373. else if (im2.getWidth() >= size)
  374. im = im2;
  375. else
  376. return Image();
  377. }
  378. else
  379. {
  380. im = im1.isValid() ? im1 : im2;
  381. }
  382. if (size == im.getWidth() && size == im.getHeight())
  383. return im;
  384. if (returnNullIfNothingBigEnough && im.getWidth() < size && im.getHeight() < size)
  385. return Image::null;
  386. Image newIm (Image::ARGB, size, size, true);
  387. Graphics g (newIm);
  388. g.drawImageWithin (im, 0, 0, size, size,
  389. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  390. return newIm;
  391. }
  392. StringPairArray Project::getPreprocessorDefs() const
  393. {
  394. return parsePreprocessorDefs (getProjectPreprocessorDefs().toString());
  395. }
  396. //==============================================================================
  397. Project::Item Project::getMainGroup()
  398. {
  399. return Item (*this, projectRoot.getChildWithName (Tags::projectMainGroup));
  400. }
  401. static void findImages (const Project::Item& item, OwnedArray<Project::Item>& found)
  402. {
  403. if (item.isImageFile())
  404. {
  405. found.add (new Project::Item (item));
  406. }
  407. else if (item.isGroup())
  408. {
  409. for (int i = 0; i < item.getNumChildren(); ++i)
  410. findImages (item.getChild (i), found);
  411. }
  412. }
  413. void Project::findAllImageItems (OwnedArray<Project::Item>& items)
  414. {
  415. findImages (getMainGroup(), items);
  416. }
  417. //==============================================================================
  418. Project::Item::Item (Project& project_, const ValueTree& node_)
  419. : project (&project_), node (node_)
  420. {
  421. }
  422. Project::Item::Item (const Item& other)
  423. : project (other.project), node (other.node)
  424. {
  425. }
  426. Project::Item& Project::Item::operator= (const Project::Item& other)
  427. {
  428. project = other.project;
  429. node = other.node;
  430. return *this;
  431. }
  432. Project::Item::~Item()
  433. {
  434. }
  435. String Project::Item::getID() const { return node [Ids::id_]; }
  436. void Project::Item::setID (const String& newID) { node.setProperty (Ids::id_, newID, nullptr); }
  437. String Project::Item::getImageFileID() const { return "id:" + getID(); }
  438. Project::Item Project::Item::createGroup (Project& project, const String& name)
  439. {
  440. Item group (project, ValueTree (Tags::group));
  441. group.initialiseNodeValues();
  442. group.getName() = name;
  443. return group;
  444. }
  445. bool Project::Item::isFile() const { return node.hasType (Tags::file); }
  446. bool Project::Item::isGroup() const { return node.hasType (Tags::group) || isMainGroup(); }
  447. bool Project::Item::isMainGroup() const { return node.hasType (Tags::projectMainGroup); }
  448. bool Project::Item::isImageFile() const { return isFile() && getFile().hasFileExtension ("png;jpg;jpeg;gif;drawable"); }
  449. Project::Item Project::Item::findItemWithID (const String& targetId) const
  450. {
  451. if (node [Ids::id_] == targetId)
  452. return *this;
  453. if (isGroup())
  454. {
  455. for (int i = getNumChildren(); --i >= 0;)
  456. {
  457. Item found (getChild(i).findItemWithID (targetId));
  458. if (found.isValid())
  459. return found;
  460. }
  461. }
  462. return Item (*project, ValueTree::invalid);
  463. }
  464. bool Project::Item::canContain (const Item& child) const
  465. {
  466. if (isFile())
  467. return false;
  468. if (isGroup())
  469. return child.isFile() || child.isGroup();
  470. jassertfalse
  471. return false;
  472. }
  473. bool Project::Item::shouldBeAddedToTargetProject() const
  474. {
  475. return isFile();
  476. }
  477. bool Project::Item::shouldBeCompiled() const { return getShouldCompileValue().getValue(); }
  478. Value Project::Item::getShouldCompileValue() const { return node.getPropertyAsValue (Ids::compile, getUndoManager()); }
  479. bool Project::Item::shouldBeAddedToBinaryResources() const { return getShouldAddToResourceValue().getValue(); }
  480. Value Project::Item::getShouldAddToResourceValue() const { return node.getPropertyAsValue (Ids::resource, getUndoManager()); }
  481. Value Project::Item::getShouldInhibitWarningsValue() const { return node.getPropertyAsValue (Ids::noWarnings, getUndoManager()); }
  482. String Project::Item::getFilePath() const
  483. {
  484. if (isFile())
  485. return node [Ids::file].toString();
  486. else
  487. return String::empty;
  488. }
  489. File Project::Item::getFile() const
  490. {
  491. if (isFile())
  492. return getProject().resolveFilename (node [Ids::file].toString());
  493. else
  494. return File::nonexistent;
  495. }
  496. void Project::Item::setFile (const File& file)
  497. {
  498. setFile (RelativePath (getProject().getRelativePathForFile (file), RelativePath::projectFolder));
  499. jassert (getFile() == file);
  500. }
  501. void Project::Item::setFile (const RelativePath& file)
  502. {
  503. jassert (file.getRoot() == RelativePath::projectFolder);
  504. jassert (isFile());
  505. node.setProperty (Ids::file, file.toUnixStyle(), getUndoManager());
  506. node.setProperty (Ids::name, file.getFileName(), getUndoManager());
  507. }
  508. bool Project::Item::renameFile (const File& newFile)
  509. {
  510. const File oldFile (getFile());
  511. if (oldFile.moveFileTo (newFile))
  512. {
  513. setFile (newFile);
  514. OpenDocumentManager::getInstance()->fileHasBeenRenamed (oldFile, newFile);
  515. return true;
  516. }
  517. return false;
  518. }
  519. Project::Item Project::Item::findItemForFile (const File& file) const
  520. {
  521. if (getFile() == file)
  522. return *this;
  523. if (isGroup())
  524. {
  525. for (int i = getNumChildren(); --i >= 0;)
  526. {
  527. Item found (getChild(i).findItemForFile (file));
  528. if (found.isValid())
  529. return found;
  530. }
  531. }
  532. return Item (getProject(), ValueTree::invalid);
  533. }
  534. File Project::Item::determineGroupFolder() const
  535. {
  536. jassert (isGroup());
  537. File f;
  538. for (int i = 0; i < getNumChildren(); ++i)
  539. {
  540. f = getChild(i).getFile();
  541. if (f.exists())
  542. return f.getParentDirectory();
  543. }
  544. Item parent (getParent());
  545. if (parent != *this)
  546. {
  547. f = parent.determineGroupFolder();
  548. if (f.getChildFile (getName().toString()).isDirectory())
  549. f = f.getChildFile (getName().toString());
  550. }
  551. else
  552. {
  553. f = getProject().getFile().getParentDirectory();
  554. if (f.getChildFile ("Source").isDirectory())
  555. f = f.getChildFile ("Source");
  556. }
  557. return f;
  558. }
  559. void Project::Item::initialiseNodeValues()
  560. {
  561. if (! node.hasProperty (Ids::id_))
  562. setID (createAlphaNumericUID());
  563. if (isFile())
  564. {
  565. node.setProperty (Ids::name, getFile().getFileName(), 0);
  566. }
  567. else if (isGroup())
  568. {
  569. for (int i = getNumChildren(); --i >= 0;)
  570. getChild(i).initialiseNodeValues();
  571. }
  572. }
  573. Value Project::Item::getName() const
  574. {
  575. return node.getPropertyAsValue (Ids::name, getUndoManager());
  576. }
  577. void Project::Item::addChild (const Item& newChild, int insertIndex)
  578. {
  579. node.addChild (newChild.getNode(), insertIndex, getUndoManager());
  580. }
  581. void Project::Item::removeItemFromProject()
  582. {
  583. node.getParent().removeChild (node, getUndoManager());
  584. }
  585. Project::Item Project::Item::getParent() const
  586. {
  587. if (isMainGroup() || ! isGroup())
  588. return *this;
  589. return Item (getProject(), node.getParent());
  590. }
  591. struct ItemSorter
  592. {
  593. static int compareElements (const ValueTree& first, const ValueTree& second)
  594. {
  595. return first [Ids::name].toString().compareIgnoreCase (second [Ids::name].toString());
  596. }
  597. };
  598. void Project::Item::sortAlphabetically()
  599. {
  600. ItemSorter sorter;
  601. node.sort (sorter, getUndoManager(), true);
  602. }
  603. Project::Item Project::Item::addNewSubGroup (const String& name, int insertIndex)
  604. {
  605. Item group (createGroup (getProject(), name));
  606. jassert (canContain (group));
  607. addChild (group, insertIndex);
  608. return group;
  609. }
  610. bool Project::Item::addFile (const File& file, int insertIndex)
  611. {
  612. if (file == File::nonexistent || file.isHidden() || file.getFileName().startsWithChar ('.'))
  613. return false;
  614. if (file.isDirectory())
  615. {
  616. Item group (addNewSubGroup (file.getFileNameWithoutExtension(), insertIndex));
  617. DirectoryIterator iter (file, false, "*", File::findFilesAndDirectories);
  618. while (iter.next())
  619. {
  620. if (! getProject().getMainGroup().findItemForFile (iter.getFile()).isValid())
  621. group.addFile (iter.getFile(), -1);
  622. }
  623. group.sortAlphabetically();
  624. }
  625. else if (file.existsAsFile())
  626. {
  627. if (! getProject().getMainGroup().findItemForFile (file).isValid())
  628. {
  629. Item item (getProject(), ValueTree (Tags::file));
  630. item.initialiseNodeValues();
  631. item.getName() = file.getFileName();
  632. item.getShouldCompileValue() = file.hasFileExtension ("cpp;mm;c;m;cc;cxx");
  633. item.getShouldAddToResourceValue() = getProject().shouldBeAddedToBinaryResourcesByDefault (file);
  634. if (canContain (item))
  635. {
  636. item.setFile (file);
  637. addChild (item, insertIndex);
  638. }
  639. }
  640. }
  641. else
  642. {
  643. jassertfalse;
  644. }
  645. return true;
  646. }
  647. bool Project::Item::addRelativeFile (const RelativePath& file, int insertIndex, bool shouldCompile)
  648. {
  649. Item item (getProject(), ValueTree (Tags::file));
  650. item.initialiseNodeValues();
  651. item.getName() = file.getFileName();
  652. item.getShouldCompileValue() = shouldCompile;
  653. item.getShouldAddToResourceValue() = getProject().shouldBeAddedToBinaryResourcesByDefault (file);
  654. if (canContain (item))
  655. {
  656. item.setFile (file);
  657. addChild (item, insertIndex);
  658. return true;
  659. }
  660. return false;
  661. }
  662. const Drawable* Project::Item::getIcon() const
  663. {
  664. if (isFile())
  665. {
  666. if (isImageFile())
  667. return StoredSettings::getInstance()->getImageFileIcon();
  668. return LookAndFeel::getDefaultLookAndFeel().getDefaultDocumentFileImage();
  669. }
  670. else if (isMainGroup())
  671. {
  672. return &(getProject().mainProjectIcon);
  673. }
  674. return LookAndFeel::getDefaultLookAndFeel().getDefaultFolderImage();
  675. }
  676. //==============================================================================
  677. ValueTree Project::getConfigNode()
  678. {
  679. return projectRoot.getOrCreateChildWithName (Tags::configGroup, nullptr);
  680. }
  681. void Project::getAllConfigFlags (OwnedArray <ConfigFlag>& flags)
  682. {
  683. OwnedArray<LibraryModule> modules;
  684. getProjectType().createRequiredModules (*this, modules);
  685. int i;
  686. for (i = 0; i < modules.size(); ++i)
  687. modules.getUnchecked(i)->getConfigFlags (*this, flags);
  688. for (i = 0; i < flags.size(); ++i)
  689. flags.getUnchecked(i)->value.referTo (getConfigFlag (flags.getUnchecked(i)->symbol));
  690. }
  691. const char* const Project::configFlagDefault = "default";
  692. const char* const Project::configFlagEnabled = "enabled";
  693. const char* const Project::configFlagDisabled = "disabled";
  694. Value Project::getConfigFlag (const String& name)
  695. {
  696. const ValueTree configNode (getConfigNode());
  697. Value v (configNode.getPropertyAsValue (name, getUndoManagerFor (configNode)));
  698. if (v.getValue().toString().isEmpty())
  699. v = configFlagDefault;
  700. return v;
  701. }
  702. bool Project::isConfigFlagEnabled (const String& name) const
  703. {
  704. return projectRoot.getChildWithName (Tags::configGroup).getProperty (name) == configFlagEnabled;
  705. }
  706. //==============================================================================
  707. ValueTree Project::getConfigurations() const
  708. {
  709. return projectRoot.getChildWithName (Tags::configurations);
  710. }
  711. int Project::getNumConfigurations() const
  712. {
  713. return getConfigurations().getNumChildren();
  714. }
  715. Project::BuildConfiguration Project::getConfiguration (int index)
  716. {
  717. jassert (index < getConfigurations().getNumChildren());
  718. return BuildConfiguration (this, getConfigurations().getChild (index));
  719. }
  720. bool Project::hasConfigurationNamed (const String& name) const
  721. {
  722. const ValueTree configs (getConfigurations());
  723. for (int i = configs.getNumChildren(); --i >= 0;)
  724. if (configs.getChild(i) [Ids::name].toString() == name)
  725. return true;
  726. return false;
  727. }
  728. String Project::getUniqueConfigName (String name) const
  729. {
  730. String nameRoot (name);
  731. while (CharacterFunctions::isDigit (nameRoot.getLastCharacter()))
  732. nameRoot = nameRoot.dropLastCharacters (1);
  733. nameRoot = nameRoot.trim();
  734. int suffix = 2;
  735. while (hasConfigurationNamed (name))
  736. name = nameRoot + " " + String (suffix++);
  737. return name;
  738. }
  739. void Project::addNewConfiguration (BuildConfiguration* configToCopy)
  740. {
  741. const String configName (getUniqueConfigName (configToCopy != nullptr ? configToCopy->config [Ids::name].toString()
  742. : "New Build Configuration"));
  743. ValueTree configs (getConfigurations());
  744. if (! configs.isValid())
  745. {
  746. projectRoot.addChild (ValueTree (Tags::configurations), 0, getUndoManagerFor (projectRoot));
  747. configs = getConfigurations();
  748. }
  749. ValueTree newConfig (Tags::configuration);
  750. if (configToCopy != nullptr)
  751. newConfig = configToCopy->config.createCopy();
  752. newConfig.setProperty (Ids::name, configName, 0);
  753. configs.addChild (newConfig, -1, getUndoManagerFor (configs));
  754. }
  755. void Project::deleteConfiguration (int index)
  756. {
  757. ValueTree configs (getConfigurations());
  758. configs.removeChild (index, getUndoManagerFor (getConfigurations()));
  759. }
  760. void Project::createDefaultConfigs()
  761. {
  762. for (int i = 0; i < 2; ++i)
  763. {
  764. addNewConfiguration (nullptr);
  765. BuildConfiguration config = getConfiguration (i);
  766. const bool debugConfig = i == 0;
  767. config.getName() = debugConfig ? "Debug" : "Release";
  768. config.isDebug() = debugConfig;
  769. config.getOptimisationLevel() = debugConfig ? 1 : 2;
  770. config.getTargetBinaryName() = getProjectFilenameRoot();
  771. }
  772. }
  773. //==============================================================================
  774. Project::BuildConfiguration::BuildConfiguration (Project* project_, const ValueTree& configNode)
  775. : project (project_),
  776. config (configNode)
  777. {
  778. }
  779. Project::BuildConfiguration::BuildConfiguration (const BuildConfiguration& other)
  780. : project (other.project),
  781. config (other.config)
  782. {
  783. }
  784. const Project::BuildConfiguration& Project::BuildConfiguration::operator= (const BuildConfiguration& other)
  785. {
  786. project = other.project;
  787. config = other.config;
  788. return *this;
  789. }
  790. Project::BuildConfiguration::~BuildConfiguration()
  791. {
  792. }
  793. String Project::BuildConfiguration::getGCCOptimisationFlag() const
  794. {
  795. const int level = (int) getOptimisationLevel().getValue();
  796. return String (level <= 1 ? "0" : (level == 2 ? "s" : "3"));
  797. }
  798. const char* const Project::BuildConfiguration::osxVersionDefault = "default";
  799. const char* const Project::BuildConfiguration::osxVersion10_4 = "10.4 SDK";
  800. const char* const Project::BuildConfiguration::osxVersion10_5 = "10.5 SDK";
  801. const char* const Project::BuildConfiguration::osxVersion10_6 = "10.6 SDK";
  802. const char* const Project::BuildConfiguration::osxArch_Default = "default";
  803. const char* const Project::BuildConfiguration::osxArch_Native = "Native";
  804. const char* const Project::BuildConfiguration::osxArch_32BitUniversal = "32BitUniversal";
  805. const char* const Project::BuildConfiguration::osxArch_64BitUniversal = "64BitUniversal";
  806. const char* const Project::BuildConfiguration::osxArch_64Bit = "64BitIntel";
  807. void Project::BuildConfiguration::createPropertyEditors (Array <PropertyComponent*>& props)
  808. {
  809. props.add (new TextPropertyComponent (getName(), "Name", 96, false));
  810. props.getLast()->setTooltip ("The name of this configuration.");
  811. props.add (new BooleanPropertyComponent (isDebug(), "Debug mode", "Debugging enabled"));
  812. props.getLast()->setTooltip ("If enabled, this means that the configuration should be built with debug synbols.");
  813. const char* optimisationLevels[] = { "No optimisation", "Optimise for size and speed", "Optimise for maximum speed", 0 };
  814. const int optimisationLevelValues[] = { 1, 2, 3, 0 };
  815. props.add (new ChoicePropertyComponent (getOptimisationLevel(), "Optimisation", StringArray (optimisationLevels), Array<var> (optimisationLevelValues)));
  816. props.getLast()->setTooltip ("The optimisation level for this configuration");
  817. props.add (new TextPropertyComponent (getTargetBinaryName(), "Binary name", 256, false));
  818. props.getLast()->setTooltip ("The filename to use for the destination binary executable file. Don't add a suffix to this, because platform-specific suffixes will be added for each target platform.");
  819. props.add (new TextPropertyComponent (getTargetBinaryRelativePath(), "Binary location", 1024, false));
  820. props.getLast()->setTooltip ("The folder in which the finished binary should be placed. Leave this blank to cause the binary to be placed in its default location in the build folder.");
  821. props.add (new TextPropertyComponent (getHeaderSearchPath(), "Header search path", 16384, false));
  822. props.getLast()->setTooltip ("Extra header search paths. Use semi-colons to separate multiple paths.");
  823. props.add (new TextPropertyComponent (getBuildConfigPreprocessorDefs(), "Preprocessor definitions", 32768, false));
  824. props.getLast()->setTooltip ("Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace or commas to separate the items - to include a space or comma in a definition, precede it with a backslash.");
  825. if (getMacSDKVersion().toString().isEmpty())
  826. getMacSDKVersion() = osxVersionDefault;
  827. const char* osxVersions[] = { "Use Default", osxVersion10_4, osxVersion10_5, osxVersion10_6, 0 };
  828. const char* osxVersionValues[] = { osxVersionDefault, osxVersion10_4, osxVersion10_5, osxVersion10_6, 0 };
  829. props.add (new ChoicePropertyComponent (getMacSDKVersion(), "OSX Base SDK Version", StringArray (osxVersions), Array<var> (osxVersionValues)));
  830. props.getLast()->setTooltip ("The version of OSX to link against in the XCode build.");
  831. if (getMacCompatibilityVersion().toString().isEmpty())
  832. getMacCompatibilityVersion() = osxVersionDefault;
  833. props.add (new ChoicePropertyComponent (getMacCompatibilityVersion(), "OSX Compatibility Version", StringArray (osxVersions), Array<var> (osxVersionValues)));
  834. props.getLast()->setTooltip ("The minimum version of OSX that the target binary will be compatible with.");
  835. const char* osxArch[] = { "Use Default", "Native architecture of build machine", "Universal Binary (32-bit)", "Universal Binary (64-bit)", "64-bit Intel", 0 };
  836. const char* osxArchValues[] = { osxArch_Default, osxArch_Native, osxArch_32BitUniversal, osxArch_64BitUniversal, osxArch_64Bit, 0 };
  837. if (getMacArchitecture().toString().isEmpty())
  838. getMacArchitecture() = osxArch_Default;
  839. props.add (new ChoicePropertyComponent (getMacArchitecture(), "OSX Architecture", StringArray (osxArch), Array<var> (osxArchValues)));
  840. props.getLast()->setTooltip ("The type of OSX binary that will be produced.");
  841. for (int i = props.size(); --i >= 0;)
  842. props.getUnchecked(i)->setPreferredHeight (22);
  843. }
  844. StringPairArray Project::BuildConfiguration::getAllPreprocessorDefs() const
  845. {
  846. return mergePreprocessorDefs (project->getPreprocessorDefs(),
  847. parsePreprocessorDefs (getBuildConfigPreprocessorDefs().toString()));
  848. }
  849. StringArray Project::BuildConfiguration::getHeaderSearchPaths() const
  850. {
  851. StringArray s;
  852. s.addTokens (getHeaderSearchPath().toString(), ";", String::empty);
  853. return s;
  854. }
  855. //==============================================================================
  856. ValueTree Project::getExporters()
  857. {
  858. ValueTree exporters (projectRoot.getChildWithName (Tags::exporters));
  859. if (! exporters.isValid())
  860. {
  861. projectRoot.addChild (ValueTree (Tags::exporters), 0, getUndoManagerFor (projectRoot));
  862. exporters = getExporters();
  863. }
  864. return exporters;
  865. }
  866. int Project::getNumExporters()
  867. {
  868. return getExporters().getNumChildren();
  869. }
  870. ProjectExporter* Project::createExporter (int index)
  871. {
  872. jassert (index >= 0 && index < getNumExporters());
  873. return ProjectExporter::createExporter (*this, getExporters().getChild (index));
  874. }
  875. void Project::addNewExporter (int exporterIndex)
  876. {
  877. ScopedPointer<ProjectExporter> exp (ProjectExporter::createNewExporter (*this, exporterIndex));
  878. ValueTree exporters (getExporters());
  879. exporters.addChild (exp->getSettings(), -1, getUndoManagerFor (exporters));
  880. }
  881. void Project::deleteExporter (int index)
  882. {
  883. ValueTree exporters (getExporters());
  884. exporters.removeChild (index, getUndoManagerFor (exporters));
  885. }
  886. void Project::createDefaultExporters()
  887. {
  888. ValueTree exporters (getExporters());
  889. exporters.removeAllChildren (getUndoManagerFor (exporters));
  890. for (int i = 0; i < ProjectExporter::getNumExporters(); ++i)
  891. addNewExporter (i);
  892. }
  893. //==============================================================================
  894. String Project::getFileTemplate (const String& templateName)
  895. {
  896. int dataSize;
  897. const char* data = BinaryData::getNamedResource (templateName.toUTF8(), dataSize);
  898. if (data == nullptr)
  899. {
  900. jassertfalse;
  901. return String::empty;
  902. }
  903. return String::fromUTF8 (data, dataSize);
  904. }
  905. //==============================================================================
  906. void Project::resaveJucerFile (const File& file)
  907. {
  908. if (! file.exists())
  909. {
  910. std::cout << "The file " << file.getFullPathName() << " doesn't exist!" << std::endl;
  911. return;
  912. }
  913. if (! file.hasFileExtension (Project::projectFileExtension))
  914. {
  915. std::cout << file.getFullPathName() << " isn't a valid jucer project file!" << std::endl;
  916. return;
  917. }
  918. Project newDoc (file);
  919. if (! newDoc.loadFrom (file, true))
  920. {
  921. std::cout << "Failed to load the project file: " << file.getFullPathName() << std::endl;
  922. return;
  923. }
  924. std::cout << "The Jucer - Re-saving file: " << file.getFullPathName() << std::endl;
  925. String error (newDoc.saveDocument (file));
  926. if (error.isNotEmpty())
  927. {
  928. std::cout << "Error when writing project: " << error << std::endl;
  929. return;
  930. }
  931. }