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.

561 lines
21KB

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