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.

605 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. << "namespace ProjectInfo" << newLine
  343. << "{" << newLine
  344. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getTitle()).quoted() << ";" << newLine
  345. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  346. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  347. << "}" << newLine
  348. << newLine
  349. << "#endif // " << headerGuard << newLine;
  350. }
  351. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  352. {
  353. MemoryOutputStream mem;
  354. writeAppHeader (mem, modules);
  355. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  356. }
  357. void writeBinaryDataFiles()
  358. {
  359. const File binaryDataH (project.getBinaryDataHeaderFile());
  360. ResourceFile resourceFile (project);
  361. if (resourceFile.getNumFiles() > 0)
  362. {
  363. resourceFile.setClassName ("BinaryData");
  364. Array<File> binaryDataFiles;
  365. int maxSize = project.getMaxBinaryFileSize().getValue();
  366. if (maxSize <= 0)
  367. maxSize = 10 * 1024 * 1024;
  368. if (resourceFile.write (binaryDataFiles, maxSize))
  369. {
  370. hasBinaryData = true;
  371. for (int i = 0; i < binaryDataFiles.size(); ++i)
  372. {
  373. const File& f = binaryDataFiles.getReference(i);
  374. filesCreated.add (f);
  375. generatedFilesGroup.addFile (f, -1, ! f.hasFileExtension (".h"));
  376. }
  377. }
  378. else
  379. {
  380. addError ("Can't create binary resources file: "
  381. + project.getBinaryDataCppFile(0).getFullPathName());
  382. }
  383. }
  384. else
  385. {
  386. for (int i = 20; --i >= 0;)
  387. project.getBinaryDataCppFile (i).deleteFile();
  388. binaryDataH.deleteFile();
  389. }
  390. }
  391. void writeReadmeFile()
  392. {
  393. MemoryOutputStream out;
  394. out << newLine
  395. << " Important Note!!" << newLine
  396. << " ================" << newLine
  397. << newLine
  398. << "The purpose of this folder is to contain files that are auto-generated by the Introjucer," << newLine
  399. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  400. << "the Introjucer saves your project." << newLine
  401. << newLine
  402. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  403. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  404. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  405. << "modifications after the Introjucer has saved its changes)." << newLine;
  406. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  407. }
  408. static void sortGroupRecursively (Project::Item group)
  409. {
  410. group.sortAlphabetically (true);
  411. for (int i = group.getNumChildren(); --i >= 0;)
  412. sortGroupRecursively (group.getChild(i));
  413. }
  414. void addError (const String& message)
  415. {
  416. const ScopedLock sl (errorLock);
  417. errors.add (message);
  418. }
  419. void writeProjects (const OwnedArray<LibraryModule>& modules)
  420. {
  421. ThreadPool threadPool;
  422. // keep a copy of the basic generated files group, as each exporter may modify it.
  423. const ValueTree originalGeneratedGroup (generatedFilesGroup.state.createCopy());
  424. for (Project::ExporterIterator exporter (project); exporter.next();)
  425. {
  426. if (exporter->getTargetFolder().createDirectory())
  427. {
  428. exporter->copyMainGroupFromProject();
  429. exporter->settings = exporter->settings.createCopy();
  430. exporter->addToExtraSearchPaths (RelativePath ("JuceLibraryCode", RelativePath::projectFolder));
  431. generatedFilesGroup.state = originalGeneratedGroup.createCopy();
  432. project.getProjectType().prepareExporter (*exporter);
  433. for (int j = 0; j < modules.size(); ++j)
  434. modules.getUnchecked(j)->prepareExporter (*exporter, *this);
  435. sortGroupRecursively (generatedFilesGroup);
  436. exporter->getAllGroups().add (generatedFilesGroup);
  437. threadPool.addJob (new ExporterJob (*this, exporter.exporter.release(), modules), true);
  438. }
  439. else
  440. {
  441. addError ("Can't create folder: " + exporter->getTargetFolder().getFullPathName());
  442. }
  443. }
  444. while (threadPool.getNumJobs() > 0)
  445. Thread::sleep (10);
  446. }
  447. class ExporterJob : public ThreadPoolJob
  448. {
  449. public:
  450. ExporterJob (ProjectSaver& ps, ProjectExporter* pe,
  451. const OwnedArray<LibraryModule>& moduleList)
  452. : ThreadPoolJob ("export"),
  453. owner (ps), exporter (pe), modules (moduleList)
  454. {
  455. }
  456. JobStatus runJob()
  457. {
  458. try
  459. {
  460. exporter->create (modules);
  461. std::cout << "Finished saving: " << exporter->getName() << std::endl;
  462. }
  463. catch (ProjectExporter::SaveError& error)
  464. {
  465. owner.addError (error.message);
  466. }
  467. return jobHasFinished;
  468. }
  469. private:
  470. ProjectSaver& owner;
  471. ScopedPointer<ProjectExporter> exporter;
  472. const OwnedArray<LibraryModule>& modules;
  473. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ExporterJob)
  474. };
  475. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProjectSaver)
  476. };
  477. #endif // __JUCER_PROJECTSAVER_JUCEHEADER__