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.

1097 lines
40KB

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