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.

583 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 : 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. lookAndFeelChanged();
  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 lookAndFeelChanged() override
  178. {
  179. cancelButton.setColour (TextButton::buttonColourId, findColour (secondaryButtonBackgroundColourId));
  180. releaseNotesEditor.applyFontToAllText (releaseNotesEditor.getFont());
  181. }
  182. void setParentWindow (DialogWindow* parent)
  183. {
  184. parentWindow = parent;
  185. }
  186. void exitModalStateWithResult (int result)
  187. {
  188. if (parentWindow != nullptr)
  189. parentWindow->exitModalState (result);
  190. }
  191. Label titleLabel, contentLabel, releaseNotesLabel;
  192. TextEditor releaseNotesEditor;
  193. TextButton chooseButton { "Choose Location..." }, cancelButton { "Cancel" };
  194. ToggleButton dontAskAgainButton { "Don't ask again" };
  195. std::unique_ptr<Drawable> juceIcon;
  196. Rectangle<int> juceIconBounds { 10, 10, 64, 64 };
  197. DialogWindow* parentWindow = nullptr;
  198. };
  199. void LatestVersionCheckerAndUpdater::askUserForLocationToDownload (const VersionInfo::Asset& asset)
  200. {
  201. chooser = std::make_unique<FileChooser> ("Please select the location into which you would like to install the new version",
  202. File { getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get() });
  203. chooser->launchAsync (FileBrowserComponent::openMode | FileBrowserComponent::canSelectDirectories,
  204. [weakThis = WeakReference<LatestVersionCheckerAndUpdater> { this }, asset] (const FileChooser& fc)
  205. {
  206. auto targetFolder = fc.getResult();
  207. if (targetFolder == File{})
  208. return;
  209. // By default we will install into 'targetFolder/JUCE', but we should install into
  210. // 'targetFolder' if that is an existing JUCE directory.
  211. bool willOverwriteJuceFolder = [&targetFolder]
  212. {
  213. if (isJUCEFolder (targetFolder))
  214. return true;
  215. targetFolder = targetFolder.getChildFile ("JUCE");
  216. return isJUCEFolder (targetFolder);
  217. }();
  218. auto targetFolderPath = targetFolder.getFullPathName();
  219. const auto onResult = [weakThis, asset, targetFolder] (int result)
  220. {
  221. if (weakThis == nullptr || result == 0)
  222. return;
  223. weakThis->downloadAndInstall (asset, targetFolder);
  224. };
  225. if (willOverwriteJuceFolder)
  226. {
  227. if (targetFolder.getChildFile (".git").isDirectory())
  228. {
  229. auto options = MessageBoxOptions::makeOptionsOk (MessageBoxIconType::WarningIcon,
  230. "Downloading New JUCE Version",
  231. targetFolderPath + "\n\n"
  232. "is a GIT repository!\n\n"
  233. "You should use a \"git pull\" to update it to the latest version.");
  234. if (weakThis != nullptr)
  235. weakThis->messageBox = AlertWindow::showScopedAsync (options, nullptr);
  236. return;
  237. }
  238. auto options = MessageBoxOptions::makeOptionsOkCancel (MessageBoxIconType::WarningIcon,
  239. "Overwrite Existing JUCE Folder?",
  240. "Do you want to replace the folder\n\n" + targetFolderPath + "\n\n"
  241. "with the latest version from juce.com?\n\n"
  242. "This will move the existing folder to " + targetFolderPath + "_old.\n\n"
  243. "Replacing the folder that contains the currently running Projucer executable may not work on Windows.");
  244. if (weakThis != nullptr)
  245. weakThis->messageBox = AlertWindow::showScopedAsync (options, onResult);
  246. return;
  247. }
  248. if (targetFolder.exists())
  249. {
  250. auto options = MessageBoxOptions::makeOptionsOkCancel (MessageBoxIconType::WarningIcon,
  251. "Existing File Or Directory",
  252. "Do you want to move\n\n" + targetFolderPath + "\n\n"
  253. "to\n\n" + targetFolderPath + "_old?");
  254. if (weakThis != nullptr)
  255. weakThis->messageBox = AlertWindow::showScopedAsync (options, onResult);
  256. return;
  257. }
  258. if (weakThis != nullptr)
  259. weakThis->downloadAndInstall (asset, targetFolder);
  260. });
  261. }
  262. void LatestVersionCheckerAndUpdater::askUserAboutNewVersion (const String& newVersionString,
  263. const String& releaseNotes,
  264. const VersionInfo::Asset& asset)
  265. {
  266. if (backgroundCheck)
  267. addNotificationToOpenProjects (asset);
  268. else
  269. showDialogWindow (newVersionString, releaseNotes, asset);
  270. }
  271. void LatestVersionCheckerAndUpdater::showDialogWindow (const String& newVersionString,
  272. const String& releaseNotes,
  273. const VersionInfo::Asset& asset)
  274. {
  275. dialogWindow = UpdateDialog::launchDialog (newVersionString, releaseNotes);
  276. if (auto* mm = ModalComponentManager::getInstance())
  277. {
  278. mm->attachCallback (dialogWindow.get(),
  279. ModalCallbackFunction::create ([this, asset] (int result)
  280. {
  281. if (result == 1)
  282. askUserForLocationToDownload (asset);
  283. dialogWindow.reset();
  284. }));
  285. }
  286. }
  287. void LatestVersionCheckerAndUpdater::addNotificationToOpenProjects (const VersionInfo::Asset& asset)
  288. {
  289. for (auto* window : ProjucerApplication::getApp().mainWindowList.windows)
  290. {
  291. if (auto* project = window->getProject())
  292. {
  293. auto ignore = [safeWindow = Component::SafePointer<MainWindow> { window }]
  294. {
  295. if (safeWindow != nullptr)
  296. safeWindow->getProject()->removeProjectMessage (ProjectMessages::Ids::newVersionAvailable);
  297. };
  298. auto dontAskAgain = [ignore]
  299. {
  300. ignore();
  301. ProjucerApplication::getApp().setAutomaticVersionCheckingEnabled (false);
  302. };
  303. project->addProjectMessage (ProjectMessages::Ids::newVersionAvailable,
  304. { { "Download", [this, asset] { askUserForLocationToDownload (asset); } },
  305. { "Ignore", std::move (ignore) },
  306. { "Don't ask again", std::move (dontAskAgain) } });
  307. }
  308. }
  309. }
  310. //==============================================================================
  311. class DownloadAndInstallThread : private ThreadWithProgressWindow
  312. {
  313. public:
  314. DownloadAndInstallThread (const VersionInfo::Asset& a, const File& t, std::function<void (Result)>&& cb)
  315. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  316. asset (a), targetFolder (t), completionCallback (std::move (cb))
  317. {
  318. launchThread (Priority::low);
  319. }
  320. private:
  321. void run() override
  322. {
  323. setProgress (-1.0);
  324. MemoryBlock zipData;
  325. auto result = download (zipData);
  326. if (result.wasOk() && ! threadShouldExit())
  327. result = install (zipData);
  328. MessageManager::callAsync ([result, callback = completionCallback]
  329. {
  330. callback (result);
  331. });
  332. }
  333. Result download (MemoryBlock& dest)
  334. {
  335. setStatusMessage ("Downloading...");
  336. int statusCode = 0;
  337. auto inStream = VersionInfo::createInputStreamForAsset (asset, statusCode);
  338. if (inStream != nullptr && statusCode == 200)
  339. {
  340. int64 total = 0;
  341. MemoryOutputStream mo (dest, true);
  342. for (;;)
  343. {
  344. if (threadShouldExit())
  345. return Result::fail ("Cancelled");
  346. auto written = mo.writeFromInputStream (*inStream, 8192);
  347. if (written == 0)
  348. break;
  349. total += written;
  350. setStatusMessage ("Downloading... " + File::descriptionOfSizeInBytes (total));
  351. }
  352. return Result::ok();
  353. }
  354. return Result::fail ("Failed to download from: " + asset.url);
  355. }
  356. Result install (const MemoryBlock& data)
  357. {
  358. setStatusMessage ("Installing...");
  359. MemoryInputStream input (data, false);
  360. ZipFile zip (input);
  361. if (zip.getNumEntries() == 0)
  362. return Result::fail ("The downloaded file was not a valid JUCE file!");
  363. struct ScopedDownloadFolder
  364. {
  365. explicit ScopedDownloadFolder (const File& installTargetFolder)
  366. {
  367. folder = installTargetFolder.getSiblingFile (installTargetFolder.getFileNameWithoutExtension() + "_download").getNonexistentSibling();
  368. jassert (folder.createDirectory());
  369. }
  370. ~ScopedDownloadFolder() { folder.deleteRecursively(); }
  371. File folder;
  372. };
  373. ScopedDownloadFolder unzipTarget (targetFolder);
  374. if (! unzipTarget.folder.isDirectory())
  375. return Result::fail ("Couldn't create a temporary folder to unzip the new version!");
  376. auto r = zip.uncompressTo (unzipTarget.folder);
  377. if (r.failed())
  378. return r;
  379. if (threadShouldExit())
  380. return Result::fail ("Cancelled");
  381. #if JUCE_LINUX || JUCE_BSD || JUCE_MAC
  382. r = setFilePermissions (unzipTarget.folder, zip);
  383. if (r.failed())
  384. return r;
  385. if (threadShouldExit())
  386. return Result::fail ("Cancelled");
  387. #endif
  388. if (targetFolder.exists())
  389. {
  390. auto oldFolder = targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old").getNonexistentSibling();
  391. if (! targetFolder.moveFileTo (oldFolder))
  392. return Result::fail ("Could not remove the existing folder!\n\n"
  393. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  394. "Please select a folder that is writable by the current user.");
  395. }
  396. if (! unzipTarget.folder.getChildFile ("JUCE").moveFileTo (targetFolder))
  397. return Result::fail ("Could not overwrite the existing folder!\n\n"
  398. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  399. "Please select a folder that is writable by the current user.");
  400. return Result::ok();
  401. }
  402. Result setFilePermissions (const File& root, const ZipFile& zip)
  403. {
  404. constexpr uint32 executableFlag = (1 << 22);
  405. for (int i = 0; i < zip.getNumEntries(); ++i)
  406. {
  407. auto* entry = zip.getEntry (i);
  408. if ((entry->externalFileAttributes & executableFlag) != 0 && entry->filename.getLastCharacter() != '/')
  409. {
  410. auto exeFile = root.getChildFile (entry->filename);
  411. if (! exeFile.exists())
  412. return Result::fail ("Failed to find executable file when setting permissions " + exeFile.getFileName());
  413. if (! exeFile.setExecutePermission (true))
  414. return Result::fail ("Failed to set executable file permission for " + exeFile.getFileName());
  415. }
  416. }
  417. return Result::ok();
  418. }
  419. VersionInfo::Asset asset;
  420. File targetFolder;
  421. std::function<void (Result)> completionCallback;
  422. };
  423. static void restartProcess (const File& targetFolder)
  424. {
  425. #if JUCE_MAC || JUCE_LINUX || JUCE_BSD
  426. #if JUCE_MAC
  427. auto newProcess = targetFolder.getChildFile ("Projucer.app").getChildFile ("Contents").getChildFile ("MacOS").getChildFile ("Projucer");
  428. #elif JUCE_LINUX || JUCE_BSD
  429. auto newProcess = targetFolder.getChildFile ("Projucer");
  430. #endif
  431. StringArray command ("/bin/sh", "-c", "while killall -0 Projucer; do sleep 5; done; " + newProcess.getFullPathName().quoted());
  432. #elif JUCE_WINDOWS
  433. auto newProcess = targetFolder.getChildFile ("Projucer.exe");
  434. auto command = "cmd.exe /c\"@echo off & for /l %a in (0) do ( tasklist | find \"Projucer\" >nul & ( if errorlevel 1 ( "
  435. + targetFolder.getChildFile ("Projucer.exe").getFullPathName().quoted() + " & exit /b ) else ( timeout /t 10 >nul ) ) )\"";
  436. #endif
  437. if (newProcess.existsAsFile())
  438. {
  439. ChildProcess restartProcess;
  440. restartProcess.start (command, 0);
  441. ProjucerApplication::getApp().systemRequestedQuit();
  442. }
  443. }
  444. void LatestVersionCheckerAndUpdater::downloadAndInstall (const VersionInfo::Asset& asset, const File& targetFolder)
  445. {
  446. installer.reset (new DownloadAndInstallThread (asset, targetFolder, [this, targetFolder] (const auto result)
  447. {
  448. if (result.failed())
  449. {
  450. auto options = MessageBoxOptions::makeOptionsOk (MessageBoxIconType::WarningIcon,
  451. "Installation Failed",
  452. result.getErrorMessage());
  453. messageBox = AlertWindow::showScopedAsync (options, nullptr);
  454. }
  455. else
  456. {
  457. installer.reset();
  458. restartProcess (targetFolder);
  459. }
  460. }));
  461. }
  462. //==============================================================================
  463. JUCE_IMPLEMENT_SINGLETON (LatestVersionCheckerAndUpdater)