Updater.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. #include "ui/Updater.h"
  2. #include <atomic>
  3. #include <memory>
  4. #include <mutex>
  5. #include <optional>
  6. #include "platform/Package.h"
  7. #include "platform/Paths.h"
  8. #include "ui/I18n.h"
  9. #include "ui/Theme.h"
  10. #include "ui/WindowOwner.h"
  11. #if JUCE_WINDOWS
  12. #ifndef NOMINMAX
  13. #define NOMINMAX
  14. #endif
  15. #include <windows.h>
  16. #else
  17. #include <unistd.h>
  18. #endif
  19. namespace lynx::updater
  20. {
  21. namespace
  22. {
  23. // the failure text of a download stopped by Cancel (never shown)
  24. const juce::String cancelledMarker ("\x01" "cancelled");
  25. juce::String env (const char* name) { return juce::SystemStats::getEnvironmentVariable (name, {}).trim(); }
  26. juce::String fromUtf8 (const std::string& s) { return juce::String::fromUTF8 (s.c_str()); }
  27. std::string utf8 (const juce::String& s) { return s.toStdString(); }
  28. // --- where things go (a test profile keeps them all inside it) --------------------------------------------------
  29. juce::File updateFolder()
  30. {
  31. const auto profile = platform::profileOverride();
  32. const auto base = profile != juce::File() ? profile.getChildFile ("Temp") : juce::File::getSpecialLocation (juce::File::tempDirectory);
  33. return base.getChildFile ("LYNX-update");
  34. }
  35. juce::File downloadsFolder()
  36. {
  37. const auto profile = platform::profileOverride();
  38. if (profile != juce::File())
  39. return profile.getChildFile ("Downloads");
  40. #if JUCE_WINDOWS
  41. // the Downloads known folder (it can be moved to another drive)
  42. const auto known = juce::WindowsRegistry::getValue (
  43. "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\User Shell Folders\\{374DE290-123F-4565-9164-39C4925E467B}");
  44. if (known.isNotEmpty())
  45. {
  46. wchar_t expanded[MAX_PATH * 2] {};
  47. if (ExpandEnvironmentStringsW (known.toWideCharPointer(), expanded, (DWORD) std::size (expanded)) > 0)
  48. if (const juce::File f { juce::String (expanded) }; juce::File::isAbsolutePath (f.getFullPathName()) && f.isDirectory())
  49. return f;
  50. }
  51. #endif
  52. const auto xdg = env ("XDG_DOWNLOAD_DIR");
  53. if (juce::File::isAbsolutePath (xdg) && juce::File (xdg).isDirectory())
  54. return juce::File (xdg);
  55. return juce::File::getSpecialLocation (juce::File::userHomeDirectory).getChildFile ("Downloads");
  56. }
  57. juce::File settingsPath() { return platform::settingsFile ("updates.txt"); }
  58. juce::File cachePath() { return platform::settingsFile ("update-cache.json"); }
  59. update::Settings loadSettings() { return update::parseSettings (utf8 (settingsPath().loadFileAsString())); }
  60. void saveSettings (const update::Settings& s) { settingsPath().replaceWithText (fromUtf8 (update::formatSettings (s))); }
  61. update::Version runningVersion()
  62. {
  63. const auto forced = env ("LYNX_UPDATE_VERSION");
  64. return update::parseVersion (utf8 (forced.isNotEmpty() ? forced : juce::String (JUCE_APPLICATION_VERSION_STRING)));
  65. }
  66. juce::String overrideUrl() { return env ("LYNX_UPDATE_URL"); }
  67. juce::String userAgent() { return "LYNX-SHARE/" + juce::String (JUCE_APPLICATION_VERSION_STRING) + " (update check)"; }
  68. #if JUCE_LINUX || JUCE_BSD
  69. juce::File findInPath (const juce::String& program)
  70. {
  71. for (const auto& dir : juce::StringArray::fromTokens (env ("PATH"), ":", {}))
  72. if (const auto f = juce::File (dir).getChildFile (program); dir.isNotEmpty() && juce::File::isAbsolutePath (dir) && f.existsAsFile())
  73. return f;
  74. return {};
  75. }
  76. #endif
  77. juce::File appImageFile()
  78. {
  79. const auto path = env ("APPIMAGE");
  80. return juce::File::isAbsolutePath (path) && juce::File (path).existsAsFile() ? juce::File (path) : juce::File();
  81. }
  82. void log (const juce::String& line)
  83. {
  84. updateFolder().createDirectory();
  85. updateFolder().getChildFile ("update.log").appendText (juce::Time::getCurrentTime().toISO8601 (true) + " " + line + "\n");
  86. }
  87. // ================================================================================================================
  88. // the controller: state, the worker thread, the network
  89. // ================================================================================================================
  90. enum class Phase
  91. {
  92. idle,
  93. checking,
  94. available, // the bar offers the update
  95. downloading, // (progress, Cancel)
  96. working, // appimageupdatetool runs
  97. ready, // downloaded and checked: "Install and restart" / "Restart now"
  98. saved, // zip / dmg saved to Downloads
  99. failed,
  100. updated // the first start after an update by the installer
  101. };
  102. class Controller final : public juce::ChangeBroadcaster,
  103. private juce::Thread
  104. {
  105. public:
  106. Controller() : juce::Thread ("LYNX update check") {}
  107. ~Controller() override { stop(); }
  108. // --- state (message thread) ---
  109. Phase phase = Phase::idle;
  110. bool manual = false, hidden = false;
  111. update::Release release;
  112. juce::String error;
  113. std::atomic<float> progress { -1.0f };
  114. juce::File result; // the downloaded file / the AppImage to start
  115. Host host;
  116. // round 190gh (B2): `release` is an older version being installed (Help › Go back to...), not an update
  117. bool rollingBack = false;
  118. void stop()
  119. {
  120. cancelled = true;
  121. {
  122. const std::lock_guard<std::mutex> lock (active);
  123. if (stream != nullptr)
  124. stream->cancel();
  125. if (process != nullptr)
  126. process->kill();
  127. }
  128. stopThread (4000);
  129. }
  130. bool busy() const { return isThreadRunning(); }
  131. void setPhase (Phase p)
  132. {
  133. phase = p;
  134. hidden = false;
  135. sendChangeMessage();
  136. }
  137. // runs `job` on the worker thread; false when one is already running
  138. bool run (std::function<void()> job)
  139. {
  140. // (a job posts its result just before it ends: give it that moment)
  141. if (isThreadRunning() && ! waitForThreadToExit (2000))
  142. return false;
  143. cancelled = false;
  144. pending = std::move (job);
  145. startThread (juce::Thread::Priority::low);
  146. return true;
  147. }
  148. // `fn` on the message thread, unless the controller is gone by then
  149. void post (std::function<void()> fn)
  150. {
  151. juce::MessageManager::callAsync ([token = std::weak_ptr<int> (alive), fn = std::move (fn)] {
  152. if (! token.expired())
  153. fn();
  154. });
  155. }
  156. bool isCancelled() const { return cancelled.load() || threadShouldExit(); }
  157. // GET `url` into `dest`. `expected` (bytes, 0 = unknown) for the progress; `quick` = a short overall timeout (the
  158. // release list). False with `error` on failure or Cancel.
  159. bool download (const juce::String& url, const juce::File& dest, std::int64_t expected, bool quick, juce::String& failure)
  160. {
  161. dest.getParentDirectory().createDirectory();
  162. dest.deleteFile();
  163. #if JUCE_LINUX || JUCE_BSD
  164. // (LYNX is built without libcurl, JUCE_USE_CURL=0: the curl program fetches it, as the crash report upload)
  165. juce::StringArray args { "curl", "-sS", "-L", "--connect-timeout", "8", "-A", userAgent(), "-o", dest.getFullPathName(), "-w", "%{http_code}" };
  166. if (quick)
  167. args.addArray ({ "-m", "20", "-H", "Accept: application/vnd.github+json" });
  168. else
  169. args.addArray ({ "--speed-limit", "1", "--speed-time", "30" });
  170. args.add (url);
  171. auto child = std::make_unique<juce::ChildProcess>();
  172. if (! child->start (args, juce::ChildProcess::wantStdOut))
  173. {
  174. failure = tr ("the curl program is missing");
  175. return false;
  176. }
  177. {
  178. const std::lock_guard<std::mutex> lock (active);
  179. process = child.get();
  180. }
  181. while (child->isRunning())
  182. {
  183. if (isCancelled())
  184. child->kill();
  185. if (expected > 0)
  186. setProgress ((float) juce::jlimit (0.0, 1.0, (double) dest.getSize() / (double) expected));
  187. juce::Thread::sleep (150);
  188. }
  189. const auto code = child->readAllProcessOutput().trim().getIntValue();
  190. {
  191. const std::lock_guard<std::mutex> lock (active);
  192. process = nullptr;
  193. }
  194. if (isCancelled())
  195. {
  196. dest.deleteFile();
  197. failure = cancelledMarker;
  198. return false;
  199. }
  200. if (code != 200)
  201. {
  202. dest.deleteFile();
  203. failure = code == 0 ? tr ("no connection") : "HTTP " + juce::String (code);
  204. return false;
  205. }
  206. return dest.existsAsFile();
  207. #else
  208. juce::WebInputStream web (juce::URL (url), false);
  209. web.withExtraHeaders ("User-Agent: " + userAgent() + "\r\nAccept: " + (quick ? "application/vnd.github+json" : "application/octet-stream"))
  210. .withConnectionTimeout (quick ? 10000 : 20000)
  211. .withNumRedirectsToFollow (5);
  212. {
  213. const std::lock_guard<std::mutex> lock (active);
  214. stream = &web;
  215. }
  216. struct Clear
  217. {
  218. Controller& c;
  219. ~Clear()
  220. {
  221. const std::lock_guard<std::mutex> lock (c.active);
  222. c.stream = nullptr;
  223. }
  224. } clear { *this };
  225. if (isCancelled() || ! web.connect (nullptr))
  226. {
  227. failure = isCancelled() ? cancelledMarker : tr ("no connection");
  228. return false;
  229. }
  230. const auto status = web.getStatusCode();
  231. if (status != 200)
  232. {
  233. failure = "HTTP " + juce::String (status);
  234. return false;
  235. }
  236. const auto total = web.getTotalLength() > 0 ? web.getTotalLength() : expected;
  237. bool ok = true;
  238. {
  239. juce::FileOutputStream out (dest);
  240. if (! out.openedOk())
  241. {
  242. failure = tr ("can't write {0}", { dest.getFullPathName() });
  243. return false;
  244. }
  245. juce::HeapBlock<char> buffer (65536);
  246. std::int64_t got = 0;
  247. const auto started = juce::Time::getMillisecondCounter();
  248. while (! web.isExhausted())
  249. {
  250. if (isCancelled())
  251. {
  252. failure = cancelledMarker;
  253. ok = false;
  254. break;
  255. }
  256. const auto n = web.read (buffer, 65536);
  257. if (n < 0 || (n == 0 && ! web.isExhausted() && web.isError()))
  258. {
  259. failure = tr ("the connection was lost");
  260. ok = false;
  261. break;
  262. }
  263. if (n == 0)
  264. {
  265. if (web.isExhausted())
  266. break;
  267. if (quick && juce::Time::getMillisecondCounter() - started > 20000)
  268. {
  269. failure = tr ("no connection");
  270. ok = false;
  271. break;
  272. }
  273. juce::Thread::sleep (20);
  274. continue;
  275. }
  276. if (! out.write (buffer, (size_t) n))
  277. {
  278. failure = tr ("can't write {0}", { dest.getFullPathName() });
  279. ok = false;
  280. break;
  281. }
  282. got += n;
  283. if (total > 0)
  284. setProgress ((float) juce::jlimit (0.0, 1.0, (double) got / (double) total));
  285. if (quick && juce::Time::getMillisecondCounter() - started > 20000)
  286. {
  287. failure = tr ("no connection");
  288. ok = false;
  289. break;
  290. }
  291. }
  292. out.flush();
  293. ok = ok && ! out.getStatus().failed();
  294. }
  295. if (! ok)
  296. dest.deleteFile();
  297. return ok;
  298. #endif
  299. }
  300. bool fetchText (const juce::String& url, juce::String& text, juce::String& failure)
  301. {
  302. const auto file = updateFolder().getChildFile ("fetch-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt()) + ".tmp");
  303. const bool ok = download (url, file, 0, true, failure);
  304. if (ok)
  305. text = file.loadFileAsString();
  306. file.deleteFile();
  307. return ok;
  308. }
  309. // sends a change message at most ~8 times a second while downloading
  310. void setProgress (float p)
  311. {
  312. progress = p;
  313. const auto now = juce::Time::getMillisecondCounter();
  314. if (now - lastProgressPost < 120)
  315. return;
  316. lastProgressPost = now;
  317. post ([this] { sendChangeMessage(); });
  318. }
  319. juce::ChildProcess* process = nullptr;
  320. std::mutex active;
  321. private:
  322. void run() override
  323. {
  324. if (pending)
  325. pending();
  326. pending = nullptr;
  327. }
  328. std::function<void()> pending;
  329. std::atomic<bool> cancelled { false };
  330. juce::WebInputStream* stream = nullptr;
  331. juce::uint32 lastProgressPost = 0;
  332. std::shared_ptr<int> alive = std::make_shared<int> (0);
  333. };
  334. std::unique_ptr<Controller>& instancePtr()
  335. {
  336. static std::unique_ptr<Controller> p;
  337. return p;
  338. }
  339. Controller& controller()
  340. {
  341. auto& p = instancePtr();
  342. if (p == nullptr)
  343. p = std::make_unique<Controller>();
  344. return *p;
  345. }
  346. void message (juce::MessageBoxIconType icon, const juce::String& title, const juce::String& text)
  347. {
  348. if (platform::testMode())
  349. platform::testModeLog ("update: " + title + ": " + text);
  350. juce::AlertWindow::showMessageBoxAsync (icon, title, text);
  351. }
  352. // --- the check ----------------------------------------------------------------------------------------------------
  353. void check (bool manual)
  354. {
  355. auto& c = controller();
  356. if (c.busy())
  357. return;
  358. if (! manual && (c.phase == Phase::available || c.phase == Phase::ready))
  359. return;
  360. const auto url = overrideUrl();
  361. c.manual = manual;
  362. if (manual)
  363. c.setPhase (Phase::checking);
  364. c.run ([&c, manual, url] {
  365. juce::String text, failure;
  366. auto settings = loadSettings();
  367. const auto now = juce::Time::currentTimeMillis();
  368. const bool fixture = url.isNotEmpty();
  369. bool fetched = false;
  370. if (! manual && ! fixture && update::cacheFresh (settings.lastCheckMs, now) && cachePath().existsAsFile())
  371. text = cachePath().loadFileAsString();
  372. else if (c.fetchText (fixture ? url : juce::String (update::releasesUrl), text, failure))
  373. fetched = true;
  374. std::string parseError;
  375. auto releases = failure.isEmpty() ? update::parseReleases (utf8 (text), &parseError) : std::vector<update::Release>();
  376. if (failure.isEmpty() && releases.empty() && ! parseError.empty())
  377. failure = fromUtf8 (parseError);
  378. if (fetched && failure.isEmpty() && ! fixture)
  379. {
  380. cachePath().replaceWithText (text);
  381. settings.lastCheckMs = now;
  382. saveSettings (settings);
  383. }
  384. const auto running = runningVersion();
  385. const auto best = update::newestIndex (releases, running);
  386. update::Release found;
  387. if (best >= 0)
  388. found = releases[(std::size_t) best];
  389. c.post ([&c, manual, failure, best, found, settings, running] {
  390. if (c.phase == Phase::checking)
  391. c.phase = Phase::idle;
  392. if (failure.isNotEmpty())
  393. {
  394. if (manual)
  395. message (juce::MessageBoxIconType::WarningIcon, tr ("Check for updates"), tr ("Could not check for updates ({0}). Try again later.", { failure }));
  396. c.sendChangeMessage();
  397. return;
  398. }
  399. if (best < 0)
  400. {
  401. if (manual)
  402. message (juce::MessageBoxIconType::InfoIcon, tr ("Check for updates"),
  403. tr ("You're up to date: LYNX SHARE {0} is the newest version.", { fromUtf8 (running.text()) }));
  404. c.sendChangeMessage();
  405. return;
  406. }
  407. if (! update::shouldShow (found, settings, manual))
  408. {
  409. c.sendChangeMessage();
  410. return;
  411. }
  412. c.release = found;
  413. c.rollingBack = false;
  414. c.error.clear();
  415. c.setPhase (Phase::available);
  416. });
  417. });
  418. }
  419. juce::String versionText (const update::Release& r) { return fromUtf8 (r.version.text()); }
  420. juce::String releasePage (const update::Release& r) { return r.page.empty() ? juce::String (update::releasesPage) : fromUtf8 (r.page); }
  421. void fail (const juce::String& why)
  422. {
  423. auto& c = controller();
  424. log ("failed: " + why);
  425. c.error = why;
  426. c.setPhase (Phase::failed);
  427. }
  428. // downloads the flavour's asset to `dest` and checks it against SHA256SUMS.txt; on the worker thread
  429. bool fetchVerified (Controller& c, const update::Asset& asset, const update::Asset* sums, const juce::File& dest, juce::String& failure)
  430. {
  431. if (sums == nullptr)
  432. {
  433. failure = tr ("the release has no checksums (SHA256SUMS.txt)");
  434. return false;
  435. }
  436. juce::String sumsText;
  437. if (! c.fetchText (fromUtf8 (sums->url), sumsText, failure))
  438. return false;
  439. const auto expected = update::checksumFor (utf8 (sumsText), asset.name);
  440. if (expected.empty())
  441. {
  442. failure = tr ("SHA256SUMS.txt has no line for {0}", { fromUtf8 (asset.name) });
  443. return false;
  444. }
  445. const auto part = dest.getSiblingFile (dest.getFileName() + ".part");
  446. c.progress = 0.0f;
  447. if (! c.download (fromUtf8 (asset.url), part, asset.size, false, failure))
  448. return false;
  449. update::Sha256Stream hash;
  450. {
  451. juce::FileInputStream in (part);
  452. if (! in.openedOk())
  453. {
  454. failure = tr ("can't read {0}", { part.getFullPathName() });
  455. return false;
  456. }
  457. juce::HeapBlock<char> buffer (1 << 16);
  458. for (int n; (n = in.read (buffer, 1 << 16)) > 0;)
  459. hash.add (buffer, (std::size_t) n);
  460. }
  461. const auto actual = hash.finish();
  462. if (! update::checksumMatches (expected, actual))
  463. {
  464. part.deleteFile();
  465. failure = tr ("the download is damaged (its checksum does not match)");
  466. log ("checksum mismatch for " + fromUtf8 (asset.name) + ": expected " + fromUtf8 (expected) + ", got " + fromUtf8 (actual));
  467. return false;
  468. }
  469. dest.deleteFile();
  470. if (! part.moveFileTo (dest))
  471. {
  472. failure = tr ("can't write {0}", { dest.getFullPathName() });
  473. return false;
  474. }
  475. log ("downloaded and checked " + dest.getFullPathName() + " (sha256 " + fromUtf8 (actual) + ")");
  476. return true;
  477. }
  478. // starts a downloaded file's job: `onDone(file)` on the message thread when it was saved and checked
  479. void downloadThen (const juce::File& dest, std::function<void (const juce::File&)> onDone)
  480. {
  481. auto& c = controller();
  482. const auto& assets = c.release.assets;
  483. const auto index = update::assetFor (flavour(), assets);
  484. if (index < 0)
  485. {
  486. juce::URL (releasePage (c.release)).launchInDefaultBrowser(); // (no file for this build in the release)
  487. return;
  488. }
  489. const auto asset = assets[(std::size_t) index];
  490. const auto sumsIndex = update::checksumsAsset (assets);
  491. const std::optional<update::Asset> sums = sumsIndex >= 0 ? std::optional<update::Asset> (assets[(std::size_t) sumsIndex]) : std::nullopt;
  492. const auto target = dest.isDirectory() ? dest.getChildFile (fromUtf8 (asset.name)) : dest;
  493. c.progress = 0.0f;
  494. log ("downloading " + fromUtf8 (asset.url) + " to " + target.getFullPathName());
  495. const bool started = c.run ([&c, asset, sums, target, onDone] {
  496. juce::String failure;
  497. const bool ok = fetchVerified (c, asset, sums ? &*sums : nullptr, target, failure);
  498. c.post ([ok, failure, target, onDone] {
  499. if (ok)
  500. onDone (target);
  501. else if (failure != cancelledMarker)
  502. fail (failure);
  503. else
  504. controller().setPhase (controller().rollingBack ? Phase::idle : Phase::available); // (round 190gh)
  505. });
  506. });
  507. if (started) // (the result is posted to this thread: it comes after this)
  508. c.setPhase (Phase::downloading);
  509. }
  510. // round 190gh (B2): the settings once the other version's file is in place (AppImage, zip, dmg; the installer does it
  511. // after its restart, in afterStart): after an update the running version becomes the previous one; after going back
  512. // the version left is skipped
  513. void recordSwitch()
  514. {
  515. auto& c = controller();
  516. auto s = loadSettings();
  517. s = c.rollingBack ? update::afterRollback (s, runningVersion()) : update::afterUpdate (s, runningVersion());
  518. saveSettings (s);
  519. log (juce::String (c.rollingBack ? "going back from " : "updating from ") + fromUtf8 (runningVersion().text()) + " to " + versionText (c.release));
  520. }
  521. // --- applying -----------------------------------------------------------------------------------------------------
  522. #if JUCE_WINDOWS
  523. std::uint32_t currentPid() { return (std::uint32_t) GetCurrentProcessId(); }
  524. #else
  525. std::uint32_t currentPid() { return (std::uint32_t) getpid(); }
  526. #endif
  527. // Windows installer build: a copy of LYNX.exe waits for this process to end, installs and restarts LYNX SHARE
  528. void installAndRestart (const juce::File& setup)
  529. {
  530. auto& c = controller();
  531. if (! c.host.confirmDiscard)
  532. return;
  533. c.host.confirmDiscard ([setup] {
  534. auto& c = controller();
  535. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  536. const auto helper = updateFolder().getChildFile ("LYNX-updater.exe");
  537. helper.deleteFile();
  538. if (! exe.copyFileTo (helper))
  539. {
  540. fail (tr ("can't write {0}", { helper.getFullPathName() }));
  541. return;
  542. }
  543. updateFolder().getChildFile ("result.txt").deleteFile();
  544. // the version being installed, for the "was updated to" bar on the next start
  545. // (round 190gh: the version it replaces, and whether it goes back, for the settings after the restart;
  546. // round 190hl: in a layout 0.1.27 and older read too, core/UpdateCheck.h formatInstalling)
  547. update::InstallingNote note;
  548. note.version = c.release.version.text();
  549. note.from = runningVersion().text();
  550. note.rollback = c.rollingBack;
  551. updateFolder().getChildFile ("installing.txt").replaceWithText (fromUtf8 (update::formatInstalling (note)));
  552. updateFolder().getChildFile ("installing-notes.md").replaceWithText (fromUtf8 (c.release.body));
  553. // round 190hl: going back skips the version left NOW, in the settings every older version reads; the older
  554. // version that starts after the installer may not know about going back (0.1.27 and older) and would offer
  555. // this one again at once. (The previous version is used up after the restart, by versions that know it.)
  556. const auto settingsBefore = loadSettings();
  557. if (c.rollingBack)
  558. saveSettings (update::skipLeft (settingsBefore, runningVersion()));
  559. juce::StringArray args { helper.getFullPathName(), "--apply-update", setup.getFullPathName(), exe.getParentDirectory().getFullPathName(),
  560. juce::String ((juce::int64) currentPid()) };
  561. if (const auto project = c.host.currentProject ? c.host.currentProject() : juce::File(); project.existsAsFile())
  562. args.add (project.getFullPathName());
  563. log ("starting " + args.joinIntoString (" "));
  564. juce::ChildProcess child;
  565. if (! child.start (args, 0))
  566. {
  567. if (c.rollingBack)
  568. saveSettings (settingsBefore); // (nothing was installed: the skip goes again)
  569. fail (tr ("can't start {0}", { helper.getFullPathName() }));
  570. return;
  571. }
  572. if (c.rollingBack)
  573. log ("skipped " + fromUtf8 (runningVersion().text()) + " before the installer of " + versionText (c.release) + " runs");
  574. juce::JUCEApplication::quit();
  575. });
  576. }
  577. void restartInto (const juce::File& program)
  578. {
  579. auto& c = controller();
  580. if (! c.host.confirmDiscard)
  581. return;
  582. c.host.confirmDiscard ([program] {
  583. auto& c = controller();
  584. juce::StringArray args { program.getFullPathName() };
  585. if (const auto project = c.host.currentProject ? c.host.currentProject() : juce::File(); project.existsAsFile())
  586. args.add (project.getFullPathName());
  587. juce::ChildProcess child;
  588. if (! child.start (args, 0))
  589. {
  590. fail (tr ("can't start {0}", { program.getFullPathName() }));
  591. return;
  592. }
  593. juce::JUCEApplication::quit();
  594. });
  595. }
  596. void appImageUpdate()
  597. {
  598. auto& c = controller();
  599. const auto current = appImageFile();
  600. #if JUCE_LINUX || JUCE_BSD
  601. // AppImageUpdate's command-line tool: the zsync update information embedded by scripts/package-linux.sh
  602. // (zsync|https://lynx-share.com/update/...) fetches only the changed blocks, then -O replaces the file
  603. // (going back downloads the older AppImage: the tool only knows the newest one)
  604. if (const auto tool = findInPath ("appimageupdatetool"); current != juce::File() && tool != juce::File() && overrideUrl().isEmpty() && ! c.rollingBack)
  605. {
  606. c.progress = -1.0f;
  607. c.setPhase (Phase::working);
  608. log ("running " + tool.getFullPathName() + " -O " + current.getFullPathName());
  609. c.run ([&c, tool, current] {
  610. auto child = std::make_unique<juce::ChildProcess>();
  611. bool ok = false;
  612. juce::String output;
  613. if (child->start (juce::StringArray { tool.getFullPathName(), "-O", current.getFullPathName() }))
  614. {
  615. {
  616. const std::lock_guard<std::mutex> lock (c.active);
  617. c.process = child.get();
  618. }
  619. output = child->readAllProcessOutput();
  620. child->waitForProcessToFinish (600000);
  621. ok = ! c.isCancelled() && child->getExitCode() == 0;
  622. const std::lock_guard<std::mutex> lock (c.active);
  623. c.process = nullptr;
  624. }
  625. const auto cancelled = c.isCancelled();
  626. c.post ([ok, cancelled, output, current] {
  627. log ("appimageupdatetool: " + output.trim().getLastCharacters (2000));
  628. if (ok)
  629. {
  630. controller().result = current;
  631. recordSwitch();
  632. controller().setPhase (Phase::ready);
  633. }
  634. else if (cancelled)
  635. controller().setPhase (Phase::available);
  636. else
  637. fail (tr ("appimageupdatetool could not update the AppImage"));
  638. });
  639. });
  640. return;
  641. }
  642. #endif
  643. // no AppImageUpdate: the new AppImage beside the old one (Downloads when that folder can't be written)
  644. auto folder = current != juce::File() ? current.getParentDirectory() : downloadsFolder();
  645. if (! folder.hasWriteAccess())
  646. folder = downloadsFolder();
  647. folder.createDirectory();
  648. downloadThen (folder, [] (const juce::File& file) {
  649. file.setExecutePermission (true);
  650. controller().result = file;
  651. recordSwitch();
  652. controller().setPhase (Phase::ready);
  653. });
  654. }
  655. void startUpdate()
  656. {
  657. auto& c = controller();
  658. switch (update::methodFor (flavour()))
  659. {
  660. case update::Method::runInstaller:
  661. updateFolder().createDirectory();
  662. downloadThen (updateFolder(), [] (const juce::File& setup) {
  663. controller().result = setup;
  664. controller().setPhase (Phase::ready);
  665. installAndRestart (setup); // (the save prompt; Cancel leaves "Install and restart" on the bar)
  666. });
  667. break;
  668. case update::Method::downloadAndReveal:
  669. downloadsFolder().createDirectory();
  670. downloadThen (downloadsFolder(), [] (const juce::File& file) {
  671. controller().result = file;
  672. recordSwitch();
  673. controller().setPhase (Phase::saved);
  674. if (! platform::testMode())
  675. file.revealToUser();
  676. else
  677. platform::testModeLog ("update: saved " + file.getFullPathName());
  678. });
  679. break;
  680. case update::Method::appImageUpdate: appImageUpdate(); break;
  681. case update::Method::openPage:
  682. juce::URL (releasePage (c.release)).launchInDefaultBrowser();
  683. break;
  684. case update::Method::none: break;
  685. }
  686. }
  687. void readyAction()
  688. {
  689. auto& c = controller();
  690. if (update::methodFor (flavour()) == update::Method::runInstaller)
  691. installAndRestart (c.result);
  692. else
  693. restartInto (c.result);
  694. }
  695. } // namespace
  696. // ================================================================================================================
  697. // public
  698. // ================================================================================================================
  699. update::Flavour flavour()
  700. {
  701. static const update::Flavour f = [] {
  702. update::Facts facts;
  703. #if JUCE_WINDOWS
  704. facts.os = "windows";
  705. #elif JUCE_MAC
  706. facts.os = "macos";
  707. #elif JUCE_LINUX || JUCE_BSD
  708. facts.os = "linux";
  709. #endif
  710. facts.packaged = platform::runningPackaged();
  711. const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
  712. facts.uninstallerBesideExe = exe.getSiblingFile ("Uninstall.exe").existsAsFile();
  713. facts.appImagePath = utf8 (appImageFile().getFullPathName());
  714. facts.forced = utf8 (env ("LYNX_UPDATE_FLAVOUR"));
  715. return update::detectFlavour (facts);
  716. }();
  717. return f;
  718. }
  719. bool offered() { return update::checksForUpdates (flavour()); }
  720. bool automatic() { return loadSettings().automatic; }
  721. void setAutomatic (bool on)
  722. {
  723. auto s = loadSettings();
  724. if (s.automatic == on)
  725. return;
  726. s.automatic = on;
  727. saveSettings (s);
  728. }
  729. void setHost (Host host) { controller().host = std::move (host); }
  730. // set when this start follows an update: no automatic check this session (the "updated" bar stays)
  731. static bool justUpdated = false;
  732. void startAutomaticCheck()
  733. {
  734. // round 190gh (B2), tests: LYNX_TEST_MODE + LYNX_UPDATE_URL + LYNX_UPDATE_GO_BACK=1 go back at start, without asking
  735. if (offered() && platform::testMode() && overrideUrl().isNotEmpty() && env ("LYNX_UPDATE_GO_BACK") == "1")
  736. {
  737. goBack();
  738. return;
  739. }
  740. if (! offered() || ! automatic() || justUpdated)
  741. return;
  742. // LYNX_TEST_MODE: no network, unless a test fixture is named
  743. if (platform::testMode() && overrideUrl().isEmpty())
  744. return;
  745. check (false);
  746. }
  747. void checkNow()
  748. {
  749. if (! offered())
  750. return;
  751. if (platform::testMode() && overrideUrl().isEmpty())
  752. {
  753. message (juce::MessageBoxIconType::InfoIcon, tr ("Check for updates"), "LYNX_TEST_MODE: no network (set LYNX_UPDATE_URL)");
  754. return;
  755. }
  756. check (true);
  757. }
  758. // ---------------------------------------------------------------------------------------------------------------------
  759. // round 190gh (B2): going back to the previous version
  760. // ---------------------------------------------------------------------------------------------------------------------
  761. juce::String previousVersion()
  762. {
  763. if (! offered())
  764. return {};
  765. const auto running = runningVersion();
  766. const auto settings = loadSettings();
  767. if (const auto p = update::parseVersion (settings.previous); p.valid && update::compare (p, running) < 0)
  768. return fromUtf8 (p.text());
  769. const auto list = update::parseReleases (utf8 (cachePath().loadFileAsString()));
  770. if (const auto i = update::rollbackIndex (list, running, settings.previous); i >= 0)
  771. return versionText (list[(std::size_t) i]);
  772. return {};
  773. }
  774. namespace
  775. {
  776. void startGoingBack (const update::Release& target)
  777. {
  778. auto& c = controller();
  779. c.release = target;
  780. c.rollingBack = true;
  781. c.error.clear();
  782. log ("going back to " + versionText (target) + " (" + juce::String (update::flavourId (flavour())) + ")");
  783. startUpdate();
  784. }
  785. } // namespace
  786. void goBack()
  787. {
  788. if (! offered())
  789. return;
  790. const auto title = tr ("Go back to an earlier version");
  791. if (platform::testMode() && overrideUrl().isEmpty())
  792. {
  793. message (juce::MessageBoxIconType::InfoIcon, title, "LYNX_TEST_MODE: no network (set LYNX_UPDATE_URL)");
  794. return;
  795. }
  796. auto& c = controller();
  797. if (c.busy() || c.phase == Phase::downloading || c.phase == Phase::working)
  798. {
  799. message (juce::MessageBoxIconType::InfoIcon, title, tr ("An update is being downloaded. Wait until it is done, or cancel it on the bar."));
  800. return;
  801. }
  802. const auto url = overrideUrl();
  803. c.run ([&c, url, title] {
  804. juce::String text, failure;
  805. c.fetchText (url.isNotEmpty() ? url : juce::String (update::releasesUrl), text, failure);
  806. std::string parseError;
  807. auto releases = failure.isEmpty() ? update::parseReleases (utf8 (text), &parseError) : std::vector<update::Release>();
  808. if (failure.isEmpty() && releases.empty() && ! parseError.empty())
  809. failure = fromUtf8 (parseError);
  810. const auto running = runningVersion();
  811. const auto index = update::rollbackIndex (releases, running, loadSettings().previous);
  812. update::Release target;
  813. if (index >= 0)
  814. target = releases[(std::size_t) index];
  815. c.post ([failure, index, target, running, title] {
  816. if (failure.isNotEmpty())
  817. {
  818. message (juce::MessageBoxIconType::WarningIcon, title, tr ("Could not get the list of versions ({0}). Try again later.", { failure }));
  819. return;
  820. }
  821. if (index < 0)
  822. {
  823. message (juce::MessageBoxIconType::InfoIcon, title,
  824. tr ("No version older than LYNX SHARE {0} is available to go back to.", { fromUtf8 (running.text()) }));
  825. return;
  826. }
  827. const auto older = versionText (target), now = fromUtf8 (running.text());
  828. if (platform::testMode()) // (tests: no question)
  829. {
  830. platform::testModeLog ("update: going back from " + now + " to " + older);
  831. startGoingBack (target);
  832. return;
  833. }
  834. const auto how = update::methodFor (flavour()) == update::Method::openPage
  835. ? tr ("Its download page opens in your browser.")
  836. : tr ("It is downloaded from GitHub and checked like an update; your project is saved first and opened again.");
  837. juce::AlertWindow::showOkCancelBox (
  838. juce::MessageBoxIconType::QuestionIcon, tr ("Go back to LYNX SHARE {0}?", { older }),
  839. tr ("LYNX SHARE {0} will be replaced by the earlier {1}. {2}\n\nProjects saved with {0} still open in {1}; LYNX SHARE says when a "
  840. "project comes from a newer version. The automatic check won't offer {0} again; Help > Check for updates... still does.",
  841. { now, older, how }),
  842. tr ("Go back"), tr ("Cancel"), nullptr, juce::ModalCallbackFunction::create ([target] (int result) {
  843. if (result == 1)
  844. startGoingBack (target);
  845. }));
  846. });
  847. });
  848. }
  849. void shutdown()
  850. {
  851. if (auto& p = instancePtr(); p != nullptr)
  852. {
  853. p->stop();
  854. p.reset();
  855. }
  856. }
  857. void afterStart()
  858. {
  859. const auto folder = updateFolder();
  860. const auto resultFile = folder.getChildFile ("result.txt");
  861. if (resultFile.existsAsFile())
  862. {
  863. const auto values = juce::StringArray::fromLines (resultFile.loadFileAsString());
  864. juce::String result, detail, version;
  865. for (const auto& line : values)
  866. {
  867. if (line.startsWith ("result=")) result = line.fromFirstOccurrenceOf ("=", false, false).trim();
  868. if (line.startsWith ("detail=")) detail = line.fromFirstOccurrenceOf ("=", false, false).trim();
  869. if (line.startsWith ("version=")) version = line.fromFirstOccurrenceOf ("=", false, false).trim();
  870. }
  871. resultFile.deleteFile();
  872. const auto installing = folder.getChildFile ("installing.txt");
  873. // round 190gh (B2): the version it replaced and whether it went back (any line order: round 190hl)
  874. const auto note = update::parseInstalling (utf8 (installing.loadFileAsString()));
  875. if (version.isEmpty())
  876. version = fromUtf8 (note.version);
  877. const auto from = fromUtf8 (note.from);
  878. const bool wentBack = note.rollback;
  879. log ("after start: update result " + result + (detail.isNotEmpty() ? " (" + detail + ")" : juce::String()));
  880. if (result == "ok")
  881. {
  882. justUpdated = true;
  883. auto& c = controller();
  884. if (const auto replaced = update::parseVersion (utf8 (from)); replaced.valid)
  885. {
  886. auto s = loadSettings();
  887. saveSettings (wentBack ? update::afterRollback (s, replaced) : update::afterUpdate (s, replaced));
  888. }
  889. c.rollingBack = wentBack;
  890. // the release notes come from the cached list when there is one
  891. const auto list = update::parseReleases (utf8 (cachePath().loadFileAsString()));
  892. c.release = {};
  893. const auto installed = version.isNotEmpty() ? update::parseVersion (utf8 (version)) : runningVersion();
  894. for (const auto& r : list)
  895. if (update::compare (r.version, installed) == 0)
  896. c.release = r;
  897. if (c.release.tag.empty())
  898. {
  899. c.release.version = installed;
  900. c.release.body = utf8 (folder.getChildFile ("installing-notes.md").loadFileAsString());
  901. }
  902. c.setPhase (Phase::updated);
  903. }
  904. else
  905. message (juce::MessageBoxIconType::WarningIcon, tr ("Update"),
  906. tr ("The update could not be installed ({0}). This version of LYNX SHARE is still installed; details in {1}.",
  907. { detail, folder.getChildFile ("update.log").getFullPathName() }));
  908. }
  909. folder.getChildFile ("installing.txt").deleteFile();
  910. folder.getChildFile ("installing-notes.md").deleteFile();
  911. // the installer and the helper copy of LYNX.exe go (nothing has been downloaded yet in this session)
  912. for (const auto& f : folder.findChildFiles (juce::File::findFiles, false, "*.exe;*.part;*.tmp"))
  913. f.deleteFile();
  914. // the helper may still be ending: its copy once more a little later, unless an update of this session needs the folder
  915. // (a new download is already there by then, and "Install and restart" copies the helper again)
  916. juce::Timer::callAfterDelay (15000, [folder] {
  917. const auto phase = controller().phase;
  918. if (phase == Phase::idle || phase == Phase::checking || phase == Phase::available || phase == Phase::updated
  919. || phase == Phase::failed || phase == Phase::saved)
  920. folder.getChildFile ("LYNX-updater.exe").deleteFile();
  921. });
  922. }
  923. bool runApplyHelper (const juce::StringArray& args)
  924. {
  925. const auto at = args.indexOf ("--apply-update");
  926. if (at < 0)
  927. return false;
  928. #if JUCE_WINDOWS
  929. const juce::File setup (args[at + 1].unquoted()), folder (args[at + 2].unquoted());
  930. const auto pid = (DWORD) args[at + 3].getLargeIntValue();
  931. const auto project = args[at + 4].unquoted();
  932. const auto resultFile = setup.getSiblingFile ("result.txt");
  933. auto finish = [&] (bool ok, const juce::String& detail) {
  934. log (juce::String ("helper: ") + (ok ? "installed" : "FAILED") + (detail.isNotEmpty() ? " (" + detail + ")" : juce::String()));
  935. resultFile.replaceWithText ("result=" + juce::String (ok ? "ok" : "failed") + "\ndetail=" + detail + "\n");
  936. // LYNX SHARE starts again (the old one when the installation failed: it shows why)
  937. const auto exe = folder.getChildFile ("LYNX.exe");
  938. if (exe.existsAsFile())
  939. exe.startAsProcess (juce::File::isAbsolutePath (project) ? project.quoted() : juce::String());
  940. };
  941. log ("helper: waiting for process " + juce::String ((int) pid) + ", then " + setup.getFullPathName() + " into " + folder.getFullPathName());
  942. if (! setup.existsAsFile() || ! folder.isDirectory())
  943. {
  944. finish (false, "missing " + (! setup.existsAsFile() ? setup.getFullPathName() : folder.getFullPathName()));
  945. return true;
  946. }
  947. if (pid != 0)
  948. if (auto process = OpenProcess (SYNCHRONIZE, FALSE, pid))
  949. {
  950. const auto waited = WaitForSingleObject (process, 120000);
  951. CloseHandle (process);
  952. if (waited == WAIT_TIMEOUT)
  953. {
  954. finish (false, "LYNX SHARE did not close");
  955. return true;
  956. }
  957. }
  958. // plugin sandbox / scan child processes of LYNX.exe end a moment later: wait until the exe can be replaced
  959. const auto exe = folder.getChildFile ("LYNX.exe");
  960. for (int i = 0; i < 150 && exe.existsAsFile(); ++i)
  961. {
  962. auto h = CreateFileW (exe.getFullPathName().toWideCharPointer(), GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
  963. if (h != INVALID_HANDLE_VALUE)
  964. {
  965. CloseHandle (h);
  966. break;
  967. }
  968. Sleep (200);
  969. }
  970. // NSIS: /S silent, /D=<folder> last and unquoted (it may contain spaces)
  971. auto command = "\"" + setup.getFullPathName() + "\" /S /D=" + folder.getFullPathName();
  972. STARTUPINFOW si {};
  973. si.cb = sizeof (si);
  974. PROCESS_INFORMATION pi {};
  975. std::wstring line (command.toWideCharPointer());
  976. if (! CreateProcessW (nullptr, line.data(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi))
  977. {
  978. finish (false, "can't start the installer (error " + juce::String ((int) GetLastError()) + ")");
  979. return true;
  980. }
  981. const auto waited = WaitForSingleObject (pi.hProcess, 600000);
  982. DWORD code = 1;
  983. GetExitCodeProcess (pi.hProcess, &code);
  984. CloseHandle (pi.hThread);
  985. CloseHandle (pi.hProcess);
  986. if (waited == WAIT_TIMEOUT)
  987. finish (false, "the installer did not finish");
  988. else
  989. finish (code == 0, code == 0 ? juce::String() : "installer exit code " + juce::String ((int) code));
  990. #else
  991. juce::ignoreUnused (at);
  992. #endif
  993. return true;
  994. }
  995. // ================================================================================================================
  996. // the bar
  997. // ================================================================================================================
  998. UpdateBar::UpdateBar()
  999. {
  1000. message.setFont (theme::font (theme::type::body));
  1001. message.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  1002. message.setMinimumHorizontalScale (0.8f);
  1003. addAndMakeVisible (message);
  1004. for (auto* b : { &notesButton, &updateButton, &otherButton })
  1005. addChildComponent (*b);
  1006. updateButton.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  1007. updateButton.setColour (juce::TextButton::textColourOffId, theme::colour::onAccent);
  1008. juce::Path cross;
  1009. cross.startNewSubPath (0, 0);
  1010. cross.lineTo (10, 10);
  1011. cross.startNewSubPath (10, 0);
  1012. cross.lineTo (0, 10);
  1013. juce::DrawablePath normal, over;
  1014. normal.setPath (cross);
  1015. normal.setStrokeType (juce::PathStrokeType (1.6f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  1016. normal.setFill (juce::FillType());
  1017. normal.setStrokeFill (theme::colour::textSecondary);
  1018. over.setPath (cross);
  1019. over.setStrokeType (juce::PathStrokeType (1.6f, juce::PathStrokeType::curved, juce::PathStrokeType::rounded));
  1020. over.setFill (juce::FillType());
  1021. over.setStrokeFill (theme::colour::textPrimary);
  1022. closeButton.setImages (&normal, &over, &over);
  1023. closeButton.setEdgeIndent (8);
  1024. addAndMakeVisible (closeButton);
  1025. notesButton.onClick = [] { showReleaseNotes(); };
  1026. updateButton.onClick = [] {
  1027. auto& c = controller();
  1028. if (c.phase == Phase::available || c.phase == Phase::failed)
  1029. startUpdate();
  1030. else if (c.phase == Phase::ready)
  1031. readyAction();
  1032. };
  1033. otherButton.onClick = [] {
  1034. auto& c = controller();
  1035. if (c.phase == Phase::downloading || c.phase == Phase::working)
  1036. c.stop();
  1037. else if (c.phase == Phase::saved)
  1038. c.result.revealToUser();
  1039. else if (c.phase == Phase::failed)
  1040. juce::URL (releasePage (c.release)).launchInDefaultBrowser();
  1041. };
  1042. closeButton.onClick = [] {
  1043. auto& c = controller();
  1044. if (c.phase == Phase::available) // ✕ = skip this version
  1045. {
  1046. auto s = loadSettings();
  1047. s.skipped = c.release.version.text();
  1048. saveSettings (s);
  1049. log ("skipped " + versionText (c.release));
  1050. }
  1051. c.hidden = true;
  1052. c.sendChangeMessage();
  1053. };
  1054. controller().addChangeListener (this);
  1055. setVisible (false);
  1056. refresh();
  1057. }
  1058. UpdateBar::~UpdateBar()
  1059. {
  1060. if (auto& p = instancePtr(); p != nullptr)
  1061. p->removeChangeListener (this);
  1062. }
  1063. void UpdateBar::changeListenerCallback (juce::ChangeBroadcaster*) { refresh(); }
  1064. void UpdateBar::refresh()
  1065. {
  1066. auto& c = controller();
  1067. const auto v = versionText (c.release);
  1068. bool show = ! c.hidden;
  1069. notesButton.setVisible (false);
  1070. updateButton.setVisible (false);
  1071. otherButton.setVisible (false);
  1072. closeButton.setVisible (true);
  1073. closeButton.setTooltip (tr ("Hide"));
  1074. progress = -1.0f;
  1075. const bool installer = update::methodFor (flavour()) == update::Method::runInstaller;
  1076. switch (c.phase)
  1077. {
  1078. case Phase::available:
  1079. text = tr ("LYNX SHARE {0} is available", { v });
  1080. notesButton.setButtonText (tr ("What's new"));
  1081. notesButton.setVisible (true);
  1082. updateButton.setButtonText (update::methodFor (flavour()) == update::Method::openPage ? tr ("Download...") : tr ("Update"));
  1083. updateButton.setVisible (true);
  1084. closeButton.setTooltip (tr ("Skip this version"));
  1085. break;
  1086. case Phase::downloading:
  1087. progress = c.progress.load();
  1088. if (c.rollingBack) // (round 190gh)
  1089. text = progress >= 0.0f ? tr ("Going back to LYNX SHARE {0}: downloading... {1}%", { v, juce::String (juce::roundToInt (progress * 100.0f)) })
  1090. : tr ("Going back to LYNX SHARE {0}: downloading...", { v });
  1091. else
  1092. text = progress >= 0.0f ? tr ("Downloading LYNX SHARE {0}... {1}%", { v, juce::String (juce::roundToInt (progress * 100.0f)) })
  1093. : tr ("Downloading LYNX SHARE {0}...", { v });
  1094. otherButton.setButtonText (tr ("Cancel"));
  1095. otherButton.setVisible (true);
  1096. closeButton.setVisible (false);
  1097. break;
  1098. case Phase::working:
  1099. text = tr ("Updating the AppImage to LYNX SHARE {0}...", { v });
  1100. otherButton.setButtonText (tr ("Cancel"));
  1101. otherButton.setVisible (true);
  1102. closeButton.setVisible (false);
  1103. break;
  1104. case Phase::ready:
  1105. if (c.rollingBack) // (round 190gh)
  1106. text = installer ? tr ("The earlier LYNX SHARE {0} is downloaded and ready to install", { v }) : tr ("The earlier LYNX SHARE {0} is ready", { v });
  1107. else
  1108. text = installer ? tr ("LYNX SHARE {0} is downloaded and ready to install", { v }) : tr ("LYNX SHARE {0} is ready", { v });
  1109. notesButton.setButtonText (tr ("What's new"));
  1110. notesButton.setVisible (! c.rollingBack);
  1111. updateButton.setButtonText (installer ? tr ("Install and restart") : tr ("Restart now"));
  1112. updateButton.setVisible (true);
  1113. break;
  1114. case Phase::saved:
  1115. text = tr ("LYNX SHARE {0} was saved to {1}", { v, c.result.getParentDirectory().getFullPathName() });
  1116. otherButton.setButtonText (tr ("Show in folder"));
  1117. otherButton.setVisible (true);
  1118. break;
  1119. case Phase::failed:
  1120. text = tr ("The update failed: {0}", { c.error });
  1121. updateButton.setButtonText (tr ("Try again"));
  1122. updateButton.setVisible (true);
  1123. otherButton.setButtonText (tr ("Open the release page"));
  1124. otherButton.setVisible (true);
  1125. break;
  1126. case Phase::updated:
  1127. text = c.rollingBack ? tr ("LYNX SHARE went back to {0}. Help > Check for updates... offers the newer version again.", { v })
  1128. : tr ("LYNX SHARE was updated to {0}", { v });
  1129. notesButton.setButtonText (tr ("What's new"));
  1130. notesButton.setVisible (! c.release.body.empty() && ! c.rollingBack);
  1131. break;
  1132. case Phase::idle:
  1133. case Phase::checking: show = false; break;
  1134. }
  1135. message.setText (text, juce::dontSendNotification);
  1136. resized();
  1137. repaint();
  1138. if (show != isVisible())
  1139. {
  1140. setVisible (show);
  1141. if (onVisibilityChanged)
  1142. onVisibilityChanged();
  1143. }
  1144. }
  1145. void UpdateBar::showForSnapshot (int state)
  1146. {
  1147. auto& c = controller();
  1148. c.release = {};
  1149. c.release.version = update::parseVersion ("0.1.22-alpha");
  1150. c.release.body = "## New\n- The Update button";
  1151. c.result = downloadsFolder().getChildFile ("LYNX-0.1.22-alpha-windows-x64.zip");
  1152. c.error = tr ("the download is damaged (its checksum does not match)");
  1153. c.progress = 0.42f;
  1154. c.rollingBack = state >= 4; // (round 190gh: going back, downloading; went back)
  1155. if (c.rollingBack)
  1156. c.release.version = update::parseVersion ("0.1.27");
  1157. c.phase = state == 1 || state == 4 ? Phase::downloading : state == 2 ? Phase::failed : state == 3 ? Phase::ready : state == 5 ? Phase::updated : Phase::available;
  1158. c.hidden = false;
  1159. refresh();
  1160. }
  1161. void UpdateBar::paint (juce::Graphics& g)
  1162. {
  1163. g.fillAll (theme::colour::bg3);
  1164. g.setColour (theme::colour::accent);
  1165. g.fillRect (0, 0, 3, getHeight());
  1166. g.setColour (theme::colour::border);
  1167. g.fillRect (0, getHeight() - 1, getWidth(), 1);
  1168. if (progress >= 0.0f)
  1169. {
  1170. g.setColour (theme::colour::accent);
  1171. g.fillRect (0.0f, (float) getHeight() - 2.0f, (float) getWidth() * progress, 2.0f);
  1172. }
  1173. }
  1174. void UpdateBar::resized()
  1175. {
  1176. auto r = getLocalBounds().reduced (0, 4).withTrimmedLeft (12).withTrimmedRight (4);
  1177. if (closeButton.isVisible())
  1178. closeButton.setBounds (r.removeFromRight (r.getHeight() + 4));
  1179. auto place = [&r] (juce::TextButton& b) {
  1180. if (! b.isVisible())
  1181. return;
  1182. const auto w = juce::jmax (70, b.getBestWidthForHeight (r.getHeight()) + 8);
  1183. b.setBounds (r.removeFromRight (w));
  1184. r.removeFromRight (6);
  1185. };
  1186. place (updateButton);
  1187. place (otherButton);
  1188. place (notesButton);
  1189. message.setBounds (r);
  1190. }
  1191. // ================================================================================================================
  1192. // the release notes window
  1193. // ================================================================================================================
  1194. namespace
  1195. {
  1196. // The release notes as one laid-out AttributedString (a 45 KB release body inserted run by run into a TextEditor took
  1197. // seconds on Windows: each insert re-lays the whole text out). Laid out again only when the width changes.
  1198. class NotesText final : public juce::Component
  1199. {
  1200. public:
  1201. explicit NotesText (const std::vector<update::NoteLine>& lines)
  1202. {
  1203. using K = update::NoteLine::Kind;
  1204. text.setWordWrap (juce::AttributedString::byWord);
  1205. text.setLineSpacing (2.0f);
  1206. auto add = [this] (const juce::String& s, const juce::Font& font, juce::Colour colour) { text.append (s, font, colour); };
  1207. if (lines.empty())
  1208. add (tr ("This release has no notes."), theme::font (theme::type::body), theme::colour::textSecondary);
  1209. for (const auto& l : lines)
  1210. {
  1211. const auto t = juce::String::fromUTF8 (l.text.c_str());
  1212. switch (l.kind)
  1213. {
  1214. case K::heading:
  1215. add (t + "\n", theme::font (l.level <= 1 ? theme::type::title + 3.0f : l.level == 2 ? theme::type::title + 1.0f : theme::type::body + 1.0f, true),
  1216. l.level <= 2 ? theme::colour::accent : theme::colour::textPrimary);
  1217. break;
  1218. case K::bullet:
  1219. add (juce::String::repeatedString (" ", l.level) + juce::String::fromUTF8 ("\xE2\x80\xA2 ") + t + "\n", theme::font (theme::type::body),
  1220. theme::colour::textPrimary);
  1221. break;
  1222. case K::text: add (t + "\n", theme::font (theme::type::body), theme::colour::textSecondary); break;
  1223. case K::blank: add ("\n", theme::font (theme::type::small), theme::colour::textSecondary); break;
  1224. }
  1225. }
  1226. }
  1227. // lays the text out for `width` and takes the height it needs
  1228. void fitWidth (int width)
  1229. {
  1230. if (width == laidOutWidth)
  1231. return;
  1232. laidOutWidth = width;
  1233. layout.createLayout (text, (float) juce::jmax (100, width - 2 * margin));
  1234. setSize (width, (int) std::ceil (layout.getHeight()) + 2 * margin);
  1235. }
  1236. void paint (juce::Graphics& g) override { layout.draw (g, getLocalBounds().reduced (margin).toFloat()); }
  1237. private:
  1238. static constexpr int margin = 12;
  1239. juce::AttributedString text;
  1240. juce::TextLayout layout;
  1241. int laidOutWidth = -1;
  1242. };
  1243. class NotesPanel final : public juce::Component
  1244. {
  1245. public:
  1246. explicit NotesPanel (const update::Release& r) : notes (update::releaseNotes (r.body))
  1247. {
  1248. title.setText (r.name.empty() ? "LYNX SHARE " + versionText (r) : fromUtf8 (r.name), juce::dontSendNotification);
  1249. title.setFont (theme::font (theme::type::title + 3.0f, true));
  1250. title.setColour (juce::Label::textColourId, theme::colour::textPrimary);
  1251. addAndMakeVisible (title);
  1252. viewport.setViewedComponent (&notes, false);
  1253. viewport.setScrollBarsShown (true, false);
  1254. viewport.setScrollBarThickness (10);
  1255. addAndMakeVisible (viewport);
  1256. page = releasePage (r);
  1257. githubButton.setButtonText (tr ("Open on GitHub"));
  1258. githubButton.onClick = [this] { juce::URL (page).launchInDefaultBrowser(); };
  1259. closeButton.setButtonText (tr ("Close"));
  1260. closeButton.onClick = [this] {
  1261. if (auto* w = findParentComponentOfClass<juce::DialogWindow>())
  1262. w->exitModalState (0); // (launchAsync: deleted when dismissed)
  1263. };
  1264. const auto canUpdate = controller().phase == Phase::available && update::methodFor (flavour()) != update::Method::none;
  1265. updateButton.setButtonText (update::methodFor (flavour()) == update::Method::openPage ? tr ("Download...") : tr ("Update"));
  1266. updateButton.setColour (juce::TextButton::buttonColourId, theme::colour::accent);
  1267. updateButton.setColour (juce::TextButton::textColourOffId, theme::colour::onAccent);
  1268. updateButton.onClick = [this] {
  1269. startUpdate();
  1270. closeButton.triggerClick();
  1271. };
  1272. updateButton.setVisible (canUpdate);
  1273. for (auto* b : { &githubButton, &closeButton })
  1274. addAndMakeVisible (*b);
  1275. addChildComponent (updateButton);
  1276. setSize (680, 540);
  1277. }
  1278. void paint (juce::Graphics& g) override
  1279. {
  1280. g.fillAll (theme::colour::bg2);
  1281. g.setColour (theme::colour::bg1);
  1282. g.fillRect (viewport.getBounds());
  1283. g.setColour (theme::colour::border);
  1284. g.drawRect (viewport.getBounds().expanded (1));
  1285. }
  1286. void resized() override
  1287. {
  1288. auto r = getLocalBounds().reduced (16);
  1289. title.setBounds (r.removeFromTop (30));
  1290. r.removeFromTop (8);
  1291. auto buttons = r.removeFromBottom (30);
  1292. r.removeFromBottom (12);
  1293. viewport.setBounds (r.reduced (1));
  1294. notes.fitWidth (viewport.getMaximumVisibleWidth());
  1295. closeButton.setBounds (buttons.removeFromRight (100));
  1296. buttons.removeFromRight (8);
  1297. if (updateButton.isVisible())
  1298. {
  1299. updateButton.setBounds (buttons.removeFromRight (120));
  1300. buttons.removeFromRight (8);
  1301. }
  1302. githubButton.setBounds (buttons.removeFromLeft (150));
  1303. }
  1304. private:
  1305. juce::Label title;
  1306. NotesText notes;
  1307. juce::Viewport viewport;
  1308. juce::TextButton githubButton, closeButton, updateButton;
  1309. juce::String page;
  1310. };
  1311. } // namespace
  1312. void showReleaseNotes()
  1313. {
  1314. const auto& release = controller().release;
  1315. juce::DialogWindow::LaunchOptions options;
  1316. options.content.setOwned (fitContentToScreen (std::make_unique<NotesPanel> (release)).release());
  1317. options.dialogTitle = tr ("What's new in LYNX SHARE {0}", { versionText (release) });
  1318. options.dialogBackgroundColour = theme::colour::bg2;
  1319. options.useNativeTitleBar = true;
  1320. options.resizable = true;
  1321. options.escapeKeyTriggersCloseButton = true;
  1322. if (auto* dialog = options.launchAsync())
  1323. {
  1324. dialog->setResizeLimits (420, 320, 1600, 1400);
  1325. keepAboveMainWindow (*dialog);
  1326. }
  1327. }
  1328. std::unique_ptr<juce::Component> makeReleaseNotesForSnapshot()
  1329. {
  1330. update::Release r;
  1331. r.name = "LYNX SHARE 0.1.22-alpha";
  1332. r.version = update::parseVersion ("0.1.22-alpha");
  1333. r.body = "## New\n- **In-app updates**: a bar shows when a new version is out; *Update* installs it.\n"
  1334. " - Windows installer: downloads, checks and installs it, then restarts.\n- Help › Check for updates...\n\n"
  1335. "## Fixes\n- The [Mixer](https://lynx-share.com) keeps its layout.\n\nThanks to everyone who reported a bug!";
  1336. controller().release = r;
  1337. controller().phase = Phase::available;
  1338. return std::make_unique<NotesPanel> (r);
  1339. }
  1340. } // namespace lynx::updater