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.

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