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.

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