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.

551 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  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 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../Application/jucer_Headers.h"
  20. #include "jucer_Application.h"
  21. #include "jucer_AutoUpdater.h"
  22. //==============================================================================
  23. LatestVersionCheckerAndUpdater::LatestVersionCheckerAndUpdater()
  24. : Thread ("VersionChecker")
  25. {
  26. }
  27. LatestVersionCheckerAndUpdater::~LatestVersionCheckerAndUpdater()
  28. {
  29. stopThread (1000);
  30. clearSingletonInstance();
  31. }
  32. void LatestVersionCheckerAndUpdater::checkForNewVersion (bool showAlerts)
  33. {
  34. if (! isThreadRunning())
  35. {
  36. showAlertWindows = showAlerts;
  37. startThread (3);
  38. }
  39. }
  40. //==============================================================================
  41. void LatestVersionCheckerAndUpdater::run()
  42. {
  43. queryUpdateServer();
  44. if (! threadShouldExit())
  45. MessageManager::callAsync ([this] { processResult(); });
  46. }
  47. //==============================================================================
  48. String getOSString()
  49. {
  50. #if JUCE_MAC
  51. return "OSX";
  52. #elif JUCE_WINDOWS
  53. return "Windows";
  54. #elif JUCE_LINUX
  55. return "Linux";
  56. #else
  57. jassertfalse;
  58. return "Unknown";
  59. #endif
  60. }
  61. namespace VersionHelpers
  62. {
  63. String formatProductVersion (int versionNum)
  64. {
  65. int major = (versionNum & 0xff0000) >> 16;
  66. int minor = (versionNum & 0x00ff00) >> 8;
  67. int build = (versionNum & 0x0000ff) >> 0;
  68. return String (major) + '.' + String (minor) + '.' + String (build);
  69. }
  70. String getProductVersionString()
  71. {
  72. return formatProductVersion (ProjectInfo::versionNumber);
  73. }
  74. bool isNewVersion (const String& current, const String& other)
  75. {
  76. auto currentTokens = StringArray::fromTokens (current, ".", {});
  77. auto otherTokens = StringArray::fromTokens (other, ".", {});
  78. jassert (currentTokens.size() == 3 && otherTokens.size() == 3);
  79. if (currentTokens[0].getIntValue() == otherTokens[0].getIntValue())
  80. {
  81. if (currentTokens[1].getIntValue() == otherTokens[1].getIntValue())
  82. return currentTokens[2].getIntValue() < otherTokens[2].getIntValue();
  83. return currentTokens[1].getIntValue() < otherTokens[1].getIntValue();
  84. }
  85. return currentTokens[0].getIntValue() < otherTokens[0].getIntValue();
  86. }
  87. }
  88. void LatestVersionCheckerAndUpdater::queryUpdateServer()
  89. {
  90. StringPairArray responseHeaders;
  91. URL latestVersionURL ("https://my.roli.com/software_versions/update_to/Projucer/"
  92. + VersionHelpers::getProductVersionString() + '/' + getOSString()
  93. + "?language=" + SystemStats::getUserLanguage());
  94. std::unique_ptr<InputStream> inStream (latestVersionURL.createInputStream (false, nullptr, nullptr,
  95. "X-API-Key: 265441b-343403c-20f6932-76361d\nContent-Type: "
  96. "application/json\nAccept: application/json; version=1",
  97. 0, &responseHeaders, &statusCode, 0));
  98. if (threadShouldExit())
  99. return;
  100. if (inStream.get() != nullptr && (statusCode == 303 || statusCode == 400))
  101. {
  102. if (statusCode == 303)
  103. relativeDownloadPath = responseHeaders["Location"];
  104. jassert (relativeDownloadPath.isNotEmpty());
  105. jsonReply = JSON::parse (inStream->readEntireStreamAsString());
  106. }
  107. else if (showAlertWindows)
  108. {
  109. if (statusCode == 204)
  110. AlertWindow::showMessageBoxAsync (AlertWindow::InfoIcon, "No New Version Available", "Your JUCE version is up to date.");
  111. else
  112. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Network Error", "Could not connect to the web server.\n"
  113. "Please check your internet connection and try again.");
  114. }
  115. }
  116. void LatestVersionCheckerAndUpdater::processResult()
  117. {
  118. if (! jsonReply.isObject())
  119. return;
  120. if (statusCode == 400)
  121. {
  122. auto errorObject = jsonReply.getDynamicObject()->getProperty ("error");
  123. if (errorObject.isObject())
  124. {
  125. auto message = errorObject.getProperty ("message", {}).toString();
  126. if (message.isNotEmpty())
  127. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "JUCE Updater", message);
  128. }
  129. }
  130. else if (statusCode == 303)
  131. {
  132. askUserAboutNewVersion (jsonReply.getProperty ("version", {}).toString(),
  133. jsonReply.getProperty ("notes", {}).toString());
  134. }
  135. }
  136. //==============================================================================
  137. class UpdateDialog : public Component
  138. {
  139. public:
  140. UpdateDialog (const String& newVersion, const String& releaseNotes)
  141. {
  142. titleLabel.setText ("JUCE version " + newVersion, dontSendNotification);
  143. titleLabel.setFont ({ 15.0f, Font::bold });
  144. titleLabel.setJustificationType (Justification::centred);
  145. addAndMakeVisible (titleLabel);
  146. contentLabel.setText ("A new version of JUCE is available - would you like to download it?", dontSendNotification);
  147. contentLabel.setFont (15.0f);
  148. contentLabel.setJustificationType (Justification::topLeft);
  149. addAndMakeVisible (contentLabel);
  150. releaseNotesLabel.setText ("Release notes:", dontSendNotification);
  151. releaseNotesLabel.setFont (15.0f);
  152. releaseNotesLabel.setJustificationType (Justification::topLeft);
  153. addAndMakeVisible (releaseNotesLabel);
  154. releaseNotesEditor.setMultiLine (true);
  155. releaseNotesEditor.setReadOnly (true);
  156. releaseNotesEditor.setText (releaseNotes);
  157. addAndMakeVisible (releaseNotesEditor);
  158. addAndMakeVisible (chooseButton);
  159. chooseButton.onClick = [this] { exitModalStateWithResult (1); };
  160. addAndMakeVisible (cancelButton);
  161. cancelButton.onClick = [this]
  162. {
  163. if (dontAskAgainButton.getToggleState())
  164. getGlobalProperties().setValue (Ids::dontQueryForUpdate.toString(), 1);
  165. else
  166. getGlobalProperties().removeValue (Ids::dontQueryForUpdate);
  167. exitModalStateWithResult (-1);
  168. };
  169. dontAskAgainButton.setToggleState (getGlobalProperties().getValue (Ids::dontQueryForUpdate, {}).isNotEmpty(), dontSendNotification);
  170. addAndMakeVisible (dontAskAgainButton);
  171. juceIcon.reset (Drawable::createFromImageData (BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize));
  172. lookAndFeelChanged();
  173. setSize (500, 280);
  174. }
  175. void resized() override
  176. {
  177. auto b = getLocalBounds().reduced (10);
  178. auto topSlice = b.removeFromTop (juceIconBounds.getHeight())
  179. .withTrimmedLeft (juceIconBounds.getWidth());
  180. titleLabel.setBounds (topSlice.removeFromTop (25));
  181. topSlice.removeFromTop (5);
  182. contentLabel.setBounds (topSlice.removeFromTop (25));
  183. auto buttonBounds = b.removeFromBottom (60);
  184. buttonBounds.removeFromBottom (25);
  185. chooseButton.setBounds (buttonBounds.removeFromLeft (buttonBounds.getWidth() / 2).reduced (20, 0));
  186. cancelButton.setBounds (buttonBounds.reduced (20, 0));
  187. dontAskAgainButton.setBounds (cancelButton.getBounds().withY (cancelButton.getBottom() + 5).withHeight (20));
  188. releaseNotesEditor.setBounds (b.reduced (0, 10));
  189. }
  190. void paint (Graphics& g) override
  191. {
  192. g.fillAll (findColour (backgroundColourId));
  193. if (juceIcon != nullptr)
  194. juceIcon->drawWithin (g, juceIconBounds.toFloat(),
  195. RectanglePlacement::stretchToFit, 1.0f);
  196. }
  197. static std::unique_ptr<DialogWindow> launchDialog (const String& newVersion, const String& releaseNotes)
  198. {
  199. DialogWindow::LaunchOptions options;
  200. options.dialogTitle = "Download JUCE version " + newVersion + "?";
  201. options.resizable = false;
  202. auto* content = new UpdateDialog (newVersion, releaseNotes);
  203. options.content.set (content, true);
  204. std::unique_ptr<DialogWindow> dialog (options.create());
  205. content->setParentWindow (dialog.get());
  206. dialog->enterModalState (true, nullptr, true);
  207. return dialog;
  208. }
  209. private:
  210. void lookAndFeelChanged() override
  211. {
  212. cancelButton.setColour (TextButton::buttonColourId, findColour (secondaryButtonBackgroundColourId));
  213. releaseNotesEditor.applyFontToAllText (releaseNotesEditor.getFont());
  214. }
  215. void setParentWindow (DialogWindow* parent)
  216. {
  217. parentWindow = parent;
  218. }
  219. void exitModalStateWithResult (int result)
  220. {
  221. if (parentWindow != nullptr)
  222. parentWindow->exitModalState (result);
  223. }
  224. Label titleLabel, contentLabel, releaseNotesLabel;
  225. TextEditor releaseNotesEditor;
  226. TextButton chooseButton { "Choose Location..." }, cancelButton { "Cancel" };
  227. ToggleButton dontAskAgainButton { "Don't ask again" };
  228. std::unique_ptr<Drawable> juceIcon;
  229. Rectangle<int> juceIconBounds { 10, 10, 64, 64 };
  230. DialogWindow* parentWindow = nullptr;
  231. };
  232. void LatestVersionCheckerAndUpdater::askUserForLocationToDownload()
  233. {
  234. FileChooser chooser ("Please select the location into which you'd like to install the new version",
  235. { getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get() });
  236. if (chooser.browseForDirectory())
  237. {
  238. auto targetFolder = chooser.getResult();
  239. if (isJUCEFolder (targetFolder))
  240. {
  241. if (targetFolder.getChildFile (".git").isDirectory())
  242. {
  243. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Downloading New JUCE Version",
  244. "This folder is a GIT repository!\n\nYou should use a \"git pull\" to update it to the latest version.");
  245. return;
  246. }
  247. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Overwrite Existing JUCE Folder?",
  248. String ("Do you want to overwrite the folder:\n\n" + targetFolder.getFullPathName() + "\n\n..with the latest version from juce.com?\n\n"
  249. "This will move the existing folder to " + targetFolder.getFullPathName() + "_old.")))
  250. {
  251. return;
  252. }
  253. }
  254. else
  255. {
  256. targetFolder = targetFolder.getChildFile ("JUCE").getNonexistentSibling();
  257. }
  258. downloadAndInstall (targetFolder);
  259. }
  260. }
  261. void LatestVersionCheckerAndUpdater::askUserAboutNewVersion (const String& newVersion, const String& releaseNotes)
  262. {
  263. if (newVersion.isNotEmpty() && releaseNotes.isNotEmpty()
  264. && VersionHelpers::isNewVersion (VersionHelpers::getProductVersionString(), newVersion))
  265. {
  266. dialogWindow = UpdateDialog::launchDialog (newVersion, releaseNotes);
  267. if (auto* mm = ModalComponentManager::getInstance())
  268. mm->attachCallback (dialogWindow.get(), ModalCallbackFunction::create ([this] (int result)
  269. {
  270. if (result == 1)
  271. askUserForLocationToDownload();
  272. dialogWindow.reset();
  273. }));
  274. }
  275. }
  276. //==============================================================================
  277. class DownloadAndInstallThread : private ThreadWithProgressWindow
  278. {
  279. public:
  280. DownloadAndInstallThread (const URL& u, const File& t, std::function<void()>&& cb)
  281. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  282. downloadURL (u), targetFolder (t), completionCallback (std::move (cb))
  283. {
  284. launchThread (3);
  285. }
  286. private:
  287. void run() override
  288. {
  289. setProgress (-1.0);
  290. MemoryBlock zipData;
  291. auto result = download (zipData);
  292. if (result.wasOk() && ! threadShouldExit())
  293. result = install (zipData);
  294. if (result.failed())
  295. MessageManager::callAsync ([result] () { AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Installation Failed", result.getErrorMessage()); });
  296. else
  297. MessageManager::callAsync (completionCallback);
  298. }
  299. Result download (MemoryBlock& dest)
  300. {
  301. setStatusMessage ("Downloading...");
  302. int statusCode = 0;
  303. StringPairArray responseHeaders;
  304. std::unique_ptr<InputStream> inStream (downloadURL.createInputStream (false, nullptr, nullptr, {}, 0,
  305. &responseHeaders, &statusCode, 0));
  306. if (inStream != nullptr && statusCode == 200)
  307. {
  308. int64 total = 0;
  309. MemoryOutputStream mo (dest, true);
  310. for (;;)
  311. {
  312. if (threadShouldExit())
  313. return Result::fail ("Cancelled");
  314. auto written = mo.writeFromInputStream (*inStream, 8192);
  315. if (written == 0)
  316. break;
  317. total += written;
  318. setStatusMessage ("Downloading... " + File::descriptionOfSizeInBytes (total));
  319. }
  320. return Result::ok();
  321. }
  322. return Result::fail ("Failed to download from: " + downloadURL.toString (false));
  323. }
  324. Result install (MemoryBlock& data)
  325. {
  326. setStatusMessage ("Installing...");
  327. auto result = unzipDownload (data);
  328. if (threadShouldExit())
  329. result = Result::fail ("Cancelled");
  330. if (result.failed())
  331. return result;
  332. return Result::ok();
  333. }
  334. Result unzipDownload (const MemoryBlock& data)
  335. {
  336. MemoryInputStream input (data, false);
  337. ZipFile zip (input);
  338. if (zip.getNumEntries() == 0)
  339. return Result::fail ("The downloaded file was not a valid JUCE file!");
  340. auto unzipTarget = File::createTempFile ({});
  341. if (! unzipTarget.createDirectory())
  342. return Result::fail ("Couldn't create a temporary folder to unzip the new version!");
  343. auto r = zip.uncompressTo (unzipTarget);
  344. if (r.failed())
  345. {
  346. unzipTarget.deleteRecursively();
  347. return r;
  348. }
  349. r = applyAutoUpdaterFile (unzipTarget);
  350. if (r.failed())
  351. {
  352. unzipTarget.deleteRecursively();
  353. return r;
  354. }
  355. if (targetFolder.exists())
  356. {
  357. auto oldFolder = targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old").getNonexistentSibling();
  358. if (! targetFolder.moveFileTo (oldFolder))
  359. {
  360. unzipTarget.deleteRecursively();
  361. return Result::fail ("Could not remove the existing folder!\n\n"
  362. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  363. "Please select a folder that is writable by the current user.");
  364. }
  365. }
  366. if (! unzipTarget.moveFileTo (targetFolder))
  367. {
  368. unzipTarget.deleteRecursively();
  369. return Result::fail ("Could not overwrite the existing folder!\n\n"
  370. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  371. "Please select a folder that is writable by the current user.");
  372. }
  373. return Result::ok();
  374. }
  375. Result applyAutoUpdaterFile (const File& root)
  376. {
  377. auto autoUpdaterFile = root.getChildFile (".autoupdater.xml");
  378. if (autoUpdaterFile.existsAsFile())
  379. {
  380. #if JUCE_LINUX || JUCE_MAC
  381. if (auto parent = parseXML (autoUpdaterFile))
  382. {
  383. if (auto* execElement = parent->getChildByName ("EXECUTABLE"))
  384. {
  385. forEachXmlChildElementWithTagName (*execElement, e, "FILE")
  386. {
  387. auto file = root.getChildFile (e->getAllSubText());
  388. if (file.exists() && ! file.setExecutePermission (true))
  389. return Result::fail ("Failed to set executable file permission for " + file.getFileName());
  390. }
  391. }
  392. }
  393. #endif
  394. autoUpdaterFile.deleteFile();
  395. }
  396. return Result::ok();
  397. }
  398. URL downloadURL;
  399. File targetFolder;
  400. std::function<void()> completionCallback;
  401. };
  402. void restartProcess (const File& targetFolder)
  403. {
  404. #if JUCE_MAC || JUCE_LINUX
  405. #if JUCE_MAC
  406. auto newProcess = targetFolder.getChildFile ("Projucer.app").getChildFile ("Contents").getChildFile ("MacOS").getChildFile ("Projucer");
  407. #elif JUCE_LINUX
  408. auto newProcess = targetFolder.getChildFile ("Projucer");
  409. #endif
  410. StringArray command ("/bin/sh", "-c", "while killall -0 Projucer; do sleep 5; done; " + newProcess.getFullPathName().quoted());
  411. #elif JUCE_WINDOWS
  412. auto newProcess = targetFolder.getChildFile ("Projucer.exe");
  413. auto command = "cmd.exe /c\"@echo off & for /l %a in (0) do ( tasklist | find \"Projucer\" >nul & ( if errorlevel 1 ( "
  414. + targetFolder.getChildFile ("Projucer.exe").getFullPathName().quoted() + " & exit /b ) else ( timeout /t 10 >nul ) ) )\"";
  415. #endif
  416. if (newProcess.existsAsFile())
  417. {
  418. ChildProcess restartProcess;
  419. restartProcess.start (command, 0);
  420. ProjucerApplication::getApp().systemRequestedQuit();
  421. }
  422. }
  423. void LatestVersionCheckerAndUpdater::downloadAndInstall (const File& targetFolder)
  424. {
  425. installer.reset (new DownloadAndInstallThread ({ relativeDownloadPath }, targetFolder,
  426. [this, targetFolder]
  427. {
  428. installer.reset();
  429. restartProcess (targetFolder);
  430. }));
  431. }
  432. //==============================================================================
  433. JUCE_IMPLEMENT_SINGLETON (LatestVersionCheckerAndUpdater)