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.

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