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.

851 lines
30KB

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