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.

541 lines
20KB

  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 "../Application/jucer_Headers.h"
  19. #include "jucer_Application.h"
  20. #include "jucer_AutoUpdater.h"
  21. //==============================================================================
  22. LatestVersionCheckerAndUpdater::LatestVersionCheckerAndUpdater()
  23. : Thread ("VersionChecker")
  24. {
  25. }
  26. LatestVersionCheckerAndUpdater::~LatestVersionCheckerAndUpdater()
  27. {
  28. stopThread (6000);
  29. clearSingletonInstance();
  30. }
  31. void LatestVersionCheckerAndUpdater::checkForNewVersion (bool background)
  32. {
  33. if (! isThreadRunning())
  34. {
  35. backgroundCheck = background;
  36. startThread (3);
  37. }
  38. }
  39. //==============================================================================
  40. void LatestVersionCheckerAndUpdater::run()
  41. {
  42. auto info = VersionInfo::fetchLatestFromUpdateServer();
  43. if (info == nullptr)
  44. {
  45. if (! backgroundCheck)
  46. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  47. "Update Server Communication Error",
  48. "Failed to communicate with the JUCE update server.\n"
  49. "Please try again in a few minutes.\n\n"
  50. "If this problem persists you can download the latest version of JUCE from juce.com");
  51. return;
  52. }
  53. if (! info->isNewerVersionThanCurrent())
  54. {
  55. if (! backgroundCheck)
  56. AlertWindow::showMessageBoxAsync (AlertWindow::InfoIcon,
  57. "No New Version Available",
  58. "Your JUCE version is up to date.");
  59. return;
  60. }
  61. auto osString = []
  62. {
  63. #if JUCE_MAC
  64. return "osx";
  65. #elif JUCE_WINDOWS
  66. return "windows";
  67. #elif JUCE_LINUX
  68. return "linux";
  69. #else
  70. jassertfalse;
  71. return "Unknown";
  72. #endif
  73. }();
  74. String requiredFilename ("juce-" + info->versionString + "-" + osString + ".zip");
  75. for (auto& asset : info->assets)
  76. {
  77. if (asset.name == requiredFilename)
  78. {
  79. auto versionString = info->versionString;
  80. auto releaseNotes = info->releaseNotes;
  81. MessageManager::callAsync ([this, versionString, releaseNotes, asset]
  82. {
  83. askUserAboutNewVersion (versionString, releaseNotes, asset);
  84. });
  85. return;
  86. }
  87. }
  88. if (! backgroundCheck)
  89. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  90. "Failed to find any new downloads",
  91. "Please try again in a few minutes.");
  92. }
  93. //==============================================================================
  94. class UpdateDialog : public Component
  95. {
  96. public:
  97. UpdateDialog (const String& newVersion, const String& releaseNotes)
  98. {
  99. titleLabel.setText ("JUCE version " + newVersion, dontSendNotification);
  100. titleLabel.setFont ({ 15.0f, Font::bold });
  101. titleLabel.setJustificationType (Justification::centred);
  102. addAndMakeVisible (titleLabel);
  103. contentLabel.setText ("A new version of JUCE is available - would you like to download it?", dontSendNotification);
  104. contentLabel.setFont (15.0f);
  105. contentLabel.setJustificationType (Justification::topLeft);
  106. addAndMakeVisible (contentLabel);
  107. releaseNotesLabel.setText ("Release notes:", dontSendNotification);
  108. releaseNotesLabel.setFont (15.0f);
  109. releaseNotesLabel.setJustificationType (Justification::topLeft);
  110. addAndMakeVisible (releaseNotesLabel);
  111. releaseNotesEditor.setMultiLine (true);
  112. releaseNotesEditor.setReadOnly (true);
  113. releaseNotesEditor.setText (releaseNotes);
  114. addAndMakeVisible (releaseNotesEditor);
  115. addAndMakeVisible (chooseButton);
  116. chooseButton.onClick = [this] { exitModalStateWithResult (1); };
  117. addAndMakeVisible (cancelButton);
  118. cancelButton.onClick = [this]
  119. {
  120. ProjucerApplication::getApp().setAutomaticVersionCheckingEnabled (! dontAskAgainButton.getToggleState());
  121. exitModalStateWithResult (-1);
  122. };
  123. dontAskAgainButton.setToggleState (! ProjucerApplication::getApp().isAutomaticVersionCheckingEnabled(), dontSendNotification);
  124. addAndMakeVisible (dontAskAgainButton);
  125. juceIcon = Drawable::createFromImageData (BinaryData::juce_icon_png,
  126. BinaryData::juce_icon_pngSize);
  127. lookAndFeelChanged();
  128. setSize (500, 280);
  129. }
  130. void resized() override
  131. {
  132. auto b = getLocalBounds().reduced (10);
  133. auto topSlice = b.removeFromTop (juceIconBounds.getHeight())
  134. .withTrimmedLeft (juceIconBounds.getWidth());
  135. titleLabel.setBounds (topSlice.removeFromTop (25));
  136. topSlice.removeFromTop (5);
  137. contentLabel.setBounds (topSlice.removeFromTop (25));
  138. auto buttonBounds = b.removeFromBottom (60);
  139. buttonBounds.removeFromBottom (25);
  140. chooseButton.setBounds (buttonBounds.removeFromLeft (buttonBounds.getWidth() / 2).reduced (20, 0));
  141. cancelButton.setBounds (buttonBounds.reduced (20, 0));
  142. dontAskAgainButton.setBounds (cancelButton.getBounds().withY (cancelButton.getBottom() + 5).withHeight (20));
  143. releaseNotesEditor.setBounds (b.reduced (0, 10));
  144. }
  145. void paint (Graphics& g) override
  146. {
  147. g.fillAll (findColour (backgroundColourId));
  148. if (juceIcon != nullptr)
  149. juceIcon->drawWithin (g, juceIconBounds.toFloat(),
  150. RectanglePlacement::stretchToFit, 1.0f);
  151. }
  152. static std::unique_ptr<DialogWindow> launchDialog (const String& newVersionString,
  153. const String& releaseNotes)
  154. {
  155. DialogWindow::LaunchOptions options;
  156. options.dialogTitle = "Download JUCE version " + newVersionString + "?";
  157. options.resizable = false;
  158. auto* content = new UpdateDialog (newVersionString, releaseNotes);
  159. options.content.set (content, true);
  160. std::unique_ptr<DialogWindow> dialog (options.create());
  161. content->setParentWindow (dialog.get());
  162. dialog->enterModalState (true, nullptr, true);
  163. return dialog;
  164. }
  165. private:
  166. void lookAndFeelChanged() override
  167. {
  168. cancelButton.setColour (TextButton::buttonColourId, findColour (secondaryButtonBackgroundColourId));
  169. releaseNotesEditor.applyFontToAllText (releaseNotesEditor.getFont());
  170. }
  171. void setParentWindow (DialogWindow* parent)
  172. {
  173. parentWindow = parent;
  174. }
  175. void exitModalStateWithResult (int result)
  176. {
  177. if (parentWindow != nullptr)
  178. parentWindow->exitModalState (result);
  179. }
  180. Label titleLabel, contentLabel, releaseNotesLabel;
  181. TextEditor releaseNotesEditor;
  182. TextButton chooseButton { "Choose Location..." }, cancelButton { "Cancel" };
  183. ToggleButton dontAskAgainButton { "Don't ask again" };
  184. std::unique_ptr<Drawable> juceIcon;
  185. Rectangle<int> juceIconBounds { 10, 10, 64, 64 };
  186. DialogWindow* parentWindow = nullptr;
  187. };
  188. void LatestVersionCheckerAndUpdater::askUserForLocationToDownload (const VersionInfo::Asset& asset)
  189. {
  190. FileChooser chooser ("Please select the location into which you would like to install the new version",
  191. { getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get() });
  192. if (chooser.browseForDirectory())
  193. {
  194. auto targetFolder = chooser.getResult();
  195. // By default we will install into 'targetFolder/JUCE', but we should install into
  196. // 'targetFolder' if that is an existing JUCE directory.
  197. bool willOverwriteJuceFolder = [&targetFolder]
  198. {
  199. if (isJUCEFolder (targetFolder))
  200. return true;
  201. targetFolder = targetFolder.getChildFile ("JUCE");
  202. return isJUCEFolder (targetFolder);
  203. }();
  204. auto targetFolderPath = targetFolder.getFullPathName();
  205. if (willOverwriteJuceFolder)
  206. {
  207. if (targetFolder.getChildFile (".git").isDirectory())
  208. {
  209. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Downloading New JUCE Version",
  210. targetFolderPath + "\n\nis a GIT repository!\n\nYou should use a \"git pull\" to update it to the latest version.");
  211. return;
  212. }
  213. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Overwrite Existing JUCE Folder?",
  214. "Do you want to replace the folder\n\n" + targetFolderPath + "\n\nwith the latest version from juce.com?\n\n"
  215. "This will move the existing folder to " + targetFolderPath + "_old.\n\n"
  216. "Replacing the folder that contains the currently running Projucer executable may not work on Windows."))
  217. {
  218. return;
  219. }
  220. }
  221. else if (targetFolder.exists())
  222. {
  223. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Existing File Or Directory",
  224. "Do you want to move\n\n" + targetFolderPath + "\n\nto\n\n" + targetFolderPath + "_old?"))
  225. {
  226. return;
  227. }
  228. }
  229. downloadAndInstall (asset, targetFolder);
  230. }
  231. }
  232. void LatestVersionCheckerAndUpdater::askUserAboutNewVersion (const String& newVersionString,
  233. const String& releaseNotes,
  234. const VersionInfo::Asset& asset)
  235. {
  236. if (backgroundCheck)
  237. addNotificationToOpenProjects (asset);
  238. else
  239. showDialogWindow (newVersionString, releaseNotes, asset);
  240. }
  241. void LatestVersionCheckerAndUpdater::showDialogWindow (const String& newVersionString,
  242. const String& releaseNotes,
  243. const VersionInfo::Asset& asset)
  244. {
  245. dialogWindow = UpdateDialog::launchDialog (newVersionString, releaseNotes);
  246. if (auto* mm = ModalComponentManager::getInstance())
  247. {
  248. mm->attachCallback (dialogWindow.get(),
  249. ModalCallbackFunction::create ([this, asset] (int result)
  250. {
  251. if (result == 1)
  252. askUserForLocationToDownload (asset);
  253. dialogWindow.reset();
  254. }));
  255. }
  256. }
  257. void LatestVersionCheckerAndUpdater::addNotificationToOpenProjects (const VersionInfo::Asset& asset)
  258. {
  259. for (auto* window : ProjucerApplication::getApp().mainWindowList.windows)
  260. {
  261. if (auto* project = window->getProject())
  262. {
  263. Component::SafePointer<MainWindow> safeWindow (window);
  264. auto ignore = [safeWindow]
  265. {
  266. if (safeWindow != nullptr)
  267. safeWindow->getProject()->removeProjectMessage (ProjectMessages::Ids::newVersionAvailable);
  268. };
  269. auto dontAskAgain = [ignore]
  270. {
  271. ignore();
  272. ProjucerApplication::getApp().setAutomaticVersionCheckingEnabled (false);
  273. };
  274. project->addProjectMessage (ProjectMessages::Ids::newVersionAvailable,
  275. { { "Download", [this, asset] { askUserForLocationToDownload (asset); } },
  276. { "Ignore", std::move (ignore) },
  277. { "Don't ask again", std::move (dontAskAgain) } });
  278. }
  279. }
  280. }
  281. //==============================================================================
  282. class DownloadAndInstallThread : private ThreadWithProgressWindow
  283. {
  284. public:
  285. DownloadAndInstallThread (const VersionInfo::Asset& a, const File& t, std::function<void()>&& cb)
  286. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  287. asset (a), targetFolder (t), completionCallback (std::move (cb))
  288. {
  289. launchThread (3);
  290. }
  291. private:
  292. void run() override
  293. {
  294. setProgress (-1.0);
  295. MemoryBlock zipData;
  296. auto result = download (zipData);
  297. if (result.wasOk() && ! threadShouldExit())
  298. result = install (zipData);
  299. if (result.failed())
  300. MessageManager::callAsync ([result] { AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  301. "Installation Failed",
  302. result.getErrorMessage()); });
  303. else
  304. MessageManager::callAsync (completionCallback);
  305. }
  306. Result download (MemoryBlock& dest)
  307. {
  308. setStatusMessage ("Downloading...");
  309. int statusCode = 0;
  310. auto inStream = VersionInfo::createInputStreamForAsset (asset, statusCode);
  311. if (inStream != nullptr && statusCode == 200)
  312. {
  313. int64 total = 0;
  314. MemoryOutputStream mo (dest, true);
  315. for (;;)
  316. {
  317. if (threadShouldExit())
  318. return Result::fail ("Cancelled");
  319. auto written = mo.writeFromInputStream (*inStream, 8192);
  320. if (written == 0)
  321. break;
  322. total += written;
  323. setStatusMessage ("Downloading... " + File::descriptionOfSizeInBytes (total));
  324. }
  325. return Result::ok();
  326. }
  327. return Result::fail ("Failed to download from: " + asset.url);
  328. }
  329. Result install (const MemoryBlock& data)
  330. {
  331. setStatusMessage ("Installing...");
  332. MemoryInputStream input (data, false);
  333. ZipFile zip (input);
  334. if (zip.getNumEntries() == 0)
  335. return Result::fail ("The downloaded file was not a valid JUCE file!");
  336. struct ScopedDownloadFolder
  337. {
  338. explicit ScopedDownloadFolder (const File& installTargetFolder)
  339. {
  340. folder = installTargetFolder.getSiblingFile (installTargetFolder.getFileNameWithoutExtension() + "_download").getNonexistentSibling();
  341. jassert (folder.createDirectory());
  342. }
  343. ~ScopedDownloadFolder() { folder.deleteRecursively(); }
  344. File folder;
  345. };
  346. ScopedDownloadFolder unzipTarget (targetFolder);
  347. if (! unzipTarget.folder.isDirectory())
  348. return Result::fail ("Couldn't create a temporary folder to unzip the new version!");
  349. auto r = zip.uncompressTo (unzipTarget.folder);
  350. if (r.failed())
  351. return r;
  352. if (threadShouldExit())
  353. return Result::fail ("Cancelled");
  354. #if JUCE_LINUX || JUCE_MAC
  355. r = setFilePermissions (unzipTarget.folder, zip);
  356. if (r.failed())
  357. return r;
  358. if (threadShouldExit())
  359. return Result::fail ("Cancelled");
  360. #endif
  361. if (targetFolder.exists())
  362. {
  363. auto oldFolder = targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old").getNonexistentSibling();
  364. if (! targetFolder.moveFileTo (oldFolder))
  365. return Result::fail ("Could not remove the existing folder!\n\n"
  366. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  367. "Please select a folder that is writable by the current user.");
  368. }
  369. if (! unzipTarget.folder.getChildFile ("JUCE").moveFileTo (targetFolder))
  370. return Result::fail ("Could not overwrite the existing folder!\n\n"
  371. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  372. "Please select a folder that is writable by the current user.");
  373. return Result::ok();
  374. }
  375. Result setFilePermissions (const File& root, const ZipFile& zip)
  376. {
  377. constexpr uint32 executableFlag = (1 << 22);
  378. for (int i = 0; i < zip.getNumEntries(); ++i)
  379. {
  380. auto* entry = zip.getEntry (i);
  381. if ((entry->externalFileAttributes & executableFlag) != 0 && entry->filename.getLastCharacter() != '/')
  382. {
  383. auto exeFile = root.getChildFile (entry->filename);
  384. if (! exeFile.exists())
  385. return Result::fail ("Failed to find executable file when setting permissions " + exeFile.getFileName());
  386. if (! exeFile.setExecutePermission (true))
  387. return Result::fail ("Failed to set executable file permission for " + exeFile.getFileName());
  388. }
  389. }
  390. return Result::ok();
  391. }
  392. VersionInfo::Asset asset;
  393. File targetFolder;
  394. std::function<void()> completionCallback;
  395. };
  396. static void restartProcess (const File& targetFolder)
  397. {
  398. #if JUCE_MAC || JUCE_LINUX
  399. #if JUCE_MAC
  400. auto newProcess = targetFolder.getChildFile ("Projucer.app").getChildFile ("Contents").getChildFile ("MacOS").getChildFile ("Projucer");
  401. #elif JUCE_LINUX
  402. auto newProcess = targetFolder.getChildFile ("Projucer");
  403. #endif
  404. StringArray command ("/bin/sh", "-c", "while killall -0 Projucer; do sleep 5; done; " + newProcess.getFullPathName().quoted());
  405. #elif JUCE_WINDOWS
  406. auto newProcess = targetFolder.getChildFile ("Projucer.exe");
  407. auto command = "cmd.exe /c\"@echo off & for /l %a in (0) do ( tasklist | find \"Projucer\" >nul & ( if errorlevel 1 ( "
  408. + targetFolder.getChildFile ("Projucer.exe").getFullPathName().quoted() + " & exit /b ) else ( timeout /t 10 >nul ) ) )\"";
  409. #endif
  410. if (newProcess.existsAsFile())
  411. {
  412. ChildProcess restartProcess;
  413. restartProcess.start (command, 0);
  414. ProjucerApplication::getApp().systemRequestedQuit();
  415. }
  416. }
  417. void LatestVersionCheckerAndUpdater::downloadAndInstall (const VersionInfo::Asset& asset, const File& targetFolder)
  418. {
  419. installer.reset (new DownloadAndInstallThread (asset, targetFolder,
  420. [this, targetFolder]
  421. {
  422. installer.reset();
  423. restartProcess (targetFolder);
  424. }));
  425. }
  426. //==============================================================================
  427. JUCE_IMPLEMENT_SINGLETON (LatestVersionCheckerAndUpdater)