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.

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