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.

605 lines
22KB

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