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.

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