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.

597 lines
21KB

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