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.

691 lines
25KB

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