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.

1172 lines
42KB

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