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.

1654 lines
61KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../Application/jucer_Headers.h"
  20. #include "jucer_Project.h"
  21. #include "../ProjectSaving/jucer_ProjectSaver.h"
  22. #include "../Application/jucer_Application.h"
  23. namespace
  24. {
  25. String makeValid4CC (const String& seed)
  26. {
  27. auto s = CodeHelpers::makeValidIdentifier (seed, false, true, false) + "xxxx";
  28. return s.substring (0, 1).toUpperCase()
  29. + s.substring (1, 4).toLowerCase();
  30. }
  31. }
  32. //==============================================================================
  33. Project::Project (const File& f)
  34. : FileBasedDocument (projectFileExtension,
  35. String ("*") + projectFileExtension,
  36. "Choose a Jucer project to load",
  37. "Save Jucer project")
  38. {
  39. Logger::writeToLog ("Loading project: " + f.getFullPathName());
  40. setFile (f);
  41. removeDefunctExporters();
  42. updateOldModulePaths();
  43. updateOldStyleConfigList();
  44. setCppVersionFromOldExporterSettings();
  45. moveOldPropertyFromProjectToAllExporters (Ids::bigIcon);
  46. moveOldPropertyFromProjectToAllExporters (Ids::smallIcon);
  47. initialiseProjectValues();
  48. initialiseMainGroup();
  49. initialiseAudioPluginValues();
  50. parsedPreprocessorDefs = parsePreprocessorDefs (preprocessorDefsValue.get());
  51. getModules().sortAlphabetically();
  52. projectRoot.addListener (this);
  53. setChangedFlag (false);
  54. modificationTime = getFile().getLastModificationTime();
  55. }
  56. Project::~Project()
  57. {
  58. projectRoot.removeListener (this);
  59. ProjucerApplication::getApp().openDocumentManager.closeAllDocumentsUsingProject (*this, false);
  60. }
  61. const char* Project::projectFileExtension = ".jucer";
  62. //==============================================================================
  63. void Project::setTitle (const String& newTitle)
  64. {
  65. projectNameValue = newTitle;
  66. updateTitle();
  67. }
  68. void Project::updateTitle()
  69. {
  70. getMainGroup().getNameValue() = getProjectNameString();
  71. bundleIdentifierValue.setDefault (getDefaultBundleIdentifierString());
  72. pluginAAXIdentifierValue.setDefault (getDefaultAAXIdentifierString());
  73. }
  74. String Project::getDocumentTitle()
  75. {
  76. return getProjectNameString();
  77. }
  78. void Project::updateProjectSettings()
  79. {
  80. projectRoot.setProperty (Ids::jucerVersion, ProjectInfo::versionString, nullptr);
  81. projectRoot.setProperty (Ids::name, getDocumentTitle(), nullptr);
  82. }
  83. bool Project::setCppVersionFromOldExporterSettings()
  84. {
  85. auto highestLanguageStandard = -1;
  86. for (Project::ExporterIterator exporter (*this); exporter.next();)
  87. {
  88. if (exporter->isXcode()) // cpp version was per-build configuration for xcode exporters
  89. {
  90. for (ProjectExporter::ConfigIterator config (*exporter); config.next();)
  91. {
  92. auto cppLanguageStandard = config->getValue (Ids::cppLanguageStandard).getValue();
  93. if (cppLanguageStandard != var())
  94. {
  95. auto versionNum = cppLanguageStandard.toString().getLastCharacters (2).getIntValue();
  96. if (versionNum > highestLanguageStandard)
  97. highestLanguageStandard = versionNum;
  98. }
  99. }
  100. }
  101. else
  102. {
  103. auto cppLanguageStandard = exporter->getSetting (Ids::cppLanguageStandard).getValue();
  104. if (cppLanguageStandard != var())
  105. {
  106. if (cppLanguageStandard.toString().containsIgnoreCase ("latest"))
  107. {
  108. cppStandardValue = "latest";
  109. return true;
  110. }
  111. auto versionNum = cppLanguageStandard.toString().getLastCharacters (2).getIntValue();
  112. if (versionNum > highestLanguageStandard)
  113. highestLanguageStandard = versionNum;
  114. }
  115. }
  116. }
  117. if (highestLanguageStandard != -1 && highestLanguageStandard >= 11)
  118. {
  119. cppStandardValue = highestLanguageStandard;
  120. return true;
  121. }
  122. return false;
  123. }
  124. void Project::updateDeprecatedProjectSettingsInteractively()
  125. {
  126. jassert (! ProjucerApplication::getApp().isRunningCommandLine);
  127. for (Project::ExporterIterator exporter (*this); exporter.next();)
  128. exporter->updateDeprecatedProjectSettingsInteractively();
  129. }
  130. void Project::initialiseMainGroup()
  131. {
  132. // Create main file group if missing
  133. if (! projectRoot.getChildWithName (Ids::MAINGROUP).isValid())
  134. {
  135. Item mainGroup (*this, ValueTree (Ids::MAINGROUP), false);
  136. projectRoot.addChild (mainGroup.state, 0, 0);
  137. }
  138. getMainGroup().initialiseMissingProperties();
  139. }
  140. void Project::initialiseProjectValues()
  141. {
  142. projectNameValue.referTo (projectRoot, Ids::name, getUndoManager(), "JUCE Project");
  143. projectUIDValue.referTo (projectRoot, Ids::ID, getUndoManager(), createAlphaNumericUID());
  144. projectTypeValue.referTo (projectRoot, Ids::projectType, getUndoManager(), ProjectType_GUIApp::getTypeName());
  145. versionValue.referTo (projectRoot, Ids::version, getUndoManager(), "1.0.0");
  146. bundleIdentifierValue.referTo (projectRoot, Ids::bundleIdentifier, getUndoManager(), getDefaultBundleIdentifierString());
  147. companyNameValue.referTo (projectRoot, Ids::companyName, getUndoManager());
  148. companyCopyrightValue.referTo (projectRoot, Ids::companyCopyright, getUndoManager());
  149. companyWebsiteValue.referTo (projectRoot, Ids::companyWebsite, getUndoManager());
  150. companyEmailValue.referTo (projectRoot, Ids::companyEmail, getUndoManager());
  151. displaySplashScreenValue.referTo (projectRoot, Ids::displaySplashScreen, getUndoManager(), ! ProjucerApplication::getApp().isPaidOrGPL());
  152. splashScreenColourValue.referTo (projectRoot, Ids::splashScreenColour, getUndoManager(), "Dark");
  153. reportAppUsageValue.referTo (projectRoot, Ids::reportAppUsage, getUndoManager());
  154. if (ProjucerApplication::getApp().isPaidOrGPL())
  155. {
  156. reportAppUsageValue.setDefault (ProjucerApplication::getApp().licenseController->getState().applicationUsageDataState
  157. == LicenseState::ApplicationUsageData::enabled);
  158. }
  159. else
  160. {
  161. reportAppUsageValue.setDefault (true);
  162. }
  163. cppStandardValue.referTo (projectRoot, Ids::cppLanguageStandard, getUndoManager(), "14");
  164. headerSearchPathsValue.referTo (projectRoot, Ids::headerPath, getUndoManager());
  165. preprocessorDefsValue.referTo (projectRoot, Ids::defines, getUndoManager());
  166. userNotesValue.referTo (projectRoot, Ids::userNotes, getUndoManager());
  167. maxBinaryFileSizeValue.referTo (projectRoot, Ids::maxBinaryFileSize, getUndoManager(), 10240 * 1024);
  168. includeBinaryDataInAppConfigValue.referTo (projectRoot, Ids::includeBinaryInAppConfig, getUndoManager(), true);
  169. binaryDataNamespaceValue.referTo (projectRoot, Ids::binaryDataNamespace, getUndoManager(), "BinaryData");
  170. }
  171. void Project::initialiseAudioPluginValues()
  172. {
  173. buildVSTValue.referTo (projectRoot, Ids::buildVST, getUndoManager(), true);
  174. buildVST3Value.referTo (projectRoot, Ids::buildVST3, getUndoManager(), false);
  175. buildAUValue.referTo (projectRoot, Ids::buildAU, getUndoManager(), true);
  176. buildAUv3Value.referTo (projectRoot, Ids::buildAUv3, getUndoManager(), false);
  177. buildRTASValue.referTo (projectRoot, Ids::buildRTAS, getUndoManager(), false);
  178. buildAAXValue.referTo (projectRoot, Ids::buildAAX, getUndoManager(), false);
  179. buildStandaloneValue.referTo (projectRoot, Ids::buildStandalone, getUndoManager(), false);
  180. enableIAAValue.referTo (projectRoot, Ids::enableIAA, getUndoManager(), false);
  181. pluginNameValue.referTo (projectRoot, Ids::pluginName, getUndoManager(), getProjectNameString());
  182. pluginDescriptionValue.referTo (projectRoot, Ids::pluginDesc, getUndoManager(), getProjectNameString());
  183. pluginManufacturerValue.referTo (projectRoot, Ids::pluginManufacturer, getUndoManager(), "yourcompany");
  184. pluginManufacturerCodeValue.referTo (projectRoot, Ids::pluginManufacturerCode, getUndoManager(), "Manu");
  185. pluginCodeValue.referTo (projectRoot, Ids::pluginCode, getUndoManager(), makeValid4CC (getProjectUIDString() + getProjectUIDString()));
  186. pluginChannelConfigsValue.referTo (projectRoot, Ids::pluginChannelConfigs, getUndoManager());
  187. pluginIsSynthValue.referTo (projectRoot, Ids::pluginIsSynth, getUndoManager(), false);
  188. pluginWantsMidiInputValue.referTo (projectRoot, Ids::pluginWantsMidiIn, getUndoManager(), false);
  189. pluginProducesMidiOutValue.referTo (projectRoot, Ids::pluginProducesMidiOut, getUndoManager(), false);
  190. pluginIsMidiEffectPluginValue.referTo (projectRoot, Ids::pluginIsMidiEffectPlugin, getUndoManager(), false);
  191. pluginEditorNeedsKeyFocusValue.referTo (projectRoot, Ids::pluginEditorRequiresKeys, getUndoManager(), false);
  192. pluginVSTCategoryValue.referTo (projectRoot, Ids::pluginVSTCategory, getUndoManager());
  193. pluginAUExportPrefixValue.referTo (projectRoot, Ids::pluginAUExportPrefix, getUndoManager(),
  194. CodeHelpers::makeValidIdentifier (getProjectNameString(), false, true, false) + "AU");
  195. pluginAUMainTypeValue.referTo (projectRoot, Ids::pluginAUMainType, getUndoManager());
  196. pluginRTASCategoryValue.referTo (projectRoot, Ids::pluginRTASCategory, getUndoManager());
  197. pluginRTASBypassDisabledValue.referTo (projectRoot, Ids::pluginRTASDisableBypass, getUndoManager());
  198. pluginRTASMultiMonoDisabledValue.referTo (projectRoot, Ids::pluginRTASDisableMultiMono, getUndoManager());
  199. pluginAAXIdentifierValue.referTo (projectRoot, Ids::aaxIdentifier, getUndoManager(), getDefaultAAXIdentifierString());
  200. pluginAAXCategoryValue.referTo (projectRoot, Ids::pluginAAXCategory, getUndoManager(), "AAX_ePlugInCategory_Dynamics");
  201. pluginAAXBypassDisabledValue.referTo (projectRoot, Ids::pluginAAXDisableBypass, getUndoManager());
  202. pluginAAXMultiMonoDisabledValue.referTo (projectRoot, Ids::pluginAAXDisableMultiMono, getUndoManager());
  203. }
  204. void Project::updateOldStyleConfigList()
  205. {
  206. auto deprecatedConfigsList = projectRoot.getChildWithName (Ids::CONFIGURATIONS);
  207. if (deprecatedConfigsList.isValid())
  208. {
  209. projectRoot.removeChild (deprecatedConfigsList, nullptr);
  210. for (Project::ExporterIterator exporter (*this); exporter.next();)
  211. {
  212. if (exporter->getNumConfigurations() == 0)
  213. {
  214. auto newConfigs = deprecatedConfigsList.createCopy();
  215. if (! exporter->isXcode())
  216. {
  217. for (auto j = newConfigs.getNumChildren(); --j >= 0;)
  218. {
  219. auto config = newConfigs.getChild (j);
  220. config.removeProperty (Ids::osxSDK, nullptr);
  221. config.removeProperty (Ids::osxCompatibility, nullptr);
  222. config.removeProperty (Ids::osxArchitecture, nullptr);
  223. }
  224. }
  225. exporter->settings.addChild (newConfigs, 0, nullptr);
  226. }
  227. }
  228. }
  229. }
  230. void Project::moveOldPropertyFromProjectToAllExporters (Identifier name)
  231. {
  232. if (projectRoot.hasProperty (name))
  233. {
  234. for (Project::ExporterIterator exporter (*this); exporter.next();)
  235. exporter->settings.setProperty (name, projectRoot [name], nullptr);
  236. projectRoot.removeProperty (name, nullptr);
  237. }
  238. }
  239. void Project::removeDefunctExporters()
  240. {
  241. auto exporters = projectRoot.getChildWithName (Ids::EXPORTFORMATS);
  242. StringPairArray oldExporters;
  243. oldExporters.set ("ANDROID", "Android Ant Exporter");
  244. oldExporters.set ("MSVC6", "MSVC6");
  245. oldExporters.set ("VS2010", "Visual Studio 2010");
  246. oldExporters.set ("VS2012", "Visual Studio 2012");
  247. for (auto& key : oldExporters.getAllKeys())
  248. {
  249. auto oldExporter = exporters.getChildWithName (key);
  250. if (oldExporter.isValid())
  251. {
  252. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  253. TRANS (oldExporters[key]),
  254. TRANS ("The " + oldExporters[key] + " Exporter is deprecated. The exporter will be removed from this project."));
  255. exporters.removeChild (oldExporter, nullptr);
  256. }
  257. }
  258. }
  259. void Project::updateOldModulePaths()
  260. {
  261. for (Project::ExporterIterator exporter (*this); exporter.next();)
  262. exporter->updateOldModulePaths();
  263. }
  264. //==============================================================================
  265. static int getVersionElement (StringRef v, int index)
  266. {
  267. StringArray parts = StringArray::fromTokens (v, "., ", {});
  268. return parts [parts.size() - index - 1].getIntValue();
  269. }
  270. static int getJuceVersion (const String& v)
  271. {
  272. return getVersionElement (v, 2) * 100000
  273. + getVersionElement (v, 1) * 1000
  274. + getVersionElement (v, 0);
  275. }
  276. static int getBuiltJuceVersion()
  277. {
  278. return JUCE_MAJOR_VERSION * 100000
  279. + JUCE_MINOR_VERSION * 1000
  280. + JUCE_BUILDNUMBER;
  281. }
  282. static bool isAnyModuleNewerThanProjucer (const OwnedArray<ModuleDescription>& modules)
  283. {
  284. for (auto i = modules.size(); --i >= 0;)
  285. {
  286. auto* m = modules.getUnchecked(i);
  287. if (m->getID().startsWith ("juce_")
  288. && getJuceVersion (m->getVersion()) > getBuiltJuceVersion())
  289. return true;
  290. }
  291. return false;
  292. }
  293. void Project::warnAboutOldProjucerVersion()
  294. {
  295. ModuleList available;
  296. available.scanGlobalJuceModulePath();
  297. if (! isAnyModuleNewerThanProjucer (available.modules))
  298. available.scanGlobalUserModulePath();
  299. if (! isAnyModuleNewerThanProjucer (available.modules))
  300. available.scanProjectExporterModulePaths (*this);
  301. if (! isAnyModuleNewerThanProjucer (available.modules))
  302. return;
  303. // Projucer is out of date!
  304. if (ProjucerApplication::getApp().isRunningCommandLine)
  305. std::cout << "WARNING! This version of the Projucer is out-of-date!" << std::endl;
  306. else
  307. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  308. "Projucer",
  309. "This version of the Projucer is out-of-date!"
  310. "\n\n"
  311. "Always make sure that you're running the very latest version, "
  312. "preferably compiled directly from the JUCE repository that you're working with!");
  313. }
  314. //==============================================================================
  315. static File lastDocumentOpened;
  316. File Project::getLastDocumentOpened() { return lastDocumentOpened; }
  317. void Project::setLastDocumentOpened (const File& file) { lastDocumentOpened = file; }
  318. static void registerRecentFile (const File& file)
  319. {
  320. RecentlyOpenedFilesList::registerRecentFileNatively (file);
  321. getAppSettings().recentFiles.addFile (file);
  322. getAppSettings().flush();
  323. }
  324. static void forgetRecentFile (const File& file)
  325. {
  326. RecentlyOpenedFilesList::forgetRecentFileNatively (file);
  327. getAppSettings().recentFiles.removeFile (file);
  328. getAppSettings().flush();
  329. }
  330. //==============================================================================
  331. Result Project::loadDocument (const File& file)
  332. {
  333. ScopedPointer<XmlElement> xml (XmlDocument::parse (file));
  334. if (xml == nullptr || ! xml->hasTagName (Ids::JUCERPROJECT.toString()))
  335. return Result::fail ("Not a valid Jucer project!");
  336. auto newTree = ValueTree::fromXml (*xml);
  337. if (! newTree.hasType (Ids::JUCERPROJECT))
  338. return Result::fail ("The document contains errors and couldn't be parsed!");
  339. registerRecentFile (file);
  340. enabledModulesList.reset();
  341. projectRoot = newTree;
  342. initialiseProjectValues();
  343. initialiseMainGroup();
  344. initialiseAudioPluginValues();
  345. parsedPreprocessorDefs = parsePreprocessorDefs (preprocessorDefsValue.get());
  346. removeDefunctExporters();
  347. updateOldModulePaths();
  348. setChangedFlag (false);
  349. if (! ProjucerApplication::getApp().isRunningCommandLine)
  350. warnAboutOldProjucerVersion();
  351. return Result::ok();
  352. }
  353. Result Project::saveDocument (const File& file)
  354. {
  355. return saveProject (file, false);
  356. }
  357. Result Project::saveProject (const File& file, bool isCommandLineApp)
  358. {
  359. if (isSaving)
  360. return Result::ok();
  361. if (isTemporaryProject())
  362. {
  363. askUserWhereToSaveProject();
  364. return Result::ok();
  365. }
  366. updateProjectSettings();
  367. if (! isCommandLineApp && ! isTemporaryProject())
  368. registerRecentFile (file);
  369. const ScopedValueSetter<bool> vs (isSaving, true, false);
  370. ProjectSaver saver (*this, file);
  371. return saver.save (! isCommandLineApp, shouldWaitAfterSaving, specifiedExporterToSave);
  372. }
  373. Result Project::saveResourcesOnly (const File& file)
  374. {
  375. ProjectSaver saver (*this, file);
  376. return saver.saveResourcesOnly();
  377. }
  378. //==============================================================================
  379. void Project::setTemporaryDirectory (const File& dir) noexcept
  380. {
  381. tempDirectory = dir;
  382. // remove this file from the recent documents list as it is a temporary project
  383. forgetRecentFile (getFile());
  384. }
  385. void Project::askUserWhereToSaveProject()
  386. {
  387. FileChooser fc ("Save Project");
  388. fc.browseForDirectory();
  389. if (fc.getResult().exists())
  390. moveTemporaryDirectory (fc.getResult());
  391. }
  392. void Project::moveTemporaryDirectory (const File& newParentDirectory)
  393. {
  394. auto newDirectory = newParentDirectory.getChildFile (tempDirectory.getFileName());
  395. auto oldJucerFileName = getFile().getFileName();
  396. saveProjectRootToFile();
  397. tempDirectory.copyDirectoryTo (newDirectory);
  398. tempDirectory.deleteRecursively();
  399. tempDirectory = File();
  400. // reload project from new location
  401. if (auto* window = ProjucerApplication::getApp().mainWindowList.getMainWindowForFile (getFile()))
  402. {
  403. Component::SafePointer<MainWindow> safeWindow (window);
  404. MessageManager::callAsync ([safeWindow, newDirectory, oldJucerFileName]
  405. {
  406. if (safeWindow != nullptr)
  407. safeWindow.getComponent()->moveProject (newDirectory.getChildFile (oldJucerFileName));
  408. });
  409. }
  410. }
  411. bool Project::saveProjectRootToFile()
  412. {
  413. ScopedPointer<XmlElement> xml (projectRoot.createXml());
  414. if (xml == nullptr)
  415. {
  416. jassertfalse;
  417. return false;
  418. }
  419. MemoryOutputStream mo;
  420. xml->writeToStream (mo, {});
  421. return FileHelpers::overwriteFileWithNewDataIfDifferent (getFile(), mo);
  422. }
  423. //==============================================================================
  424. static void sendProjectSettingAnalyticsEvent (StringRef label)
  425. {
  426. StringPairArray data;
  427. data.set ("label", label);
  428. Analytics::getInstance()->logEvent ("Project Setting", data, ProjucerAnalyticsEvent::projectEvent);
  429. }
  430. void Project::valueTreePropertyChanged (ValueTree& tree, const Identifier& property)
  431. {
  432. if (tree.getRoot() == tree)
  433. {
  434. if (property == Ids::projectType)
  435. {
  436. sendChangeMessage();
  437. sendProjectSettingAnalyticsEvent ("Project Type = " + projectTypeValue.get().toString());
  438. }
  439. else if (property == Ids::name)
  440. {
  441. updateTitle();
  442. }
  443. else if (property == Ids::defines)
  444. {
  445. parsedPreprocessorDefs = parsePreprocessorDefs (preprocessorDefsValue.get());
  446. }
  447. else if (property == Ids::cppLanguageStandard)
  448. {
  449. sendProjectSettingAnalyticsEvent ("C++ Standard = " + cppStandardValue.get().toString());
  450. }
  451. changed();
  452. }
  453. }
  454. void Project::valueTreeChildAdded (ValueTree&, ValueTree&) { changed(); }
  455. void Project::valueTreeChildRemoved (ValueTree&, ValueTree&, int) { changed(); }
  456. void Project::valueTreeChildOrderChanged (ValueTree&, int, int) { changed(); }
  457. void Project::valueTreeParentChanged (ValueTree&) {}
  458. //==============================================================================
  459. bool Project::hasProjectBeenModified()
  460. {
  461. auto oldModificationTime = modificationTime;
  462. modificationTime = getFile().getLastModificationTime();
  463. return (modificationTime.toMilliseconds() > (oldModificationTime.toMilliseconds() + 1000LL));
  464. }
  465. //==============================================================================
  466. File Project::resolveFilename (String filename) const
  467. {
  468. if (filename.isEmpty())
  469. return {};
  470. filename = replacePreprocessorDefs (getPreprocessorDefs(), filename);
  471. #if ! JUCE_WINDOWS
  472. if (filename.startsWith ("~"))
  473. return File::getSpecialLocation (File::userHomeDirectory).getChildFile (filename.trimCharactersAtStart ("~/"));
  474. #endif
  475. if (FileHelpers::isAbsolutePath (filename))
  476. return File::createFileWithoutCheckingPath (FileHelpers::currentOSStylePath (filename)); // (avoid assertions for windows-style paths)
  477. return getFile().getSiblingFile (FileHelpers::currentOSStylePath (filename));
  478. }
  479. String Project::getRelativePathForFile (const File& file) const
  480. {
  481. auto filename = file.getFullPathName();
  482. auto relativePathBase = getFile().getParentDirectory();
  483. auto p1 = relativePathBase.getFullPathName();
  484. auto p2 = file.getFullPathName();
  485. while (p1.startsWithChar (File::getSeparatorChar()))
  486. p1 = p1.substring (1);
  487. while (p2.startsWithChar (File::getSeparatorChar()))
  488. p2 = p2.substring (1);
  489. if (p1.upToFirstOccurrenceOf (File::getSeparatorString(), true, false)
  490. .equalsIgnoreCase (p2.upToFirstOccurrenceOf (File::getSeparatorString(), true, false)))
  491. {
  492. filename = FileHelpers::getRelativePathFrom (file, relativePathBase);
  493. }
  494. return filename;
  495. }
  496. //==============================================================================
  497. const ProjectType& Project::getProjectType() const
  498. {
  499. if (auto* type = ProjectType::findType (getProjectTypeString()))
  500. return *type;
  501. auto* guiType = ProjectType::findType (ProjectType_GUIApp::getTypeName());
  502. jassert (guiType != nullptr);
  503. return *guiType;
  504. }
  505. bool Project::shouldBuildTargetType (ProjectType::Target::Type targetType) const noexcept
  506. {
  507. auto& projectType = getProjectType();
  508. if (! projectType.supportsTargetType (targetType))
  509. return false;
  510. switch (targetType)
  511. {
  512. case ProjectType::Target::VSTPlugIn:
  513. return shouldBuildVST();
  514. case ProjectType::Target::VST3PlugIn:
  515. return shouldBuildVST3();
  516. case ProjectType::Target::AAXPlugIn:
  517. return shouldBuildAAX();
  518. case ProjectType::Target::RTASPlugIn:
  519. return shouldBuildRTAS();
  520. case ProjectType::Target::AudioUnitPlugIn:
  521. return shouldBuildAU();
  522. case ProjectType::Target::AudioUnitv3PlugIn:
  523. return shouldBuildAUv3();
  524. case ProjectType::Target::StandalonePlugIn:
  525. return shouldBuildStandalonePlugin();
  526. case ProjectType::Target::AggregateTarget:
  527. case ProjectType::Target::SharedCodeTarget:
  528. return projectType.isAudioPlugin();
  529. case ProjectType::Target::unspecified:
  530. return false;
  531. default:
  532. break;
  533. }
  534. return true;
  535. }
  536. ProjectType::Target::Type Project::getTargetTypeFromFilePath (const File& file, bool returnSharedTargetIfNoValidSuffix)
  537. {
  538. if (LibraryModule::CompileUnit::hasSuffix (file, "_AU")) return ProjectType::Target::AudioUnitPlugIn;
  539. else if (LibraryModule::CompileUnit::hasSuffix (file, "_AUv3")) return ProjectType::Target::AudioUnitv3PlugIn;
  540. else if (LibraryModule::CompileUnit::hasSuffix (file, "_AAX")) return ProjectType::Target::AAXPlugIn;
  541. else if (LibraryModule::CompileUnit::hasSuffix (file, "_RTAS")) return ProjectType::Target::RTASPlugIn;
  542. else if (LibraryModule::CompileUnit::hasSuffix (file, "_VST2")) return ProjectType::Target::VSTPlugIn;
  543. else if (LibraryModule::CompileUnit::hasSuffix (file, "_VST3")) return ProjectType::Target::VST3PlugIn;
  544. else if (LibraryModule::CompileUnit::hasSuffix (file, "_Standalone")) return ProjectType::Target::StandalonePlugIn;
  545. return (returnSharedTargetIfNoValidSuffix ? ProjectType::Target::SharedCodeTarget : ProjectType::Target::unspecified);
  546. }
  547. const char* ProjectType::Target::getName() const noexcept
  548. {
  549. switch (type)
  550. {
  551. case GUIApp: return "App";
  552. case ConsoleApp: return "ConsoleApp";
  553. case StaticLibrary: return "Static Library";
  554. case DynamicLibrary: return "Dynamic Library";
  555. case VSTPlugIn: return "VST";
  556. case VST3PlugIn: return "VST3";
  557. case AudioUnitPlugIn: return "AU";
  558. case StandalonePlugIn: return "Standalone Plugin";
  559. case AudioUnitv3PlugIn: return "AUv3 AppExtension";
  560. case AAXPlugIn: return "AAX";
  561. case RTASPlugIn: return "RTAS";
  562. case SharedCodeTarget: return "Shared Code";
  563. case AggregateTarget: return "All";
  564. default: return "undefined";
  565. }
  566. }
  567. ProjectType::Target::TargetFileType ProjectType::Target::getTargetFileType() const noexcept
  568. {
  569. switch (type)
  570. {
  571. case GUIApp: return executable;
  572. case ConsoleApp: return executable;
  573. case StaticLibrary: return staticLibrary;
  574. case DynamicLibrary: return sharedLibraryOrDLL;
  575. case VSTPlugIn: return pluginBundle;
  576. case VST3PlugIn: return pluginBundle;
  577. case AudioUnitPlugIn: return pluginBundle;
  578. case StandalonePlugIn: return executable;
  579. case AudioUnitv3PlugIn: return macOSAppex;
  580. case AAXPlugIn: return pluginBundle;
  581. case RTASPlugIn: return pluginBundle;
  582. case SharedCodeTarget: return staticLibrary;
  583. default:
  584. break;
  585. }
  586. return unknown;
  587. }
  588. //==============================================================================
  589. void Project::createPropertyEditors (PropertyListBuilder& props)
  590. {
  591. props.add (new TextPropertyComponent (projectNameValue, "Project Name", 256, false),
  592. "The name of the project.");
  593. props.add (new TextPropertyComponent (versionValue, "Project Version", 16, false),
  594. "The project's version number, This should be in the format major.minor.point[.point]");
  595. props.add (new TextPropertyComponent (companyNameValue, "Company Name", 256, false),
  596. "Your company name, which will be added to the properties of the binary where possible");
  597. props.add (new TextPropertyComponent (companyCopyrightValue, "Company Copyright", 256, false),
  598. "Your company copyright, which will be added to the properties of the binary where possible");
  599. props.add (new TextPropertyComponent (companyWebsiteValue, "Company Website", 256, false),
  600. "Your company website, which will be added to the properties of the binary where possible");
  601. props.add (new TextPropertyComponent (companyEmailValue, "Company E-mail", 256, false),
  602. "Your company e-mail, which will be added to the properties of the binary where possible");
  603. {
  604. String licenseRequiredTagline ("Required for closed source applications without an Indie or Pro JUCE license");
  605. String licenseRequiredInfo ("In accordance with the terms of the JUCE 5 End-Use License Agreement (www.juce.com/juce-5-licence), "
  606. "this option can only be disabled for closed source applications if you have a JUCE Indie or Pro "
  607. "license, or are using JUCE under the GPL v3 license.");
  608. StringPairArray description;
  609. description.set ("Report JUCE app usage", "This option controls the collection of usage data from users of this JUCE application.");
  610. description.set ("Display the JUCE splash screen", "This option controls the display of the standard JUCE splash screen.");
  611. if (ProjucerApplication::getApp().isPaidOrGPL())
  612. {
  613. props.add (new ChoicePropertyComponent (reportAppUsageValue, String ("Report JUCE App Usage") + " (" + licenseRequiredTagline + ")"),
  614. description["Report JUCE app usage"] + " " + licenseRequiredInfo);
  615. props.add (new ChoicePropertyComponent (displaySplashScreenValue, String ("Display the JUCE Splash Screen") + " (" + licenseRequiredTagline + ")"),
  616. description["Display the JUCE splash screen"] + " " + licenseRequiredInfo);
  617. }
  618. else
  619. {
  620. StringArray options;
  621. Array<var> vars;
  622. options.add (licenseRequiredTagline);
  623. vars.add (var());
  624. props.add (new ChoicePropertyComponent (Value(), "Report JUCE App Usage", options, vars),
  625. description["Report JUCE app usage"] + " " + licenseRequiredInfo);
  626. props.add (new ChoicePropertyComponent (Value(), "Display the JUCE Splash Screen", options, vars),
  627. description["Display the JUCE splash screen"] + " " + licenseRequiredInfo);
  628. }
  629. }
  630. props.add (new ChoicePropertyComponent (splashScreenColourValue, "Splash Screen Colour",
  631. { "Dark", "Light" },
  632. { "Dark", "Light" }),
  633. "Choose the colour of the JUCE splash screen.");
  634. {
  635. StringArray projectTypeNames;
  636. Array<var> projectTypeCodes;
  637. auto types = ProjectType::getAllTypes();
  638. for (int i = 0; i < types.size(); ++i)
  639. {
  640. projectTypeNames.add (types.getUnchecked(i)->getDescription());
  641. projectTypeCodes.add (types.getUnchecked(i)->getType());
  642. }
  643. props.add (new ChoicePropertyComponent (projectTypeValue, "Project Type", projectTypeNames, projectTypeCodes),
  644. "The project type for which settings should be shown.");
  645. }
  646. props.add (new TextPropertyComponent (bundleIdentifierValue, "Bundle Identifier", 256, false),
  647. "A unique identifier for this product, mainly for use in OSX/iOS builds. It should be something like 'com.yourcompanyname.yourproductname'");
  648. if (getProjectType().isAudioPlugin())
  649. createAudioPluginPropertyEditors (props);
  650. {
  651. const int maxSizes[] = { 20480, 10240, 6144, 2048, 1024, 512, 256, 128, 64 };
  652. StringArray maxSizeNames;
  653. Array<var> maxSizeCodes;
  654. for (int i = 0; i < numElementsInArray (maxSizes); ++i)
  655. {
  656. auto sizeInBytes = maxSizes[i] * 1024;
  657. maxSizeNames.add (File::descriptionOfSizeInBytes (sizeInBytes));
  658. maxSizeCodes.add (sizeInBytes);
  659. }
  660. props.add (new ChoicePropertyComponent (maxBinaryFileSizeValue, "BinaryData.cpp Size Limit", maxSizeNames, maxSizeCodes),
  661. "When splitting binary data into multiple cpp files, the Projucer attempts to keep the file sizes below this threshold. "
  662. "(Note that individual resource files which are larger than this size cannot be split across multiple cpp files).");
  663. }
  664. props.add (new ChoicePropertyComponent (includeBinaryDataInAppConfigValue, "Include BinaryData in AppConfig"),
  665. "Include BinaryData.h in the AppConfig.h file");
  666. props.add (new TextPropertyComponent (binaryDataNamespaceValue, "BinaryData Namespace", 256, false),
  667. "The namespace containing the binary assests.");
  668. props.add (new ChoicePropertyComponent (cppStandardValue, "C++ Language Standard",
  669. { "C++11", "C++14", "C++17", "Use Latest" },
  670. { "11", "14", "17", "latest" }),
  671. "The standard of the C++ language that will be used for compilation.");
  672. props.add (new TextPropertyComponent (preprocessorDefsValue, "Preprocessor Definitions", 32768, true),
  673. "Global preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace, commas, or "
  674. "new-lines to separate the items - to include a space or comma in a definition, precede it with a backslash.");
  675. props.addSearchPathProperty (headerSearchPathsValue, "Header Search Paths", "Global header search paths.");
  676. props.add (new TextPropertyComponent (userNotesValue, "Notes", 32768, true),
  677. "Extra comments: This field is not used for code or project generation, it's just a space where you can express your thoughts.");
  678. }
  679. void Project::createAudioPluginPropertyEditors (PropertyListBuilder& props)
  680. {
  681. props.add (new ChoicePropertyComponent (buildVSTValue, "Build VST"),
  682. "Whether the project should produce a VST plugin.");
  683. props.add (new ChoicePropertyComponent (buildVST3Value, "Build VST3"),
  684. "Whether the project should produce a VST3 plugin.");
  685. props.add (new ChoicePropertyComponent (buildAUValue, "Build AudioUnit"),
  686. "Whether the project should produce an AudioUnit plugin.");
  687. props.add (new ChoicePropertyComponent (buildAUv3Value, "Build AudioUnit v3"),
  688. "Whether the project should produce an AudioUnit version 3 plugin.");
  689. props.add (new ChoicePropertyComponent (buildRTASValue, "Build RTAS"),
  690. "Whether the project should produce an RTAS plugin.");
  691. props.add (new ChoicePropertyComponent (buildAAXValue, "Build AAX"),
  692. "Whether the project should produce an AAX plugin.");
  693. props.add (new ChoicePropertyComponent (buildStandaloneValue, "Build Standalone Plug-In"),
  694. "Whether the project should produce a standalone version of your plugin.");
  695. props.add (new ChoicePropertyComponent (enableIAAValue, "Enable Inter-App Audio"),
  696. "Whether a standalone plug-in should be an Inter-App Audio app. You should also enable the audio "
  697. "background capability in the iOS exporter.");
  698. props.add (new TextPropertyComponent (pluginNameValue, "Plugin Name", 128, false),
  699. "The name of your plugin (keep it short!)");
  700. props.add (new TextPropertyComponent (pluginDescriptionValue, "Plugin Description", 256, false),
  701. "A short description of your plugin.");
  702. props.add (new TextPropertyComponent (pluginManufacturerValue, "Plugin Manufacturer", 256, false),
  703. "The name of your company (cannot be blank).");
  704. props.add (new TextPropertyComponent (pluginManufacturerCodeValue, "Plugin Manufacturer Code", 4, false),
  705. "A four-character unique ID for your company. Note that for AU compatibility, this must contain at least one upper-case letter!");
  706. props.add (new TextPropertyComponent (pluginCodeValue, "Plugin Code", 4, false),
  707. "A four-character unique ID for your plugin. Note that for AU compatibility, this must contain at least one upper-case letter!");
  708. props.add (new TextPropertyComponent (pluginChannelConfigsValue, "Plugin Channel Configurations", 1024, false),
  709. "This list is a comma-separated set list in the form {numIns, numOuts} and each pair indicates a valid plug-in "
  710. "configuration. For example {1, 1}, {2, 2} means that the plugin can be used either with 1 input and 1 output, "
  711. "or with 2 inputs and 2 outputs. If your plug-in requires side-chains, aux output buses etc., then you must leave "
  712. "this field empty and override the isBusesLayoutSupported callback in your AudioProcessor.");
  713. props.add (new ChoicePropertyComponent (pluginIsSynthValue, "Plugin is a Synth"),
  714. "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.");
  715. props.add (new ChoicePropertyComponent (pluginWantsMidiInputValue, "Plugin Midi Input"),
  716. "Enable this if you want your plugin to accept midi messages.");
  717. props.add (new ChoicePropertyComponent (pluginProducesMidiOutValue, "Plugin Midi Output"),
  718. "Enable this if your plugin is going to produce midi messages.");
  719. props.add (new ChoicePropertyComponent (pluginIsMidiEffectPluginValue, "Midi Effect Plugin"),
  720. "Enable this if your plugin only processes midi and no audio.");
  721. props.add (new ChoicePropertyComponent (pluginEditorNeedsKeyFocusValue, "Plugin Editor Requires Keyboard Focus"),
  722. "Enable this if your plugin needs keyboard input - some hosts can be a bit funny about keyboard focus..");
  723. props.add (new TextPropertyComponent (pluginAUExportPrefixValue, "Plugin AU Export Prefix", 128, false),
  724. "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.");
  725. props.add (new TextPropertyComponent (pluginAUMainTypeValue, "Plugin AU Main Type", 128, false),
  726. "In an AU, this is the value that is set as JucePlugin_AUMainType. Leave it blank unless you want to use a custom value.");
  727. props.add (new TextPropertyComponent (pluginVSTCategoryValue, "Plugin VST Category", 128, false),
  728. "In a VST, this is the value that is set as JucePlugin_VSTCategory. Leave it blank unless you want to use a custom value.");
  729. props.add (new TextPropertyComponent (pluginRTASCategoryValue, "Plugin RTAS Category", 128, false),
  730. "(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, "
  731. "ePlugInCategory_PitchShift, ePlugInCategory_Reverb, ePlugInCategory_Delay, "
  732. "ePlugInCategory_Modulation, ePlugInCategory_Harmonic, ePlugInCategory_NoiseReduction, "
  733. "ePlugInCategory_Dither, ePlugInCategory_SoundField");
  734. props.add (new TextPropertyComponent (pluginAAXCategoryValue, "Plugin AAX Category", 128, false),
  735. "This is one of the categories from the AAX_EPlugInCategory enum");
  736. props.add (new TextPropertyComponent (pluginAAXIdentifierValue, "Plugin AAX Identifier", 256, false),
  737. "The value to use for the JucePlugin_AAXIdentifier setting");
  738. }
  739. //==============================================================================
  740. static StringArray getVersionSegments (const Project& p)
  741. {
  742. auto segments = StringArray::fromTokens (p.getVersionString(), ",.", "");
  743. segments.trim();
  744. segments.removeEmptyStrings();
  745. return segments;
  746. }
  747. int Project::getVersionAsHexInteger() const
  748. {
  749. auto segments = getVersionSegments (*this);
  750. auto value = (segments[0].getIntValue() << 16)
  751. + (segments[1].getIntValue() << 8)
  752. + segments[2].getIntValue();
  753. if (segments.size() >= 4)
  754. value = (value << 8) + segments[3].getIntValue();
  755. return value;
  756. }
  757. String Project::getVersionAsHex() const
  758. {
  759. return "0x" + String::toHexString (getVersionAsHexInteger());
  760. }
  761. File Project::getBinaryDataCppFile (int index) const
  762. {
  763. auto cpp = getGeneratedCodeFolder().getChildFile ("BinaryData.cpp");
  764. if (index > 0)
  765. return cpp.getSiblingFile (cpp.getFileNameWithoutExtension() + String (index + 1))
  766. .withFileExtension (cpp.getFileExtension());
  767. return cpp;
  768. }
  769. Project::Item Project::getMainGroup()
  770. {
  771. return { *this, projectRoot.getChildWithName (Ids::MAINGROUP), false };
  772. }
  773. PropertiesFile& Project::getStoredProperties() const
  774. {
  775. return getAppSettings().getProjectProperties (getProjectUIDString());
  776. }
  777. static void findImages (const Project::Item& item, OwnedArray<Project::Item>& found)
  778. {
  779. if (item.isImageFile())
  780. {
  781. found.add (new Project::Item (item));
  782. }
  783. else if (item.isGroup())
  784. {
  785. for (int i = 0; i < item.getNumChildren(); ++i)
  786. findImages (item.getChild (i), found);
  787. }
  788. }
  789. void Project::findAllImageItems (OwnedArray<Project::Item>& items)
  790. {
  791. findImages (getMainGroup(), items);
  792. }
  793. //==============================================================================
  794. Project::Item::Item (Project& p, const ValueTree& s, bool isModuleCode)
  795. : project (p), state (s), belongsToModule (isModuleCode)
  796. {
  797. }
  798. Project::Item::Item (const Item& other)
  799. : project (other.project), state (other.state), belongsToModule (other.belongsToModule)
  800. {
  801. }
  802. Project::Item Project::Item::createCopy() { Item i (*this); i.state = i.state.createCopy(); return i; }
  803. String Project::Item::getID() const { return state [Ids::ID]; }
  804. void Project::Item::setID (const String& newID) { state.setProperty (Ids::ID, newID, nullptr); }
  805. Drawable* Project::Item::loadAsImageFile() const
  806. {
  807. const MessageManagerLock mml (ThreadPoolJob::getCurrentThreadPoolJob());
  808. if (! mml.lockWasGained())
  809. return nullptr;
  810. return isValid() ? Drawable::createFromImageFile (getFile())
  811. : nullptr;
  812. }
  813. Project::Item Project::Item::createGroup (Project& project, const String& name, const String& uid, bool isModuleCode)
  814. {
  815. Item group (project, ValueTree (Ids::GROUP), isModuleCode);
  816. group.setID (uid);
  817. group.initialiseMissingProperties();
  818. group.getNameValue() = name;
  819. return group;
  820. }
  821. bool Project::Item::isFile() const { return state.hasType (Ids::FILE); }
  822. bool Project::Item::isGroup() const { return state.hasType (Ids::GROUP) || isMainGroup(); }
  823. bool Project::Item::isMainGroup() const { return state.hasType (Ids::MAINGROUP); }
  824. bool Project::Item::isImageFile() const
  825. {
  826. return isFile() && (ImageFileFormat::findImageFormatForFileExtension (getFile()) != nullptr
  827. || getFile().hasFileExtension ("svg"));
  828. }
  829. Project::Item Project::Item::findItemWithID (const String& targetId) const
  830. {
  831. if (state [Ids::ID] == targetId)
  832. return *this;
  833. if (isGroup())
  834. {
  835. for (auto i = getNumChildren(); --i >= 0;)
  836. {
  837. auto found = getChild(i).findItemWithID (targetId);
  838. if (found.isValid())
  839. return found;
  840. }
  841. }
  842. return Item (project, ValueTree(), false);
  843. }
  844. bool Project::Item::canContain (const Item& child) const
  845. {
  846. if (isFile())
  847. return false;
  848. if (isGroup())
  849. return child.isFile() || child.isGroup();
  850. jassertfalse;
  851. return false;
  852. }
  853. bool Project::Item::shouldBeAddedToTargetProject() const { return isFile(); }
  854. Value Project::Item::getShouldCompileValue() { return state.getPropertyAsValue (Ids::compile, getUndoManager()); }
  855. bool Project::Item::shouldBeCompiled() const { return state [Ids::compile]; }
  856. Value Project::Item::getShouldAddToBinaryResourcesValue() { return state.getPropertyAsValue (Ids::resource, getUndoManager()); }
  857. bool Project::Item::shouldBeAddedToBinaryResources() const { return state [Ids::resource]; }
  858. Value Project::Item::getShouldAddToXcodeResourcesValue() { return state.getPropertyAsValue (Ids::xcodeResource, getUndoManager()); }
  859. bool Project::Item::shouldBeAddedToXcodeResources() const { return state [Ids::xcodeResource]; }
  860. Value Project::Item::getShouldInhibitWarningsValue() { return state.getPropertyAsValue (Ids::noWarnings, getUndoManager()); }
  861. bool Project::Item::shouldInhibitWarnings() const { return state [Ids::noWarnings]; }
  862. bool Project::Item::isModuleCode() const { return belongsToModule; }
  863. String Project::Item::getFilePath() const
  864. {
  865. if (isFile())
  866. return state [Ids::file].toString();
  867. return {};
  868. }
  869. File Project::Item::getFile() const
  870. {
  871. if (isFile())
  872. return project.resolveFilename (state [Ids::file].toString());
  873. return {};
  874. }
  875. void Project::Item::setFile (const File& file)
  876. {
  877. setFile (RelativePath (project.getRelativePathForFile (file), RelativePath::projectFolder));
  878. jassert (getFile() == file);
  879. }
  880. void Project::Item::setFile (const RelativePath& file)
  881. {
  882. jassert (isFile());
  883. state.setProperty (Ids::file, file.toUnixStyle(), getUndoManager());
  884. state.setProperty (Ids::name, file.getFileName(), getUndoManager());
  885. }
  886. bool Project::Item::renameFile (const File& newFile)
  887. {
  888. auto oldFile = getFile();
  889. if (oldFile.moveFileTo (newFile)
  890. || (newFile.exists() && ! oldFile.exists()))
  891. {
  892. setFile (newFile);
  893. ProjucerApplication::getApp().openDocumentManager.fileHasBeenRenamed (oldFile, newFile);
  894. return true;
  895. }
  896. return false;
  897. }
  898. bool Project::Item::containsChildForFile (const RelativePath& file) const
  899. {
  900. return state.getChildWithProperty (Ids::file, file.toUnixStyle()).isValid();
  901. }
  902. Project::Item Project::Item::findItemForFile (const File& file) const
  903. {
  904. if (getFile() == file)
  905. return *this;
  906. if (isGroup())
  907. {
  908. for (auto i = getNumChildren(); --i >= 0;)
  909. {
  910. auto found = getChild(i).findItemForFile (file);
  911. if (found.isValid())
  912. return found;
  913. }
  914. }
  915. return Item (project, ValueTree(), false);
  916. }
  917. File Project::Item::determineGroupFolder() const
  918. {
  919. jassert (isGroup());
  920. File f;
  921. for (int i = 0; i < getNumChildren(); ++i)
  922. {
  923. f = getChild(i).getFile();
  924. if (f.exists())
  925. return f.getParentDirectory();
  926. }
  927. auto parent = getParent();
  928. if (parent != *this)
  929. {
  930. f = parent.determineGroupFolder();
  931. if (f.getChildFile (getName()).isDirectory())
  932. f = f.getChildFile (getName());
  933. }
  934. else
  935. {
  936. f = project.getProjectFolder();
  937. if (f.getChildFile ("Source").isDirectory())
  938. f = f.getChildFile ("Source");
  939. }
  940. return f;
  941. }
  942. void Project::Item::initialiseMissingProperties()
  943. {
  944. if (! state.hasProperty (Ids::ID))
  945. setID (createAlphaNumericUID());
  946. if (isFile())
  947. {
  948. state.setProperty (Ids::name, getFile().getFileName(), nullptr);
  949. }
  950. else if (isGroup())
  951. {
  952. for (auto i = getNumChildren(); --i >= 0;)
  953. getChild(i).initialiseMissingProperties();
  954. }
  955. }
  956. Value Project::Item::getNameValue()
  957. {
  958. return state.getPropertyAsValue (Ids::name, getUndoManager());
  959. }
  960. String Project::Item::getName() const
  961. {
  962. return state [Ids::name];
  963. }
  964. void Project::Item::addChild (const Item& newChild, int insertIndex)
  965. {
  966. state.addChild (newChild.state, insertIndex, getUndoManager());
  967. }
  968. void Project::Item::removeItemFromProject()
  969. {
  970. state.getParent().removeChild (state, getUndoManager());
  971. }
  972. Project::Item Project::Item::getParent() const
  973. {
  974. if (isMainGroup() || ! isGroup())
  975. return *this;
  976. return { project, state.getParent(), belongsToModule };
  977. }
  978. struct ItemSorter
  979. {
  980. static int compareElements (const ValueTree& first, const ValueTree& second)
  981. {
  982. return first [Ids::name].toString().compareNatural (second [Ids::name].toString());
  983. }
  984. };
  985. struct ItemSorterWithGroupsAtStart
  986. {
  987. static int compareElements (const ValueTree& first, const ValueTree& second)
  988. {
  989. auto firstIsGroup = first.hasType (Ids::GROUP);
  990. auto secondIsGroup = second.hasType (Ids::GROUP);
  991. if (firstIsGroup == secondIsGroup)
  992. return first [Ids::name].toString().compareNatural (second [Ids::name].toString());
  993. return firstIsGroup ? -1 : 1;
  994. }
  995. };
  996. static void sortGroup (ValueTree& state, bool keepGroupsAtStart, UndoManager* undoManager)
  997. {
  998. if (keepGroupsAtStart)
  999. {
  1000. ItemSorterWithGroupsAtStart sorter;
  1001. state.sort (sorter, undoManager, true);
  1002. }
  1003. else
  1004. {
  1005. ItemSorter sorter;
  1006. state.sort (sorter, undoManager, true);
  1007. }
  1008. }
  1009. static bool isGroupSorted (const ValueTree& state, bool keepGroupsAtStart)
  1010. {
  1011. if (state.getNumChildren() == 0)
  1012. return false;
  1013. if (state.getNumChildren() == 1)
  1014. return true;
  1015. auto stateCopy = state.createCopy();
  1016. sortGroup (stateCopy, keepGroupsAtStart, nullptr);
  1017. return stateCopy.isEquivalentTo (state);
  1018. }
  1019. void Project::Item::sortAlphabetically (bool keepGroupsAtStart, bool recursive)
  1020. {
  1021. sortGroup (state, keepGroupsAtStart, getUndoManager());
  1022. if (recursive)
  1023. for (auto i = getNumChildren(); --i >= 0;)
  1024. getChild(i).sortAlphabetically (keepGroupsAtStart, true);
  1025. }
  1026. Project::Item Project::Item::getOrCreateSubGroup (const String& name)
  1027. {
  1028. for (auto i = state.getNumChildren(); --i >= 0;)
  1029. {
  1030. auto child = state.getChild (i);
  1031. if (child.getProperty (Ids::name) == name && child.hasType (Ids::GROUP))
  1032. return { project, child, belongsToModule };
  1033. }
  1034. return addNewSubGroup (name, -1);
  1035. }
  1036. Project::Item Project::Item::addNewSubGroup (const String& name, int insertIndex)
  1037. {
  1038. auto newID = createGUID (getID() + name + String (getNumChildren()));
  1039. int n = 0;
  1040. while (project.getMainGroup().findItemWithID (newID).isValid())
  1041. newID = createGUID (newID + String (++n));
  1042. auto group = createGroup (project, name, newID, belongsToModule);
  1043. jassert (canContain (group));
  1044. addChild (group, insertIndex);
  1045. return group;
  1046. }
  1047. bool Project::Item::addFileAtIndex (const File& file, int insertIndex, const bool shouldCompile)
  1048. {
  1049. if (file == File() || file.isHidden() || file.getFileName().startsWithChar ('.'))
  1050. return false;
  1051. if (file.isDirectory())
  1052. {
  1053. auto group = addNewSubGroup (file.getFileName(), insertIndex);
  1054. for (DirectoryIterator iter (file, false, "*", File::findFilesAndDirectories); iter.next();)
  1055. if (! project.getMainGroup().findItemForFile (iter.getFile()).isValid())
  1056. group.addFileRetainingSortOrder (iter.getFile(), shouldCompile);
  1057. }
  1058. else if (file.existsAsFile())
  1059. {
  1060. if (! project.getMainGroup().findItemForFile (file).isValid())
  1061. addFileUnchecked (file, insertIndex, shouldCompile);
  1062. }
  1063. else
  1064. {
  1065. jassertfalse;
  1066. }
  1067. return true;
  1068. }
  1069. bool Project::Item::addFileRetainingSortOrder (const File& file, bool shouldCompile)
  1070. {
  1071. auto wasSortedGroupsNotFirst = isGroupSorted (state, false);
  1072. auto wasSortedGroupsFirst = isGroupSorted (state, true);
  1073. if (! addFileAtIndex (file, 0, shouldCompile))
  1074. return false;
  1075. if (wasSortedGroupsNotFirst || wasSortedGroupsFirst)
  1076. sortAlphabetically (wasSortedGroupsFirst, false);
  1077. return true;
  1078. }
  1079. void Project::Item::addFileUnchecked (const File& file, int insertIndex, const bool shouldCompile)
  1080. {
  1081. Item item (project, ValueTree (Ids::FILE), belongsToModule);
  1082. item.initialiseMissingProperties();
  1083. item.getNameValue() = file.getFileName();
  1084. item.getShouldCompileValue() = shouldCompile && file.hasFileExtension (fileTypesToCompileByDefault);
  1085. item.getShouldAddToBinaryResourcesValue() = project.shouldBeAddedToBinaryResourcesByDefault (file);
  1086. if (canContain (item))
  1087. {
  1088. item.setFile (file);
  1089. addChild (item, insertIndex);
  1090. }
  1091. }
  1092. bool Project::Item::addRelativeFile (const RelativePath& file, int insertIndex, bool shouldCompile)
  1093. {
  1094. Item item (project, ValueTree (Ids::FILE), belongsToModule);
  1095. item.initialiseMissingProperties();
  1096. item.getNameValue() = file.getFileName();
  1097. item.getShouldCompileValue() = shouldCompile;
  1098. item.getShouldAddToBinaryResourcesValue() = project.shouldBeAddedToBinaryResourcesByDefault (file);
  1099. if (canContain (item))
  1100. {
  1101. item.setFile (file);
  1102. addChild (item, insertIndex);
  1103. return true;
  1104. }
  1105. return false;
  1106. }
  1107. Icon Project::Item::getIcon (bool isOpen) const
  1108. {
  1109. auto& icons = getIcons();
  1110. if (isFile())
  1111. {
  1112. if (isImageFile())
  1113. return Icon (icons.imageDoc, Colours::transparentBlack);
  1114. return { icons.file, Colours::transparentBlack };
  1115. }
  1116. if (isMainGroup())
  1117. return { icons.juceLogo, Colours::orange };
  1118. return { isOpen ? icons.openFolder : icons.closedFolder, Colours::transparentBlack };
  1119. }
  1120. bool Project::Item::isIconCrossedOut() const
  1121. {
  1122. return isFile()
  1123. && ! (shouldBeCompiled()
  1124. || shouldBeAddedToBinaryResources()
  1125. || getFile().hasFileExtension (headerFileExtensions));
  1126. }
  1127. //==============================================================================
  1128. ValueTree Project::getConfigNode()
  1129. {
  1130. return projectRoot.getOrCreateChildWithName (Ids::JUCEOPTIONS, nullptr);
  1131. }
  1132. ValueWithDefault Project::getConfigFlag (const String& name)
  1133. {
  1134. auto configNode = getConfigNode();
  1135. return { configNode, name, getUndoManagerFor (configNode) };
  1136. }
  1137. bool Project::isConfigFlagEnabled (const String& name, bool defaultIsEnabled) const
  1138. {
  1139. auto configValue = projectRoot.getChildWithName (Ids::JUCEOPTIONS).getProperty (name, "default");
  1140. if (configValue == "default")
  1141. return defaultIsEnabled;
  1142. return configValue;
  1143. }
  1144. //==============================================================================
  1145. String Project::getPluginRTASCategoryCode()
  1146. {
  1147. if (static_cast<bool> (isPluginSynth()))
  1148. return "ePlugInCategory_SWGenerators";
  1149. auto s = getPluginRTASCategoryString();
  1150. if (s.isEmpty())
  1151. s = "ePlugInCategory_None";
  1152. return s;
  1153. }
  1154. String Project::getAUMainTypeString()
  1155. {
  1156. auto s = getPluginAUMainTypeString();
  1157. if (s.isEmpty())
  1158. {
  1159. // Unfortunately, Rez uses a header where kAudioUnitType_MIDIProcessor is undefined
  1160. // Use aumi instead.
  1161. if (isPluginMidiEffect()) s = "'aumi'";
  1162. else if (isPluginSynth()) s = "kAudioUnitType_MusicDevice";
  1163. else if (pluginWantsMidiInput()) s = "kAudioUnitType_MusicEffect";
  1164. else s = "kAudioUnitType_Effect";
  1165. }
  1166. return s;
  1167. }
  1168. String Project::getAUMainTypeCode()
  1169. {
  1170. auto s = getPluginAUMainTypeString();
  1171. if (s.isEmpty())
  1172. {
  1173. if (isPluginMidiEffect()) s = "aumi";
  1174. else if (isPluginSynth()) s = "aumu";
  1175. else if (pluginWantsMidiInput()) s = "aumf";
  1176. else s = "aufx";
  1177. }
  1178. return s;
  1179. }
  1180. String Project::getIAATypeCode()
  1181. {
  1182. String s;
  1183. if (pluginWantsMidiInput())
  1184. {
  1185. if (isPluginSynth())
  1186. s = "auri";
  1187. else
  1188. s = "aurm";
  1189. }
  1190. else
  1191. {
  1192. if (isPluginSynth())
  1193. s = "aurg";
  1194. else
  1195. s = "aurx";
  1196. }
  1197. return s;
  1198. }
  1199. String Project::getIAAPluginName()
  1200. {
  1201. auto s = getPluginManufacturerString();
  1202. s << ": ";
  1203. s << getPluginNameString();
  1204. return s;
  1205. }
  1206. String Project::getPluginVSTCategoryString()
  1207. {
  1208. auto s = pluginVSTCategoryValue.get().toString().trim();
  1209. if (s.isEmpty())
  1210. s = isPluginSynth() ? "kPlugCategSynth" : "kPlugCategEffect";
  1211. return s;
  1212. }
  1213. bool Project::isAUPluginHost()
  1214. {
  1215. return getModules().isModuleEnabled ("juce_audio_processors") && isConfigFlagEnabled ("JUCE_PLUGINHOST_AU");
  1216. }
  1217. bool Project::isVSTPluginHost()
  1218. {
  1219. return getModules().isModuleEnabled ("juce_audio_processors") && isConfigFlagEnabled ("JUCE_PLUGINHOST_VST");
  1220. }
  1221. bool Project::isVST3PluginHost()
  1222. {
  1223. return getModules().isModuleEnabled ("juce_audio_processors") && isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3");
  1224. }
  1225. //==============================================================================
  1226. EnabledModuleList& Project::getModules()
  1227. {
  1228. if (enabledModulesList == nullptr)
  1229. enabledModulesList = new EnabledModuleList (*this, projectRoot.getOrCreateChildWithName (Ids::MODULES, nullptr));
  1230. return *enabledModulesList;
  1231. }
  1232. //==============================================================================
  1233. ValueTree Project::getExporters()
  1234. {
  1235. return projectRoot.getOrCreateChildWithName (Ids::EXPORTFORMATS, nullptr);
  1236. }
  1237. int Project::getNumExporters()
  1238. {
  1239. return getExporters().getNumChildren();
  1240. }
  1241. ProjectExporter* Project::createExporter (int index)
  1242. {
  1243. jassert (index >= 0 && index < getNumExporters());
  1244. return ProjectExporter::createExporter (*this, getExporters().getChild (index));
  1245. }
  1246. void Project::addNewExporter (const String& exporterName)
  1247. {
  1248. ScopedPointer<ProjectExporter> exp (ProjectExporter::createNewExporter (*this, exporterName));
  1249. exp->getTargetLocationValue() = exp->getTargetLocationString()
  1250. + getUniqueTargetFolderSuffixForExporter (exp->getName(), exp->getTargetLocationString());
  1251. auto exportersTree = getExporters();
  1252. exportersTree.appendChild (exp->settings, getUndoManagerFor (exportersTree));
  1253. }
  1254. void Project::createExporterForCurrentPlatform()
  1255. {
  1256. addNewExporter (ProjectExporter::getCurrentPlatformExporterName());
  1257. }
  1258. String Project::getUniqueTargetFolderSuffixForExporter (const String& exporterName, const String& base)
  1259. {
  1260. StringArray buildFolders;
  1261. auto exportersTree = getExporters();
  1262. auto type = ProjectExporter::getValueTreeNameForExporter (exporterName);
  1263. for (int i = 0; i < exportersTree.getNumChildren(); ++i)
  1264. {
  1265. auto exporterNode = exportersTree.getChild (i);
  1266. if (exporterNode.getType() == Identifier (type))
  1267. buildFolders.add (exporterNode.getProperty ("targetFolder").toString());
  1268. }
  1269. if (buildFolders.size() == 0 || ! buildFolders.contains (base))
  1270. return {};
  1271. buildFolders.remove (buildFolders.indexOf (base));
  1272. int num = 1;
  1273. for (auto f : buildFolders)
  1274. {
  1275. if (! f.endsWith ("_" + String (num)))
  1276. break;
  1277. ++num;
  1278. }
  1279. return "_" + String (num);
  1280. }
  1281. //==============================================================================
  1282. bool Project::shouldSendGUIBuilderAnalyticsEvent() noexcept
  1283. {
  1284. if (! hasSentGUIBuilderAnalyticsEvent)
  1285. {
  1286. hasSentGUIBuilderAnalyticsEvent = true;
  1287. return true;
  1288. }
  1289. return false;
  1290. }
  1291. //==============================================================================
  1292. String Project::getFileTemplate (const String& templateName)
  1293. {
  1294. int dataSize;
  1295. if (auto* data = BinaryData::getNamedResource (templateName.toUTF8(), dataSize))
  1296. return String::fromUTF8 (data, dataSize);
  1297. jassertfalse;
  1298. return {};
  1299. }
  1300. //==============================================================================
  1301. Project::ExporterIterator::ExporterIterator (Project& p) : index (-1), project (p) {}
  1302. Project::ExporterIterator::~ExporterIterator() {}
  1303. bool Project::ExporterIterator::next()
  1304. {
  1305. if (++index >= project.getNumExporters())
  1306. return false;
  1307. exporter = project.createExporter (index);
  1308. if (exporter == nullptr)
  1309. {
  1310. jassertfalse; // corrupted project file?
  1311. return next();
  1312. }
  1313. return true;
  1314. }