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.

803 lines
29KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #pragma once
  20. #include "jucer_ResourceFile.h"
  21. #include "../Project/jucer_Module.h"
  22. #include "jucer_ProjectExporter.h"
  23. //==============================================================================
  24. class ProjectSaver
  25. {
  26. public:
  27. ProjectSaver (Project& p, const File& file)
  28. : project (p),
  29. projectFile (file),
  30. generatedCodeFolder (project.getGeneratedCodeFolder()),
  31. generatedFilesGroup (Project::Item::createGroup (project, getJuceCodeGroupName(), "__generatedcode__", true))
  32. {
  33. generatedFilesGroup.setID (getGeneratedGroupID());
  34. }
  35. struct SaveThread : public ThreadWithProgressWindow
  36. {
  37. public:
  38. SaveThread (ProjectSaver& ps, bool wait, const String& exp)
  39. : ThreadWithProgressWindow ("Saving...", true, false),
  40. saver (ps),
  41. shouldWaitAfterSaving (wait),
  42. specifiedExporterToSave (exp)
  43. {}
  44. void run() override
  45. {
  46. setProgress (-1);
  47. result = saver.save (false, shouldWaitAfterSaving, specifiedExporterToSave);
  48. }
  49. ProjectSaver& saver;
  50. Result result = Result::ok();
  51. bool shouldWaitAfterSaving;
  52. String specifiedExporterToSave;
  53. JUCE_DECLARE_NON_COPYABLE (SaveThread)
  54. };
  55. Result save (bool showProgressBox, bool waitAfterSaving, const String& specifiedExporterToSave)
  56. {
  57. if (showProgressBox)
  58. {
  59. SaveThread thread (*this, waitAfterSaving, specifiedExporterToSave);
  60. thread.runThread();
  61. return thread.result;
  62. }
  63. projectLineFeed = project.getProjectLineFeed();
  64. auto appConfigUserContent = loadUserContentFromAppConfig();
  65. auto oldFile = project.getFile();
  66. project.setFile (projectFile);
  67. OwnedArray<LibraryModule> modules;
  68. project.getEnabledModules().createRequiredModules (modules);
  69. checkModuleValidity (modules);
  70. if (errors.size() == 0)
  71. {
  72. writeMainProjectFile();
  73. project.updateModificationTime();
  74. auto projectRootHash = project.getProjectRoot().toXmlString().hashCode();
  75. if (project.getProjectType().isAudioPlugin())
  76. {
  77. writePluginCharacteristicsFile();
  78. if (project.shouldBuildUnityPlugin())
  79. writeUnityScriptFile();
  80. }
  81. writeAppConfigFile (modules, appConfigUserContent);
  82. writeBinaryDataFiles();
  83. writeAppHeader (modules);
  84. writeModuleCppWrappers (modules);
  85. writeProjects (modules, specifiedExporterToSave, ! showProgressBox);
  86. runPostExportScript();
  87. // if the project root has changed after writing the other files then re-save it
  88. if (project.getProjectRoot().toXmlString().hashCode() != projectRootHash)
  89. {
  90. writeMainProjectFile();
  91. project.updateModificationTime();
  92. }
  93. if (generatedCodeFolder.exists())
  94. {
  95. writeReadmeFile();
  96. deleteUnwantedFilesIn (generatedCodeFolder);
  97. }
  98. if (errors.size() == 0)
  99. {
  100. // Workaround for a bug where Xcode thinks the project is invalid if opened immediately
  101. // after writing
  102. if (waitAfterSaving)
  103. Thread::sleep (2000);
  104. return Result::ok();
  105. }
  106. }
  107. project.setFile (oldFile);
  108. return Result::fail (errors[0]);
  109. }
  110. Result saveResourcesOnly()
  111. {
  112. writeBinaryDataFiles();
  113. if (errors.size() > 0)
  114. return Result::fail (errors[0]);
  115. return Result::ok();
  116. }
  117. Result saveContentNeededForLiveBuild()
  118. {
  119. OwnedArray<LibraryModule> modules;
  120. project.getEnabledModules().createRequiredModules (modules);
  121. checkModuleValidity (modules);
  122. if (errors.size() == 0)
  123. {
  124. if (project.getProjectType().isAudioPlugin())
  125. writePluginCharacteristicsFile();
  126. writeAppConfigFile (modules, loadUserContentFromAppConfig());
  127. writeBinaryDataFiles();
  128. writeAppHeader (modules);
  129. writeModuleCppWrappers (modules);
  130. return Result::ok();
  131. }
  132. return Result::fail (errors[0]);
  133. }
  134. Project::Item saveGeneratedFile (const String& filePath, const MemoryOutputStream& newData)
  135. {
  136. if (! generatedCodeFolder.createDirectory())
  137. {
  138. addError ("Couldn't create folder: " + generatedCodeFolder.getFullPathName());
  139. return Project::Item (project, ValueTree(), false);
  140. }
  141. auto file = generatedCodeFolder.getChildFile (filePath);
  142. if (replaceFileIfDifferent (file, newData))
  143. return addFileToGeneratedGroup (file);
  144. return { project, {}, true };
  145. }
  146. Project::Item addFileToGeneratedGroup (const File& file)
  147. {
  148. auto item = generatedFilesGroup.findItemForFile (file);
  149. if (item.isValid())
  150. return item;
  151. generatedFilesGroup.addFileAtIndex (file, -1, true);
  152. return generatedFilesGroup.findItemForFile (file);
  153. }
  154. void setExtraAppConfigFileContent (const String& content)
  155. {
  156. extraAppConfigContent = content;
  157. }
  158. static void writeAutoGenWarningComment (OutputStream& out)
  159. {
  160. out << "/*" << newLine << newLine
  161. << " IMPORTANT! This file is auto-generated each time you save your" << newLine
  162. << " project - if you alter its contents, your changes may be overwritten!" << newLine
  163. << newLine;
  164. }
  165. static const char* getGeneratedGroupID() noexcept { return "__jucelibfiles"; }
  166. Project::Item& getGeneratedCodeGroup() { return generatedFilesGroup; }
  167. static String getJuceCodeGroupName() { return "JUCE Library Code"; }
  168. File getGeneratedCodeFolder() const { return generatedCodeFolder; }
  169. bool replaceFileIfDifferent (const File& f, const MemoryOutputStream& newData)
  170. {
  171. filesCreated.add (f);
  172. if (! FileHelpers::overwriteFileWithNewDataIfDifferent (f, newData))
  173. {
  174. addError ("Can't write to file: " + f.getFullPathName());
  175. return false;
  176. }
  177. return true;
  178. }
  179. static bool shouldFolderBeIgnoredWhenCopying (const File& f)
  180. {
  181. return f.getFileName() == ".git" || f.getFileName() == ".svn" || f.getFileName() == ".cvs";
  182. }
  183. bool copyFolder (const File& source, const File& dest)
  184. {
  185. if (source.isDirectory() && dest.createDirectory())
  186. {
  187. for (auto& f : source.findChildFiles (File::findFiles, false))
  188. {
  189. auto target = dest.getChildFile (f.getFileName());
  190. filesCreated.add (target);
  191. if (! f.copyFileTo (target))
  192. return false;
  193. }
  194. for (auto& f : source.findChildFiles (File::findDirectories, false))
  195. if (! shouldFolderBeIgnoredWhenCopying (f))
  196. if (! copyFolder (f, dest.getChildFile (f.getFileName())))
  197. return false;
  198. return true;
  199. }
  200. return false;
  201. }
  202. Project& project;
  203. SortedSet<File> filesCreated;
  204. private:
  205. const File projectFile, generatedCodeFolder;
  206. Project::Item generatedFilesGroup;
  207. String extraAppConfigContent;
  208. StringArray errors;
  209. CriticalSection errorLock;
  210. File appConfigFile;
  211. bool hasBinaryData = false;
  212. String projectLineFeed = "\r\n";
  213. // Recursively clears out any files in a folder that we didn't create, but avoids
  214. // any folders containing hidden files that might be used by version-control systems.
  215. bool deleteUnwantedFilesIn (const File& parent)
  216. {
  217. bool folderIsNowEmpty = true;
  218. DirectoryIterator i (parent, false, "*", File::findFilesAndDirectories);
  219. Array<File> filesToDelete;
  220. bool isFolder;
  221. while (i.next (&isFolder, nullptr, nullptr, nullptr, nullptr, nullptr))
  222. {
  223. auto f = i.getFile();
  224. if (filesCreated.contains (f) || shouldFileBeKept (f.getFileName()))
  225. {
  226. folderIsNowEmpty = false;
  227. }
  228. else if (isFolder)
  229. {
  230. if (deleteUnwantedFilesIn (f))
  231. filesToDelete.add (f);
  232. else
  233. folderIsNowEmpty = false;
  234. }
  235. else
  236. {
  237. filesToDelete.add (f);
  238. }
  239. }
  240. for (int j = filesToDelete.size(); --j >= 0;)
  241. filesToDelete.getReference(j).deleteRecursively();
  242. return folderIsNowEmpty;
  243. }
  244. static bool shouldFileBeKept (const String& filename)
  245. {
  246. static const char* filesToKeep[] = { ".svn", ".cvs", "CMakeLists.txt" };
  247. for (auto* f : filesToKeep)
  248. if (filename == f)
  249. return true;
  250. return false;
  251. }
  252. void writeMainProjectFile()
  253. {
  254. if (auto xml = project.getProjectRoot().createXml())
  255. {
  256. XmlElement::TextFormat format;
  257. format.newLineChars = projectLineFeed.toRawUTF8();
  258. MemoryOutputStream mo (8192);
  259. xml->writeTo (mo, format);
  260. replaceFileIfDifferent (projectFile, mo);
  261. }
  262. else
  263. {
  264. jassertfalse;
  265. }
  266. }
  267. static int findLongestModuleName (const OwnedArray<LibraryModule>& modules)
  268. {
  269. int longest = 0;
  270. for (auto& m : modules)
  271. longest = jmax (longest, m->getID().length());
  272. return longest;
  273. }
  274. File getAppConfigFile() const { return generatedCodeFolder.getChildFile (project.getAppConfigFilename()); }
  275. String loadUserContentFromAppConfig() const
  276. {
  277. StringArray userContent;
  278. bool foundCodeSection = false;
  279. auto lines = StringArray::fromLines (getAppConfigFile().loadFileAsString());
  280. for (int i = 0; i < lines.size(); ++i)
  281. {
  282. if (lines[i].contains ("[BEGIN_USER_CODE_SECTION]"))
  283. {
  284. for (int j = i + 1; j < lines.size() && ! lines[j].contains ("[END_USER_CODE_SECTION]"); ++j)
  285. userContent.add (lines[j]);
  286. foundCodeSection = true;
  287. break;
  288. }
  289. }
  290. if (! foundCodeSection)
  291. {
  292. userContent.add ({});
  293. userContent.add ("// (You can add your own code in this section, and the Projucer will not overwrite it)");
  294. userContent.add ({});
  295. }
  296. return userContent.joinIntoString (projectLineFeed) + projectLineFeed;
  297. }
  298. void checkModuleValidity (OwnedArray<LibraryModule>& modules)
  299. {
  300. if (project.getNumExporters() == 0)
  301. {
  302. addError ("No exporters found!\n"
  303. "Please add an exporter before saving.");
  304. return;
  305. }
  306. for (auto moduleIter = modules.begin(); moduleIter != modules.end(); ++moduleIter)
  307. {
  308. if (auto* module = *moduleIter)
  309. {
  310. if (! module->isValid())
  311. {
  312. addError ("At least one of your JUCE module paths is invalid!\n"
  313. "Please go to the Modules settings page and ensure each path points to the correct JUCE modules folder.");
  314. return;
  315. }
  316. if (project.getEnabledModules().getExtraDependenciesNeeded (module->getID()).size() > 0)
  317. {
  318. addError ("At least one of your modules has missing dependencies!\n"
  319. "Please go to the settings page of the highlighted modules and add the required dependencies.");
  320. return;
  321. }
  322. }
  323. else
  324. {
  325. // this should never happen!
  326. jassertfalse;
  327. }
  328. }
  329. }
  330. void writeAppConfig (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules, const String& userContent)
  331. {
  332. writeAutoGenWarningComment (out);
  333. out << " There's a section below where you can add your own custom code safely, and the" << newLine
  334. << " Projucer will preserve the contents of that block, but the best way to change" << newLine
  335. << " any of these definitions is by using the Projucer's project settings." << newLine
  336. << newLine
  337. << " Any commented-out settings will assume their default values." << newLine
  338. << newLine
  339. << "*/" << newLine
  340. << newLine;
  341. out << "#pragma once" << newLine
  342. << newLine
  343. << "//==============================================================================" << newLine
  344. << "// [BEGIN_USER_CODE_SECTION]" << newLine
  345. << userContent
  346. << "// [END_USER_CODE_SECTION]" << newLine;
  347. out << newLine
  348. << "/*" << newLine
  349. << " ==============================================================================" << newLine
  350. << newLine
  351. << " In accordance with the terms of the JUCE 5 End-Use License Agreement, the" << newLine
  352. << " JUCE Code in SECTION A cannot be removed, changed or otherwise rendered" << newLine
  353. << " ineffective unless you have a JUCE Indie or Pro license, or are using JUCE" << newLine
  354. << " under the GPL v3 license." << newLine
  355. << newLine
  356. << " End User License Agreement: www.juce.com/juce-5-licence" << newLine
  357. << newLine
  358. << " ==============================================================================" << newLine
  359. << "*/" << newLine
  360. << newLine
  361. << "// BEGIN SECTION A" << newLine
  362. << newLine
  363. << "#ifndef JUCE_DISPLAY_SPLASH_SCREEN" << newLine
  364. << " #define JUCE_DISPLAY_SPLASH_SCREEN " << (project.shouldDisplaySplashScreen() ? "1" : "0") << newLine
  365. << "#endif" << newLine << newLine
  366. << "#ifndef JUCE_REPORT_APP_USAGE" << newLine
  367. << " #define JUCE_REPORT_APP_USAGE " << (project.shouldReportAppUsage() ? "1" : "0") << newLine
  368. << "#endif" << newLine
  369. << newLine
  370. << "// END SECTION A" << newLine
  371. << newLine
  372. << "#define JUCE_USE_DARK_SPLASH_SCREEN " << (project.getSplashScreenColourString() == "Dark" ? "1" : "0") << newLine
  373. << newLine
  374. << "#define JUCE_PROJUCER_VERSION 0x" << String::toHexString (ProjectInfo::versionNumber) << newLine;
  375. out << newLine
  376. << "//==============================================================================" << newLine;
  377. auto longestName = findLongestModuleName (modules);
  378. for (auto& m : modules)
  379. out << "#define JUCE_MODULE_AVAILABLE_" << m->getID()
  380. << String::repeatedString (" ", longestName + 5 - m->getID().length()) << " 1" << newLine;
  381. out << newLine << "#define JUCE_GLOBAL_MODULE_SETTINGS_INCLUDED 1" << newLine;
  382. for (auto& m : modules)
  383. {
  384. OwnedArray<Project::ConfigFlag> flags;
  385. m->getConfigFlags (project, flags);
  386. if (flags.size() > 0)
  387. {
  388. out << newLine
  389. << "//==============================================================================" << newLine
  390. << "// " << m->getID() << " flags:" << newLine;
  391. for (auto* flag : flags)
  392. {
  393. out << newLine
  394. << "#ifndef " << flag->symbol
  395. << newLine
  396. << (flag->value.isUsingDefault() ? " //#define " : " #define ") << flag->symbol << " " << (flag->value.get() ? "1" : "0")
  397. << newLine
  398. << "#endif"
  399. << newLine;
  400. }
  401. }
  402. }
  403. if (extraAppConfigContent.isNotEmpty())
  404. out << newLine << extraAppConfigContent.trimEnd() << newLine;
  405. {
  406. auto& type = project.getProjectType();
  407. auto isStandaloneApplication = (! type.isAudioPlugin() && ! type.isDynamicLibrary());
  408. out << newLine
  409. << "//==============================================================================" << newLine
  410. << "#ifndef JUCE_STANDALONE_APPLICATION" << newLine
  411. << " #if defined(JucePlugin_Name) && defined(JucePlugin_Build_Standalone)" << newLine
  412. << " #define JUCE_STANDALONE_APPLICATION JucePlugin_Build_Standalone" << newLine
  413. << " #else" << newLine
  414. << " #define JUCE_STANDALONE_APPLICATION " << (isStandaloneApplication ? "1" : "0") << newLine
  415. << " #endif" << newLine
  416. << "#endif" << newLine;
  417. }
  418. }
  419. void writeAppConfigFile (const OwnedArray<LibraryModule>& modules, const String& userContent)
  420. {
  421. appConfigFile = getAppConfigFile();
  422. MemoryOutputStream mem;
  423. mem.setNewLineString (projectLineFeed);
  424. writeAppConfig (mem, modules, userContent);
  425. saveGeneratedFile (project.getAppConfigFilename(), mem);
  426. }
  427. void writeAppHeader (MemoryOutputStream& out, const OwnedArray<LibraryModule>& modules)
  428. {
  429. writeAutoGenWarningComment (out);
  430. out << " This is the header file that your files should include in order to get all the" << newLine
  431. << " JUCE library headers. You should avoid including the JUCE headers directly in" << newLine
  432. << " your own source files, because that wouldn't pick up the correct configuration" << newLine
  433. << " options for your app." << newLine
  434. << newLine
  435. << "*/" << newLine << newLine;
  436. out << "#pragma once" << newLine << newLine;
  437. if (appConfigFile.exists())
  438. out << CodeHelpers::createIncludeStatement (project.getAppConfigFilename()) << newLine;
  439. if (modules.size() > 0)
  440. {
  441. out << newLine;
  442. for (int i = 0; i < modules.size(); ++i)
  443. modules.getUnchecked(i)->writeIncludes (*this, out);
  444. out << newLine;
  445. }
  446. if (hasBinaryData && project.shouldIncludeBinaryInJuceHeader())
  447. out << CodeHelpers::createIncludeStatement (project.getBinaryDataHeaderFile(), appConfigFile) << newLine;
  448. out << newLine
  449. << "#if defined (JUCE_PROJUCER_VERSION) && JUCE_PROJUCER_VERSION < JUCE_VERSION" << newLine
  450. << " /** If you've hit this error then the version of the Projucer that was used to generate this project is" << newLine
  451. << " older than the version of the JUCE modules being included. To fix this error, re-save your project" << newLine
  452. << " using the latest version of the Projucer or, if you aren't using the Projucer to manage your project," << newLine
  453. << " remove the JUCE_PROJUCER_VERSION define from the AppConfig.h file." << newLine
  454. << " */" << newLine
  455. << " #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
  456. << "#endif" << newLine
  457. << newLine
  458. << "#if ! DONT_SET_USING_JUCE_NAMESPACE" << newLine
  459. << " // If your code uses a lot of JUCE classes, then this will obviously save you" << newLine
  460. << " // a lot of typing, but can be disabled by setting DONT_SET_USING_JUCE_NAMESPACE." << newLine
  461. << " using namespace juce;" << newLine
  462. << "#endif" << newLine
  463. << newLine
  464. << "#if ! JUCE_DONT_DECLARE_PROJECTINFO" << newLine
  465. << "namespace ProjectInfo" << newLine
  466. << "{" << newLine
  467. << " const char* const projectName = " << CppTokeniserFunctions::addEscapeChars (project.getProjectNameString()).quoted() << ";" << newLine
  468. << " const char* const companyName = " << CppTokeniserFunctions::addEscapeChars (project.getCompanyNameString()).quoted() << ";" << newLine
  469. << " const char* const versionString = " << CppTokeniserFunctions::addEscapeChars (project.getVersionString()).quoted() << ";" << newLine
  470. << " const int versionNumber = " << project.getVersionAsHex() << ";" << newLine
  471. << "}" << newLine
  472. << "#endif" << newLine;
  473. }
  474. void writeAppHeader (const OwnedArray<LibraryModule>& modules)
  475. {
  476. MemoryOutputStream mem;
  477. mem.setNewLineString (projectLineFeed);
  478. writeAppHeader (mem, modules);
  479. saveGeneratedFile (project.getJuceSourceHFilename(), mem);
  480. }
  481. void writeModuleCppWrappers (const OwnedArray<LibraryModule>& modules)
  482. {
  483. for (auto* module : modules)
  484. {
  485. for (auto& cu : module->getAllCompileUnits())
  486. {
  487. MemoryOutputStream mem;
  488. mem.setNewLineString (projectLineFeed);
  489. writeAutoGenWarningComment (mem);
  490. mem << "*/" << newLine
  491. << newLine
  492. << "#include " << project.getAppConfigFilename().quoted() << newLine
  493. << "#include <";
  494. if (cu.file.getFileExtension() != ".r") // .r files are included without the path
  495. mem << module->getID() << "/";
  496. mem << cu.file.getFileName() << ">" << newLine;
  497. replaceFileIfDifferent (generatedCodeFolder.getChildFile (cu.getFilenameForProxyFile()), mem);
  498. }
  499. }
  500. }
  501. void writeBinaryDataFiles()
  502. {
  503. auto binaryDataH = project.getBinaryDataHeaderFile();
  504. ResourceFile resourceFile (project);
  505. if (resourceFile.getNumFiles() > 0)
  506. {
  507. auto dataNamespace = project.getBinaryDataNamespaceString().trim();
  508. if (dataNamespace.isEmpty())
  509. dataNamespace = "BinaryData";
  510. resourceFile.setClassName (dataNamespace);
  511. Array<File> binaryDataFiles;
  512. auto maxSize = project.getMaxBinaryFileSize();
  513. if (maxSize <= 0)
  514. maxSize = 10 * 1024 * 1024;
  515. auto r = resourceFile.write (binaryDataFiles, maxSize);
  516. if (r.wasOk())
  517. {
  518. hasBinaryData = true;
  519. for (auto& f : binaryDataFiles)
  520. {
  521. filesCreated.add (f);
  522. generatedFilesGroup.addFileRetainingSortOrder (f, ! f.hasFileExtension (".h"));
  523. }
  524. }
  525. else
  526. {
  527. addError (r.getErrorMessage());
  528. }
  529. }
  530. else
  531. {
  532. for (int i = 20; --i >= 0;)
  533. project.getBinaryDataCppFile (i).deleteFile();
  534. binaryDataH.deleteFile();
  535. }
  536. }
  537. void writeReadmeFile()
  538. {
  539. MemoryOutputStream out;
  540. out.setNewLineString (projectLineFeed);
  541. out << newLine
  542. << " Important Note!!" << newLine
  543. << " ================" << newLine
  544. << newLine
  545. << "The purpose of this folder is to contain files that are auto-generated by the Projucer," << newLine
  546. << "and ALL files in this folder will be mercilessly DELETED and completely re-written whenever" << newLine
  547. << "the Projucer saves your project." << newLine
  548. << newLine
  549. << "Therefore, it's a bad idea to make any manual changes to the files in here, or to" << newLine
  550. << "put any of your own files in here if you don't want to lose them. (Of course you may choose" << newLine
  551. << "to add the folder's contents to your version-control system so that you can re-merge your own" << newLine
  552. << "modifications after the Projucer has saved its changes)." << newLine;
  553. replaceFileIfDifferent (generatedCodeFolder.getChildFile ("ReadMe.txt"), out);
  554. }
  555. void addError (const String& message)
  556. {
  557. const ScopedLock sl (errorLock);
  558. errors.add (message);
  559. }
  560. void writePluginCharacteristicsFile();
  561. void writeUnityScriptFile()
  562. {
  563. auto unityScriptContents = replaceLineFeeds (BinaryData::jucer_UnityPluginGUIScript_cs,
  564. projectLineFeed);
  565. auto projectName = Project::addUnityPluginPrefixIfNecessary (project.getProjectNameString());
  566. unityScriptContents = unityScriptContents.replace ("%%plugin_class_name%%", projectName.replace (" ", "_"))
  567. .replace ("%%plugin_name%%", projectName)
  568. .replace ("%%plugin_vendor%%", project.getPluginManufacturerString())
  569. .replace ("%%plugin_description%%", project.getPluginDescriptionString());
  570. auto f = getGeneratedCodeFolder().getChildFile (project.getUnityScriptName());
  571. MemoryOutputStream out;
  572. out << unityScriptContents;
  573. replaceFileIfDifferent (f, out);
  574. }
  575. void writeProjects (const OwnedArray<LibraryModule>&, const String&, bool);
  576. void runPostExportScript()
  577. {
  578. #if JUCE_WINDOWS
  579. auto cmdString = project.getPostExportShellCommandWinString();
  580. #else
  581. auto cmdString = project.getPostExportShellCommandPosixString();
  582. #endif
  583. auto shellCommand = cmdString.replace ("%%1%%", project.getProjectFolder().getFullPathName());
  584. if (shellCommand.isNotEmpty())
  585. {
  586. #if JUCE_WINDOWS
  587. StringArray argList ("cmd.exe", "/c");
  588. #else
  589. StringArray argList ("/bin/sh", "-c");
  590. #endif
  591. argList.add (shellCommand);
  592. ChildProcess shellProcess;
  593. if (! shellProcess.start (argList))
  594. {
  595. addError ("Failed to run shell command: " + argList.joinIntoString (" "));
  596. return;
  597. }
  598. if (! shellProcess.waitForProcessToFinish (10000))
  599. {
  600. addError ("Timeout running shell command: " + argList.joinIntoString (" "));
  601. return;
  602. }
  603. auto exitCode = shellProcess.getExitCode();
  604. if (exitCode != 0)
  605. addError ("Shell command: " + argList.joinIntoString (" ") + " failed with exit code: " + String (exitCode));
  606. }
  607. }
  608. void saveExporter (ProjectExporter* exporter, const OwnedArray<LibraryModule>& modules)
  609. {
  610. try
  611. {
  612. exporter->create (modules);
  613. if (! exporter->isCLion())
  614. std::cout << "Finished saving: " << exporter->getName() << std::endl;
  615. }
  616. catch (ProjectExporter::SaveError& error)
  617. {
  618. addError (error.message);
  619. }
  620. }
  621. class ExporterJob : public ThreadPoolJob
  622. {
  623. public:
  624. ExporterJob (ProjectSaver& ps, ProjectExporter* pe,
  625. const OwnedArray<LibraryModule>& moduleList)
  626. : ThreadPoolJob ("export"),
  627. owner (ps), exporter (pe), modules (moduleList)
  628. {
  629. }
  630. JobStatus runJob() override
  631. {
  632. owner.saveExporter (exporter.get(), modules);
  633. return jobHasFinished;
  634. }
  635. private:
  636. ProjectSaver& owner;
  637. std::unique_ptr<ProjectExporter> exporter;
  638. const OwnedArray<LibraryModule>& modules;
  639. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ExporterJob)
  640. };
  641. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ProjectSaver)
  642. };