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.

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