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.

877 lines
30KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. writeLV2DefinesFile();
  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 7 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-7-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::writeLV2DefinesFile()
  406. {
  407. if (! project.shouldBuildLV2())
  408. return;
  409. writeOrRemoveGeneratedFile (Project::getJuceLV2DefinesFilename(), [&] (MemoryOutputStream& mem)
  410. {
  411. writeLV2Defines (mem);
  412. });
  413. }
  414. void ProjectSaver::writeAppHeader (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules)
  415. {
  416. writeAutoGenWarningComment (out);
  417. out << " This is the header file that your files should include in order to get all the" << newLine
  418. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  419. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  420. << " options for your app." << newLine
  421. << newLine
  422. << "*/" << newLine << newLine;
  423. out << "#pragma once" << newLine << newLine;
  424. if (getAppConfigFile().exists() && project.shouldUseAppConfig())
  425. out << CodeHelpers::createIncludeStatement (Project::getAppConfigFilename()) << newLine;
  426. if (modules.size() > 0)
  427. {
  428. out << newLine;
  429. for (auto* module : modules)
  430. module->writeIncludes (*this, out);
  431. out << newLine;
  432. }
  433. if (hasBinaryData && project.shouldIncludeBinaryInJuceHeader())
  434. out << CodeHelpers::createIncludeStatement (project.getBinaryDataHeaderFile(), getAppConfigFile()) << newLine;
  435. out << newLine
  436. << "#if defined (JUCE_PROJUCER_VERSION) && JUCE_PROJUCER_VERSION < JUCE_VERSION" << newLine
  437. << " /** If you've hit this error then the version of the Projucer that was used to generate this project is" << newLine
  438. << " older than the version of the JUCE modules being included. To fix this error, re-save your project" << newLine
  439. << " using the latest version of the Projucer or, if you aren't using the Projucer to manage your project," << newLine
  440. << " remove the JUCE_PROJUCER_VERSION define." << newLine
  441. << " */" << newLine
  442. << " #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
  443. << "#endif" << newLine
  444. << newLine;
  445. if (project.shouldAddUsingNamespaceToJuceHeader())
  446. out << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  447. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  448. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  449. << " using namespace juce;" << newLine
  450. << "#endif" << newLine;
  451. out << newLine
  452. << "#if ! JUCE_DONT_DECLARE_PROJECTINFO" << newLine
  453. << "namespace ProjectInfo" << newLine
  454. << "{" << newLine
  455. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getProjectNameString()).quoted() << ";" << newLine
  456. << " const char* const companyName = " << CppTokeniserFunctions::addEscapeChars (project.getCompanyNameString()).quoted() << ";" << newLine
  457. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  458. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  459. << "}" << newLine
  460. << "#endif" << newLine;
  461. }
  462. void ProjectSaver::writeAppHeader (const OwnedArray<LibraryModule>& modules)
  463. {
  464. MemoryOutputStream mem;
  465. mem.setNewLineString (projectLineFeed);
  466. writeAppHeader (mem, modules);
  467. saveGeneratedFile (Project::getJuceSourceHFilename(), mem);
  468. }
  469. void ProjectSaver::writeModuleCppWrappers (const OwnedArray<LibraryModule>& modules)
  470. {
  471. for (auto* module : modules)
  472. {
  473. for (auto& cu : module->getAllCompileUnits())
  474. {
  475. MemoryOutputStream mem;
  476. mem.setNewLineString (projectLineFeed);
  477. writeAutoGenWarningComment (mem);
  478. mem << "*/" << newLine << newLine;
  479. if (project.shouldUseAppConfig())
  480. mem << "#include " << Project::getAppConfigFilename().quoted() << newLine;
  481. mem << "#include <";
  482. if (cu.file.getFileExtension() != ".r") // .r files are included without the path
  483. mem << module->getID() << "/";
  484. mem << cu.file.getFileName() << ">" << newLine;
  485. replaceFileIfDifferent (generatedCodeFolder.getChildFile (cu.getFilenameForProxyFile()), mem);
  486. }
  487. }
  488. }
  489. void ProjectSaver::writeBinaryDataFiles()
  490. {
  491. auto binaryDataH = project.getBinaryDataHeaderFile();
  492. JucerResourceFile resourceFile (project);
  493. if (resourceFile.getNumFiles() > 0)
  494. {
  495. auto dataNamespace = project.getBinaryDataNamespaceString().trim();
  496. if (dataNamespace.isEmpty())
  497. dataNamespace = "BinaryData";
  498. resourceFile.setClassName (dataNamespace);
  499. auto maxSize = project.getMaxBinaryFileSize();
  500. if (maxSize <= 0)
  501. maxSize = 10 * 1024 * 1024;
  502. Array<File> binaryDataFiles;
  503. auto r = resourceFile.write (maxSize);
  504. if (r.result.wasOk())
  505. {
  506. hasBinaryData = true;
  507. for (auto& f : r.filesCreated)
  508. {
  509. filesCreated.add (f);
  510. generatedFilesGroup.addFileRetainingSortOrder (f, ! f.hasFileExtension (".h"));
  511. }
  512. }
  513. else
  514. {
  515. addError (r.result.getErrorMessage());
  516. }
  517. }
  518. else
  519. {
  520. for (int i = 20; --i >= 0;)
  521. project.getBinaryDataCppFile (i).deleteFile();
  522. binaryDataH.deleteFile();
  523. }
  524. }
  525. void ProjectSaver::writeLV2Defines (MemoryOutputStream& mem)
  526. {
  527. String templateFile { BinaryData::JuceLV2Defines_h_in };
  528. const auto isValidUri = [&] (const String& text) { return URL (text).isWellFormed(); };
  529. if (! isValidUri (project.getLV2URI()))
  530. {
  531. addError ("LV2 URI is malformed.");
  532. return;
  533. }
  534. mem << templateFile.replace ("${JUCE_LV2URI}", project.getLV2URI());
  535. }
  536. void ProjectSaver::writeReadmeFile()
  537. {
  538. MemoryOutputStream out;
  539. out.setNewLineString (projectLineFeed);
  540. out << newLine
  541. << " Important Note!!" << newLine
  542. << " ================" << newLine
  543. << newLine
  544. << "The purpose of this folder is to contain files that are auto-generated by the Projucer," << newLine
  545. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  546. << "the Projucer saves your project." << newLine
  547. << newLine
  548. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  549. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  550. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  551. << "modifications after the Projucer has saved its changes)." << newLine;
  552. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  553. }
  554. String ProjectSaver::getAudioPluginDefines() const
  555. {
  556. const auto flags = project.getAudioPluginFlags();
  557. if (flags.size() == 0)
  558. return {};
  559. MemoryOutputStream mem;
  560. mem.setNewLineString (projectLineFeed);
  561. mem << "//==============================================================================" << newLine
  562. << "// Audio plugin settings.." << newLine
  563. << newLine;
  564. for (int i = 0; i < flags.size(); ++i)
  565. {
  566. mem << "#ifndef " << flags.getAllKeys()[i] << newLine
  567. << " #define " << flags.getAllKeys()[i].paddedRight (' ', 32) << " "
  568. << flags.getAllValues()[i] << newLine
  569. << "#endif" << newLine;
  570. }
  571. return mem.toString().trim();
  572. }
  573. void ProjectSaver::writeUnityScriptFile()
  574. {
  575. auto unityScriptContents = replaceLineFeeds (BinaryData::UnityPluginGUIScript_cs_in,
  576. projectLineFeed);
  577. auto projectName = Project::addUnityPluginPrefixIfNecessary (project.getProjectNameString());
  578. unityScriptContents = unityScriptContents.replace ("${plugin_class_name}", projectName.replace (" ", "_"))
  579. .replace ("${plugin_name}", projectName)
  580. .replace ("${plugin_vendor}", project.getPluginManufacturerString())
  581. .replace ("${plugin_description}", project.getPluginDescriptionString());
  582. auto f = generatedCodeFolder.getChildFile (project.getUnityScriptName());
  583. MemoryOutputStream out;
  584. out << unityScriptContents;
  585. replaceFileIfDifferent (f, out);
  586. }
  587. void ProjectSaver::writeProjects (const OwnedArray<LibraryModule>& modules, ProjectExporter* specifiedExporterToSave)
  588. {
  589. ThreadPool threadPool;
  590. // keep a copy of the basic generated files group, as each exporter may modify it.
  591. auto originalGeneratedGroup = generatedFilesGroup.state.createCopy();
  592. CLionProjectExporter* clionExporter = nullptr;
  593. std::vector<std::unique_ptr<ProjectExporter>> exporters;
  594. try
  595. {
  596. for (Project::ExporterIterator exp (project); exp.next();)
  597. {
  598. if (specifiedExporterToSave != nullptr && exp->getUniqueName() != specifiedExporterToSave->getUniqueName())
  599. continue;
  600. exporters.push_back (std::move (exp.exporter));
  601. }
  602. for (auto& exporter : exporters)
  603. {
  604. exporter->initialiseDependencyPathValues();
  605. if (exporter->getTargetFolder().createDirectory())
  606. {
  607. if (exporter->isCLion())
  608. {
  609. clionExporter = dynamic_cast<CLionProjectExporter*> (exporter.get());
  610. }
  611. else
  612. {
  613. exporter->copyMainGroupFromProject();
  614. exporter->settings = exporter->settings.createCopy();
  615. exporter->addToExtraSearchPaths (build_tools::RelativePath ("JuceLibraryCode", build_tools::RelativePath::projectFolder));
  616. generatedFilesGroup.state = originalGeneratedGroup.createCopy();
  617. exporter->addSettingsForProjectType (project.getProjectType());
  618. for (auto* module : modules)
  619. module->addSettingsForModuleToExporter (*exporter, *this);
  620. generatedFilesGroup.sortAlphabetically (true, true);
  621. exporter->getAllGroups().add (generatedFilesGroup);
  622. }
  623. if (ProjucerApplication::getApp().isRunningCommandLine)
  624. saveExporter (*exporter, modules);
  625. else
  626. threadPool.addJob ([this, &exporter, &modules] { saveExporter (*exporter, modules); });
  627. }
  628. else
  629. {
  630. addError ("Can't create folder: " + exporter->getTargetFolder().getFullPathName());
  631. }
  632. }
  633. }
  634. catch (build_tools::SaveError& saveError)
  635. {
  636. addError (saveError.message);
  637. }
  638. while (threadPool.getNumJobs() > 0)
  639. Thread::sleep (10);
  640. if (clionExporter != nullptr)
  641. {
  642. for (auto& exporter : exporters)
  643. clionExporter->writeCMakeListsExporterSection (exporter.get());
  644. std::cout << "Finished saving: " << clionExporter->getUniqueName() << std::endl;
  645. }
  646. }
  647. void ProjectSaver::runPostExportScript()
  648. {
  649. #if JUCE_WINDOWS
  650. auto cmdString = project.getPostExportShellCommandWinString();
  651. #else
  652. auto cmdString = project.getPostExportShellCommandPosixString();
  653. #endif
  654. auto shellCommand = cmdString.replace ("%%1%%", project.getProjectFolder().getFullPathName());
  655. if (shellCommand.isNotEmpty())
  656. {
  657. #if JUCE_WINDOWS
  658. StringArray argList ("cmd.exe", "/c");
  659. #else
  660. StringArray argList ("/bin/sh", "-c");
  661. #endif
  662. argList.add (shellCommand);
  663. ChildProcess shellProcess;
  664. if (! shellProcess.start (argList))
  665. {
  666. addError ("Failed to run shell command: " + argList.joinIntoString (" "));
  667. return;
  668. }
  669. if (! shellProcess.waitForProcessToFinish (10000))
  670. {
  671. addError ("Timeout running shell command: " + argList.joinIntoString (" "));
  672. return;
  673. }
  674. auto exitCode = shellProcess.getExitCode();
  675. if (exitCode != 0)
  676. addError ("Shell command: " + argList.joinIntoString (" ") + " failed with exit code: " + String (exitCode));
  677. }
  678. }
  679. void ProjectSaver::saveExporter (ProjectExporter& exporter, const OwnedArray<LibraryModule>& modules)
  680. {
  681. try
  682. {
  683. exporter.create (modules);
  684. if (! exporter.isCLion())
  685. {
  686. auto outputString = "Finished saving: " + exporter.getUniqueName();
  687. if (MessageManager::getInstance()->isThisTheMessageThread())
  688. std::cout << outputString << std::endl;
  689. else
  690. MessageManager::callAsync ([outputString] { std::cout << outputString << std::endl; });
  691. }
  692. }
  693. catch (build_tools::SaveError& error)
  694. {
  695. addError (error.message);
  696. }
  697. }