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.

633 lines
22KB

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