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.

656 lines
23KB

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