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.

521 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #ifndef __JUCER_PROJECTSAVER_JUCEHEADER__
  19. #define __JUCER_PROJECTSAVER_JUCEHEADER__
  20. #include "jucer_ResourceFile.h"
  21. #include "../Project/jucer_Module.h"
  22. #include "jucer_ProjectExporter.h"
  23. //==============================================================================
  24. class ProjectSaver
  25. {
  26. public:
  27. ProjectSaver (Project& project_, const File& projectFile_)
  28. : project (project_),
  29. projectFile (projectFile_),
  30. generatedCodeFolder (project.getGeneratedCodeFolder()),
  31. generatedFilesGroup (Project::Item::createGroup (project, getJuceCodeGroupName(), "__generatedcode__"))
  32. {
  33. generatedFilesGroup.setID (getGeneratedGroupID());
  34. }
  35. Project& getProject() noexcept { return project; }
  36. struct SaveThread : public ThreadWithProgressWindow
  37. {
  38. public:
  39. SaveThread (ProjectSaver& saver_)
  40. : ThreadWithProgressWindow ("Saving...", true, false), saver (saver_)
  41. {}
  42. void run()
  43. {
  44. setProgress (-1);
  45. result = saver.save (false);
  46. }
  47. ProjectSaver& saver;
  48. String result;
  49. JUCE_DECLARE_NON_COPYABLE (SaveThread);
  50. };
  51. String save (bool showProgressBox)
  52. {
  53. if (showProgressBox)
  54. {
  55. SaveThread thread (*this);
  56. thread.runThread();
  57. return thread.result;
  58. }
  59. if (generatedCodeFolder.exists())
  60. deleteNonHiddenFilesIn (generatedCodeFolder);
  61. const File oldFile (project.getFile());
  62. project.setFile (projectFile);
  63. writeMainProjectFile();
  64. OwnedArray<LibraryModule> modules;
  65. {
  66. ModuleList moduleList;
  67. moduleList.rescan (ModuleList::getDefaultModulesFolder (&project));
  68. project.createRequiredModules (moduleList, modules);
  69. }
  70. if (errors.size() == 0)
  71. writeAppConfigFile (modules);
  72. if (errors.size() == 0)
  73. writeBinaryDataFiles();
  74. if (errors.size() == 0)
  75. writeAppHeader (modules);
  76. if (errors.size() == 0)
  77. writeProjects (modules);
  78. if (errors.size() == 0)
  79. writeAppConfigFile (modules); // (this is repeated in case the projects added anything to it)
  80. if (generatedCodeFolder.exists() && errors.size() == 0)
  81. writeReadmeFile();
  82. if (errors.size() > 0)
  83. project.setFile (oldFile);
  84. return errors[0];
  85. }
  86. String saveResourcesOnly()
  87. {
  88. writeBinaryDataFiles();
  89. return errors[0];
  90. }
  91. Project::Item saveGeneratedFile (const String& filePath, const MemoryOutputStream& newData)
  92. {
  93. if (! generatedCodeFolder.createDirectory())
  94. {
  95. addError ("Couldn't create folder: " + generatedCodeFolder.getFullPathName());
  96. return Project::Item (project, ValueTree::invalid);
  97. }
  98. const File file (generatedCodeFolder.getChildFile (filePath));
  99. if (replaceFileIfDifferent (file, newData))
  100. return addFileToGeneratedGroup (file);
  101. return Project::Item (project, ValueTree::invalid);
  102. }
  103. Project::Item addFileToGeneratedGroup (const File& file)
  104. {
  105. Project::Item item (generatedFilesGroup.findItemForFile (file));
  106. if (item.isValid())
  107. return item;
  108. generatedFilesGroup.addFile (file, -1, true);
  109. return generatedFilesGroup.findItemForFile (file);
  110. }
  111. void setExtraAppConfigFileContent (const String& content)
  112. {
  113. extraAppConfigContent = content;
  114. }
  115. static void writeAutoGenWarningComment (OutputStream& out)
  116. {
  117. out << "/*" << newLine << newLine
  118. << " IMPORTANT! This file is auto-generated each time you save your" << newLine
  119. << " project - if you alter its contents, your changes may be overwritten!" << newLine
  120. << newLine;
  121. }
  122. static const char* getGeneratedGroupID() noexcept { return "__jucelibfiles"; }
  123. Project::Item& getGeneratedCodeGroup() { return generatedFilesGroup; }
  124. static String getJuceCodeGroupName() { return "Juce Library Code"; }
  125. File getGeneratedCodeFolder() const { return generatedCodeFolder; }
  126. bool replaceFileIfDifferent (const File& f, const MemoryOutputStream& newData)
  127. {
  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. private:
  136. Project& project;
  137. const File projectFile, generatedCodeFolder;
  138. Project::Item generatedFilesGroup;
  139. String extraAppConfigContent;
  140. StringArray errors;
  141. CriticalSection errorLock;
  142. File appConfigFile, binaryDataCpp;
  143. // Recursively clears out a folder's contents, but leaves behind any folders
  144. // containing hidden files used by version-control systems.
  145. static bool deleteNonHiddenFilesIn (const File& parent)
  146. {
  147. bool folderIsNowEmpty = true;
  148. DirectoryIterator i (parent, false, "*", File::findFilesAndDirectories);
  149. Array<File> filesToDelete;
  150. bool isFolder;
  151. while (i.next (&isFolder, nullptr, nullptr, nullptr, nullptr, nullptr))
  152. {
  153. const File f (i.getFile());
  154. if (shouldFileBeKept (f.getFileName()))
  155. {
  156. folderIsNowEmpty = false;
  157. }
  158. else if (isFolder)
  159. {
  160. if (deleteNonHiddenFilesIn (f))
  161. filesToDelete.add (f);
  162. else
  163. folderIsNowEmpty = false;
  164. }
  165. else
  166. {
  167. filesToDelete.add (f);
  168. }
  169. }
  170. for (int j = filesToDelete.size(); --j >= 0;)
  171. filesToDelete.getReference(j).deleteRecursively();
  172. return folderIsNowEmpty;
  173. }
  174. static bool shouldFileBeKept (const String& filename)
  175. {
  176. const char* filesToKeep[] = { ".svn", ".cvs", "CMakeLists.txt" };
  177. for (int i = 0; i < numElementsInArray (filesToKeep); ++i)
  178. if (filename == filesToKeep[i])
  179. return true;
  180. return false;
  181. }
  182. void writeMainProjectFile()
  183. {
  184. ScopedPointer <XmlElement> xml (project.getProjectRoot().createXml());
  185. jassert (xml != nullptr);
  186. if (xml != nullptr)
  187. {
  188. MemoryOutputStream mo;
  189. xml->writeToStream (mo, String::empty);
  190. replaceFileIfDifferent (projectFile, mo);
  191. }
  192. }
  193. static int findLongestModuleName (const OwnedArray<LibraryModule>& modules)
  194. {
  195. int longest = 0;
  196. for (int i = modules.size(); --i >= 0;)
  197. longest = jmax (longest, modules.getUnchecked(i)->getID().length());
  198. return longest;
  199. }
  200. void writeAppConfig (OutputStream& out, const OwnedArray<LibraryModule>& modules)
  201. {
  202. writeAutoGenWarningComment (out);
  203. out << " If you want to change any of these values, use the Introjucer to do so," << newLine
  204. << " rather than editing this file directly!" << newLine
  205. << newLine
  206. << " Any commented-out settings will assume their default values." << newLine
  207. << newLine
  208. << "*/" << newLine
  209. << newLine;
  210. const String headerGuard ("__JUCE_APPCONFIG_" + project.getProjectUID().toUpperCase() + "__");
  211. out << "#ifndef " << headerGuard << newLine
  212. << "#define " << headerGuard << newLine
  213. << newLine
  214. << "//==============================================================================" << newLine;
  215. const int longestName = findLongestModuleName (modules);
  216. for (int k = 0; k < modules.size(); ++k)
  217. {
  218. LibraryModule* const m = modules.getUnchecked(k);
  219. out << "#define JUCE_MODULE_AVAILABLE_" << m->getID()
  220. << String::repeatedString (" ", longestName + 5 - m->getID().length()) << " 1" << newLine;
  221. }
  222. out << newLine;
  223. for (int j = 0; j < modules.size(); ++j)
  224. {
  225. LibraryModule* const m = modules.getUnchecked(j);
  226. OwnedArray <Project::ConfigFlag> flags;
  227. m->getConfigFlags (project, flags);
  228. if (flags.size() > 0)
  229. {
  230. out << "//==============================================================================" << newLine
  231. << "// " << m->getID() << " flags:" << newLine
  232. << newLine;
  233. for (int i = 0; i < flags.size(); ++i)
  234. {
  235. flags.getUnchecked(i)->value.referTo (project.getConfigFlag (flags.getUnchecked(i)->symbol));
  236. const Project::ConfigFlag* const f = flags[i];
  237. const String value (project.getConfigFlag (f->symbol).toString());
  238. out << "#ifndef " << f->symbol << newLine;
  239. if (value == Project::configFlagEnabled)
  240. out << " #define " << f->symbol << " 1";
  241. else if (value == Project::configFlagDisabled)
  242. out << " #define " << f->symbol << " 0";
  243. else
  244. out << " //#define " << f->symbol;
  245. out << newLine
  246. << "#endif" << newLine
  247. << newLine;
  248. }
  249. }
  250. }
  251. if (extraAppConfigContent.isNotEmpty())
  252. out << newLine << extraAppConfigContent.trimEnd() << newLine;
  253. out << newLine
  254. << "#endif // " << headerGuard << newLine;
  255. }
  256. void writeAppConfigFile (const OwnedArray<LibraryModule>& modules)
  257. {
  258. appConfigFile = generatedCodeFolder.getChildFile (project.getAppConfigFilename());
  259. MemoryOutputStream mem;
  260. writeAppConfig (mem, modules);
  261. saveGeneratedFile (project.getAppConfigFilename(), mem);
  262. }
  263. void writeAppHeader (OutputStream& out, const OwnedArray<LibraryModule>& modules)
  264. {
  265. writeAutoGenWarningComment (out);
  266. out << " This is the header file that your files should include in order to get all the" << newLine
  267. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  268. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  269. << " options for your app." << newLine
  270. << newLine
  271. << "*/" << newLine << newLine;
  272. String headerGuard ("__APPHEADERFILE_" + project.getProjectUID().toUpperCase() + "__");
  273. out << "#ifndef " << headerGuard << newLine
  274. << "#define " << headerGuard << newLine << newLine;
  275. if (appConfigFile.exists())
  276. out << CodeHelpers::createIncludeStatement (project.getAppConfigFilename()) << newLine;
  277. for (int i = 0; i < modules.size(); ++i)
  278. modules.getUnchecked(i)->writeIncludes (*this, out);
  279. if (binaryDataCpp.exists())
  280. out << CodeHelpers::createIncludeStatement (binaryDataCpp.withFileExtension (".h"), appConfigFile) << newLine;
  281. out << newLine
  282. << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  283. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  284. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  285. << " using namespace juce;" << newLine
  286. << "#endif" << newLine
  287. << newLine
  288. << "namespace ProjectInfo" << newLine
  289. << "{" << newLine
  290. << " const char* const projectName = " << CodeHelpers::addEscapeChars (project.getProjectName().toString()).quoted() << ";" << newLine
  291. << " const char* const versionString = " << CodeHelpers::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  292. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  293. << "}" << newLine
  294. << newLine
  295. << "#endif // " << headerGuard << newLine;
  296. }
  297. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  298. {
  299. MemoryOutputStream mem;
  300. writeAppHeader (mem, modules);
  301. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  302. }
  303. void writeBinaryDataFiles()
  304. {
  305. binaryDataCpp = generatedCodeFolder.getChildFile ("BinaryData.cpp");
  306. ResourceFile resourceFile (project);
  307. if (resourceFile.getNumFiles() > 0)
  308. {
  309. resourceFile.setClassName ("BinaryData");
  310. if (resourceFile.write (binaryDataCpp))
  311. {
  312. generatedFilesGroup.addFile (binaryDataCpp, -1, true);
  313. generatedFilesGroup.addFile (binaryDataCpp.withFileExtension (".h"), -1, false);
  314. }
  315. else
  316. {
  317. addError ("Can't create binary resources file: " + binaryDataCpp.getFullPathName());
  318. }
  319. }
  320. else
  321. {
  322. binaryDataCpp.deleteFile();
  323. binaryDataCpp.withFileExtension ("h").deleteFile();
  324. }
  325. }
  326. void writeReadmeFile()
  327. {
  328. MemoryOutputStream out;
  329. out << newLine
  330. << " Important Note!!" << newLine
  331. << " ================" << newLine
  332. << newLine
  333. << "The purpose of this folder is to contain files that are auto-generated by the Introjucer," << newLine
  334. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  335. << "the Introjucer saves your project." << newLine
  336. << newLine
  337. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  338. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  339. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  340. << "modifications after the Introjucer has saved its changes)." << newLine;
  341. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  342. }
  343. static void sortGroupRecursively (Project::Item group)
  344. {
  345. group.sortAlphabetically (true);
  346. for (int i = group.getNumChildren(); --i >= 0;)
  347. sortGroupRecursively (group.getChild(i));
  348. }
  349. void addError (const String& message)
  350. {
  351. const ScopedLock sl (errorLock);
  352. errors.add (message);
  353. }
  354. void writeProjects (const OwnedArray<LibraryModule>& modules)
  355. {
  356. ThreadPool threadPool;
  357. // keep a copy of the basic generated files group, as each exporter may modify it.
  358. const ValueTree originalGeneratedGroup (generatedFilesGroup.state.createCopy());
  359. for (Project::ExporterIterator exporter (project); exporter.next();)
  360. {
  361. if (exporter->getTargetFolder().createDirectory())
  362. {
  363. exporter->addToExtraSearchPaths (RelativePath ("JuceLibraryCode", RelativePath::projectFolder));
  364. generatedFilesGroup.state = originalGeneratedGroup.createCopy();
  365. project.getProjectType().prepareExporter (*exporter);
  366. for (int j = 0; j < modules.size(); ++j)
  367. modules.getUnchecked(j)->prepareExporter (*exporter, *this);
  368. sortGroupRecursively (generatedFilesGroup);
  369. exporter->groups.add (generatedFilesGroup);
  370. threadPool.addJob (new ExporterJob (*this, exporter.exporter.release(), modules), true);
  371. }
  372. else
  373. {
  374. addError ("Can't create folder: " + exporter->getTargetFolder().getFullPathName());
  375. }
  376. }
  377. while (threadPool.getNumJobs() > 0)
  378. Thread::sleep (10);
  379. }
  380. class ExporterJob : public ThreadPoolJob
  381. {
  382. public:
  383. ExporterJob (ProjectSaver& owner_, ProjectExporter* exporter_,
  384. const OwnedArray<LibraryModule>& modules_)
  385. : ThreadPoolJob ("export"),
  386. owner (owner_), exporter (exporter_), modules (modules_)
  387. {
  388. }
  389. JobStatus runJob()
  390. {
  391. try
  392. {
  393. exporter->create (modules);
  394. std::cout << "Finished saving: " << exporter->getName() << std::endl;
  395. }
  396. catch (ProjectExporter::SaveError& error)
  397. {
  398. owner.addError (error.message);
  399. }
  400. return jobHasFinished;
  401. }
  402. private:
  403. ProjectSaver& owner;
  404. ScopedPointer<ProjectExporter> exporter;
  405. const OwnedArray<LibraryModule>& modules;
  406. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ExporterJob);
  407. };
  408. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProjectSaver);
  409. };
  410. #endif // __JUCER_PROJECTSAVER_JUCEHEADER__