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.

607 lines
22KB

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