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.

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