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.

588 lines
22KB

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