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.

554 lines
21KB

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