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.

829 lines
29KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include "jucer_ProjectSaver.h"
  19. #include "jucer_ProjectExport_CLion.h"
  20. #include "../Application/jucer_Application.h"
  21. static constexpr const char* generatedGroupID = "__jucelibfiles";
  22. static constexpr const char* generatedGroupUID = "__generatedcode__";
  23. //==============================================================================
  24. ProjectSaver::ProjectSaver (Project& p)
  25. : project (p),
  26. generatedCodeFolder (project.getGeneratedCodeFolder()),
  27. generatedFilesGroup (Project::Item::createGroup (project, getJuceCodeGroupName(), generatedGroupUID, true)),
  28. projectLineFeed (project.getProjectLineFeed())
  29. {
  30. generatedFilesGroup.setID (generatedGroupID);
  31. }
  32. Result ProjectSaver::save (ProjectExporter* exporterToSave)
  33. {
  34. if (! ProjucerApplication::getApp().isRunningCommandLine)
  35. {
  36. SaveThreadWithProgressWindow thread (*this, exporterToSave);
  37. thread.runThread();
  38. return thread.result;
  39. }
  40. return saveProject (exporterToSave);
  41. }
  42. Result ProjectSaver::saveResourcesOnly()
  43. {
  44. writeBinaryDataFiles();
  45. if (! errors.isEmpty())
  46. return Result::fail (errors[0]);
  47. return Result::ok();
  48. }
  49. void ProjectSaver::saveBasicProjectItems (const OwnedArray<LibraryModule>& modules, const String& appConfigUserContent)
  50. {
  51. writePluginDefines();
  52. writeAppConfigFile (modules, appConfigUserContent);
  53. writeBinaryDataFiles();
  54. writeAppHeader (modules);
  55. writeModuleCppWrappers (modules);
  56. }
  57. Result ProjectSaver::saveContentNeededForLiveBuild()
  58. {
  59. auto modules = getModules();
  60. if (errors.isEmpty())
  61. {
  62. saveBasicProjectItems (modules, loadUserContentFromAppConfig());
  63. return Result::ok();
  64. }
  65. return Result::fail (errors[0]);
  66. }
  67. Project::Item ProjectSaver::addFileToGeneratedGroup (const File& file)
  68. {
  69. auto item = generatedFilesGroup.findItemForFile (file);
  70. if (item.isValid())
  71. return item;
  72. generatedFilesGroup.addFileAtIndex (file, -1, true);
  73. return generatedFilesGroup.findItemForFile (file);
  74. }
  75. bool ProjectSaver::copyFolder (const File& source, const File& dest)
  76. {
  77. if (source.isDirectory() && dest.createDirectory())
  78. {
  79. for (auto& f : source.findChildFiles (File::findFiles, false))
  80. {
  81. auto target = dest.getChildFile (f.getFileName());
  82. filesCreated.add (target);
  83. if (! f.copyFileTo (target))
  84. return false;
  85. }
  86. for (auto& f : source.findChildFiles (File::findDirectories, false))
  87. {
  88. auto name = f.getFileName();
  89. if (name == ".git" || name == ".svn" || name == ".cvs")
  90. continue;
  91. if (! copyFolder (f, dest.getChildFile (f.getFileName())))
  92. return false;
  93. }
  94. return true;
  95. }
  96. return false;
  97. }
  98. //==============================================================================
  99. Project::Item ProjectSaver::saveGeneratedFile (const String& filePath, const MemoryOutputStream& newData)
  100. {
  101. if (! generatedCodeFolder.createDirectory())
  102. {
  103. addError ("Couldn't create folder: " + generatedCodeFolder.getFullPathName());
  104. return Project::Item (project, {}, false);
  105. }
  106. auto file = generatedCodeFolder.getChildFile (filePath);
  107. if (replaceFileIfDifferent (file, newData))
  108. return addFileToGeneratedGroup (file);
  109. return { project, {}, true };
  110. }
  111. bool ProjectSaver::replaceFileIfDifferent (const File& f, const MemoryOutputStream& newData)
  112. {
  113. filesCreated.add (f);
  114. if (! build_tools::overwriteFileWithNewDataIfDifferent (f, newData))
  115. {
  116. addError ("Can't write to file: " + f.getFullPathName());
  117. return false;
  118. }
  119. return true;
  120. }
  121. bool ProjectSaver::deleteUnwantedFilesIn (const File& parent)
  122. {
  123. // Recursively clears out any files in a folder that we didn't create, but avoids
  124. // any folders containing hidden files that might be used by version-control systems.
  125. auto shouldFileBeKept = [] (const String& filename)
  126. {
  127. static StringArray filesToKeep (".svn", ".cvs", "CMakeLists.txt");
  128. return filesToKeep.contains (filename);
  129. };
  130. bool folderIsNowEmpty = true;
  131. Array<File> filesToDelete;
  132. for (const auto& i : RangedDirectoryIterator (parent, false, "*", File::findFilesAndDirectories))
  133. {
  134. auto f = i.getFile();
  135. if (filesCreated.contains (f) || shouldFileBeKept (f.getFileName()))
  136. {
  137. folderIsNowEmpty = false;
  138. }
  139. else if (i.isDirectory())
  140. {
  141. if (deleteUnwantedFilesIn (f))
  142. filesToDelete.add (f);
  143. else
  144. folderIsNowEmpty = false;
  145. }
  146. else
  147. {
  148. filesToDelete.add (f);
  149. }
  150. }
  151. for (int j = filesToDelete.size(); --j >= 0;)
  152. filesToDelete.getReference (j).deleteRecursively();
  153. return folderIsNowEmpty;
  154. }
  155. //==============================================================================
  156. void ProjectSaver::addError (const String& message)
  157. {
  158. const ScopedLock sl (errorLock);
  159. errors.add (message);
  160. }
  161. //==============================================================================
  162. File ProjectSaver::getAppConfigFile() const
  163. {
  164. return generatedCodeFolder.getChildFile (Project::getAppConfigFilename());
  165. }
  166. File ProjectSaver::getPluginDefinesFile() const
  167. {
  168. return generatedCodeFolder.getChildFile (Project::getPluginDefinesFilename());
  169. }
  170. String ProjectSaver::loadUserContentFromAppConfig() const
  171. {
  172. StringArray userContent;
  173. bool foundCodeSection = false;
  174. auto lines = StringArray::fromLines (getAppConfigFile().loadFileAsString());
  175. for (int i = 0; i < lines.size(); ++i)
  176. {
  177. if (lines[i].contains ("[BEGIN_USER_CODE_SECTION]"))
  178. {
  179. for (int j = i + 1; j < lines.size() && ! lines[j].contains ("[END_USER_CODE_SECTION]"); ++j)
  180. userContent.add (lines[j]);
  181. foundCodeSection = true;
  182. break;
  183. }
  184. }
  185. if (! foundCodeSection)
  186. {
  187. userContent.add ({});
  188. userContent.add ("// (You can add your own code in this section, and the Projucer will not overwrite it)");
  189. userContent.add ({});
  190. }
  191. return userContent.joinIntoString (projectLineFeed) + projectLineFeed;
  192. }
  193. //==============================================================================
  194. OwnedArray<LibraryModule> ProjectSaver::getModules()
  195. {
  196. OwnedArray<LibraryModule> modules;
  197. project.getEnabledModules().createRequiredModules (modules);
  198. for (auto* module : modules)
  199. {
  200. if (! module->isValid())
  201. {
  202. addError ("At least one of your JUCE module paths is invalid!\n"
  203. "Please go to the Modules settings page and ensure each path points to the correct JUCE modules folder.");
  204. return {};
  205. }
  206. if (project.getEnabledModules().getExtraDependenciesNeeded (module->getID()).size() > 0)
  207. {
  208. addError ("At least one of your modules has missing dependencies!\n"
  209. "Please go to the settings page of the highlighted modules and add the required dependencies.");
  210. return {};
  211. }
  212. }
  213. return modules;
  214. }
  215. //==============================================================================
  216. Result ProjectSaver::saveProject (ProjectExporter* specifiedExporterToSave)
  217. {
  218. if (project.getNumExporters() == 0)
  219. {
  220. return Result::fail ("No exporters found!\n"
  221. "Please add an exporter before saving.");
  222. }
  223. auto oldProjectFile = project.getFile();
  224. auto modules = getModules();
  225. if (errors.isEmpty())
  226. {
  227. if (project.isAudioPluginProject())
  228. {
  229. if (project.shouldBuildUnityPlugin())
  230. writeUnityScriptFile();
  231. }
  232. saveBasicProjectItems (modules, loadUserContentFromAppConfig());
  233. writeProjects (modules, specifiedExporterToSave);
  234. runPostExportScript();
  235. project.writeProjectFile();
  236. if (generatedCodeFolder.exists())
  237. {
  238. writeReadmeFile();
  239. deleteUnwantedFilesIn (generatedCodeFolder);
  240. }
  241. if (errors.isEmpty())
  242. return Result::ok();
  243. }
  244. project.setFile (oldProjectFile);
  245. return Result::fail (errors[0]);
  246. }
  247. //==============================================================================
  248. static void writeAutoGenWarningComment (OutputStream& out)
  249. {
  250. out << "/*" << newLine << newLine
  251. << " IMPORTANT! This file is auto-generated each time you save your" << newLine
  252. << " project - if you alter its contents, your changes may be overwritten!" << newLine
  253. << newLine;
  254. }
  255. void ProjectSaver::writePluginDefines (MemoryOutputStream& out) const
  256. {
  257. const auto pluginDefines = getAudioPluginDefines();
  258. if (pluginDefines.isEmpty())
  259. return;
  260. writeAutoGenWarningComment (out);
  261. out << "*/" << newLine << newLine
  262. << "#pragma once" << newLine << newLine
  263. << pluginDefines << newLine;
  264. }
  265. void ProjectSaver::writeAppConfig (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules, const String& userContent)
  266. {
  267. if (! project.shouldUseAppConfig())
  268. return;
  269. writeAutoGenWarningComment (out);
  270. out << " There's a section below where you can add your own custom code safely, and the" << newLine
  271. << " Projucer will preserve the contents of that block, but the best way to change" << newLine
  272. << " any of these definitions is by using the Projucer's project settings." << newLine
  273. << newLine
  274. << " Any commented-out settings will assume their default values." << newLine
  275. << newLine
  276. << "*/" << newLine
  277. << newLine;
  278. out << "#pragma once" << newLine
  279. << newLine
  280. << "//==============================================================================" << newLine
  281. << "// [BEGIN_USER_CODE_SECTION]" << newLine
  282. << userContent
  283. << "// [END_USER_CODE_SECTION]" << newLine;
  284. if (getPluginDefinesFile().existsAsFile() && getAudioPluginDefines().isNotEmpty())
  285. out << newLine << CodeHelpers::createIncludeStatement (Project::getPluginDefinesFilename()) << newLine;
  286. out << newLine
  287. << "/*" << newLine
  288. << " ==============================================================================" << newLine
  289. << newLine
  290. << " In accordance with the terms of the JUCE 5 End-Use License Agreement, the" << newLine
  291. << " JUCE Code in SECTION A cannot be removed, changed or otherwise rendered" << newLine
  292. << " ineffective unless you have a JUCE Indie or Pro license, or are using JUCE" << newLine
  293. << " under the GPL v3 license." << newLine
  294. << newLine
  295. << " End User License Agreement: www.juce.com/juce-5-licence" << newLine
  296. << newLine
  297. << " ==============================================================================" << newLine
  298. << "*/" << newLine
  299. << newLine
  300. << "// BEGIN SECTION A" << newLine
  301. << newLine
  302. << "#ifndef JUCE_DISPLAY_SPLASH_SCREEN" << newLine
  303. << " #define JUCE_DISPLAY_SPLASH_SCREEN " << (project.shouldDisplaySplashScreen() ? "1" : "0") << newLine
  304. << "#endif" << newLine << newLine
  305. << "// END SECTION A" << newLine
  306. << newLine
  307. << "#define JUCE_USE_DARK_SPLASH_SCREEN " << (project.getSplashScreenColourString() == "Dark" ? "1" : "0") << newLine
  308. << newLine
  309. << "#define JUCE_PROJUCER_VERSION 0x" << String::toHexString (ProjectInfo::versionNumber) << newLine;
  310. out << newLine
  311. << "//==============================================================================" << newLine;
  312. auto longestModuleName = [&modules]()
  313. {
  314. int longest = 0;
  315. for (auto* module : modules)
  316. longest = jmax (longest, module->getID().length());
  317. return longest;
  318. }();
  319. for (auto* module : modules)
  320. {
  321. out << "#define JUCE_MODULE_AVAILABLE_" << module->getID()
  322. << String::repeatedString (" ", longestModuleName + 5 - module->getID().length()) << " 1" << newLine;
  323. }
  324. out << newLine << "#define JUCE_GLOBAL_MODULE_SETTINGS_INCLUDED 1" << newLine;
  325. for (auto* module : modules)
  326. {
  327. OwnedArray<Project::ConfigFlag> flags;
  328. module->getConfigFlags (project, flags);
  329. if (flags.size() > 0)
  330. {
  331. out << newLine
  332. << "//==============================================================================" << newLine
  333. << "// " << module->getID() << " flags:" << newLine;
  334. for (auto* flag : flags)
  335. {
  336. out << newLine
  337. << "#ifndef " << flag->symbol
  338. << newLine
  339. << (flag->value.isUsingDefault() ? " //#define " : " #define ") << flag->symbol << " " << (flag->value.get() ? "1" : "0")
  340. << newLine
  341. << "#endif"
  342. << newLine;
  343. }
  344. }
  345. }
  346. auto& type = project.getProjectType();
  347. auto isStandaloneApplication = (! type.isAudioPlugin() && ! type.isDynamicLibrary());
  348. out << newLine
  349. << "//==============================================================================" << newLine
  350. << "#ifndef JUCE_STANDALONE_APPLICATION" << newLine
  351. << " #if defined(JucePlugin_Name) && defined(JucePlugin_Build_Standalone)" << newLine
  352. << " #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone" << newLine
  353. << " #else" << newLine
  354. << " #define JUCE_STANDALONE_APPLICATION " << (isStandaloneApplication ? "1" : "0") << newLine
  355. << " #endif" << newLine
  356. << "#endif" << newLine;
  357. }
  358. template <typename WriterCallback>
  359. void ProjectSaver::writeOrRemoveGeneratedFile (const String& name, WriterCallback&& writerCallback)
  360. {
  361. MemoryOutputStream mem;
  362. mem.setNewLineString (projectLineFeed);
  363. writerCallback (mem);
  364. if (mem.getDataSize() != 0)
  365. {
  366. saveGeneratedFile (name, mem);
  367. return;
  368. }
  369. const auto destFile = generatedCodeFolder.getChildFile (name);
  370. if (destFile.existsAsFile())
  371. {
  372. if (! destFile.deleteFile())
  373. addError ("Couldn't remove unnecessary file: " + destFile.getFullPathName());
  374. }
  375. }
  376. void ProjectSaver::writePluginDefines()
  377. {
  378. writeOrRemoveGeneratedFile (Project::getPluginDefinesFilename(), [&] (MemoryOutputStream& mem)
  379. {
  380. writePluginDefines (mem);
  381. });
  382. }
  383. void ProjectSaver::writeAppConfigFile (const OwnedArray<LibraryModule>& modules, const String& userContent)
  384. {
  385. writeOrRemoveGeneratedFile (Project::getAppConfigFilename(), [&] (MemoryOutputStream& mem)
  386. {
  387. writeAppConfig (mem, modules, userContent);
  388. });
  389. }
  390. void ProjectSaver::writeAppHeader (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules)
  391. {
  392. writeAutoGenWarningComment (out);
  393. out << " This is the header file that your files should include in order to get all the" << newLine
  394. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  395. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  396. << " options for your app." << newLine
  397. << newLine
  398. << "*/" << newLine << newLine;
  399. out << "#pragma once" << newLine << newLine;
  400. if (getAppConfigFile().exists() && project.shouldUseAppConfig())
  401. out << CodeHelpers::createIncludeStatement (Project::getAppConfigFilename()) << newLine;
  402. if (modules.size() > 0)
  403. {
  404. out << newLine;
  405. for (auto* module : modules)
  406. module->writeIncludes (*this, out);
  407. out << newLine;
  408. }
  409. if (hasBinaryData && project.shouldIncludeBinaryInJuceHeader())
  410. out << CodeHelpers::createIncludeStatement (project.getBinaryDataHeaderFile(), getAppConfigFile()) << newLine;
  411. out << newLine
  412. << "#if defined (JUCE_PROJUCER_VERSION) && JUCE_PROJUCER_VERSION < JUCE_VERSION" << newLine
  413. << " /** If you've hit this error then the version of the Projucer that was used to generate this project is" << newLine
  414. << " older than the version of the JUCE modules being included. To fix this error, re-save your project" << newLine
  415. << " using the latest version of the Projucer or, if you aren't using the Projucer to manage your project," << newLine
  416. << " remove the JUCE_PROJUCER_VERSION define from the AppConfig.h file." << newLine
  417. << " */" << newLine
  418. << " #error \"This project was last saved using an outdated version of the Projucer! Re-save this project with the latest version to fix this error.\"" << newLine
  419. << "#endif" << newLine
  420. << newLine;
  421. if (project.shouldAddUsingNamespaceToJuceHeader())
  422. out << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  423. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  424. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  425. << " using namespace juce;" << newLine
  426. << "#endif" << newLine;
  427. out << newLine
  428. << "#if ! JUCE_DONT_DECLARE_PROJECTINFO" << newLine
  429. << "namespace ProjectInfo" << newLine
  430. << "{" << newLine
  431. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getProjectNameString()).quoted() << ";" << newLine
  432. << " const char* const companyName = " << CppTokeniserFunctions::addEscapeChars (project.getCompanyNameString()).quoted() << ";" << newLine
  433. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  434. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  435. << "}" << newLine
  436. << "#endif" << newLine;
  437. }
  438. void ProjectSaver::writeAppHeader (const OwnedArray<LibraryModule>& modules)
  439. {
  440. MemoryOutputStream mem;
  441. mem.setNewLineString (projectLineFeed);
  442. writeAppHeader (mem, modules);
  443. saveGeneratedFile (Project::getJuceSourceHFilename(), mem);
  444. }
  445. void ProjectSaver::writeModuleCppWrappers (const OwnedArray<LibraryModule>& modules)
  446. {
  447. for (auto* module : modules)
  448. {
  449. for (auto& cu : module->getAllCompileUnits())
  450. {
  451. MemoryOutputStream mem;
  452. mem.setNewLineString (projectLineFeed);
  453. writeAutoGenWarningComment (mem);
  454. mem << "*/" << newLine << newLine;
  455. if (project.shouldUseAppConfig())
  456. mem << "#include " << Project::getAppConfigFilename().quoted() << newLine;
  457. mem << "#include <";
  458. if (cu.file.getFileExtension() != ".r") // .r files are included without the path
  459. mem << module->getID() << "/";
  460. mem << cu.file.getFileName() << ">" << newLine;
  461. replaceFileIfDifferent (generatedCodeFolder.getChildFile (cu.getFilenameForProxyFile()), mem);
  462. }
  463. }
  464. }
  465. void ProjectSaver::writeBinaryDataFiles()
  466. {
  467. auto binaryDataH = project.getBinaryDataHeaderFile();
  468. JucerResourceFile resourceFile (project);
  469. if (resourceFile.getNumFiles() > 0)
  470. {
  471. auto dataNamespace = project.getBinaryDataNamespaceString().trim();
  472. if (dataNamespace.isEmpty())
  473. dataNamespace = "BinaryData";
  474. resourceFile.setClassName (dataNamespace);
  475. auto maxSize = project.getMaxBinaryFileSize();
  476. if (maxSize <= 0)
  477. maxSize = 10 * 1024 * 1024;
  478. Array<File> binaryDataFiles;
  479. auto r = resourceFile.write (maxSize);
  480. if (r.result.wasOk())
  481. {
  482. hasBinaryData = true;
  483. for (auto& f : r.filesCreated)
  484. {
  485. filesCreated.add (f);
  486. generatedFilesGroup.addFileRetainingSortOrder (f, ! f.hasFileExtension (".h"));
  487. }
  488. }
  489. else
  490. {
  491. addError (r.result.getErrorMessage());
  492. }
  493. }
  494. else
  495. {
  496. for (int i = 20; --i >= 0;)
  497. project.getBinaryDataCppFile (i).deleteFile();
  498. binaryDataH.deleteFile();
  499. }
  500. }
  501. void ProjectSaver::writeReadmeFile()
  502. {
  503. MemoryOutputStream out;
  504. out.setNewLineString (projectLineFeed);
  505. out << newLine
  506. << " Important Note!!" << newLine
  507. << " ================" << newLine
  508. << newLine
  509. << "The purpose of this folder is to contain files that are auto-generated by the Projucer," << newLine
  510. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  511. << "the Projucer saves your project." << newLine
  512. << newLine
  513. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  514. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  515. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  516. << "modifications after the Projucer has saved its changes)." << newLine;
  517. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  518. }
  519. String ProjectSaver::getAudioPluginDefines() const
  520. {
  521. const auto flags = project.getAudioPluginFlags();
  522. if (flags.size() == 0)
  523. return {};
  524. MemoryOutputStream mem;
  525. mem.setNewLineString (projectLineFeed);
  526. mem << "//==============================================================================" << newLine
  527. << "// Audio plugin settings.." << newLine
  528. << newLine;
  529. for (int i = 0; i < flags.size(); ++i)
  530. {
  531. mem << "#ifndef " << flags.getAllKeys()[i] << newLine
  532. << " #define " << flags.getAllKeys()[i].paddedRight (' ', 32) << " "
  533. << flags.getAllValues()[i] << newLine
  534. << "#endif" << newLine;
  535. }
  536. return mem.toString().trim();
  537. }
  538. void ProjectSaver::writeUnityScriptFile()
  539. {
  540. auto unityScriptContents = replaceLineFeeds (BinaryData::UnityPluginGUIScript_cs_in,
  541. projectLineFeed);
  542. auto projectName = Project::addUnityPluginPrefixIfNecessary (project.getProjectNameString());
  543. unityScriptContents = unityScriptContents.replace ("${plugin_class_name}", projectName.replace (" ", "_"))
  544. .replace ("${plugin_name}", projectName)
  545. .replace ("${plugin_vendor}", project.getPluginManufacturerString())
  546. .replace ("${plugin_description}", project.getPluginDescriptionString());
  547. auto f = generatedCodeFolder.getChildFile (project.getUnityScriptName());
  548. MemoryOutputStream out;
  549. out << unityScriptContents;
  550. replaceFileIfDifferent (f, out);
  551. }
  552. void ProjectSaver::writeProjects (const OwnedArray<LibraryModule>& modules, ProjectExporter* specifiedExporterToSave)
  553. {
  554. ThreadPool threadPool;
  555. // keep a copy of the basic generated files group, as each exporter may modify it.
  556. auto originalGeneratedGroup = generatedFilesGroup.state.createCopy();
  557. CLionProjectExporter* clionExporter = nullptr;
  558. std::vector<std::unique_ptr<ProjectExporter>> exporters;
  559. try
  560. {
  561. for (Project::ExporterIterator exp (project); exp.next();)
  562. {
  563. if (specifiedExporterToSave != nullptr && exp->getUniqueName() != specifiedExporterToSave->getUniqueName())
  564. continue;
  565. exporters.push_back (std::move (exp.exporter));
  566. }
  567. for (auto& exporter : exporters)
  568. {
  569. exporter->initialiseDependencyPathValues();
  570. if (exporter->getTargetFolder().createDirectory())
  571. {
  572. if (exporter->isCLion())
  573. {
  574. clionExporter = dynamic_cast<CLionProjectExporter*> (exporter.get());
  575. }
  576. else
  577. {
  578. exporter->copyMainGroupFromProject();
  579. exporter->settings = exporter->settings.createCopy();
  580. exporter->addToExtraSearchPaths (build_tools::RelativePath ("JuceLibraryCode", build_tools::RelativePath::projectFolder));
  581. generatedFilesGroup.state = originalGeneratedGroup.createCopy();
  582. exporter->addSettingsForProjectType (project.getProjectType());
  583. for (auto* module : modules)
  584. module->addSettingsForModuleToExporter (*exporter, *this);
  585. generatedFilesGroup.sortAlphabetically (true, true);
  586. exporter->getAllGroups().add (generatedFilesGroup);
  587. }
  588. if (ProjucerApplication::getApp().isRunningCommandLine)
  589. saveExporter (*exporter, modules);
  590. else
  591. threadPool.addJob ([this, &exporter, &modules] { saveExporter (*exporter, modules); });
  592. }
  593. else
  594. {
  595. addError ("Can't create folder: " + exporter->getTargetFolder().getFullPathName());
  596. }
  597. }
  598. }
  599. catch (build_tools::SaveError& saveError)
  600. {
  601. addError (saveError.message);
  602. }
  603. while (threadPool.getNumJobs() > 0)
  604. Thread::sleep (10);
  605. if (clionExporter != nullptr)
  606. {
  607. for (auto& exporter : exporters)
  608. clionExporter->writeCMakeListsExporterSection (exporter.get());
  609. std::cout << "Finished saving: " << clionExporter->getUniqueName() << std::endl;
  610. }
  611. }
  612. void ProjectSaver::runPostExportScript()
  613. {
  614. #if JUCE_WINDOWS
  615. auto cmdString = project.getPostExportShellCommandWinString();
  616. #else
  617. auto cmdString = project.getPostExportShellCommandPosixString();
  618. #endif
  619. auto shellCommand = cmdString.replace ("%%1%%", project.getProjectFolder().getFullPathName());
  620. if (shellCommand.isNotEmpty())
  621. {
  622. #if JUCE_WINDOWS
  623. StringArray argList ("cmd.exe", "/c");
  624. #else
  625. StringArray argList ("/bin/sh", "-c");
  626. #endif
  627. argList.add (shellCommand);
  628. ChildProcess shellProcess;
  629. if (! shellProcess.start (argList))
  630. {
  631. addError ("Failed to run shell command: " + argList.joinIntoString (" "));
  632. return;
  633. }
  634. if (! shellProcess.waitForProcessToFinish (10000))
  635. {
  636. addError ("Timeout running shell command: " + argList.joinIntoString (" "));
  637. return;
  638. }
  639. auto exitCode = shellProcess.getExitCode();
  640. if (exitCode != 0)
  641. addError ("Shell command: " + argList.joinIntoString (" ") + " failed with exit code: " + String (exitCode));
  642. }
  643. }
  644. void ProjectSaver::saveExporter (ProjectExporter& exporter, const OwnedArray<LibraryModule>& modules)
  645. {
  646. try
  647. {
  648. exporter.create (modules);
  649. if (! exporter.isCLion())
  650. {
  651. auto outputString = "Finished saving: " + exporter.getUniqueName();
  652. if (MessageManager::getInstance()->isThisTheMessageThread())
  653. std::cout << outputString << std::endl;
  654. else
  655. MessageManager::callAsync ([outputString] { std::cout << outputString << std::endl; });
  656. }
  657. }
  658. catch (build_tools::SaveError& error)
  659. {
  660. addError (error.message);
  661. }
  662. }