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.

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