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.

830 lines
29KB

  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. LatestVersionChecker::JuceVersionTriple::JuceVersionTriple()
  23. : major ((ProjectInfo::versionNumber & 0xff0000) >> 16),
  24. minor ((ProjectInfo::versionNumber & 0x00ff00) >> 8),
  25. build ((ProjectInfo::versionNumber & 0x0000ff) >> 0)
  26. {}
  27. LatestVersionChecker::JuceVersionTriple::JuceVersionTriple (int juceVersionNumber)
  28. : major ((juceVersionNumber & 0xff0000) >> 16),
  29. minor ((juceVersionNumber & 0x00ff00) >> 8),
  30. build ((juceVersionNumber & 0x0000ff) >> 0)
  31. {}
  32. LatestVersionChecker::JuceVersionTriple::JuceVersionTriple (int majorInt, int minorInt, int buildNumber)
  33. : major (majorInt),
  34. minor (minorInt),
  35. build (buildNumber)
  36. {}
  37. bool LatestVersionChecker::JuceVersionTriple::fromString (const String& versionString,
  38. LatestVersionChecker::JuceVersionTriple& result)
  39. {
  40. StringArray tokenizedString = StringArray::fromTokens (versionString, ".", StringRef());
  41. if (tokenizedString.size() != 3)
  42. return false;
  43. result.major = tokenizedString [0].getIntValue();
  44. result.minor = tokenizedString [1].getIntValue();
  45. result.build = tokenizedString [2].getIntValue();
  46. return true;
  47. }
  48. String LatestVersionChecker::JuceVersionTriple::toString() const
  49. {
  50. String retval;
  51. retval << major << '.' << minor << '.' << build;
  52. return retval;
  53. }
  54. bool LatestVersionChecker::JuceVersionTriple::operator> (const LatestVersionChecker::JuceVersionTriple& b) const noexcept
  55. {
  56. if (major == b.major)
  57. {
  58. if (minor == b.minor)
  59. return build > b.build;
  60. return minor > b.minor;
  61. }
  62. return major > b.major;
  63. }
  64. //==============================================================================
  65. struct RelaunchTimer : private Timer
  66. {
  67. RelaunchTimer (const File& f) : parentFolder (f)
  68. {
  69. startTimer (1500);
  70. }
  71. void timerCallback() override
  72. {
  73. stopTimer();
  74. File app = parentFolder.getChildFile (
  75. #if JUCE_MAC
  76. "Projucer.app");
  77. #elif JUCE_WINDOWS
  78. "Projucer.exe");
  79. #elif JUCE_LINUX
  80. "Projucer");
  81. #endif
  82. JUCEApplication::quit();
  83. if (app.exists())
  84. {
  85. app.setExecutePermission (true);
  86. #if JUCE_MAC
  87. app.getChildFile ("Contents")
  88. .getChildFile ("MacOS")
  89. .getChildFile ("Projucer").setExecutePermission (true);
  90. #endif
  91. app.startAsProcess();
  92. }
  93. delete this;
  94. }
  95. File parentFolder;
  96. };
  97. //==============================================================================
  98. class DownloadNewVersionThread : public ThreadWithProgressWindow
  99. {
  100. public:
  101. DownloadNewVersionThread (LatestVersionChecker& versionChecker,URL u,
  102. const String& extraHeaders, File target)
  103. : ThreadWithProgressWindow ("Downloading New Version", true, true),
  104. owner (versionChecker),
  105. result (Result::ok()),
  106. url (u), headers (extraHeaders), targetFolder (target)
  107. {
  108. }
  109. static void performDownload (LatestVersionChecker& versionChecker, URL u,
  110. const String& extraHeaders, File targetFolder)
  111. {
  112. DownloadNewVersionThread d (versionChecker, u, extraHeaders, targetFolder);
  113. if (d.runThread())
  114. {
  115. if (d.result.failed())
  116. {
  117. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  118. "Installation Failed",
  119. d.result.getErrorMessage());
  120. }
  121. else
  122. {
  123. new RelaunchTimer (targetFolder);
  124. }
  125. }
  126. }
  127. void run() override
  128. {
  129. setProgress (-1.0);
  130. MemoryBlock zipData;
  131. result = download (zipData);
  132. if (result.wasOk() && ! threadShouldExit())
  133. {
  134. setStatusMessage ("Installing...");
  135. result = owner.performUpdate (zipData, targetFolder);
  136. }
  137. }
  138. Result download (MemoryBlock& dest)
  139. {
  140. setStatusMessage ("Downloading...");
  141. int statusCode = 302;
  142. const int maxRedirects = 5;
  143. // we need to do the redirecting manually due to inconsistencies on the way headers are handled on redirects
  144. ScopedPointer<InputStream> in;
  145. for (int redirect = 0; redirect < maxRedirects; ++redirect)
  146. {
  147. StringPairArray responseHeaders;
  148. in.reset (url.createInputStream (false, nullptr, nullptr, headers,
  149. 10000, &responseHeaders, &statusCode, 0));
  150. if (in == nullptr || statusCode != 302)
  151. break;
  152. String redirectPath = responseHeaders ["Location"];
  153. if (redirectPath.isEmpty())
  154. break;
  155. url = owner.getLatestVersionURL (headers, redirectPath);
  156. }
  157. if (in != nullptr && statusCode == 200)
  158. {
  159. int64 total = 0;
  160. MemoryOutputStream mo (dest, true);
  161. for (;;)
  162. {
  163. if (threadShouldExit())
  164. return Result::fail ("cancel");
  165. int64 written = mo.writeFromInputStream (*in, 8192);
  166. if (written == 0)
  167. break;
  168. total += written;
  169. setStatusMessage (String (TRANS ("Downloading... (123)"))
  170. .replace ("123", File::descriptionOfSizeInBytes (total)));
  171. }
  172. return Result::ok();
  173. }
  174. return Result::fail ("Failed to download from: " + url.toString (false));
  175. }
  176. LatestVersionChecker& owner;
  177. Result result;
  178. URL url;
  179. String headers;
  180. File targetFolder;
  181. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DownloadNewVersionThread)
  182. };
  183. //==============================================================================
  184. class UpdateUserDialog : public Component
  185. {
  186. public:
  187. UpdateUserDialog (const LatestVersionChecker::JuceVersionTriple& version,
  188. const String& productName,
  189. const String& releaseNotes,
  190. const char* overwriteFolderPath)
  191. : hasOverwriteButton (overwriteFolderPath != nullptr)
  192. {
  193. addAndMakeVisible (titleLabel = new Label ("Title Label",
  194. TRANS ("Download \"123\" version 456?").replace ("123", productName)
  195. .replace ("456", version.toString())));
  196. titleLabel->setFont (Font (15.00f, Font::bold));
  197. titleLabel->setJustificationType (Justification::centredLeft);
  198. titleLabel->setEditable (false, false, false);
  199. addAndMakeVisible (contentLabel = new Label ("Content Label",
  200. TRANS ("A new version of \"123\" is available - would you like to download it?")
  201. .replace ("123", productName)));
  202. contentLabel->setFont (Font (15.00f, Font::plain));
  203. contentLabel->setJustificationType (Justification::topLeft);
  204. contentLabel->setEditable (false, false, false);
  205. addAndMakeVisible (okButton = new TextButton ("OK Button"));
  206. okButton->setButtonText (TRANS(hasOverwriteButton ? "Choose Another Folder..." : "OK"));
  207. okButton->onClick = [this] { exitParentDialog (2); };
  208. addAndMakeVisible (cancelButton = new TextButton ("Cancel Button"));
  209. cancelButton->setButtonText (TRANS("Cancel"));
  210. cancelButton->onClick = [this] { exitParentDialog (-1); };
  211. addAndMakeVisible (changeLogLabel = new Label ("Change Log Label",
  212. TRANS("Release Notes:")));
  213. changeLogLabel->setFont (Font (15.00f, Font::plain));
  214. changeLogLabel->setJustificationType (Justification::topLeft);
  215. changeLogLabel->setEditable (false, false, false);
  216. addAndMakeVisible (changeLog = new TextEditor ("Change Log"));
  217. changeLog->setMultiLine (true);
  218. changeLog->setReturnKeyStartsNewLine (true);
  219. changeLog->setReadOnly (true);
  220. changeLog->setScrollbarsShown (true);
  221. changeLog->setCaretVisible (false);
  222. changeLog->setPopupMenuEnabled (false);
  223. changeLog->setText (releaseNotes);
  224. if (hasOverwriteButton)
  225. {
  226. addAndMakeVisible (overwriteLabel = new Label ("Overwrite Label",
  227. TRANS("Updating will overwrite everything in the following folder:")));
  228. overwriteLabel->setFont (Font (15.00f, Font::plain));
  229. overwriteLabel->setJustificationType (Justification::topLeft);
  230. overwriteLabel->setEditable (false, false, false);
  231. addAndMakeVisible (overwritePath = new Label ("Overwrite Path", overwriteFolderPath));
  232. overwritePath->setFont (Font (15.00f, Font::bold));
  233. overwritePath->setJustificationType (Justification::topLeft);
  234. overwritePath->setEditable (false, false, false);
  235. addAndMakeVisible (overwriteButton = new TextButton ("Overwrite Button"));
  236. overwriteButton->setButtonText (TRANS("Overwrite"));
  237. overwriteButton->onClick = [this] { exitParentDialog (1); };
  238. }
  239. juceIcon = Drawable::createFromImageData (BinaryData::juce_icon_png,
  240. BinaryData::juce_icon_pngSize);
  241. setSize (518, overwritePath != nullptr ? 345 : 269);
  242. lookAndFeelChanged();
  243. }
  244. ~UpdateUserDialog()
  245. {
  246. titleLabel.reset();
  247. contentLabel.reset();
  248. okButton.reset();
  249. cancelButton.reset();
  250. changeLogLabel.reset();
  251. changeLog.reset();
  252. overwriteLabel.reset();
  253. overwritePath.reset();
  254. overwriteButton.reset();
  255. juceIcon.reset();
  256. }
  257. void paint (Graphics& g) override
  258. {
  259. g.fillAll (findColour (backgroundColourId));
  260. g.setColour (findColour (defaultTextColourId));
  261. if (juceIcon != nullptr)
  262. juceIcon->drawWithin (g, Rectangle<float> (20, 17, 64, 64),
  263. RectanglePlacement::stretchToFit, 1.000f);
  264. }
  265. void resized() override
  266. {
  267. titleLabel->setBounds (88, 10, 397, 24);
  268. contentLabel->setBounds (88, 40, 397, 51);
  269. changeLogLabel->setBounds (22, 92, 341, 24);
  270. changeLog->setBounds (24, 112, 476, 102);
  271. if (hasOverwriteButton)
  272. {
  273. okButton->setBounds (getWidth() - 24 - 174, getHeight() - 37, 174, 28);
  274. overwriteButton->setBounds ((getWidth() - 24 - 174) + -14 - 86, getHeight() - 37, 86, 28);
  275. cancelButton->setBounds (24, getHeight() - 37, 70, 28);
  276. overwriteLabel->setBounds (24, 238, 472, 16);
  277. overwritePath->setBounds (24, 262, 472, 40);
  278. }
  279. else
  280. {
  281. okButton->setBounds (getWidth() - 24 - 47, getHeight() - 37, 47, 28);
  282. cancelButton->setBounds ((getWidth() - 24 - 47) + -14 - 70, getHeight() - 37, 70, 28);
  283. }
  284. }
  285. void exitParentDialog (int returnVal)
  286. {
  287. if (auto* parentDialog = findParentComponentOfClass<DialogWindow>())
  288. parentDialog->exitModalState (returnVal);
  289. else
  290. jassertfalse;
  291. }
  292. static DialogWindow* launch (const LatestVersionChecker::JuceVersionTriple& version,
  293. const String& productName,
  294. const String& releaseNotes,
  295. const char* overwritePath = nullptr)
  296. {
  297. OptionalScopedPointer<Component> userDialog (new UpdateUserDialog (version, productName,
  298. releaseNotes, overwritePath), true);
  299. DialogWindow::LaunchOptions lo;
  300. lo.dialogTitle = TRANS ("Download \"123\" version 456?").replace ("456", version.toString())
  301. .replace ("123", productName);
  302. lo.dialogBackgroundColour = userDialog->findColour (backgroundColourId);
  303. lo.content = userDialog;
  304. lo.componentToCentreAround = nullptr;
  305. lo.escapeKeyTriggersCloseButton = true;
  306. lo.useNativeTitleBar = true;
  307. lo.resizable = false;
  308. lo.useBottomRightCornerResizer = false;
  309. return lo.launchAsync();
  310. }
  311. private:
  312. bool hasOverwriteButton;
  313. ScopedPointer<Label> titleLabel, contentLabel, changeLogLabel, overwriteLabel, overwritePath;
  314. ScopedPointer<TextButton> okButton, cancelButton;
  315. ScopedPointer<TextEditor> changeLog;
  316. ScopedPointer<TextButton> overwriteButton;
  317. ScopedPointer<Drawable> juceIcon;
  318. void lookAndFeelChanged() override
  319. {
  320. cancelButton->setColour (TextButton::buttonColourId,
  321. findColour (secondaryButtonBackgroundColourId));
  322. changeLog->applyFontToAllText (changeLog->getFont());
  323. }
  324. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UpdateUserDialog)
  325. };
  326. //==============================================================================
  327. class UpdaterDialogModalCallback : public ModalComponentManager::Callback
  328. {
  329. public:
  330. struct DelayedCallback : private Timer
  331. {
  332. DelayedCallback (LatestVersionChecker& versionChecker,
  333. URL& newVersionToDownload,
  334. const String& extraHeaders,
  335. const File& appParentFolder,
  336. int returnValue)
  337. : parent (versionChecker), download (newVersionToDownload),
  338. headers (extraHeaders), folder (appParentFolder), result (returnValue)
  339. {
  340. startTimer (200);
  341. }
  342. private:
  343. void timerCallback() override
  344. {
  345. stopTimer();
  346. parent.modalStateFinished (result, download, headers, folder);
  347. delete this;
  348. }
  349. LatestVersionChecker& parent;
  350. URL download;
  351. String headers;
  352. File folder;
  353. int result;
  354. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DelayedCallback)
  355. };
  356. UpdaterDialogModalCallback (LatestVersionChecker& versionChecker,
  357. URL& newVersionToDownload,
  358. const String& extraHeaders,
  359. const File& appParentFolder)
  360. : parent (versionChecker), download (newVersionToDownload),
  361. headers (extraHeaders), folder (appParentFolder)
  362. {}
  363. void modalStateFinished (int returnValue) override
  364. {
  365. // the dialog window is only closed after this function exits
  366. // so we need a deferred callback to the parent. Unfortunately
  367. // our instance is also deleted after this function is used
  368. // so we can't use our own instance for a timer callback
  369. // we must allocate a new one.
  370. new DelayedCallback (parent, download, headers, folder, returnValue);
  371. }
  372. private:
  373. LatestVersionChecker& parent;
  374. URL download;
  375. String headers;
  376. File folder;
  377. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (UpdaterDialogModalCallback)
  378. };
  379. //==============================================================================
  380. LatestVersionChecker::LatestVersionChecker() : Thread ("Updater"),
  381. statusCode (-1),
  382. hasAttemptedToReadWebsite (false)
  383. {
  384. startTimer (2000);
  385. }
  386. LatestVersionChecker::~LatestVersionChecker()
  387. {
  388. stopThread (20000);
  389. }
  390. String LatestVersionChecker::getOSString()
  391. {
  392. SystemStats::OperatingSystemType osType = SystemStats::getOperatingSystemType();
  393. if ((osType & SystemStats::MacOSX) != 0) return "OSX";
  394. else if ((osType & SystemStats::Windows) != 0) return "Windows";
  395. else if ((osType & SystemStats::Linux) != 0) return "Linux";
  396. else return SystemStats::getOperatingSystemName();
  397. }
  398. const LatestVersionChecker::JuceServerLocationsAndKeys& LatestVersionChecker::getJuceServerURLsAndKeys() const
  399. {
  400. static LatestVersionChecker::JuceServerLocationsAndKeys urlsAndKeys =
  401. {
  402. "https://my.roli.com",
  403. "265441b-343403c-20f6932-76361d",
  404. 1,
  405. "/software_versions/update_to/Projucer/"
  406. };
  407. return urlsAndKeys;
  408. }
  409. int LatestVersionChecker::getProductVersionNumber() const { return ProjectInfo::versionNumber; }
  410. const char* LatestVersionChecker::getProductName() const { return ProjectInfo::projectName; }
  411. bool LatestVersionChecker::allowCustomLocation() const { return true; }
  412. Result LatestVersionChecker::performUpdate (const MemoryBlock& data, File& targetFolder)
  413. {
  414. File unzipTarget;
  415. bool isUsingTempFolder = false;
  416. {
  417. MemoryInputStream input (data, false);
  418. ZipFile zip (input);
  419. if (zip.getNumEntries() == 0)
  420. return Result::fail ("The downloaded file wasn't a valid JUCE file!");
  421. unzipTarget = targetFolder;
  422. if (unzipTarget.exists())
  423. {
  424. isUsingTempFolder = true;
  425. unzipTarget = targetFolder.getNonexistentSibling();
  426. if (! unzipTarget.createDirectory())
  427. return Result::fail ("Couldn't create a folder to unzip the new version!");
  428. }
  429. Result r (zip.uncompressTo (unzipTarget));
  430. if (r.failed())
  431. {
  432. if (isUsingTempFolder)
  433. unzipTarget.deleteRecursively();
  434. return r;
  435. }
  436. }
  437. if (isUsingTempFolder)
  438. {
  439. File oldFolder (targetFolder.getSiblingFile (targetFolder.getFileNameWithoutExtension() + "_old")
  440. .getNonexistentSibling());
  441. if (! targetFolder.moveFileTo (oldFolder))
  442. {
  443. unzipTarget.deleteRecursively();
  444. return Result::fail ("Could not remove the existing folder!");
  445. }
  446. if (! unzipTarget.moveFileTo (targetFolder))
  447. {
  448. unzipTarget.deleteRecursively();
  449. return Result::fail ("Could not overwrite the existing folder!");
  450. }
  451. }
  452. return Result::ok();
  453. }
  454. URL LatestVersionChecker::getLatestVersionURL (String& headers, const String& path) const
  455. {
  456. const LatestVersionChecker::JuceServerLocationsAndKeys& urlsAndKeys = getJuceServerURLsAndKeys();
  457. String updateURL;
  458. bool isAbsolute = (path.startsWith ("http://") || path.startsWith ("https://"));
  459. bool isRedirect = path.isNotEmpty();
  460. if (isAbsolute)
  461. {
  462. updateURL = path;
  463. }
  464. else
  465. {
  466. updateURL << urlsAndKeys.updateSeverHostname
  467. << (isRedirect ? path : String (urlsAndKeys.updatePath));
  468. if (! isRedirect)
  469. {
  470. updateURL << JuceVersionTriple (getProductVersionNumber()).toString() << '/'
  471. << getOSString() << "?language=" << SystemStats::getUserLanguage();
  472. }
  473. }
  474. headers.clear();
  475. if (! isAbsolute)
  476. {
  477. headers << "X-API-Key: " << urlsAndKeys.publicAPIKey;
  478. if (! isRedirect)
  479. {
  480. headers << "\nContent-Type: application/json\n"
  481. << "Accept: application/json; version=" << urlsAndKeys.apiVersion;
  482. }
  483. }
  484. return URL (updateURL);
  485. }
  486. URL LatestVersionChecker::getLatestVersionURL (String& headers) const
  487. {
  488. String emptyString;
  489. return getLatestVersionURL (headers, emptyString);
  490. }
  491. void LatestVersionChecker::checkForNewVersion()
  492. {
  493. hasAttemptedToReadWebsite = true;
  494. {
  495. String extraHeaders;
  496. URL updateURL (getLatestVersionURL (extraHeaders));
  497. StringPairArray responseHeaders;
  498. const int numRedirects = 0;
  499. const ScopedPointer<InputStream> in (updateURL.createInputStream (false, nullptr, nullptr,
  500. extraHeaders, 0, &responseHeaders,
  501. &statusCode, numRedirects));
  502. if (threadShouldExit())
  503. return; // can't connect: fail silently.
  504. if (in != nullptr && (statusCode == 303 || statusCode == 400))
  505. {
  506. // if this doesn't fail then there is a new version available.
  507. // By leaving the scope of this function we will abort the download
  508. // to give the user a chance to cancel an update
  509. if (statusCode == 303)
  510. newRelativeDownloadPath = responseHeaders ["Location"];
  511. jsonReply = JSON::parse (in->readEntireStreamAsString());
  512. }
  513. }
  514. if (! threadShouldExit())
  515. startTimer (100);
  516. }
  517. bool LatestVersionChecker::processResult (var reply, const String& downloadPath)
  518. {
  519. if (statusCode == 303)
  520. {
  521. String versionString = reply.getProperty ("version", var()).toString();
  522. String releaseNotes = reply.getProperty ("notes", var()).toString();
  523. JuceVersionTriple version;
  524. if (versionString.isNotEmpty() && releaseNotes.isNotEmpty())
  525. {
  526. if (JuceVersionTriple::fromString (versionString, version))
  527. {
  528. String extraHeaders;
  529. URL newVersionToDownload = getLatestVersionURL (extraHeaders, downloadPath);
  530. return askUserAboutNewVersion (version, releaseNotes, newVersionToDownload, extraHeaders);
  531. }
  532. }
  533. }
  534. else if (statusCode == 400)
  535. {
  536. // In the far-distant future, this may be contacting a defunct
  537. // URL, so hopefully the website will contain a helpful message
  538. // for the user..
  539. var errorObj = reply.getDynamicObject()->getProperty ("error");
  540. if (errorObj.isObject())
  541. {
  542. String message = errorObj.getProperty ("message", var()).toString();
  543. if (message.isNotEmpty())
  544. {
  545. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  546. TRANS("JUCE Updater"),
  547. message);
  548. return false;
  549. }
  550. }
  551. }
  552. // try again
  553. return true;
  554. }
  555. bool LatestVersionChecker::askUserAboutNewVersion (const LatestVersionChecker::JuceVersionTriple& version,
  556. const String& releaseNotes,
  557. URL& newVersionToDownload,
  558. const String& extraHeaders)
  559. {
  560. JuceVersionTriple currentVersion (getProductVersionNumber());
  561. if (version > currentVersion)
  562. {
  563. File appParentFolder (File::getSpecialLocation (File::currentApplicationFile).getParentDirectory());
  564. DialogWindow* modalDialog = nullptr;
  565. if (isZipFolder (appParentFolder) && allowCustomLocation())
  566. {
  567. modalDialog = UpdateUserDialog::launch (version, getProductName(), releaseNotes,
  568. appParentFolder.getFullPathName().toRawUTF8());
  569. }
  570. else
  571. {
  572. modalDialog = UpdateUserDialog::launch (version, getProductName(), releaseNotes);
  573. }
  574. if (modalDialog != nullptr)
  575. {
  576. UpdaterDialogModalCallback* callback = new UpdaterDialogModalCallback (*this,
  577. newVersionToDownload,
  578. extraHeaders,
  579. appParentFolder);
  580. // attachCallback will delete callback
  581. if (ModalComponentManager* mm = ModalComponentManager::getInstance())
  582. mm->attachCallback (modalDialog, callback);
  583. }
  584. return false;
  585. }
  586. return true;
  587. }
  588. void LatestVersionChecker::modalStateFinished (int result,
  589. URL& newVersionToDownload,
  590. const String& extraHeaders,
  591. File appParentFolder)
  592. {
  593. if (result == 1 || result == 2)
  594. {
  595. if (result == 1 || ! allowCustomLocation())
  596. DownloadNewVersionThread::performDownload (*this, newVersionToDownload, extraHeaders, appParentFolder);
  597. else
  598. askUserForLocationToDownload (newVersionToDownload, extraHeaders);
  599. }
  600. }
  601. void LatestVersionChecker::askUserForLocationToDownload (URL& newVersionToDownload, const String& extraHeaders)
  602. {
  603. File targetFolder (EnabledModuleList::findGlobalModulesFolder());
  604. if (isJUCEModulesFolder (targetFolder))
  605. targetFolder = targetFolder.getParentDirectory();
  606. FileChooser chooser (TRANS("Please select the location into which you'd like to install the new version"),
  607. targetFolder);
  608. if (chooser.browseForDirectory())
  609. {
  610. targetFolder = chooser.getResult();
  611. if (isJUCEModulesFolder (targetFolder))
  612. targetFolder = targetFolder.getParentDirectory();
  613. if (targetFolder.getChildFile ("JUCE").isDirectory())
  614. targetFolder = targetFolder.getChildFile ("JUCE");
  615. if (targetFolder.getChildFile (".git").isDirectory())
  616. {
  617. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  618. TRANS ("Downloading new JUCE version"),
  619. TRANS ("This folder is a GIT repository!\n\n"
  620. "You should use a \"git pull\" to update it to the latest version. "
  621. "Or to use the Projucer to get an update, you should select an empty "
  622. "folder into which you'd like to download the new code."));
  623. return;
  624. }
  625. if (isJUCEFolder (targetFolder))
  626. {
  627. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  628. TRANS("Overwrite existing JUCE folder?"),
  629. TRANS("Do you want to overwrite the folder:\n\n"
  630. "xfldrx\n\n"
  631. " ..with the latest version from juce.com?\n\n"
  632. "(Please note that this will overwrite everything in that folder!)")
  633. .replace ("xfldrx", targetFolder.getFullPathName())))
  634. {
  635. return;
  636. }
  637. }
  638. else
  639. {
  640. targetFolder = targetFolder.getChildFile ("JUCE").getNonexistentSibling();
  641. }
  642. DownloadNewVersionThread::performDownload (*this, newVersionToDownload, extraHeaders, targetFolder);
  643. }
  644. }
  645. bool LatestVersionChecker::isZipFolder (const File& f)
  646. {
  647. return f.getChildFile ("modules").isDirectory()
  648. && f.getChildFile ("extras").isDirectory()
  649. && f.getChildFile ("examples").isDirectory()
  650. && ! f.getChildFile (".git").isDirectory();
  651. }
  652. void LatestVersionChecker::timerCallback()
  653. {
  654. stopTimer();
  655. if (hasAttemptedToReadWebsite)
  656. {
  657. bool restartTimer = true;
  658. if (jsonReply.isObject())
  659. restartTimer = processResult (jsonReply, newRelativeDownloadPath);
  660. hasAttemptedToReadWebsite = false;
  661. if (restartTimer)
  662. startTimer (7200000);
  663. }
  664. else
  665. {
  666. startThread (3);
  667. }
  668. }
  669. void LatestVersionChecker::run()
  670. {
  671. checkForNewVersion();
  672. }