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.

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