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.

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