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.

497 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 6 technical preview.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For this technical preview, this file is not subject to commercial licensing.
  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 (1000);
  24. clearSingletonInstance();
  25. }
  26. void LatestVersionCheckerAndUpdater::checkForNewVersion (bool showAlerts)
  27. {
  28. if (! isThreadRunning())
  29. {
  30. showAlertWindows = showAlerts;
  31. startThread (3);
  32. }
  33. }
  34. //==============================================================================
  35. void LatestVersionCheckerAndUpdater::run()
  36. {
  37. auto info = VersionInfo::fetchLatestFromUpdateServer();
  38. if (info == nullptr)
  39. {
  40. if (showAlertWindows)
  41. AlertWindow::showMessageBoxAsync (AlertWindow::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 (showAlertWindows)
  51. AlertWindow::showMessageBoxAsync (AlertWindow::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. #else
  65. jassertfalse;
  66. return "Unknown";
  67. #endif
  68. }();
  69. String requiredFilename ("juce-" + info->versionString + "-" + osString + ".zip");
  70. for (auto& asset : info->assets)
  71. {
  72. if (asset.name == requiredFilename)
  73. {
  74. auto versionString = info->versionString;
  75. auto releaseNotes = info->releaseNotes;
  76. MessageManager::callAsync ([this, versionString, releaseNotes, asset]
  77. {
  78. askUserAboutNewVersion (versionString, releaseNotes, asset);
  79. });
  80. return;
  81. }
  82. }
  83. if (showAlertWindows)
  84. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  85. "Failed to find any new downloads",
  86. "Please try again in a few minutes.");
  87. }
  88. //==============================================================================
  89. class UpdateDialog : public Component
  90. {
  91. public:
  92. UpdateDialog (const String& newVersion, const String& releaseNotes)
  93. {
  94. titleLabel.setText ("JUCE version " + newVersion, dontSendNotification);
  95. titleLabel.setFont ({ 15.0f, Font::bold });
  96. titleLabel.setJustificationType (Justification::centred);
  97. addAndMakeVisible (titleLabel);
  98. contentLabel.setText ("A new version of JUCE is available - would you like to download it?", dontSendNotification);
  99. contentLabel.setFont (15.0f);
  100. contentLabel.setJustificationType (Justification::topLeft);
  101. addAndMakeVisible (contentLabel);
  102. releaseNotesLabel.setText ("Release notes:", dontSendNotification);
  103. releaseNotesLabel.setFont (15.0f);
  104. releaseNotesLabel.setJustificationType (Justification::topLeft);
  105. addAndMakeVisible (releaseNotesLabel);
  106. releaseNotesEditor.setMultiLine (true);
  107. releaseNotesEditor.setReadOnly (true);
  108. releaseNotesEditor.setText (releaseNotes);
  109. addAndMakeVisible (releaseNotesEditor);
  110. addAndMakeVisible (chooseButton);
  111. chooseButton.onClick = [this] { exitModalStateWithResult (1); };
  112. addAndMakeVisible (cancelButton);
  113. cancelButton.onClick = [this]
  114. {
  115. if (dontAskAgainButton.getToggleState())
  116. getGlobalProperties().setValue (Ids::dontQueryForUpdate.toString(), 1);
  117. else
  118. getGlobalProperties().removeValue (Ids::dontQueryForUpdate);
  119. exitModalStateWithResult (-1);
  120. };
  121. dontAskAgainButton.setToggleState (getGlobalProperties().getValue (Ids::dontQueryForUpdate, {}).isNotEmpty(), dontSendNotification);
  122. addAndMakeVisible (dontAskAgainButton);
  123. juceIcon = Drawable::createFromImageData (BinaryData::juce_icon_png,
  124. BinaryData::juce_icon_pngSize);
  125. lookAndFeelChanged();
  126. setSize (500, 280);
  127. }
  128. void resized() override
  129. {
  130. auto b = getLocalBounds().reduced (10);
  131. auto topSlice = b.removeFromTop (juceIconBounds.getHeight())
  132. .withTrimmedLeft (juceIconBounds.getWidth());
  133. titleLabel.setBounds (topSlice.removeFromTop (25));
  134. topSlice.removeFromTop (5);
  135. contentLabel.setBounds (topSlice.removeFromTop (25));
  136. auto buttonBounds = b.removeFromBottom (60);
  137. buttonBounds.removeFromBottom (25);
  138. chooseButton.setBounds (buttonBounds.removeFromLeft (buttonBounds.getWidth() / 2).reduced (20, 0));
  139. cancelButton.setBounds (buttonBounds.reduced (20, 0));
  140. dontAskAgainButton.setBounds (cancelButton.getBounds().withY (cancelButton.getBottom() + 5).withHeight (20));
  141. releaseNotesEditor.setBounds (b.reduced (0, 10));
  142. }
  143. void paint (Graphics& g) override
  144. {
  145. g.fillAll (findColour (backgroundColourId));
  146. if (juceIcon != nullptr)
  147. juceIcon->drawWithin (g, juceIconBounds.toFloat(),
  148. RectanglePlacement::stretchToFit, 1.0f);
  149. }
  150. static std::unique_ptr<DialogWindow> launchDialog (const String& newVersionString,
  151. const String& releaseNotes)
  152. {
  153. DialogWindow::LaunchOptions options;
  154. options.dialogTitle = "Download JUCE version " + newVersionString + "?";
  155. options.resizable = false;
  156. auto* content = new UpdateDialog (newVersionString, releaseNotes);
  157. options.content.set (content, true);
  158. std::unique_ptr<DialogWindow> dialog (options.create());
  159. content->setParentWindow (dialog.get());
  160. dialog->enterModalState (true, nullptr, true);
  161. return dialog;
  162. }
  163. private:
  164. void lookAndFeelChanged() override
  165. {
  166. cancelButton.setColour (TextButton::buttonColourId, findColour (secondaryButtonBackgroundColourId));
  167. releaseNotesEditor.applyFontToAllText (releaseNotesEditor.getFont());
  168. }
  169. void setParentWindow (DialogWindow* parent)
  170. {
  171. parentWindow = parent;
  172. }
  173. void exitModalStateWithResult (int result)
  174. {
  175. if (parentWindow != nullptr)
  176. parentWindow->exitModalState (result);
  177. }
  178. Label titleLabel, contentLabel, releaseNotesLabel;
  179. TextEditor releaseNotesEditor;
  180. TextButton chooseButton { "Choose Location..." }, cancelButton { "Cancel" };
  181. ToggleButton dontAskAgainButton { "Don't ask again" };
  182. std::unique_ptr<Drawable> juceIcon;
  183. Rectangle<int> juceIconBounds { 10, 10, 64, 64 };
  184. DialogWindow* parentWindow = nullptr;
  185. };
  186. void LatestVersionCheckerAndUpdater::askUserForLocationToDownload (const VersionInfo::Asset& asset)
  187. {
  188. FileChooser chooser ("Please select the location into which you would like to install the new version",
  189. { getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get() });
  190. if (chooser.browseForDirectory())
  191. {
  192. auto targetFolder = chooser.getResult();
  193. // By default we will install into 'targetFolder/JUCE', but we should install into
  194. // 'targetFolder' if that is an existing JUCE directory.
  195. bool willOverwriteJuceFolder = [&targetFolder]
  196. {
  197. if (isJUCEFolder (targetFolder))
  198. return true;
  199. targetFolder = targetFolder.getChildFile ("JUCE");
  200. return isJUCEFolder (targetFolder);
  201. }();
  202. auto targetFolderPath = targetFolder.getFullPathName();
  203. if (willOverwriteJuceFolder)
  204. {
  205. if (targetFolder.getChildFile (".git").isDirectory())
  206. {
  207. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Downloading New JUCE Version",
  208. targetFolderPath + "\n\nis a GIT repository!\n\nYou should use a \"git pull\" to update it to the latest version.");
  209. return;
  210. }
  211. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Overwrite Existing JUCE Folder?",
  212. "Do you want to replace the folder\n\n" + targetFolderPath + "\n\nwith the latest version from juce.com?\n\n"
  213. "This will move the existing folder to " + targetFolderPath + "_old."))
  214. {
  215. return;
  216. }
  217. }
  218. else if (targetFolder.exists())
  219. {
  220. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Existing File Or Directory",
  221. "Do you want to move\n\n" + targetFolderPath + "\n\nto\n\n" + targetFolderPath + "_old?"))
  222. {
  223. return;
  224. }
  225. }
  226. downloadAndInstall (asset, targetFolder);
  227. }
  228. }
  229. void LatestVersionCheckerAndUpdater::askUserAboutNewVersion (const String& newVersionString,
  230. const String& releaseNotes,
  231. const VersionInfo::Asset& asset)
  232. {
  233. dialogWindow = UpdateDialog::launchDialog (newVersionString, releaseNotes);
  234. if (auto* mm = ModalComponentManager::getInstance())
  235. mm->attachCallback (dialogWindow.get(),
  236. ModalCallbackFunction::create ([this, asset] (int result)
  237. {
  238. if (result == 1)
  239. askUserForLocationToDownload (asset);
  240. dialogWindow.reset();
  241. }));
  242. }
  243. //==============================================================================
  244. class DownloadAndInstallThread : private ThreadWithProgressWindow
  245. {
  246. public:
  247. DownloadAndInstallThread (const VersionInfo::Asset& a, const File& t, std::function<void()>&& cb)
  248. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  249. asset (a), targetFolder (t), completionCallback (std::move (cb))
  250. {
  251. launchThread (3);
  252. }
  253. private:
  254. void run() override
  255. {
  256. setProgress (-1.0);
  257. MemoryBlock zipData;
  258. auto result = download (zipData);
  259. if (result.wasOk() && ! threadShouldExit())
  260. result = install (zipData);
  261. if (result.failed())
  262. MessageManager::callAsync ([result] { AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  263. "Installation Failed",
  264. result.getErrorMessage()); });
  265. else
  266. MessageManager::callAsync (completionCallback);
  267. }
  268. Result download (MemoryBlock& dest)
  269. {
  270. setStatusMessage ("Downloading...");
  271. int statusCode = 0;
  272. auto inStream = VersionInfo::createInputStreamForAsset (asset, statusCode);
  273. if (inStream != nullptr && statusCode == 200)
  274. {
  275. int64 total = 0;
  276. MemoryOutputStream mo (dest, true);
  277. for (;;)
  278. {
  279. if (threadShouldExit())
  280. return Result::fail ("Cancelled");
  281. auto written = mo.writeFromInputStream (*inStream, 8192);
  282. if (written == 0)
  283. break;
  284. total += written;
  285. setStatusMessage ("Downloading... " + File::descriptionOfSizeInBytes (total));
  286. }
  287. return Result::ok();
  288. }
  289. return Result::fail ("Failed to download from: " + asset.url);
  290. }
  291. Result install (const MemoryBlock& data)
  292. {
  293. setStatusMessage ("Installing...");
  294. MemoryInputStream input (data, false);
  295. ZipFile zip (input);
  296. if (zip.getNumEntries() == 0)
  297. return Result::fail ("The downloaded file was not a valid JUCE file!");
  298. struct ScopedDownloadFolder
  299. {
  300. ScopedDownloadFolder (const File& installTargetFolder)
  301. {
  302. folder = installTargetFolder.getSiblingFile (installTargetFolder.getFileNameWithoutExtension() + "_download").getNonexistentSibling();
  303. jassert (folder.createDirectory());
  304. }
  305. ~ScopedDownloadFolder() { folder.deleteRecursively(); }
  306. File folder;
  307. };
  308. ScopedDownloadFolder unzipTarget (targetFolder);
  309. if (! unzipTarget.folder.isDirectory())
  310. return Result::fail ("Couldn't create a temporary folder to unzip the new version!");
  311. auto r = zip.uncompressTo (unzipTarget.folder);
  312. if (r.failed())
  313. return r;
  314. if (threadShouldExit())
  315. return Result::fail ("Cancelled");
  316. #if JUCE_LINUX || JUCE_MAC
  317. r = setFilePermissions (unzipTarget.folder, zip);
  318. if (r.failed())
  319. return r;
  320. if (threadShouldExit())
  321. return Result::fail ("Cancelled");
  322. #endif
  323. if (targetFolder.exists())
  324. {
  325. auto oldFolder = targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old").getNonexistentSibling();
  326. if (! targetFolder.moveFileTo (oldFolder))
  327. return Result::fail ("Could not remove the existing folder!\n\n"
  328. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  329. "Please select a folder that is writable by the current user.");
  330. }
  331. if (! unzipTarget.folder.getChildFile ("JUCE").moveFileTo (targetFolder))
  332. return Result::fail ("Could not overwrite the existing folder!\n\n"
  333. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  334. "Please select a folder that is writable by the current user.");
  335. return Result::ok();
  336. }
  337. Result setFilePermissions (const File& root, const ZipFile& zip)
  338. {
  339. constexpr uint32 executableFlag = (1 << 22);
  340. for (int i = 0; i < zip.getNumEntries(); ++i)
  341. {
  342. auto* entry = zip.getEntry (i);
  343. if ((entry->externalFileAttributes & executableFlag) != 0 && entry->filename.getLastCharacter() != '/')
  344. {
  345. auto exeFile = root.getChildFile (entry->filename);
  346. if (! exeFile.exists())
  347. return Result::fail ("Failed to find executable file when setting permissions " + exeFile.getFileName());
  348. if (! exeFile.setExecutePermission (true))
  349. return Result::fail ("Failed to set executable file permission for " + exeFile.getFileName());
  350. }
  351. }
  352. return Result::ok();
  353. }
  354. VersionInfo::Asset asset;
  355. File targetFolder;
  356. std::function<void()> completionCallback;
  357. };
  358. void restartProcess (const File& targetFolder)
  359. {
  360. #if JUCE_MAC || JUCE_LINUX
  361. #if JUCE_MAC
  362. auto newProcess = targetFolder.getChildFile ("Projucer.app").getChildFile ("Contents").getChildFile ("MacOS").getChildFile ("Projucer");
  363. #elif JUCE_LINUX
  364. auto newProcess = targetFolder.getChildFile ("Projucer");
  365. #endif
  366. StringArray command ("/bin/sh", "-c", "while killall -0 Projucer; do sleep 5; done; " + newProcess.getFullPathName().quoted());
  367. #elif JUCE_WINDOWS
  368. auto newProcess = targetFolder.getChildFile ("Projucer.exe");
  369. auto command = "cmd.exe /c\"@echo off & for /l %a in (0) do ( tasklist | find \"Projucer\" >nul & ( if errorlevel 1 ( "
  370. + targetFolder.getChildFile ("Projucer.exe").getFullPathName().quoted() + " & exit /b ) else ( timeout /t 10 >nul ) ) )\"";
  371. #endif
  372. if (newProcess.existsAsFile())
  373. {
  374. ChildProcess restartProcess;
  375. restartProcess.start (command, 0);
  376. ProjucerApplication::getApp().systemRequestedQuit();
  377. }
  378. }
  379. void LatestVersionCheckerAndUpdater::downloadAndInstall (const VersionInfo::Asset& asset, const File& targetFolder)
  380. {
  381. installer.reset (new DownloadAndInstallThread (asset, targetFolder,
  382. [this, targetFolder]
  383. {
  384. installer.reset();
  385. restartProcess (targetFolder);
  386. }));
  387. }
  388. //==============================================================================
  389. JUCE_IMPLEMENT_SINGLETON (LatestVersionCheckerAndUpdater)