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.

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