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.

606 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& 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. 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)
  71. writeAppConfigFile (modules, appConfigUserContent);
  72. if (errors.size() == 0)
  73. writeBinaryDataFiles();
  74. if (errors.size() == 0)
  75. writeAppHeader (modules);
  76. if (errors.size() == 0)
  77. writeProjects (modules);
  78. if (errors.size() == 0)
  79. writeAppConfigFile (modules, appConfigUserContent); // (this is repeated in case the projects added anything to it)
  80. if (generatedCodeFolder.exists() && errors.size() == 0)
  81. writeReadmeFile();
  82. if (generatedCodeFolder.exists())
  83. deleteUnwantedFilesIn (generatedCodeFolder);
  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. File getLocalModuleFolder (const LibraryModule& m) const { return generatedCodeFolder.getChildFile ("modules").getChildFile (m.getID()); }
  134. bool replaceFileIfDifferent (const File& f, const MemoryOutputStream& newData)
  135. {
  136. filesCreated.add (f);
  137. if (! FileHelpers::overwriteFileWithNewDataIfDifferent (f, newData))
  138. {
  139. addError ("Can't write to file: " + f.getFullPathName());
  140. return false;
  141. }
  142. return true;
  143. }
  144. bool copyFolder (const File& source, const File& dest)
  145. {
  146. if (source.isDirectory() && dest.createDirectory())
  147. {
  148. Array<File> subFiles;
  149. source.findChildFiles (subFiles, File::findFiles, false);
  150. for (int i = 0; i < subFiles.size(); ++i)
  151. {
  152. const File target (dest.getChildFile (subFiles.getReference(i).getFileName()));
  153. filesCreated.add (target);
  154. if (! subFiles.getReference(i).copyFileTo (target))
  155. return false;
  156. }
  157. subFiles.clear();
  158. source.findChildFiles (subFiles, File::findDirectories, false);
  159. for (int i = 0; i < subFiles.size(); ++i)
  160. if (! copyFolder (subFiles.getReference(i), dest.getChildFile (subFiles.getReference(i).getFileName())))
  161. return false;
  162. return true;
  163. }
  164. return false;
  165. }
  166. private:
  167. Project& project;
  168. const File projectFile, generatedCodeFolder;
  169. Project::Item generatedFilesGroup;
  170. String extraAppConfigContent;
  171. StringArray errors;
  172. CriticalSection errorLock;
  173. File appConfigFile, binaryDataCpp;
  174. SortedSet<File> filesCreated;
  175. // Recursively clears out any files in a folder that we didn't create, but avoids
  176. // any folders containing hidden files that might be used by version-control systems.
  177. bool deleteUnwantedFilesIn (const File& parent)
  178. {
  179. bool folderIsNowEmpty = true;
  180. DirectoryIterator i (parent, false, "*", File::findFilesAndDirectories);
  181. Array<File> filesToDelete;
  182. bool isFolder;
  183. while (i.next (&isFolder, nullptr, nullptr, nullptr, nullptr, nullptr))
  184. {
  185. const File f (i.getFile());
  186. if (filesCreated.contains (f) || shouldFileBeKept (f.getFileName()))
  187. {
  188. folderIsNowEmpty = false;
  189. }
  190. else if (isFolder)
  191. {
  192. if (deleteUnwantedFilesIn (f))
  193. filesToDelete.add (f);
  194. else
  195. folderIsNowEmpty = false;
  196. }
  197. else
  198. {
  199. filesToDelete.add (f);
  200. }
  201. }
  202. for (int j = filesToDelete.size(); --j >= 0;)
  203. filesToDelete.getReference(j).deleteRecursively();
  204. return folderIsNowEmpty;
  205. }
  206. static bool shouldFileBeKept (const String& filename)
  207. {
  208. const char* filesToKeep[] = { ".svn", ".cvs", "CMakeLists.txt" };
  209. for (int i = 0; i < numElementsInArray (filesToKeep); ++i)
  210. if (filename == filesToKeep[i])
  211. return true;
  212. return false;
  213. }
  214. void writeMainProjectFile()
  215. {
  216. ScopedPointer <XmlElement> xml (project.getProjectRoot().createXml());
  217. jassert (xml != nullptr);
  218. if (xml != nullptr)
  219. {
  220. MemoryOutputStream mo;
  221. xml->writeToStream (mo, String::empty);
  222. replaceFileIfDifferent (projectFile, mo);
  223. }
  224. }
  225. static int findLongestModuleName (const OwnedArray<LibraryModule>& modules)
  226. {
  227. int longest = 0;
  228. for (int i = modules.size(); --i >= 0;)
  229. longest = jmax (longest, modules.getUnchecked(i)->getID().length());
  230. return longest;
  231. }
  232. File getAppConfigFile() const { return generatedCodeFolder.getChildFile (project.getAppConfigFilename()); }
  233. String loadUserContentFromAppConfig() const
  234. {
  235. StringArray lines, userContent;
  236. lines.addLines (getAppConfigFile().loadFileAsString());
  237. bool foundCodeSection = false;
  238. for (int i = 0; i < lines.size(); ++i)
  239. {
  240. if (lines[i].contains ("[BEGIN_USER_CODE_SECTION]"))
  241. {
  242. for (int j = i + 1; j < lines.size() && ! lines[j].contains ("[END_USER_CODE_SECTION]"); ++j)
  243. userContent.add (lines[j]);
  244. foundCodeSection = true;
  245. break;
  246. }
  247. }
  248. if (! foundCodeSection)
  249. {
  250. userContent.add (String::empty);
  251. userContent.add ("// (You can add your own code in this section, and the Introjucer will not overwrite it)");
  252. userContent.add (String::empty);
  253. }
  254. return userContent.joinIntoString (newLine) + newLine;
  255. }
  256. void writeAppConfig (OutputStream& out, const OwnedArray<LibraryModule>& modules, const String& userContent)
  257. {
  258. writeAutoGenWarningComment (out);
  259. out << " There's a section below where you can add your own custom code safely, and the" << newLine
  260. << " Introjucer will preserve the contents of that block, but the best way to change" << newLine
  261. << " any of these definitions is by using the Introjucer's project settings." << newLine
  262. << newLine
  263. << " Any commented-out settings will assume their default values." << newLine
  264. << newLine
  265. << "*/" << newLine
  266. << newLine;
  267. const String headerGuard ("__JUCE_APPCONFIG_" + project.getProjectUID().toUpperCase() + "__");
  268. out << "#ifndef " << headerGuard << newLine
  269. << "#define " << headerGuard << newLine
  270. << newLine
  271. << "//==============================================================================" << newLine
  272. << "// [BEGIN_USER_CODE_SECTION]" << newLine
  273. << userContent
  274. << "// [END_USER_CODE_SECTION]" << newLine
  275. << newLine
  276. << "//==============================================================================" << newLine;
  277. const int longestName = findLongestModuleName (modules);
  278. for (int k = 0; k < modules.size(); ++k)
  279. {
  280. LibraryModule* const m = modules.getUnchecked(k);
  281. out << "#define JUCE_MODULE_AVAILABLE_" << m->getID()
  282. << String::repeatedString (" ", longestName + 5 - m->getID().length()) << " 1" << newLine;
  283. }
  284. out << newLine;
  285. for (int j = 0; j < modules.size(); ++j)
  286. {
  287. LibraryModule* const m = modules.getUnchecked(j);
  288. OwnedArray <Project::ConfigFlag> flags;
  289. m->getConfigFlags (project, flags);
  290. if (flags.size() > 0)
  291. {
  292. out << "//==============================================================================" << newLine
  293. << "// " << m->getID() << " flags:" << newLine
  294. << newLine;
  295. for (int i = 0; i < flags.size(); ++i)
  296. {
  297. flags.getUnchecked(i)->value.referTo (project.getConfigFlag (flags.getUnchecked(i)->symbol));
  298. const Project::ConfigFlag* const f = flags[i];
  299. const String value (project.getConfigFlag (f->symbol).toString());
  300. out << "#ifndef " << f->symbol << newLine;
  301. if (value == Project::configFlagEnabled)
  302. out << " #define " << f->symbol << " 1";
  303. else if (value == Project::configFlagDisabled)
  304. out << " #define " << f->symbol << " 0";
  305. else
  306. out << " //#define " << f->symbol;
  307. out << newLine
  308. << "#endif" << newLine
  309. << newLine;
  310. }
  311. }
  312. }
  313. if (extraAppConfigContent.isNotEmpty())
  314. out << newLine << extraAppConfigContent.trimEnd() << newLine;
  315. out << newLine
  316. << "#endif // " << headerGuard << newLine;
  317. }
  318. void writeAppConfigFile (const OwnedArray<LibraryModule>& modules, const String& userContent)
  319. {
  320. appConfigFile = getAppConfigFile();
  321. MemoryOutputStream mem;
  322. writeAppConfig (mem, modules, userContent);
  323. saveGeneratedFile (project.getAppConfigFilename(), mem);
  324. }
  325. void writeAppHeader (OutputStream& out, const OwnedArray<LibraryModule>& modules)
  326. {
  327. writeAutoGenWarningComment (out);
  328. out << " This is the header file that your files should include in order to get all the" << newLine
  329. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  330. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  331. << " options for your app." << newLine
  332. << newLine
  333. << "*/" << newLine << newLine;
  334. String headerGuard ("__APPHEADERFILE_" + project.getProjectUID().toUpperCase() + "__");
  335. out << "#ifndef " << headerGuard << newLine
  336. << "#define " << headerGuard << newLine << newLine;
  337. if (appConfigFile.exists())
  338. out << CodeHelpers::createIncludeStatement (project.getAppConfigFilename()) << newLine;
  339. for (int i = 0; i < modules.size(); ++i)
  340. modules.getUnchecked(i)->writeIncludes (*this, out);
  341. if (binaryDataCpp.exists())
  342. out << CodeHelpers::createIncludeStatement (binaryDataCpp.withFileExtension (".h"), appConfigFile) << newLine;
  343. out << newLine
  344. << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  345. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  346. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  347. << " using namespace juce;" << newLine
  348. << "#endif" << newLine
  349. << newLine
  350. << "namespace ProjectInfo" << newLine
  351. << "{" << newLine
  352. << " const char* const projectName = " << CodeHelpers::addEscapeChars (project.getTitle()).quoted() << ";" << newLine
  353. << " const char* const versionString = " << CodeHelpers::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  354. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  355. << "}" << newLine
  356. << newLine
  357. << "#endif // " << headerGuard << newLine;
  358. }
  359. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  360. {
  361. MemoryOutputStream mem;
  362. writeAppHeader (mem, modules);
  363. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  364. }
  365. void writeBinaryDataFiles()
  366. {
  367. binaryDataCpp = project.getBinaryDataCppFile();
  368. const File binaryDataH (binaryDataCpp.withFileExtension (".h"));
  369. ResourceFile resourceFile (project);
  370. if (resourceFile.getNumFiles() > 0)
  371. {
  372. resourceFile.setClassName ("BinaryData");
  373. if (resourceFile.write (binaryDataCpp))
  374. {
  375. filesCreated.add (binaryDataH);
  376. filesCreated.add (binaryDataCpp);
  377. generatedFilesGroup.addFile (binaryDataCpp, -1, true);
  378. generatedFilesGroup.addFile (binaryDataH, -1, false);
  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& owner_, ProjectExporter* exporter_,
  451. const OwnedArray<LibraryModule>& modules_)
  452. : ThreadPoolJob ("export"),
  453. owner (owner_), exporter (exporter_), modules (modules_)
  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__