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.

694 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. 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::empty);
  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::empty);
  252. userContent.add ("// (You can add your own code in this section, and the Projucer will not overwrite it)");
  253. userContent.add (String::empty);
  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. const String headerGuard ("__JUCE_APPCONFIG_" + project.getProjectUID().toUpperCase() + "__");
  289. out << "#ifndef " << headerGuard << newLine
  290. << "#define " << headerGuard << newLine
  291. << newLine
  292. << "//==============================================================================" << newLine
  293. << "// [BEGIN_USER_CODE_SECTION]" << newLine
  294. << userContent
  295. << "// [END_USER_CODE_SECTION]" << newLine
  296. << newLine
  297. << "//==============================================================================" << newLine;
  298. const int longestName = findLongestModuleName (modules);
  299. for (int k = 0; k < modules.size(); ++k)
  300. {
  301. LibraryModule* const m = modules.getUnchecked(k);
  302. out << "#define JUCE_MODULE_AVAILABLE_" << m->getID()
  303. << String::repeatedString (" ", longestName + 5 - m->getID().length()) << " 1" << newLine;
  304. }
  305. out << newLine;
  306. {
  307. int isStandaloneApplication = 1;
  308. const ProjectType& type = project.getProjectType();
  309. if (type.isAudioPlugin() || type.isDynamicLibrary())
  310. isStandaloneApplication = 0;
  311. // Fabian TODO
  312. out << "//==============================================================================" << newLine
  313. << "#ifndef JUCE_STANDALONE_APPLICATION" << newLine
  314. << " #ifdef JucePlugin_Build_Standalone" << newLine
  315. << " #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone" << newLine
  316. << " #else" << newLine
  317. << " #define JUCE_STANDALONE_APPLICATION " << isStandaloneApplication << newLine
  318. << " #endif" << newLine
  319. << "#endif" << newLine
  320. << newLine
  321. << "#define JUCE_GLOBAL_MODULE_SETTINGS_INCLUDED 1" << newLine;
  322. }
  323. out << newLine;
  324. for (int j = 0; j < modules.size(); ++j)
  325. {
  326. LibraryModule* const m = modules.getUnchecked(j);
  327. OwnedArray<Project::ConfigFlag> flags;
  328. m->getConfigFlags (project, flags);
  329. if (flags.size() > 0)
  330. {
  331. out << "//==============================================================================" << newLine
  332. << "// " << m->getID() << " flags:" << newLine
  333. << newLine;
  334. for (int i = 0; i < flags.size(); ++i)
  335. {
  336. flags.getUnchecked(i)->value.referTo (project.getConfigFlag (flags.getUnchecked(i)->symbol));
  337. const Project::ConfigFlag* const f = flags[i];
  338. const String value (project.getConfigFlag (f->symbol).toString());
  339. out << "#ifndef " << f->symbol << newLine;
  340. if (value == Project::configFlagEnabled)
  341. out << " #define " << f->symbol << " 1";
  342. else if (value == Project::configFlagDisabled)
  343. out << " #define " << f->symbol << " 0";
  344. else
  345. out << " //#define " << f->symbol;
  346. out << newLine
  347. << "#endif" << newLine
  348. << newLine;
  349. }
  350. }
  351. }
  352. if (extraAppConfigContent.isNotEmpty())
  353. out << newLine << extraAppConfigContent.trimEnd() << newLine;
  354. out << newLine
  355. << "#endif // " << headerGuard << newLine;
  356. }
  357. void writeAppConfigFile (const OwnedArray<LibraryModule>& modules, const String& userContent)
  358. {
  359. appConfigFile = getAppConfigFile();
  360. MemoryOutputStream mem;
  361. writeAppConfig (mem, modules, userContent);
  362. saveGeneratedFile (project.getAppConfigFilename(), mem);
  363. }
  364. void writeAppHeader (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules)
  365. {
  366. writeAutoGenWarningComment (out);
  367. out << " This is the header file that your files should include in order to get all the" << newLine
  368. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  369. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  370. << " options for your app." << newLine
  371. << newLine
  372. << "*/" << newLine << newLine;
  373. String headerGuard ("__APPHEADERFILE_" + project.getProjectUID().toUpperCase() + "__");
  374. out << "#ifndef " << headerGuard << newLine
  375. << "#define " << headerGuard << newLine << newLine;
  376. if (appConfigFile.exists())
  377. out << CodeHelpers::createIncludeStatement (project.getAppConfigFilename()) << newLine;
  378. if (modules.size() > 0)
  379. {
  380. out << newLine;
  381. for (int i = 0; i < modules.size(); ++i)
  382. modules.getUnchecked(i)->writeIncludes (*this, out);
  383. out << newLine;
  384. }
  385. if (hasBinaryData && project.shouldIncludeBinaryInAppConfig().getValue())
  386. out << CodeHelpers::createIncludeStatement (project.getBinaryDataHeaderFile(), appConfigFile) << newLine;
  387. out << newLine
  388. << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  389. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  390. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  391. << " using namespace juce;" << newLine
  392. << "#endif" << newLine
  393. << newLine
  394. << "#if ! JUCE_DONT_DECLARE_PROJECTINFO" << newLine
  395. << "namespace ProjectInfo" << newLine
  396. << "{" << newLine
  397. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getTitle()).quoted() << ";" << newLine
  398. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  399. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  400. << "}" << newLine
  401. << "#endif" << newLine
  402. << newLine
  403. << "#endif // " << headerGuard << newLine;
  404. }
  405. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  406. {
  407. MemoryOutputStream mem;
  408. writeAppHeader (mem, modules);
  409. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  410. }
  411. void writeModuleCppWrappers (const OwnedArray<LibraryModule>& modules)
  412. {
  413. for (int j = 0; j < modules.size(); ++j)
  414. {
  415. const LibraryModule& module = *modules.getUnchecked(j);
  416. Array<LibraryModule::CompileUnit> units = module.getAllCompileUnits();
  417. for (int i = 0; i < units.size(); ++i)
  418. {
  419. const LibraryModule::CompileUnit& cu = units.getReference(i);
  420. MemoryOutputStream mem;
  421. writeAutoGenWarningComment (mem);
  422. mem << "*/" << newLine
  423. << newLine
  424. << "#include " << project.getAppConfigFilename().quoted() << newLine
  425. << "#include <" << module.getID() << "/" << cu.file.getFileName() << ">" << newLine;
  426. replaceFileIfDifferent (generatedCodeFolder.getChildFile (cu.file.getFileName()), 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. resourceFile.setClassName ("BinaryData");
  437. Array<File> binaryDataFiles;
  438. int maxSize = project.getMaxBinaryFileSize().getValue();
  439. if (maxSize <= 0)
  440. maxSize = 10 * 1024 * 1024;
  441. Result r (resourceFile.write (binaryDataFiles, maxSize));
  442. if (r.wasOk())
  443. {
  444. hasBinaryData = true;
  445. for (int i = 0; i < binaryDataFiles.size(); ++i)
  446. {
  447. const File& f = binaryDataFiles.getReference(i);
  448. filesCreated.add (f);
  449. generatedFilesGroup.addFileRetainingSortOrder (f, ! f.hasFileExtension (".h"));
  450. }
  451. }
  452. else
  453. {
  454. addError (r.getErrorMessage());
  455. }
  456. }
  457. else
  458. {
  459. for (int i = 20; --i >= 0;)
  460. project.getBinaryDataCppFile (i).deleteFile();
  461. binaryDataH.deleteFile();
  462. }
  463. }
  464. void writeReadmeFile()
  465. {
  466. MemoryOutputStream out;
  467. out << newLine
  468. << " Important Note!!" << newLine
  469. << " ================" << newLine
  470. << newLine
  471. << "The purpose of this folder is to contain files that are auto-generated by the Projucer," << newLine
  472. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  473. << "the Projucer saves your project." << newLine
  474. << newLine
  475. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  476. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  477. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  478. << "modifications after the Projucer has saved its changes)." << newLine;
  479. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  480. }
  481. void addError (const String& message)
  482. {
  483. const ScopedLock sl (errorLock);
  484. errors.add (message);
  485. }
  486. void writePluginCharacteristicsFile();
  487. void writeProjects (const OwnedArray<LibraryModule>& modules)
  488. {
  489. ThreadPool threadPool;
  490. // keep a copy of the basic generated files group, as each exporter may modify it.
  491. const ValueTree originalGeneratedGroup (generatedFilesGroup.state.createCopy());
  492. for (Project::ExporterIterator exporter (project); exporter.next();)
  493. {
  494. if (exporter->getTargetFolder().createDirectory())
  495. {
  496. exporter->copyMainGroupFromProject();
  497. exporter->settings = exporter->settings.createCopy();
  498. exporter->addToExtraSearchPaths (RelativePath ("JuceLibraryCode", RelativePath::projectFolder));
  499. generatedFilesGroup.state = originalGeneratedGroup.createCopy();
  500. exporter->addSettingsForProjectType (project.getProjectType());
  501. for (auto& module: modules)
  502. module->addSettingsForModuleToExporter (*exporter, *this);
  503. if (project.getProjectType().isAudioPlugin())
  504. writePluginCharacteristicsFile();
  505. generatedFilesGroup.sortAlphabetically (true, true);
  506. exporter->getAllGroups().add (generatedFilesGroup);
  507. threadPool.addJob (new ExporterJob (*this, exporter.exporter.release(), modules), true);
  508. }
  509. else
  510. {
  511. addError ("Can't create folder: " + exporter->getTargetFolder().getFullPathName());
  512. }
  513. }
  514. while (threadPool.getNumJobs() > 0)
  515. Thread::sleep (10);
  516. }
  517. class ExporterJob : public ThreadPoolJob
  518. {
  519. public:
  520. ExporterJob (ProjectSaver& ps, ProjectExporter* pe,
  521. const OwnedArray<LibraryModule>& moduleList)
  522. : ThreadPoolJob ("export"),
  523. owner (ps), exporter (pe), modules (moduleList)
  524. {
  525. }
  526. JobStatus runJob() override
  527. {
  528. try
  529. {
  530. exporter->create (modules);
  531. std::cout << "Finished saving: " << exporter->getName() << std::endl;
  532. }
  533. catch (ProjectExporter::SaveError& error)
  534. {
  535. owner.addError (error.message);
  536. }
  537. return jobHasFinished;
  538. }
  539. private:
  540. ProjectSaver& owner;
  541. ScopedPointer<ProjectExporter> exporter;
  542. const OwnedArray<LibraryModule>& modules;
  543. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ExporterJob)
  544. };
  545. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProjectSaver)
  546. };
  547. #endif // JUCER_PROJECTSAVER_H_INCLUDED