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.

684 lines
24KB

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