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.

1196 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(), 0);
  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_GUIApp::getTypeName();
  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::JuceConfigFlag> flags;
  145. getJuceConfigFlags (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_GUIApp::getTypeName());
  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. Image Project::getBigIcon()
  338. {
  339. Item icon (getMainGroup().findItemWithID (getBigIconImageItemID().toString()));
  340. if (icon.isValid())
  341. return ImageCache::getFromFile (icon.getFile());
  342. return Image();
  343. }
  344. Image Project::getSmallIcon()
  345. {
  346. Item icon (getMainGroup().findItemWithID (getSmallIconImageItemID().toString()));
  347. if (icon.isValid())
  348. return ImageCache::getFromFile (icon.getFile());
  349. return Image();
  350. }
  351. Image Project::getBestIconForSize (int size, bool returnNullIfNothingBigEnough)
  352. {
  353. Image im;
  354. const Image im1 (getSmallIcon());
  355. const Image im2 (getBigIcon());
  356. if (im1.isValid() && im2.isValid())
  357. {
  358. if (im1.getWidth() >= size && im2.getWidth() >= size)
  359. im = im1.getWidth() < im2.getWidth() ? im1 : im2;
  360. else if (im1.getWidth() >= size)
  361. im = im1;
  362. else if (im2.getWidth() >= size)
  363. im = im2;
  364. else
  365. return Image();
  366. }
  367. else
  368. {
  369. im = im1.isValid() ? im1 : im2;
  370. }
  371. if (size == im.getWidth() && size == im.getHeight())
  372. return im;
  373. if (returnNullIfNothingBigEnough && im.getWidth() < size && im.getHeight() < size)
  374. return Image::null;
  375. Image newIm (Image::ARGB, size, size, true);
  376. Graphics g (newIm);
  377. g.drawImageWithin (im, 0, 0, size, size,
  378. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  379. return newIm;
  380. }
  381. StringPairArray Project::getPreprocessorDefs() const
  382. {
  383. return parsePreprocessorDefs (getProjectPreprocessorDefs().toString());
  384. }
  385. //==============================================================================
  386. Project::Item Project::getMainGroup()
  387. {
  388. return Item (*this, projectRoot.getChildWithName (Tags::projectMainGroup));
  389. }
  390. static void findImages (const Project::Item& item, OwnedArray<Project::Item>& found)
  391. {
  392. if (item.isImageFile())
  393. {
  394. found.add (new Project::Item (item));
  395. }
  396. else if (item.isGroup())
  397. {
  398. for (int i = 0; i < item.getNumChildren(); ++i)
  399. findImages (item.getChild (i), found);
  400. }
  401. }
  402. void Project::findAllImageItems (OwnedArray<Project::Item>& items)
  403. {
  404. findImages (getMainGroup(), items);
  405. }
  406. //==============================================================================
  407. Project::Item::Item (Project& project_, const ValueTree& node_)
  408. : project (&project_), node (node_)
  409. {
  410. }
  411. Project::Item::Item (const Item& other)
  412. : project (other.project), node (other.node)
  413. {
  414. }
  415. Project::Item& Project::Item::operator= (const Project::Item& other)
  416. {
  417. project = other.project;
  418. node = other.node;
  419. return *this;
  420. }
  421. Project::Item::~Item()
  422. {
  423. }
  424. String Project::Item::getID() const { return node [Ids::id_]; }
  425. String Project::Item::getImageFileID() const { return "id:" + getID(); }
  426. Project::Item Project::Item::createGroup (Project& project, const String& name)
  427. {
  428. Item group (project, ValueTree (Tags::group));
  429. group.initialiseNodeValues();
  430. group.getName() = name;
  431. return group;
  432. }
  433. bool Project::Item::isFile() const { return node.hasType (Tags::file); }
  434. bool Project::Item::isGroup() const { return node.hasType (Tags::group) || isMainGroup(); }
  435. bool Project::Item::isMainGroup() const { return node.hasType (Tags::projectMainGroup); }
  436. bool Project::Item::isImageFile() const { return isFile() && getFile().hasFileExtension ("png;jpg;jpeg;gif;drawable"); }
  437. Project::Item Project::Item::findItemWithID (const String& targetId) const
  438. {
  439. if (node [Ids::id_] == targetId)
  440. return *this;
  441. if (isGroup())
  442. {
  443. for (int i = getNumChildren(); --i >= 0;)
  444. {
  445. Item found (getChild(i).findItemWithID (targetId));
  446. if (found.isValid())
  447. return found;
  448. }
  449. }
  450. return Item (*project, ValueTree::invalid);
  451. }
  452. bool Project::Item::canContain (const Item& child) const
  453. {
  454. if (isFile())
  455. return false;
  456. if (isGroup())
  457. return child.isFile() || child.isGroup();
  458. jassertfalse
  459. return false;
  460. }
  461. bool Project::Item::shouldBeAddedToTargetProject() const
  462. {
  463. return isFile();
  464. }
  465. bool Project::Item::shouldBeCompiled() const
  466. {
  467. return getShouldCompileValue().getValue();
  468. }
  469. Value Project::Item::getShouldCompileValue() const
  470. {
  471. return node.getPropertyAsValue (Ids::compile, getUndoManager());
  472. }
  473. bool Project::Item::shouldBeAddedToBinaryResources() const
  474. {
  475. return getShouldAddToResourceValue().getValue();
  476. }
  477. Value Project::Item::getShouldAddToResourceValue() const
  478. {
  479. return node.getPropertyAsValue (Ids::resource, getUndoManager());
  480. }
  481. File Project::Item::getFile() const
  482. {
  483. if (isFile())
  484. return getProject().resolveFilename (node [Ids::file].toString());
  485. else
  486. return File::nonexistent;
  487. }
  488. void Project::Item::setFile (const File& file)
  489. {
  490. setFile (RelativePath (getProject().getRelativePathForFile (file), RelativePath::projectFolder));
  491. jassert (getFile() == file);
  492. }
  493. void Project::Item::setFile (const RelativePath& file)
  494. {
  495. jassert (file.getRoot() == RelativePath::projectFolder);
  496. jassert (isFile());
  497. node.setProperty (Ids::file, file.toUnixStyle(), getUndoManager());
  498. node.setProperty (Ids::name, file.getFileName(), getUndoManager());
  499. }
  500. bool Project::Item::renameFile (const File& newFile)
  501. {
  502. const File oldFile (getFile());
  503. if (oldFile.moveFileTo (newFile))
  504. {
  505. setFile (newFile);
  506. OpenDocumentManager::getInstance()->fileHasBeenRenamed (oldFile, newFile);
  507. return true;
  508. }
  509. return false;
  510. }
  511. Project::Item Project::Item::findItemForFile (const File& file) const
  512. {
  513. if (getFile() == file)
  514. return *this;
  515. if (isGroup())
  516. {
  517. for (int i = getNumChildren(); --i >= 0;)
  518. {
  519. Item found (getChild(i).findItemForFile (file));
  520. if (found.isValid())
  521. return found;
  522. }
  523. }
  524. return Item (getProject(), ValueTree::invalid);
  525. }
  526. File Project::Item::determineGroupFolder() const
  527. {
  528. jassert (isGroup());
  529. File f;
  530. for (int i = 0; i < getNumChildren(); ++i)
  531. {
  532. f = getChild(i).getFile();
  533. if (f.exists())
  534. return f.getParentDirectory();
  535. }
  536. Item parent (getParent());
  537. if (parent != *this)
  538. {
  539. f = parent.determineGroupFolder();
  540. if (f.getChildFile (getName().toString()).isDirectory())
  541. f = f.getChildFile (getName().toString());
  542. }
  543. else
  544. {
  545. f = getProject().getFile().getParentDirectory();
  546. if (f.getChildFile ("Source").isDirectory())
  547. f = f.getChildFile ("Source");
  548. }
  549. return f;
  550. }
  551. void Project::Item::initialiseNodeValues()
  552. {
  553. if (! node.hasProperty (Ids::id_))
  554. node.setProperty (Ids::id_, createAlphaNumericUID(), 0);
  555. if (isFile())
  556. {
  557. node.setProperty (Ids::name, getFile().getFileName(), 0);
  558. }
  559. else if (isGroup())
  560. {
  561. for (int i = getNumChildren(); --i >= 0;)
  562. getChild(i).initialiseNodeValues();
  563. }
  564. }
  565. Value Project::Item::getName() const
  566. {
  567. return node.getPropertyAsValue (Ids::name, getUndoManager());
  568. }
  569. void Project::Item::addChild (const Item& newChild, int insertIndex)
  570. {
  571. node.addChild (newChild.getNode(), insertIndex, getUndoManager());
  572. }
  573. void Project::Item::removeItemFromProject()
  574. {
  575. node.getParent().removeChild (node, getUndoManager());
  576. }
  577. Project::Item Project::Item::getParent() const
  578. {
  579. if (isMainGroup() || ! isGroup())
  580. return *this;
  581. return Item (getProject(), node.getParent());
  582. }
  583. struct ItemSorter
  584. {
  585. static int compareElements (const ValueTree& first, const ValueTree& second)
  586. {
  587. return first [Ids::name].toString().compareIgnoreCase (second [Ids::name].toString());
  588. }
  589. };
  590. void Project::Item::sortAlphabetically()
  591. {
  592. ItemSorter sorter;
  593. node.sort (sorter, getUndoManager(), true);
  594. }
  595. Project::Item Project::Item::addNewSubGroup (const String& name, int insertIndex)
  596. {
  597. Item group (createGroup (getProject(), name));
  598. jassert (canContain (group));
  599. addChild (group, insertIndex);
  600. return group;
  601. }
  602. bool Project::Item::addFile (const File& file, int insertIndex)
  603. {
  604. if (file == File::nonexistent || file.isHidden() || file.getFileName().startsWithChar ('.'))
  605. return false;
  606. if (file.isDirectory())
  607. {
  608. Item group (addNewSubGroup (file.getFileNameWithoutExtension(), insertIndex));
  609. DirectoryIterator iter (file, false, "*", File::findFilesAndDirectories);
  610. while (iter.next())
  611. {
  612. if (! getProject().getMainGroup().findItemForFile (iter.getFile()).isValid())
  613. group.addFile (iter.getFile(), -1);
  614. }
  615. group.sortAlphabetically();
  616. }
  617. else if (file.existsAsFile())
  618. {
  619. if (! getProject().getMainGroup().findItemForFile (file).isValid())
  620. {
  621. Item item (getProject(), ValueTree (Tags::file));
  622. item.initialiseNodeValues();
  623. item.getName() = file.getFileName();
  624. item.getShouldCompileValue() = file.hasFileExtension ("cpp;mm;c;m;cc;cxx");
  625. item.getShouldAddToResourceValue() = getProject().shouldBeAddedToBinaryResourcesByDefault (file);
  626. if (canContain (item))
  627. {
  628. item.setFile (file);
  629. addChild (item, insertIndex);
  630. }
  631. }
  632. }
  633. else
  634. {
  635. jassertfalse;
  636. }
  637. return true;
  638. }
  639. bool Project::Item::addRelativeFile (const RelativePath& file, int insertIndex)
  640. {
  641. Item item (getProject(), ValueTree (Tags::file));
  642. item.initialiseNodeValues();
  643. item.getName() = file.getFileName();
  644. item.getShouldCompileValue() = file.hasFileExtension ("cpp;mm;c;m;cc;cxx");
  645. item.getShouldAddToResourceValue() = getProject().shouldBeAddedToBinaryResourcesByDefault (file);
  646. if (canContain (item))
  647. {
  648. item.setFile (file);
  649. addChild (item, insertIndex);
  650. return true;
  651. }
  652. return false;
  653. }
  654. const Drawable* Project::Item::getIcon() const
  655. {
  656. if (isFile())
  657. {
  658. if (isImageFile())
  659. return StoredSettings::getInstance()->getImageFileIcon();
  660. return LookAndFeel::getDefaultLookAndFeel().getDefaultDocumentFileImage();
  661. }
  662. else if (isMainGroup())
  663. {
  664. return &(getProject().mainProjectIcon);
  665. }
  666. return LookAndFeel::getDefaultLookAndFeel().getDefaultFolderImage();
  667. }
  668. //==============================================================================
  669. ValueTree Project::getJuceConfigNode()
  670. {
  671. return projectRoot.getOrCreateChildWithName (Tags::configGroup, nullptr);
  672. }
  673. void Project::getJuceConfigFlags (OwnedArray <JuceConfigFlag>& flags)
  674. {
  675. ValueTree configNode (getJuceConfigNode());
  676. StringArray lines;
  677. getLocalJuceFolder().getChildFile ("juce_Config.h").readLines (lines);
  678. for (int i = 0; i < lines.size(); ++i)
  679. {
  680. String line (lines[i].trim());
  681. if (line.startsWith ("/** ") && line.containsChar (':'))
  682. {
  683. ScopedPointer <JuceConfigFlag> config (new JuceConfigFlag());
  684. config->symbol = line.substring (4).upToFirstOccurrenceOf (":", false, false).trim();
  685. if (config->symbol.length() > 4)
  686. {
  687. config->description = line.fromFirstOccurrenceOf (":", false, false).trimStart();
  688. ++i;
  689. while (! (lines[i].contains ("*/") || lines[i].contains ("@see")))
  690. {
  691. if (lines[i].trim().isNotEmpty())
  692. config->description = config->description.trim() + " " + lines[i].trim();
  693. ++i;
  694. }
  695. config->description = config->description.upToFirstOccurrenceOf ("*/", false, false);
  696. config->value.referTo (getJuceConfigFlag (config->symbol));
  697. flags.add (config.release());
  698. }
  699. }
  700. }
  701. }
  702. const char* const Project::configFlagDefault = "default";
  703. const char* const Project::configFlagEnabled = "enabled";
  704. const char* const Project::configFlagDisabled = "disabled";
  705. Value Project::getJuceConfigFlag (const String& name)
  706. {
  707. const ValueTree configNode (getJuceConfigNode());
  708. Value v (configNode.getPropertyAsValue (name, getUndoManagerFor (configNode)));
  709. if (v.getValue().toString().isEmpty())
  710. v = configFlagDefault;
  711. return v;
  712. }
  713. bool Project::isJuceConfigFlagEnabled (const String& name) const
  714. {
  715. return projectRoot.getChildWithName (Tags::configGroup).getProperty (name) == configFlagEnabled;
  716. }
  717. //==============================================================================
  718. ValueTree Project::getConfigurations() const
  719. {
  720. return projectRoot.getChildWithName (Tags::configurations);
  721. }
  722. int Project::getNumConfigurations() const
  723. {
  724. return getConfigurations().getNumChildren();
  725. }
  726. Project::BuildConfiguration Project::getConfiguration (int index)
  727. {
  728. jassert (index < getConfigurations().getNumChildren());
  729. return BuildConfiguration (this, getConfigurations().getChild (index));
  730. }
  731. bool Project::hasConfigurationNamed (const String& name) const
  732. {
  733. const ValueTree configs (getConfigurations());
  734. for (int i = configs.getNumChildren(); --i >= 0;)
  735. if (configs.getChild(i) [Ids::name].toString() == name)
  736. return true;
  737. return false;
  738. }
  739. String Project::getUniqueConfigName (String name) const
  740. {
  741. String nameRoot (name);
  742. while (CharacterFunctions::isDigit (nameRoot.getLastCharacter()))
  743. nameRoot = nameRoot.dropLastCharacters (1);
  744. nameRoot = nameRoot.trim();
  745. int suffix = 2;
  746. while (hasConfigurationNamed (name))
  747. name = nameRoot + " " + String (suffix++);
  748. return name;
  749. }
  750. void Project::addNewConfiguration (BuildConfiguration* configToCopy)
  751. {
  752. const String configName (getUniqueConfigName (configToCopy != nullptr ? configToCopy->config [Ids::name].toString()
  753. : "New Build Configuration"));
  754. ValueTree configs (getConfigurations());
  755. if (! configs.isValid())
  756. {
  757. projectRoot.addChild (ValueTree (Tags::configurations), 0, getUndoManagerFor (projectRoot));
  758. configs = getConfigurations();
  759. }
  760. ValueTree newConfig (Tags::configuration);
  761. if (configToCopy != nullptr)
  762. newConfig = configToCopy->config.createCopy();
  763. newConfig.setProperty (Ids::name, configName, 0);
  764. configs.addChild (newConfig, -1, getUndoManagerFor (configs));
  765. }
  766. void Project::deleteConfiguration (int index)
  767. {
  768. ValueTree configs (getConfigurations());
  769. configs.removeChild (index, getUndoManagerFor (getConfigurations()));
  770. }
  771. void Project::createDefaultConfigs()
  772. {
  773. for (int i = 0; i < 2; ++i)
  774. {
  775. addNewConfiguration (nullptr);
  776. BuildConfiguration config = getConfiguration (i);
  777. const bool debugConfig = i == 0;
  778. config.getName() = debugConfig ? "Debug" : "Release";
  779. config.isDebug() = debugConfig;
  780. config.getOptimisationLevel() = debugConfig ? 1 : 2;
  781. config.getTargetBinaryName() = getProjectFilenameRoot();
  782. }
  783. }
  784. //==============================================================================
  785. Project::BuildConfiguration::BuildConfiguration (Project* project_, const ValueTree& configNode)
  786. : project (project_),
  787. config (configNode)
  788. {
  789. }
  790. Project::BuildConfiguration::BuildConfiguration (const BuildConfiguration& other)
  791. : project (other.project),
  792. config (other.config)
  793. {
  794. }
  795. const Project::BuildConfiguration& Project::BuildConfiguration::operator= (const BuildConfiguration& other)
  796. {
  797. project = other.project;
  798. config = other.config;
  799. return *this;
  800. }
  801. Project::BuildConfiguration::~BuildConfiguration()
  802. {
  803. }
  804. String Project::BuildConfiguration::getGCCOptimisationFlag() const
  805. {
  806. const int level = (int) getOptimisationLevel().getValue();
  807. return String (level <= 1 ? "0" : (level == 2 ? "s" : "3"));
  808. }
  809. const char* const Project::BuildConfiguration::osxVersionDefault = "default";
  810. const char* const Project::BuildConfiguration::osxVersion10_4 = "10.4 SDK";
  811. const char* const Project::BuildConfiguration::osxVersion10_5 = "10.5 SDK";
  812. const char* const Project::BuildConfiguration::osxVersion10_6 = "10.6 SDK";
  813. const char* const Project::BuildConfiguration::osxArch_Default = "default";
  814. const char* const Project::BuildConfiguration::osxArch_Native = "Native";
  815. const char* const Project::BuildConfiguration::osxArch_32BitUniversal = "32BitUniversal";
  816. const char* const Project::BuildConfiguration::osxArch_64BitUniversal = "64BitUniversal";
  817. const char* const Project::BuildConfiguration::osxArch_64Bit = "64BitIntel";
  818. void Project::BuildConfiguration::createPropertyEditors (Array <PropertyComponent*>& props)
  819. {
  820. props.add (new TextPropertyComponent (getName(), "Name", 96, false));
  821. props.getLast()->setTooltip ("The name of this configuration.");
  822. props.add (new BooleanPropertyComponent (isDebug(), "Debug mode", "Debugging enabled"));
  823. props.getLast()->setTooltip ("If enabled, this means that the configuration should be built with debug synbols.");
  824. const char* optimisationLevels[] = { "No optimisation", "Optimise for size and speed", "Optimise for maximum speed", 0 };
  825. const int optimisationLevelValues[] = { 1, 2, 3, 0 };
  826. props.add (new ChoicePropertyComponent (getOptimisationLevel(), "Optimisation", StringArray (optimisationLevels), Array<var> (optimisationLevelValues)));
  827. props.getLast()->setTooltip ("The optimisation level for this configuration");
  828. props.add (new TextPropertyComponent (getTargetBinaryName(), "Binary name", 256, false));
  829. 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.");
  830. props.add (new TextPropertyComponent (getTargetBinaryRelativePath(), "Binary location", 1024, false));
  831. 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.");
  832. props.add (new TextPropertyComponent (getHeaderSearchPath(), "Header search path", 16384, false));
  833. props.getLast()->setTooltip ("Extra header search paths. Use semi-colons to separate multiple paths.");
  834. props.add (new TextPropertyComponent (getBuildConfigPreprocessorDefs(), "Preprocessor definitions", 32768, false));
  835. 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.");
  836. if (getMacSDKVersion().toString().isEmpty())
  837. getMacSDKVersion() = osxVersionDefault;
  838. const char* osxVersions[] = { "Use Default", osxVersion10_4, osxVersion10_5, osxVersion10_6, 0 };
  839. const char* osxVersionValues[] = { osxVersionDefault, osxVersion10_4, osxVersion10_5, osxVersion10_6, 0 };
  840. props.add (new ChoicePropertyComponent (getMacSDKVersion(), "OSX Base SDK Version", StringArray (osxVersions), Array<var> (osxVersionValues)));
  841. props.getLast()->setTooltip ("The version of OSX to link against in the XCode build.");
  842. if (getMacCompatibilityVersion().toString().isEmpty())
  843. getMacCompatibilityVersion() = osxVersionDefault;
  844. props.add (new ChoicePropertyComponent (getMacCompatibilityVersion(), "OSX Compatibility Version", StringArray (osxVersions), Array<var> (osxVersionValues)));
  845. props.getLast()->setTooltip ("The minimum version of OSX that the target binary will be compatible with.");
  846. const char* osxArch[] = { "Use Default", "Native architecture of build machine", "Universal Binary (32-bit)", "Universal Binary (64-bit)", "64-bit Intel", 0 };
  847. const char* osxArchValues[] = { osxArch_Default, osxArch_Native, osxArch_32BitUniversal, osxArch_64BitUniversal, osxArch_64Bit, 0 };
  848. if (getMacArchitecture().toString().isEmpty())
  849. getMacArchitecture() = osxArch_Default;
  850. props.add (new ChoicePropertyComponent (getMacArchitecture(), "OSX Architecture", StringArray (osxArch), Array<var> (osxArchValues)));
  851. props.getLast()->setTooltip ("The type of OSX binary that will be produced.");
  852. for (int i = props.size(); --i >= 0;)
  853. props.getUnchecked(i)->setPreferredHeight (22);
  854. }
  855. StringPairArray Project::BuildConfiguration::getAllPreprocessorDefs() const
  856. {
  857. return mergePreprocessorDefs (project->getPreprocessorDefs(),
  858. parsePreprocessorDefs (getBuildConfigPreprocessorDefs().toString()));
  859. }
  860. StringArray Project::BuildConfiguration::getHeaderSearchPaths() const
  861. {
  862. StringArray s;
  863. s.addTokens (getHeaderSearchPath().toString(), ";", String::empty);
  864. return s;
  865. }
  866. //==============================================================================
  867. ValueTree Project::getExporters()
  868. {
  869. ValueTree exporters (projectRoot.getChildWithName (Tags::exporters));
  870. if (! exporters.isValid())
  871. {
  872. projectRoot.addChild (ValueTree (Tags::exporters), 0, getUndoManagerFor (projectRoot));
  873. exporters = getExporters();
  874. }
  875. return exporters;
  876. }
  877. int Project::getNumExporters()
  878. {
  879. return getExporters().getNumChildren();
  880. }
  881. ProjectExporter* Project::createExporter (int index)
  882. {
  883. jassert (index >= 0 && index < getNumExporters());
  884. return ProjectExporter::createExporter (*this, getExporters().getChild (index));
  885. }
  886. void Project::addNewExporter (int exporterIndex)
  887. {
  888. ScopedPointer<ProjectExporter> exp (ProjectExporter::createNewExporter (*this, exporterIndex));
  889. ValueTree exporters (getExporters());
  890. exporters.addChild (exp->getSettings(), -1, getUndoManagerFor (exporters));
  891. }
  892. void Project::deleteExporter (int index)
  893. {
  894. ValueTree exporters (getExporters());
  895. exporters.removeChild (index, getUndoManagerFor (exporters));
  896. }
  897. void Project::createDefaultExporters()
  898. {
  899. ValueTree exporters (getExporters());
  900. exporters.removeAllChildren (getUndoManagerFor (exporters));
  901. for (int i = 0; i < ProjectExporter::getNumExporters(); ++i)
  902. addNewExporter (i);
  903. }
  904. //==============================================================================
  905. String Project::getFileTemplate (const String& templateName)
  906. {
  907. int dataSize;
  908. const char* data = BinaryData::getNamedResource (templateName.toUTF8(), dataSize);
  909. if (data == nullptr)
  910. {
  911. jassertfalse;
  912. return String::empty;
  913. }
  914. return String::fromUTF8 (data, dataSize);
  915. }
  916. //==============================================================================
  917. void Project::resaveJucerFile (const File& file)
  918. {
  919. if (! file.exists())
  920. {
  921. std::cout << "The file " << file.getFullPathName() << " doesn't exist!" << std::endl;
  922. return;
  923. }
  924. if (! file.hasFileExtension (Project::projectFileExtension))
  925. {
  926. std::cout << file.getFullPathName() << " isn't a valid jucer project file!" << std::endl;
  927. return;
  928. }
  929. Project newDoc (file);
  930. if (! newDoc.loadFrom (file, true))
  931. {
  932. std::cout << "Failed to load the project file: " << file.getFullPathName() << std::endl;
  933. return;
  934. }
  935. std::cout << "The Jucer - Re-saving file: " << file.getFullPathName() << std::endl;
  936. String error (newDoc.saveDocument (file));
  937. if (error.isNotEmpty())
  938. {
  939. std::cout << "Error when writing project: " << error << std::endl;
  940. return;
  941. }
  942. }