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.

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