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 = Drawable::createFromImageData (BinaryData::juce_icon_png,
  172. BinaryData::juce_icon_pngSize);
  173. lookAndFeelChanged();
  174. setSize (500, 280);
  175. }
  176. void resized() override
  177. {
  178. auto b = getLocalBounds().reduced (10);
  179. auto topSlice = b.removeFromTop (juceIconBounds.getHeight())
  180. .withTrimmedLeft (juceIconBounds.getWidth());
  181. titleLabel.setBounds (topSlice.removeFromTop (25));
  182. topSlice.removeFromTop (5);
  183. contentLabel.setBounds (topSlice.removeFromTop (25));
  184. auto buttonBounds = b.removeFromBottom (60);
  185. buttonBounds.removeFromBottom (25);
  186. chooseButton.setBounds (buttonBounds.removeFromLeft (buttonBounds.getWidth() / 2).reduced (20, 0));
  187. cancelButton.setBounds (buttonBounds.reduced (20, 0));
  188. dontAskAgainButton.setBounds (cancelButton.getBounds().withY (cancelButton.getBottom() + 5).withHeight (20));
  189. releaseNotesEditor.setBounds (b.reduced (0, 10));
  190. }
  191. void paint (Graphics& g) override
  192. {
  193. g.fillAll (findColour (backgroundColourId));
  194. if (juceIcon != nullptr)
  195. juceIcon->drawWithin (g, juceIconBounds.toFloat(),
  196. RectanglePlacement::stretchToFit, 1.0f);
  197. }
  198. static std::unique_ptr<DialogWindow> launchDialog (const String& newVersion, const String& releaseNotes)
  199. {
  200. DialogWindow::LaunchOptions options;
  201. options.dialogTitle = "Download JUCE version " + newVersion + "?";
  202. options.resizable = false;
  203. auto* content = new UpdateDialog (newVersion, releaseNotes);
  204. options.content.set (content, true);
  205. std::unique_ptr<DialogWindow> dialog (options.create());
  206. content->setParentWindow (dialog.get());
  207. dialog->enterModalState (true, nullptr, true);
  208. return dialog;
  209. }
  210. private:
  211. void lookAndFeelChanged() override
  212. {
  213. cancelButton.setColour (TextButton::buttonColourId, findColour (secondaryButtonBackgroundColourId));
  214. releaseNotesEditor.applyFontToAllText (releaseNotesEditor.getFont());
  215. }
  216. void setParentWindow (DialogWindow* parent)
  217. {
  218. parentWindow = parent;
  219. }
  220. void exitModalStateWithResult (int result)
  221. {
  222. if (parentWindow != nullptr)
  223. parentWindow->exitModalState (result);
  224. }
  225. Label titleLabel, contentLabel, releaseNotesLabel;
  226. TextEditor releaseNotesEditor;
  227. TextButton chooseButton { "Choose Location..." }, cancelButton { "Cancel" };
  228. ToggleButton dontAskAgainButton { "Don't ask again" };
  229. std::unique_ptr<Drawable> juceIcon;
  230. Rectangle<int> juceIconBounds { 10, 10, 64, 64 };
  231. DialogWindow* parentWindow = nullptr;
  232. };
  233. void LatestVersionCheckerAndUpdater::askUserForLocationToDownload()
  234. {
  235. FileChooser chooser ("Please select the location into which you'd like to install the new version",
  236. { getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get() });
  237. if (chooser.browseForDirectory())
  238. {
  239. auto targetFolder = chooser.getResult();
  240. if (isJUCEFolder (targetFolder))
  241. {
  242. if (targetFolder.getChildFile (".git").isDirectory())
  243. {
  244. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Downloading New JUCE Version",
  245. "This folder is a GIT repository!\n\nYou should use a \"git pull\" to update it to the latest version.");
  246. return;
  247. }
  248. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon, "Overwrite Existing JUCE Folder?",
  249. String ("Do you want to overwrite the folder:\n\n" + targetFolder.getFullPathName() + "\n\n..with the latest version from juce.com?\n\n"
  250. "This will move the existing folder to " + targetFolder.getFullPathName() + "_old.")))
  251. {
  252. return;
  253. }
  254. }
  255. else
  256. {
  257. targetFolder = targetFolder.getChildFile ("JUCE").getNonexistentSibling();
  258. }
  259. downloadAndInstall (targetFolder);
  260. }
  261. }
  262. void LatestVersionCheckerAndUpdater::askUserAboutNewVersion (const String& newVersion, const String& releaseNotes)
  263. {
  264. if (newVersion.isNotEmpty() && releaseNotes.isNotEmpty()
  265. && VersionHelpers::isNewVersion (VersionHelpers::getProductVersionString(), newVersion))
  266. {
  267. dialogWindow = UpdateDialog::launchDialog (newVersion, releaseNotes);
  268. if (auto* mm = ModalComponentManager::getInstance())
  269. mm->attachCallback (dialogWindow.get(), ModalCallbackFunction::create ([this] (int result)
  270. {
  271. if (result == 1)
  272. askUserForLocationToDownload();
  273. dialogWindow.reset();
  274. }));
  275. }
  276. }
  277. //==============================================================================
  278. class DownloadAndInstallThread : private ThreadWithProgressWindow
  279. {
  280. public:
  281. DownloadAndInstallThread (const URL& u, const File& t, std::function<void()>&& cb)
  282. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  283. downloadURL (u), targetFolder (t), completionCallback (std::move (cb))
  284. {
  285. launchThread (3);
  286. }
  287. private:
  288. void run() override
  289. {
  290. setProgress (-1.0);
  291. MemoryBlock zipData;
  292. auto result = download (zipData);
  293. if (result.wasOk() && ! threadShouldExit())
  294. result = install (zipData);
  295. if (result.failed())
  296. MessageManager::callAsync ([result] () { AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon, "Installation Failed", result.getErrorMessage()); });
  297. else
  298. MessageManager::callAsync (completionCallback);
  299. }
  300. Result download (MemoryBlock& dest)
  301. {
  302. setStatusMessage ("Downloading...");
  303. int statusCode = 0;
  304. StringPairArray responseHeaders;
  305. std::unique_ptr<InputStream> inStream (downloadURL.createInputStream (false, nullptr, nullptr, {}, 0,
  306. &responseHeaders, &statusCode, 0));
  307. if (inStream != nullptr && statusCode == 200)
  308. {
  309. int64 total = 0;
  310. MemoryOutputStream mo (dest, true);
  311. for (;;)
  312. {
  313. if (threadShouldExit())
  314. return Result::fail ("Cancelled");
  315. auto written = mo.writeFromInputStream (*inStream, 8192);
  316. if (written == 0)
  317. break;
  318. total += written;
  319. setStatusMessage ("Downloading... " + File::descriptionOfSizeInBytes (total));
  320. }
  321. return Result::ok();
  322. }
  323. return Result::fail ("Failed to download from: " + downloadURL.toString (false));
  324. }
  325. Result install (MemoryBlock& data)
  326. {
  327. setStatusMessage ("Installing...");
  328. auto result = unzipDownload (data);
  329. if (threadShouldExit())
  330. result = Result::fail ("Cancelled");
  331. if (result.failed())
  332. return result;
  333. return Result::ok();
  334. }
  335. Result unzipDownload (const MemoryBlock& data)
  336. {
  337. MemoryInputStream input (data, false);
  338. ZipFile zip (input);
  339. if (zip.getNumEntries() == 0)
  340. return Result::fail ("The downloaded file was not a valid JUCE file!");
  341. auto unzipTarget = File::createTempFile ({});
  342. if (! unzipTarget.createDirectory())
  343. return Result::fail ("Couldn't create a temporary folder to unzip the new version!");
  344. auto r = zip.uncompressTo (unzipTarget);
  345. if (r.failed())
  346. {
  347. unzipTarget.deleteRecursively();
  348. return r;
  349. }
  350. r = applyAutoUpdaterFile (unzipTarget);
  351. if (r.failed())
  352. {
  353. unzipTarget.deleteRecursively();
  354. return r;
  355. }
  356. if (targetFolder.exists())
  357. {
  358. auto oldFolder = targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old").getNonexistentSibling();
  359. if (! targetFolder.moveFileTo (oldFolder))
  360. {
  361. unzipTarget.deleteRecursively();
  362. return Result::fail ("Could not remove the existing folder!\n\n"
  363. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  364. "Please select a folder that is writable by the current user.");
  365. }
  366. }
  367. if (! unzipTarget.moveFileTo (targetFolder))
  368. {
  369. unzipTarget.deleteRecursively();
  370. return Result::fail ("Could not overwrite the existing folder!\n\n"
  371. "This may happen if you are trying to download into a directory that requires administrator privileges to modify.\n"
  372. "Please select a folder that is writable by the current user.");
  373. }
  374. return Result::ok();
  375. }
  376. Result applyAutoUpdaterFile (const File& root)
  377. {
  378. auto autoUpdaterFile = root.getChildFile (".autoupdater.xml");
  379. if (autoUpdaterFile.existsAsFile())
  380. {
  381. #if JUCE_LINUX || JUCE_MAC
  382. if (auto parent = parseXML (autoUpdaterFile))
  383. {
  384. if (auto* execElement = parent->getChildByName ("EXECUTABLE"))
  385. {
  386. forEachXmlChildElementWithTagName (*execElement, e, "FILE")
  387. {
  388. auto file = root.getChildFile (e->getAllSubText());
  389. if (file.exists() && ! file.setExecutePermission (true))
  390. return Result::fail ("Failed to set executable file permission for " + file.getFileName());
  391. }
  392. }
  393. }
  394. #endif
  395. autoUpdaterFile.deleteFile();
  396. }
  397. return Result::ok();
  398. }
  399. URL downloadURL;
  400. File targetFolder;
  401. std::function<void()> completionCallback;
  402. };
  403. void restartProcess (const File& targetFolder)
  404. {
  405. #if JUCE_MAC || JUCE_LINUX
  406. #if JUCE_MAC
  407. auto newProcess = targetFolder.getChildFile ("Projucer.app").getChildFile ("Contents").getChildFile ("MacOS").getChildFile ("Projucer");
  408. #elif JUCE_LINUX
  409. auto newProcess = targetFolder.getChildFile ("Projucer");
  410. #endif
  411. StringArray command ("/bin/sh", "-c", "while killall -0 Projucer; do sleep 5; done; " + newProcess.getFullPathName().quoted());
  412. #elif JUCE_WINDOWS
  413. auto newProcess = targetFolder.getChildFile ("Projucer.exe");
  414. auto command = "cmd.exe /c\"@echo off & for /l %a in (0) do ( tasklist | find \"Projucer\" >nul & ( if errorlevel 1 ( "
  415. + targetFolder.getChildFile ("Projucer.exe").getFullPathName().quoted() + " & exit /b ) else ( timeout /t 10 >nul ) ) )\"";
  416. #endif
  417. if (newProcess.existsAsFile())
  418. {
  419. ChildProcess restartProcess;
  420. restartProcess.start (command, 0);
  421. ProjucerApplication::getApp().systemRequestedQuit();
  422. }
  423. }
  424. void LatestVersionCheckerAndUpdater::downloadAndInstall (const File& targetFolder)
  425. {
  426. installer.reset (new DownloadAndInstallThread ({ relativeDownloadPath }, targetFolder,
  427. [this, targetFolder]
  428. {
  429. installer.reset();
  430. restartProcess (targetFolder);
  431. }));
  432. }
  433. //==============================================================================
  434. JUCE_IMPLEMENT_SINGLETON (LatestVersionCheckerAndUpdater)