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.

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