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.

706 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. #ifndef JUCER_PROJECTSAVER_H_INCLUDED
  18. #define JUCER_PROJECTSAVER_H_INCLUDED
  19. #include "jucer_ResourceFile.h"
  20. #include "../Project/jucer_Module.h"
  21. #include "jucer_ProjectExporter.h"
  22. //==============================================================================
  23. class ProjectSaver
  24. {
  25. public:
  26. ProjectSaver (Project& p, const File& file)
  27. : project (p),
  28. projectFile (file),
  29. generatedCodeFolder (project.getGeneratedCodeFolder()),
  30. generatedFilesGroup (Project::Item::createGroup (project, getJuceCodeGroupName(), "__generatedcode__", true)),
  31. hasBinaryData (false)
  32. {
  33. generatedFilesGroup.setID (getGeneratedGroupID());
  34. }
  35. struct SaveThread : public ThreadWithProgressWindow
  36. {
  37. public:
  38. SaveThread (ProjectSaver& ps)
  39. : ThreadWithProgressWindow ("Saving...", true, false),
  40. saver (ps), result (Result::ok())
  41. {}
  42. void run() override
  43. {
  44. setProgress (-1);
  45. result = saver.save (false);
  46. }
  47. ProjectSaver& saver;
  48. Result result;
  49. JUCE_DECLARE_NON_COPYABLE (SaveThread)
  50. };
  51. Result save (bool showProgressBox)
  52. {
  53. if (showProgressBox)
  54. {
  55. SaveThread thread (*this);
  56. thread.runThread();
  57. return thread.result;
  58. }
  59. const String appConfigUserContent (loadUserContentFromAppConfig());
  60. const File oldFile (project.getFile());
  61. project.setFile (projectFile);
  62. writeMainProjectFile();
  63. OwnedArray<LibraryModule> modules;
  64. project.getModules().createRequiredModules (modules);
  65. checkModuleValidity (modules);
  66. if (errors.size() == 0) writeAppConfigFile (modules, appConfigUserContent);
  67. if (errors.size() == 0) writeBinaryDataFiles();
  68. if (errors.size() == 0) writeAppHeader (modules);
  69. if (errors.size() == 0) writeModuleCppWrappers (modules);
  70. if (errors.size() == 0) writeProjects (modules);
  71. if (errors.size() == 0) writeAppConfigFile (modules, appConfigUserContent); // (this is repeated in case the projects added anything to it)
  72. if (errors.size() == 0 && generatedCodeFolder.exists())
  73. writeReadmeFile();
  74. if (generatedCodeFolder.exists())
  75. deleteUnwantedFilesIn (generatedCodeFolder);
  76. if (errors.size() > 0)
  77. {
  78. project.setFile (oldFile);
  79. return Result::fail (errors[0]);
  80. }
  81. project.updateModificationTime();
  82. return Result::ok();
  83. }
  84. Result saveResourcesOnly()
  85. {
  86. writeBinaryDataFiles();
  87. if (errors.size() > 0)
  88. return Result::fail (errors[0]);
  89. return Result::ok();
  90. }
  91. Project::Item saveGeneratedFile (const String& filePath, const MemoryOutputStream& newData)
  92. {
  93. if (! generatedCodeFolder.createDirectory())
  94. {
  95. addError ("Couldn't create folder: " + generatedCodeFolder.getFullPathName());
  96. return Project::Item (project, ValueTree(), false);
  97. }
  98. const File file (generatedCodeFolder.getChildFile (filePath));
  99. if (replaceFileIfDifferent (file, newData))
  100. return addFileToGeneratedGroup (file);
  101. return Project::Item (project, ValueTree(), true);
  102. }
  103. Project::Item addFileToGeneratedGroup (const File& file)
  104. {
  105. Project::Item item (generatedFilesGroup.findItemForFile (file));
  106. if (item.isValid())
  107. return item;
  108. generatedFilesGroup.addFileAtIndex (file, -1, true);
  109. return generatedFilesGroup.findItemForFile (file);
  110. }
  111. void setExtraAppConfigFileContent (const String& content)
  112. {
  113. extraAppConfigContent = content;
  114. }
  115. static void writeAutoGenWarningComment (OutputStream& out)
  116. {
  117. out << "/*" << newLine << newLine
  118. << " IMPORTANT! This file is auto-generated each time you save your" << newLine
  119. << " project - if you alter its contents, your changes may be overwritten!" << newLine
  120. << newLine;
  121. }
  122. static const char* getGeneratedGroupID() noexcept { return "__jucelibfiles"; }
  123. Project::Item& getGeneratedCodeGroup() { return generatedFilesGroup; }
  124. static String getJuceCodeGroupName() { return "Juce Library Code"; }
  125. File getGeneratedCodeFolder() const { return generatedCodeFolder; }
  126. bool replaceFileIfDifferent (const File& f, const MemoryOutputStream& newData)
  127. {
  128. filesCreated.add (f);
  129. if (! FileHelpers::overwriteFileWithNewDataIfDifferent (f, newData))
  130. {
  131. addError ("Can't write to file: " + f.getFullPathName());
  132. return false;
  133. }
  134. return true;
  135. }
  136. static bool shouldFolderBeIgnoredWhenCopying (const File& f)
  137. {
  138. return f.getFileName() == ".git" || f.getFileName() == ".svn" || f.getFileName() == ".cvs";
  139. }
  140. bool copyFolder (const File& source, const File& dest)
  141. {
  142. if (source.isDirectory() && dest.createDirectory())
  143. {
  144. Array<File> subFiles;
  145. source.findChildFiles (subFiles, File::findFiles, false);
  146. for (int i = 0; i < subFiles.size(); ++i)
  147. {
  148. const File f (subFiles.getReference(i));
  149. const File target (dest.getChildFile (f.getFileName()));
  150. filesCreated.add (target);
  151. if (! f.copyFileTo (target))
  152. return false;
  153. }
  154. Array<File> subFolders;
  155. source.findChildFiles (subFolders, File::findDirectories, false);
  156. for (int i = 0; i < subFolders.size(); ++i)
  157. {
  158. const File f (subFolders.getReference(i));
  159. if (! shouldFolderBeIgnoredWhenCopying (f))
  160. if (! copyFolder (f, dest.getChildFile (f.getFileName())))
  161. return false;
  162. }
  163. return true;
  164. }
  165. return false;
  166. }
  167. Project& project;
  168. SortedSet<File> filesCreated;
  169. private:
  170. const File projectFile, generatedCodeFolder;
  171. Project::Item generatedFilesGroup;
  172. String extraAppConfigContent;
  173. StringArray errors;
  174. CriticalSection errorLock;
  175. File appConfigFile;
  176. bool hasBinaryData;
  177. // Recursively clears out any files in a folder that we didn't create, but avoids
  178. // any folders containing hidden files that might be used by version-control systems.
  179. bool deleteUnwantedFilesIn (const File& parent)
  180. {
  181. bool folderIsNowEmpty = true;
  182. DirectoryIterator i (parent, false, "*", File::findFilesAndDirectories);
  183. Array<File> filesToDelete;
  184. bool isFolder;
  185. while (i.next (&isFolder, nullptr, nullptr, nullptr, nullptr, nullptr))
  186. {
  187. const File f (i.getFile());
  188. if (filesCreated.contains (f) || shouldFileBeKept (f.getFileName()))
  189. {
  190. folderIsNowEmpty = false;
  191. }
  192. else if (isFolder)
  193. {
  194. if (deleteUnwantedFilesIn (f))
  195. filesToDelete.add (f);
  196. else
  197. folderIsNowEmpty = false;
  198. }
  199. else
  200. {
  201. filesToDelete.add (f);
  202. }
  203. }
  204. for (int j = filesToDelete.size(); --j >= 0;)
  205. filesToDelete.getReference(j).deleteRecursively();
  206. return folderIsNowEmpty;
  207. }
  208. static bool shouldFileBeKept (const String& filename)
  209. {
  210. static const char* filesToKeep[] = { ".svn", ".cvs", "CMakeLists.txt" };
  211. for (int i = 0; i < numElementsInArray (filesToKeep); ++i)
  212. if (filename == filesToKeep[i])
  213. return true;
  214. return false;
  215. }
  216. void writeMainProjectFile()
  217. {
  218. ScopedPointer<XmlElement> xml (project.getProjectRoot().createXml());
  219. jassert (xml != nullptr);
  220. if (xml != nullptr)
  221. {
  222. MemoryOutputStream mo;
  223. xml->writeToStream (mo, String());
  224. replaceFileIfDifferent (projectFile, mo);
  225. }
  226. }
  227. static int findLongestModuleName (const OwnedArray<LibraryModule>& modules)
  228. {
  229. int longest = 0;
  230. for (int i = modules.size(); --i >= 0;)
  231. longest = jmax (longest, modules.getUnchecked(i)->getID().length());
  232. return longest;
  233. }
  234. File getAppConfigFile() const { return generatedCodeFolder.getChildFile (project.getAppConfigFilename()); }
  235. String loadUserContentFromAppConfig() const
  236. {
  237. StringArray lines, userContent;
  238. lines.addLines (getAppConfigFile().loadFileAsString());
  239. bool foundCodeSection = false;
  240. for (int i = 0; i < lines.size(); ++i)
  241. {
  242. if (lines[i].contains ("[BEGIN_USER_CODE_SECTION]"))
  243. {
  244. for (int j = i + 1; j < lines.size() && ! lines[j].contains ("[END_USER_CODE_SECTION]"); ++j)
  245. userContent.add (lines[j]);
  246. foundCodeSection = true;
  247. break;
  248. }
  249. }
  250. if (! foundCodeSection)
  251. {
  252. userContent.add (String());
  253. userContent.add ("// (You can add your own code in this section, and the Projucer will not overwrite it)");
  254. userContent.add (String());
  255. }
  256. return userContent.joinIntoString (newLine) + newLine;
  257. }
  258. void checkModuleValidity (OwnedArray<LibraryModule>& modules)
  259. {
  260. for (LibraryModule** moduleIter = modules.begin(); moduleIter != modules.end(); ++moduleIter)
  261. {
  262. if (const LibraryModule* const module = *moduleIter)
  263. {
  264. if (! module->isValid())
  265. {
  266. addError ("At least one of your JUCE module paths is invalid!\n"
  267. "Please go to Config -> Modules and ensure each path points to the correct JUCE modules folder.");
  268. return;
  269. }
  270. }
  271. else
  272. {
  273. // this should never happen!
  274. jassertfalse;
  275. }
  276. }
  277. }
  278. void writeAppConfig (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules, const String& userContent)
  279. {
  280. writeAutoGenWarningComment (out);
  281. out << " There's a section below where you can add your own custom code safely, and the" << newLine
  282. << " Projucer will preserve the contents of that block, but the best way to change" << newLine
  283. << " any of these definitions is by using the Projucer's project settings." << newLine
  284. << newLine
  285. << " Any commented-out settings will assume their default values." << newLine
  286. << newLine
  287. << "*/" << newLine
  288. << newLine;
  289. const String headerGuard ("__JUCE_APPCONFIG_" + project.getProjectUID().toUpperCase() + "__");
  290. out << "#ifndef " << headerGuard << newLine
  291. << "#define " << headerGuard << newLine
  292. << newLine
  293. << "//==============================================================================" << newLine
  294. << "// [BEGIN_USER_CODE_SECTION]" << newLine
  295. << userContent
  296. << "// [END_USER_CODE_SECTION]" << newLine
  297. << newLine
  298. << "//==============================================================================" << newLine;
  299. const int longestName = findLongestModuleName (modules);
  300. for (int k = 0; k < modules.size(); ++k)
  301. {
  302. LibraryModule* const m = modules.getUnchecked(k);
  303. out << "#define JUCE_MODULE_AVAILABLE_" << m->getID()
  304. << String::repeatedString (" ", longestName + 5 - m->getID().length()) << " 1" << newLine;
  305. }
  306. out << newLine;
  307. {
  308. int isStandaloneApplication = 1;
  309. const ProjectType& type = project.getProjectType();
  310. if (type.isAudioPlugin() || type.isDynamicLibrary())
  311. isStandaloneApplication = 0;
  312. // Fabian TODO
  313. out << "//==============================================================================" << newLine
  314. << "#ifndef JUCE_STANDALONE_APPLICATION" << newLine
  315. << " #ifdef JucePlugin_Build_Standalone" << newLine
  316. << " #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone" << newLine
  317. << " #else" << newLine
  318. << " #define JUCE_STANDALONE_APPLICATION " << isStandaloneApplication << newLine
  319. << " #endif" << newLine
  320. << "#endif" << newLine
  321. << newLine
  322. << "#define JUCE_GLOBAL_MODULE_SETTINGS_INCLUDED 1" << newLine;
  323. }
  324. out << newLine;
  325. for (int j = 0; j < modules.size(); ++j)
  326. {
  327. LibraryModule* const m = modules.getUnchecked(j);
  328. OwnedArray<Project::ConfigFlag> flags;
  329. m->getConfigFlags (project, flags);
  330. if (flags.size() > 0)
  331. {
  332. out << "//==============================================================================" << newLine
  333. << "// " << m->getID() << " flags:" << newLine
  334. << newLine;
  335. for (int i = 0; i < flags.size(); ++i)
  336. {
  337. flags.getUnchecked(i)->value.referTo (project.getConfigFlag (flags.getUnchecked(i)->symbol));
  338. const Project::ConfigFlag* const f = flags[i];
  339. const String value (project.getConfigFlag (f->symbol).toString());
  340. out << "#ifndef " << f->symbol << newLine;
  341. if (value == Project::configFlagEnabled)
  342. out << " #define " << f->symbol << " 1";
  343. else if (value == Project::configFlagDisabled)
  344. out << " #define " << f->symbol << " 0";
  345. else if (f->defaultValue.isEmpty())
  346. out << " //#define " << f->symbol;
  347. else
  348. out << " #define " << f->symbol << " " << f->defaultValue;
  349. out << newLine
  350. << "#endif" << newLine
  351. << newLine;
  352. }
  353. }
  354. }
  355. if (extraAppConfigContent.isNotEmpty())
  356. out << newLine << extraAppConfigContent.trimEnd() << newLine;
  357. out << newLine
  358. << "#endif // " << headerGuard << newLine;
  359. }
  360. void writeAppConfigFile (const OwnedArray<LibraryModule>& modules, const String& userContent)
  361. {
  362. appConfigFile = getAppConfigFile();
  363. MemoryOutputStream mem;
  364. writeAppConfig (mem, modules, userContent);
  365. saveGeneratedFile (project.getAppConfigFilename(), mem);
  366. }
  367. void writeAppHeader (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules)
  368. {
  369. writeAutoGenWarningComment (out);
  370. out << " This is the header file that your files should include in order to get all the" << newLine
  371. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  372. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  373. << " options for your app." << newLine
  374. << newLine
  375. << "*/" << newLine << newLine;
  376. String headerGuard ("__APPHEADERFILE_" + project.getProjectUID().toUpperCase() + "__");
  377. out << "#ifndef " << headerGuard << newLine
  378. << "#define " << headerGuard << newLine << newLine;
  379. if (appConfigFile.exists())
  380. out << CodeHelpers::createIncludeStatement (project.getAppConfigFilename()) << newLine;
  381. if (modules.size() > 0)
  382. {
  383. out << newLine;
  384. for (int i = 0; i < modules.size(); ++i)
  385. modules.getUnchecked(i)->writeIncludes (*this, out);
  386. out << newLine;
  387. }
  388. if (hasBinaryData && project.shouldIncludeBinaryInAppConfig().getValue())
  389. out << CodeHelpers::createIncludeStatement (project.getBinaryDataHeaderFile(), appConfigFile) << newLine;
  390. out << newLine
  391. << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  392. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  393. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  394. << " using namespace juce;" << newLine
  395. << "#endif" << newLine
  396. << newLine
  397. << "#if ! JUCE_DONT_DECLARE_PROJECTINFO" << newLine
  398. << "namespace ProjectInfo" << newLine
  399. << "{" << newLine
  400. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getTitle()).quoted() << ";" << newLine
  401. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  402. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  403. << "}" << newLine
  404. << "#endif" << newLine
  405. << newLine
  406. << "#endif // " << headerGuard << newLine;
  407. }
  408. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  409. {
  410. MemoryOutputStream mem;
  411. writeAppHeader (mem, modules);
  412. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  413. }
  414. void writeModuleCppWrappers (const OwnedArray<LibraryModule>& modules)
  415. {
  416. for (int j = 0; j < modules.size(); ++j)
  417. {
  418. const LibraryModule& module = *modules.getUnchecked(j);
  419. Array<LibraryModule::CompileUnit> units = module.getAllCompileUnits();
  420. for (int i = 0; i < units.size(); ++i)
  421. {
  422. const LibraryModule::CompileUnit& cu = units.getReference(i);
  423. MemoryOutputStream mem;
  424. writeAutoGenWarningComment (mem);
  425. mem << "*/" << newLine
  426. << newLine
  427. << "#include " << project.getAppConfigFilename().quoted() << newLine
  428. << "#include <" << module.getID() << "/" << cu.file.getFileName() << ">" << newLine;
  429. replaceFileIfDifferent (generatedCodeFolder.getChildFile (cu.file.getFileName()), mem);
  430. }
  431. }
  432. }
  433. void writeBinaryDataFiles()
  434. {
  435. const File binaryDataH (project.getBinaryDataHeaderFile());
  436. ResourceFile resourceFile (project);
  437. if (resourceFile.getNumFiles() > 0)
  438. {
  439. resourceFile.setClassName ("BinaryData");
  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. };
  557. #endif // JUCER_PROJECTSAVER_H_INCLUDED