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.

540 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."))
  216. {
  217. return;
  218. }
  219. }
  220. else if (targetFolder.exists())
  221. {
  222. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Existing File Or Directory",
  223. "Do you want to move\n\n" + targetFolderPath + "\n\nto\n\n" + targetFolderPath + "_old?"))
  224. {
  225. return;
  226. }
  227. }
  228. downloadAndInstall (asset, targetFolder);
  229. }
  230. }
  231. void LatestVersionCheckerAndUpdater::askUserAboutNewVersion (const String& newVersionString,
  232. const String& releaseNotes,
  233. const VersionInfo::Asset& asset)
  234. {
  235. if (backgroundCheck)
  236. addNotificationToOpenProjects (asset);
  237. else
  238. showDialogWindow (newVersionString, releaseNotes, asset);
  239. }
  240. void LatestVersionCheckerAndUpdater::showDialogWindow (const String& newVersionString,
  241. const String& releaseNotes,
  242. const VersionInfo::Asset& asset)
  243. {
  244. dialogWindow = UpdateDialog::launchDialog (newVersionString, releaseNotes);
  245. if (auto* mm = ModalComponentManager::getInstance())
  246. {
  247. mm->attachCallback (dialogWindow.get(),
  248. ModalCallbackFunction::create ([this, asset] (int result)
  249. {
  250. if (result == 1)
  251. askUserForLocationToDownload (asset);
  252. dialogWindow.reset();
  253. }));
  254. }
  255. }
  256. void LatestVersionCheckerAndUpdater::addNotificationToOpenProjects (const VersionInfo::Asset& asset)
  257. {
  258. for (auto* window : ProjucerApplication::getApp().mainWindowList.windows)
  259. {
  260. if (auto* project = window->getProject())
  261. {
  262. Component::SafePointer<MainWindow> safeWindow (window);
  263. auto ignore = [safeWindow]
  264. {
  265. if (safeWindow != nullptr)
  266. safeWindow->getProject()->removeProjectMessage (ProjectMessages::Ids::newVersionAvailable);
  267. };
  268. auto dontAskAgain = [ignore]
  269. {
  270. ignore();
  271. ProjucerApplication::getApp().setAutomaticVersionCheckingEnabled (false);
  272. };
  273. project->addProjectMessage (ProjectMessages::Ids::newVersionAvailable,
  274. { { "Download", [this, asset] { askUserForLocationToDownload (asset); } },
  275. { "Ignore", std::move (ignore) },
  276. { "Don't ask again", std::move (dontAskAgain) } });
  277. }
  278. }
  279. }
  280. //==============================================================================
  281. class DownloadAndInstallThread : private ThreadWithProgressWindow
  282. {
  283. public:
  284. DownloadAndInstallThread (const VersionInfo::Asset& a, const File& t, std::function<void()>&& cb)
  285. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  286. asset (a), targetFolder (t), completionCallback (std::move (cb))
  287. {
  288. launchThread (3);
  289. }
  290. private:
  291. void run() override
  292. {
  293. setProgress (-1.0);
  294. MemoryBlock zipData;
  295. auto result = download (zipData);
  296. if (result.wasOk() && ! threadShouldExit())
  297. result = install (zipData);
  298. if (result.failed())
  299. MessageManager::callAsync ([result] { AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  300. "Installation Failed",
  301. result.getErrorMessage()); });
  302. else
  303. MessageManager::callAsync (completionCallback);
  304. }
  305. Result download (MemoryBlock& dest)
  306. {
  307. setStatusMessage ("Downloading...");
  308. int statusCode = 0;
  309. auto inStream = VersionInfo::createInputStreamForAsset (asset, statusCode);
  310. if (inStream != nullptr && statusCode == 200)
  311. {
  312. int64 total = 0;
  313. MemoryOutputStream mo (dest, true);
  314. for (;;)
  315. {
  316. if (threadShouldExit())
  317. return Result::fail ("Cancelled");
  318. auto written = mo.writeFromInputStream (*inStream, 8192);
  319. if (written == 0)
  320. break;
  321. total += written;
  322. setStatusMessage ("Downloading... " + File::descriptionOfSizeInBytes (total));
  323. }
  324. return Result::ok();
  325. }
  326. return Result::fail ("Failed to download from: " + asset.url);
  327. }
  328. Result install (const MemoryBlock& data)
  329. {
  330. setStatusMessage ("Installing...");
  331. MemoryInputStream input (data, false);
  332. ZipFile zip (input);
  333. if (zip.getNumEntries() == 0)
  334. return Result::fail ("The downloaded file was not a valid JUCE file!");
  335. struct ScopedDownloadFolder
  336. {
  337. explicit ScopedDownloadFolder (const File& installTargetFolder)
  338. {
  339. folder = installTargetFolder.getSiblingFile (installTargetFolder.getFileNameWithoutExtension() + "_download").getNonexistentSibling();
  340. jassert (folder.createDirectory());
  341. }
  342. ~ScopedDownloadFolder() { folder.deleteRecursively(); }
  343. File folder;
  344. };
  345. ScopedDownloadFolder unzipTarget (targetFolder);
  346. if (! unzipTarget.folder.isDirectory())
  347. return Result::fail ("Couldn't create a temporary folder to unzip the new version!");
  348. auto r = zip.uncompressTo (unzipTarget.folder);
  349. if (r.failed())
  350. return r;
  351. if (threadShouldExit())
  352. return Result::fail ("Cancelled");
  353. #if JUCE_LINUX || JUCE_MAC
  354. r = setFilePermissions (unzipTarget.folder, zip);
  355. if (r.failed())
  356. return r;
  357. if (threadShouldExit())
  358. return Result::fail ("Cancelled");
  359. #endif
  360. if (targetFolder.exists())
  361. {
  362. auto oldFolder = targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old").getNonexistentSibling();
  363. if (! targetFolder.moveFileTo (oldFolder))
  364. return Result::fail ("Could not remove the existing folder!\n\n"
  365. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  366. "Please select a folder that is writable by the current user.");
  367. }
  368. if (! unzipTarget.folder.getChildFile ("JUCE").moveFileTo (targetFolder))
  369. return Result::fail ("Could not overwrite the existing folder!\n\n"
  370. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  371. "Please select a folder that is writable by the current user.");
  372. return Result::ok();
  373. }
  374. Result setFilePermissions (const File& root, const ZipFile& zip)
  375. {
  376. constexpr uint32 executableFlag = (1 << 22);
  377. for (int i = 0; i < zip.getNumEntries(); ++i)
  378. {
  379. auto* entry = zip.getEntry (i);
  380. if ((entry->externalFileAttributes & executableFlag) != 0 && entry->filename.getLastCharacter() != '/')
  381. {
  382. auto exeFile = root.getChildFile (entry->filename);
  383. if (! exeFile.exists())
  384. return Result::fail ("Failed to find executable file when setting permissions " + exeFile.getFileName());
  385. if (! exeFile.setExecutePermission (true))
  386. return Result::fail ("Failed to set executable file permission for " + exeFile.getFileName());
  387. }
  388. }
  389. return Result::ok();
  390. }
  391. VersionInfo::Asset asset;
  392. File targetFolder;
  393. std::function<void()> completionCallback;
  394. };
  395. void restartProcess (const File& targetFolder)
  396. {
  397. #if JUCE_MAC || JUCE_LINUX
  398. #if JUCE_MAC
  399. auto newProcess = targetFolder.getChildFile ("Projucer.app").getChildFile ("Contents").getChildFile ("MacOS").getChildFile ("Projucer");
  400. #elif JUCE_LINUX
  401. auto newProcess = targetFolder.getChildFile ("Projucer");
  402. #endif
  403. StringArray command ("/bin/sh", "-c", "while killall -0 Projucer; do sleep 5; done; " + newProcess.getFullPathName().quoted());
  404. #elif JUCE_WINDOWS
  405. auto newProcess = targetFolder.getChildFile ("Projucer.exe");
  406. auto command = "cmd.exe /c\"@echo off & for /l %a in (0) do ( tasklist | find \"Projucer\" >nul & ( if errorlevel 1 ( "
  407. + targetFolder.getChildFile ("Projucer.exe").getFullPathName().quoted() + " & exit /b ) else ( timeout /t 10 >nul ) ) )\"";
  408. #endif
  409. if (newProcess.existsAsFile())
  410. {
  411. ChildProcess restartProcess;
  412. restartProcess.start (command, 0);
  413. ProjucerApplication::getApp().systemRequestedQuit();
  414. }
  415. }
  416. void LatestVersionCheckerAndUpdater::downloadAndInstall (const VersionInfo::Asset& asset, const File& targetFolder)
  417. {
  418. installer.reset (new DownloadAndInstallThread (asset, targetFolder,
  419. [this, targetFolder]
  420. {
  421. installer.reset();
  422. restartProcess (targetFolder);
  423. }));
  424. }
  425. //==============================================================================
  426. JUCE_IMPLEMENT_SINGLETON (LatestVersionCheckerAndUpdater)