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.

705 lines
25KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. #pragma once
  18. #include "jucer_ResourceFile.h"
  19. #include "../Project/jucer_Module.h"
  20. #include "jucer_ProjectExporter.h"
  21. //==============================================================================
  22. class ProjectSaver
  23. {
  24. public:
  25. ProjectSaver (Project& p, const File& file)
  26. : project (p),
  27. projectFile (file),
  28. generatedCodeFolder (project.getGeneratedCodeFolder()),
  29. generatedFilesGroup (Project::Item::createGroup (project, getJuceCodeGroupName(), "__generatedcode__", true)),
  30. hasBinaryData (false)
  31. {
  32. generatedFilesGroup.setID (getGeneratedGroupID());
  33. }
  34. struct SaveThread : public ThreadWithProgressWindow
  35. {
  36. public:
  37. SaveThread (ProjectSaver& ps)
  38. : ThreadWithProgressWindow ("Saving...", true, false),
  39. saver (ps), result (Result::ok())
  40. {}
  41. void run() override
  42. {
  43. setProgress (-1);
  44. result = saver.save (false);
  45. }
  46. ProjectSaver& saver;
  47. Result result;
  48. JUCE_DECLARE_NON_COPYABLE (SaveThread)
  49. };
  50. Result save (bool showProgressBox)
  51. {
  52. if (showProgressBox)
  53. {
  54. SaveThread thread (*this);
  55. thread.runThread();
  56. return thread.result;
  57. }
  58. const String appConfigUserContent (loadUserContentFromAppConfig());
  59. const File oldFile (project.getFile());
  60. project.setFile (projectFile);
  61. writeMainProjectFile();
  62. OwnedArray<LibraryModule> modules;
  63. project.getModules().createRequiredModules (modules);
  64. checkModuleValidity (modules);
  65. if (errors.size() == 0) writeAppConfigFile (modules, appConfigUserContent);
  66. if (errors.size() == 0) writeBinaryDataFiles();
  67. if (errors.size() == 0) writeAppHeader (modules);
  68. if (errors.size() == 0) writeModuleCppWrappers (modules);
  69. if (errors.size() == 0) writeProjects (modules);
  70. if (errors.size() == 0) writeAppConfigFile (modules, appConfigUserContent); // (this is repeated in case the projects added anything to it)
  71. if (errors.size() == 0 && generatedCodeFolder.exists())
  72. writeReadmeFile();
  73. if (generatedCodeFolder.exists())
  74. deleteUnwantedFilesIn (generatedCodeFolder);
  75. if (errors.size() > 0)
  76. {
  77. project.setFile (oldFile);
  78. return Result::fail (errors[0]);
  79. }
  80. project.updateModificationTime();
  81. return Result::ok();
  82. }
  83. Result saveResourcesOnly()
  84. {
  85. writeBinaryDataFiles();
  86. if (errors.size() > 0)
  87. return Result::fail (errors[0]);
  88. return Result::ok();
  89. }
  90. Project::Item saveGeneratedFile (const String& filePath, const MemoryOutputStream& newData)
  91. {
  92. if (! generatedCodeFolder.createDirectory())
  93. {
  94. addError ("Couldn't create folder: " + generatedCodeFolder.getFullPathName());
  95. return Project::Item (project, ValueTree(), false);
  96. }
  97. const File file (generatedCodeFolder.getChildFile (filePath));
  98. if (replaceFileIfDifferent (file, newData))
  99. return addFileToGeneratedGroup (file);
  100. return Project::Item (project, ValueTree(), true);
  101. }
  102. Project::Item addFileToGeneratedGroup (const File& file)
  103. {
  104. Project::Item item (generatedFilesGroup.findItemForFile (file));
  105. if (item.isValid())
  106. return item;
  107. generatedFilesGroup.addFileAtIndex (file, -1, true);
  108. return generatedFilesGroup.findItemForFile (file);
  109. }
  110. void setExtraAppConfigFileContent (const String& content)
  111. {
  112. extraAppConfigContent = content;
  113. }
  114. static void writeAutoGenWarningComment (OutputStream& out)
  115. {
  116. out << "/*" << newLine << newLine
  117. << " IMPORTANT! This file is auto-generated each time you save your" << newLine
  118. << " project - if you alter its contents, your changes may be overwritten!" << newLine
  119. << newLine;
  120. }
  121. static const char* getGeneratedGroupID() noexcept { return "__jucelibfiles"; }
  122. Project::Item& getGeneratedCodeGroup() { return generatedFilesGroup; }
  123. static String getJuceCodeGroupName() { return "Juce Library Code"; }
  124. File getGeneratedCodeFolder() const { return generatedCodeFolder; }
  125. bool replaceFileIfDifferent (const File& f, const MemoryOutputStream& newData)
  126. {
  127. filesCreated.add (f);
  128. if (! FileHelpers::overwriteFileWithNewDataIfDifferent (f, newData))
  129. {
  130. addError ("Can't write to file: " + f.getFullPathName());
  131. return false;
  132. }
  133. return true;
  134. }
  135. static bool shouldFolderBeIgnoredWhenCopying (const File& f)
  136. {
  137. return f.getFileName() == ".git" || f.getFileName() == ".svn" || f.getFileName() == ".cvs";
  138. }
  139. bool copyFolder (const File& source, const File& dest)
  140. {
  141. if (source.isDirectory() && dest.createDirectory())
  142. {
  143. Array<File> subFiles;
  144. source.findChildFiles (subFiles, File::findFiles, false);
  145. for (int i = 0; i < subFiles.size(); ++i)
  146. {
  147. const File f (subFiles.getReference(i));
  148. const File target (dest.getChildFile (f.getFileName()));
  149. filesCreated.add (target);
  150. if (! f.copyFileTo (target))
  151. return false;
  152. }
  153. Array<File> subFolders;
  154. source.findChildFiles (subFolders, File::findDirectories, false);
  155. for (int i = 0; i < subFolders.size(); ++i)
  156. {
  157. const File f (subFolders.getReference(i));
  158. if (! shouldFolderBeIgnoredWhenCopying (f))
  159. if (! copyFolder (f, dest.getChildFile (f.getFileName())))
  160. return false;
  161. }
  162. return true;
  163. }
  164. return false;
  165. }
  166. Project& project;
  167. SortedSet<File> filesCreated;
  168. private:
  169. const File projectFile, generatedCodeFolder;
  170. Project::Item generatedFilesGroup;
  171. String extraAppConfigContent;
  172. StringArray errors;
  173. CriticalSection errorLock;
  174. File appConfigFile;
  175. bool hasBinaryData;
  176. // Recursively clears out any files in a folder that we didn't create, but avoids
  177. // any folders containing hidden files that might be used by version-control systems.
  178. bool deleteUnwantedFilesIn (const File& parent)
  179. {
  180. bool folderIsNowEmpty = true;
  181. DirectoryIterator i (parent, false, "*", File::findFilesAndDirectories);
  182. Array<File> filesToDelete;
  183. bool isFolder;
  184. while (i.next (&isFolder, nullptr, nullptr, nullptr, nullptr, nullptr))
  185. {
  186. const File f (i.getFile());
  187. if (filesCreated.contains (f) || shouldFileBeKept (f.getFileName()))
  188. {
  189. folderIsNowEmpty = false;
  190. }
  191. else if (isFolder)
  192. {
  193. if (deleteUnwantedFilesIn (f))
  194. filesToDelete.add (f);
  195. else
  196. folderIsNowEmpty = false;
  197. }
  198. else
  199. {
  200. filesToDelete.add (f);
  201. }
  202. }
  203. for (int j = filesToDelete.size(); --j >= 0;)
  204. filesToDelete.getReference(j).deleteRecursively();
  205. return folderIsNowEmpty;
  206. }
  207. static bool shouldFileBeKept (const String& filename)
  208. {
  209. static const char* filesToKeep[] = { ".svn", ".cvs", "CMakeLists.txt" };
  210. for (int i = 0; i < numElementsInArray (filesToKeep); ++i)
  211. if (filename == filesToKeep[i])
  212. return true;
  213. return false;
  214. }
  215. void writeMainProjectFile()
  216. {
  217. ScopedPointer<XmlElement> xml (project.getProjectRoot().createXml());
  218. jassert (xml != nullptr);
  219. if (xml != nullptr)
  220. {
  221. MemoryOutputStream mo;
  222. xml->writeToStream (mo, String());
  223. replaceFileIfDifferent (projectFile, mo);
  224. }
  225. }
  226. static int findLongestModuleName (const OwnedArray<LibraryModule>& modules)
  227. {
  228. int longest = 0;
  229. for (int i = modules.size(); --i >= 0;)
  230. longest = jmax (longest, modules.getUnchecked(i)->getID().length());
  231. return longest;
  232. }
  233. File getAppConfigFile() const { return generatedCodeFolder.getChildFile (project.getAppConfigFilename()); }
  234. String loadUserContentFromAppConfig() const
  235. {
  236. StringArray lines, userContent;
  237. lines.addLines (getAppConfigFile().loadFileAsString());
  238. bool foundCodeSection = false;
  239. for (int i = 0; i < lines.size(); ++i)
  240. {
  241. if (lines[i].contains ("[BEGIN_USER_CODE_SECTION]"))
  242. {
  243. for (int j = i + 1; j < lines.size() && ! lines[j].contains ("[END_USER_CODE_SECTION]"); ++j)
  244. userContent.add (lines[j]);
  245. foundCodeSection = true;
  246. break;
  247. }
  248. }
  249. if (! foundCodeSection)
  250. {
  251. userContent.add (String());
  252. userContent.add ("// (You can add your own code in this section, and the Projucer will not overwrite it)");
  253. userContent.add (String());
  254. }
  255. return userContent.joinIntoString (newLine) + newLine;
  256. }
  257. void checkModuleValidity (OwnedArray<LibraryModule>& modules)
  258. {
  259. for (LibraryModule** moduleIter = modules.begin(); moduleIter != modules.end(); ++moduleIter)
  260. {
  261. if (const LibraryModule* const module = *moduleIter)
  262. {
  263. if (! module->isValid())
  264. {
  265. addError ("At least one of your JUCE module paths is invalid!\n"
  266. "Please go to Config -> Modules and ensure each path points to the correct JUCE modules folder.");
  267. return;
  268. }
  269. }
  270. else
  271. {
  272. // this should never happen!
  273. jassertfalse;
  274. }
  275. }
  276. }
  277. void writeAppConfig (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules, const String& userContent)
  278. {
  279. writeAutoGenWarningComment (out);
  280. out << " There's a section below where you can add your own custom code safely, and the" << newLine
  281. << " Projucer will preserve the contents of that block, but the best way to change" << newLine
  282. << " any of these definitions is by using the Projucer's project settings." << newLine
  283. << newLine
  284. << " Any commented-out settings will assume their default values." << newLine
  285. << newLine
  286. << "*/" << newLine
  287. << newLine;
  288. out << "#pragma once" << newLine
  289. << newLine
  290. << "//==============================================================================" << newLine
  291. << "// [BEGIN_USER_CODE_SECTION]" << newLine
  292. << userContent
  293. << "// [END_USER_CODE_SECTION]" << newLine
  294. << newLine
  295. << "//==============================================================================" << newLine;
  296. const int longestName = findLongestModuleName (modules);
  297. for (int k = 0; k < modules.size(); ++k)
  298. {
  299. LibraryModule* const m = modules.getUnchecked(k);
  300. out << "#define JUCE_MODULE_AVAILABLE_" << m->getID()
  301. << String::repeatedString (" ", longestName + 5 - m->getID().length()) << " 1" << newLine;
  302. }
  303. out << newLine;
  304. {
  305. int isStandaloneApplication = 1;
  306. const ProjectType& type = project.getProjectType();
  307. if (type.isAudioPlugin() || type.isDynamicLibrary())
  308. isStandaloneApplication = 0;
  309. // Fabian TODO
  310. out << "//==============================================================================" << newLine
  311. << "#ifndef JUCE_STANDALONE_APPLICATION" << newLine
  312. << " #if defined(JucePlugin_Name) && defined(JucePlugin_Build_Standalone)" << newLine
  313. << " #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone" << newLine
  314. << " #else" << newLine
  315. << " #define JUCE_STANDALONE_APPLICATION " << isStandaloneApplication << newLine
  316. << " #endif" << newLine
  317. << "#endif" << newLine
  318. << newLine
  319. << "#define JUCE_GLOBAL_MODULE_SETTINGS_INCLUDED 1" << newLine;
  320. }
  321. for (int j = 0; j < modules.size(); ++j)
  322. {
  323. LibraryModule* const m = modules.getUnchecked(j);
  324. OwnedArray<Project::ConfigFlag> flags;
  325. m->getConfigFlags (project, flags);
  326. if (flags.size() > 0)
  327. {
  328. out << newLine
  329. << "//==============================================================================" << newLine
  330. << "// " << m->getID() << " flags:" << newLine;
  331. for (int i = 0; i < flags.size(); ++i)
  332. {
  333. flags.getUnchecked(i)->value.referTo (project.getConfigFlag (flags.getUnchecked(i)->symbol));
  334. const Project::ConfigFlag* const f = flags[i];
  335. const String value (project.getConfigFlag (f->symbol).toString());
  336. out << newLine
  337. << "#ifndef " << f->symbol << newLine;
  338. if (value == Project::configFlagEnabled)
  339. out << " #define " << f->symbol << " 1";
  340. else if (value == Project::configFlagDisabled)
  341. out << " #define " << f->symbol << " 0";
  342. else if (f->defaultValue.isEmpty())
  343. out << " //#define " << f->symbol;
  344. else
  345. out << " #define " << f->symbol << " " << f->defaultValue;
  346. out << newLine
  347. << "#endif" << newLine;
  348. }
  349. }
  350. }
  351. if (extraAppConfigContent.isNotEmpty())
  352. out << newLine << extraAppConfigContent.trimEnd() << newLine;
  353. }
  354. void writeAppConfigFile (const OwnedArray<LibraryModule>& modules, const String& userContent)
  355. {
  356. appConfigFile = getAppConfigFile();
  357. MemoryOutputStream mem;
  358. writeAppConfig (mem, modules, userContent);
  359. saveGeneratedFile (project.getAppConfigFilename(), mem);
  360. }
  361. void writeAppHeader (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules)
  362. {
  363. writeAutoGenWarningComment (out);
  364. out << " This is the header file that your files should include in order to get all the" << newLine
  365. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  366. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  367. << " options for your app." << newLine
  368. << newLine
  369. << "*/" << newLine << newLine;
  370. out << "#pragma once" << newLine << newLine;
  371. if (appConfigFile.exists())
  372. out << CodeHelpers::createIncludeStatement (project.getAppConfigFilename()) << newLine;
  373. if (modules.size() > 0)
  374. {
  375. out << newLine;
  376. for (int i = 0; i < modules.size(); ++i)
  377. modules.getUnchecked(i)->writeIncludes (*this, out);
  378. out << newLine;
  379. }
  380. if (hasBinaryData && project.shouldIncludeBinaryInAppConfig().getValue())
  381. out << CodeHelpers::createIncludeStatement (project.getBinaryDataHeaderFile(), appConfigFile) << newLine;
  382. out << newLine
  383. << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  384. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  385. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  386. << " using namespace juce;" << newLine
  387. << "#endif" << newLine
  388. << newLine
  389. << "#if ! JUCE_DONT_DECLARE_PROJECTINFO" << newLine
  390. << "namespace ProjectInfo" << newLine
  391. << "{" << newLine
  392. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getTitle()).quoted() << ";" << newLine
  393. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  394. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  395. << "}" << newLine
  396. << "#endif" << newLine;
  397. }
  398. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  399. {
  400. MemoryOutputStream mem;
  401. writeAppHeader (mem, modules);
  402. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  403. }
  404. void writeModuleCppWrappers (const OwnedArray<LibraryModule>& modules)
  405. {
  406. for (int j = 0; j < modules.size(); ++j)
  407. {
  408. const LibraryModule& module = *modules.getUnchecked(j);
  409. Array<LibraryModule::CompileUnit> units = module.getAllCompileUnits();
  410. for (int i = 0; i < units.size(); ++i)
  411. {
  412. const LibraryModule::CompileUnit& cu = units.getReference(i);
  413. MemoryOutputStream mem;
  414. writeAutoGenWarningComment (mem);
  415. mem << "*/" << newLine
  416. << newLine
  417. << "#include " << project.getAppConfigFilename().quoted() << newLine
  418. << "#include <";
  419. auto moduleWrapperFilename = cu.file.getFileName();
  420. // .r files require a different include scheme, with a different file name
  421. if (cu.file.getFileExtension() == ".r")
  422. moduleWrapperFilename = cu.file.getFileNameWithoutExtension() + "_r.r";
  423. else
  424. mem << module.getID() << "/";
  425. mem << cu.file.getFileName() << ">" << newLine;
  426. replaceFileIfDifferent (generatedCodeFolder.getChildFile (moduleWrapperFilename), mem);
  427. }
  428. }
  429. }
  430. void writeBinaryDataFiles()
  431. {
  432. const File binaryDataH (project.getBinaryDataHeaderFile());
  433. ResourceFile resourceFile (project);
  434. if (resourceFile.getNumFiles() > 0)
  435. {
  436. auto dataNamespace = project.binaryDataNamespace().toString().trim();
  437. if (dataNamespace.isEmpty())
  438. dataNamespace = "BinaryData";
  439. resourceFile.setClassName (dataNamespace);
  440. Array<File> binaryDataFiles;
  441. int maxSize = project.getMaxBinaryFileSize().getValue();
  442. if (maxSize <= 0)
  443. maxSize = 10 * 1024 * 1024;
  444. Result r (resourceFile.write (binaryDataFiles, maxSize));
  445. if (r.wasOk())
  446. {
  447. hasBinaryData = true;
  448. for (int i = 0; i < binaryDataFiles.size(); ++i)
  449. {
  450. const File& f = binaryDataFiles.getReference(i);
  451. filesCreated.add (f);
  452. generatedFilesGroup.addFileRetainingSortOrder (f, ! f.hasFileExtension (".h"));
  453. }
  454. }
  455. else
  456. {
  457. addError (r.getErrorMessage());
  458. }
  459. }
  460. else
  461. {
  462. for (int i = 20; --i >= 0;)
  463. project.getBinaryDataCppFile (i).deleteFile();
  464. binaryDataH.deleteFile();
  465. }
  466. }
  467. void writeReadmeFile()
  468. {
  469. MemoryOutputStream out;
  470. out << newLine
  471. << " Important Note!!" << newLine
  472. << " ================" << newLine
  473. << newLine
  474. << "The purpose of this folder is to contain files that are auto-generated by the Projucer," << newLine
  475. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  476. << "the Projucer saves your project." << newLine
  477. << newLine
  478. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  479. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  480. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  481. << "modifications after the Projucer has saved its changes)." << newLine;
  482. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  483. }
  484. void addError (const String& message)
  485. {
  486. const ScopedLock sl (errorLock);
  487. errors.add (message);
  488. }
  489. void writePluginCharacteristicsFile();
  490. void writeProjects (const OwnedArray<LibraryModule>& modules)
  491. {
  492. ThreadPool threadPool;
  493. // keep a copy of the basic generated files group, as each exporter may modify it.
  494. const ValueTree originalGeneratedGroup (generatedFilesGroup.state.createCopy());
  495. try
  496. {
  497. for (Project::ExporterIterator exporter (project); exporter.next();)
  498. {
  499. if (exporter->getTargetFolder().createDirectory())
  500. {
  501. exporter->copyMainGroupFromProject();
  502. exporter->settings = exporter->settings.createCopy();
  503. exporter->addToExtraSearchPaths (RelativePath ("JuceLibraryCode", RelativePath::projectFolder));
  504. generatedFilesGroup.state = originalGeneratedGroup.createCopy();
  505. exporter->addSettingsForProjectType (project.getProjectType());
  506. for (auto& module: modules)
  507. module->addSettingsForModuleToExporter (*exporter, *this);
  508. if (project.getProjectType().isAudioPlugin())
  509. writePluginCharacteristicsFile();
  510. generatedFilesGroup.sortAlphabetically (true, true);
  511. exporter->getAllGroups().add (generatedFilesGroup);
  512. threadPool.addJob (new ExporterJob (*this, exporter.exporter.release(), modules), true);
  513. }
  514. else
  515. {
  516. addError ("Can't create folder: " + exporter->getTargetFolder().getFullPathName());
  517. }
  518. }
  519. }
  520. catch (ProjectExporter::SaveError& saveError)
  521. {
  522. addError (saveError.message);
  523. }
  524. while (threadPool.getNumJobs() > 0)
  525. Thread::sleep (10);
  526. }
  527. class ExporterJob : public ThreadPoolJob
  528. {
  529. public:
  530. ExporterJob (ProjectSaver& ps, ProjectExporter* pe,
  531. const OwnedArray<LibraryModule>& moduleList)
  532. : ThreadPoolJob ("export"),
  533. owner (ps), exporter (pe), modules (moduleList)
  534. {
  535. }
  536. JobStatus runJob() override
  537. {
  538. try
  539. {
  540. exporter->create (modules);
  541. std::cout << "Finished saving: " << exporter->getName() << std::endl;
  542. }
  543. catch (ProjectExporter::SaveError& error)
  544. {
  545. owner.addError (error.message);
  546. }
  547. return jobHasFinished;
  548. }
  549. private:
  550. ProjectSaver& owner;
  551. ScopedPointer<ProjectExporter> exporter;
  552. const OwnedArray<LibraryModule>& modules;
  553. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ExporterJob)
  554. };
  555. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProjectSaver)
  556. };