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.

559 lines
20KB

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