Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

feat(update): install updates with progress and a live check

RoversX1a3ddaeea8d5
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftl
index a6beee62..d76f9f2e 100644
--- a/thinkterm-i18n/i18n/de-DE.ftl
+++ b/thinkterm-i18n/i18n/de-DE.ftl
@@ -706,7 +706,10 @@ settings-update-unknown = Es wurde noch nicht nach Updates gesucht.
settings-update-unknown-detail = ThinkTerm { $version }
settings-update-check-now = Nach Updates suchen
settings-update-checked = Geprüft
-settings-update-automatic = Automatische Updates
+settings-update-checking = Wird geprüft…
+settings-update-checking-title = Suche nach Updates…
+settings-update-check-failed = Suche nach Updates fehlgeschlagen.
+settings-update-automatic = Automatisch prüfen
settings-update-frequency = Prüfintervall
settings-update-frequency-off = Aus
settings-update-frequency-daily = Täglich
@@ -748,10 +751,20 @@ settings-sidebar-snippets-description = Gespeicherte Befehle und Texte, die Sie
update-toast-title = ThinkTerm-Update verfügbar
update-toast-body = Klicken, um die Neuerungen zu sehen
settings-update-install = Update installieren
-settings-update-installing = Wird installiert… dieses Fenster funktioniert weiter, während die Dateien ersetzt werden.
-settings-update-installed = ThinkTerm { $version } installiert. Beenden Sie ThinkTerm und öffnen Sie es erneut, um es zu verwenden.
-settings-update-install-failed = Das Update konnte nicht installiert werden: { $error }
-settings-update-install-note = „Update installieren“ ersetzt die Dateien an Ort und Stelle; ThinkTerm läuft mit der aktuellen Version weiter, bis Sie es erneut öffnen.
+settings-update-preparing = Installation von ThinkTerm { $version } wird vorbereitet…
+settings-update-installing = Dieses Fenster funktioniert währenddessen weiter.
+settings-update-downloading = ThinkTerm { $version } wird geladen…
+settings-update-download-progress = { $done } von { $total } · { $percent } %
+settings-update-seconds-left = noch etwa { $count } s
+settings-update-minutes-left = noch etwa { $count } min
+settings-update-installing-title = ThinkTerm { $version } wird installiert…
+settings-update-installed = ThinkTerm { $version } ist installiert.
+settings-update-installed-detail = Starten Sie ThinkTerm neu, um die neue Version zu verwenden.
+settings-update-installer-started = Das Installationsprogramm läuft.
+settings-update-installer-started-detail = Es beendet ThinkTerm, installiert { $version } und öffnet es wieder.
+settings-update-install-failed-title = Das Update konnte nicht installiert werden.
+settings-update-failed-detail = Was schiefging, steht unten.
+settings-update-install-note = „Update installieren“ ersetzt die Dateien an Ort und Stelle; ThinkTerm läuft mit der aktuellen Version weiter, bis es neu gestartet wird.
settings-update-method-script = Vom Installationsskript installiert (Variante { $variant }).
settings-update-method-macapp = ThinkTerm.app wurde von Hand unter { $path } installiert; ein Update ersetzt sie dort und legt die Kommandozeilenwerkzeuge unter ~/.local/bin ab.
settings-update-method-appimage = Dies ist ein AppImage: Aktualisieren Sie es mit AppImageUpdate oder laden Sie das neue AppImage von der Releases-Seite.
diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftl
index 968c909c..f53525ae 100644
--- a/thinkterm-i18n/i18n/en-US.ftl
+++ b/thinkterm-i18n/i18n/en-US.ftl
@@ -706,7 +706,10 @@ settings-update-unknown = No update check has run yet.
settings-update-unknown-detail = ThinkTerm { $version }
settings-update-check-now = Check for Updates
settings-update-checked = Checked
-settings-update-automatic = Automatic Updates
+settings-update-checking = Checking…
+settings-update-checking-title = Checking for updates…
+settings-update-check-failed = Could not check for updates.
+settings-update-automatic = Check Automatically
settings-update-frequency = Check Frequency
settings-update-frequency-off = Off
settings-update-frequency-daily = Daily
@@ -748,10 +751,20 @@ settings-sidebar-snippets-description = Saved commands and text you can paste in
update-toast-title = ThinkTerm update available
update-toast-body = Click to see what's new
settings-update-install = Install Update
-settings-update-installing = Installing… this window keeps working while the files are replaced.
-settings-update-installed = Installed ThinkTerm { $version }. Quit and reopen ThinkTerm to use it.
-settings-update-install-failed = The update could not be installed: { $error }
-settings-update-install-note = Install Update replaces the files in place; ThinkTerm keeps running the current version until you reopen it.
+settings-update-preparing = Preparing to install ThinkTerm { $version }…
+settings-update-installing = This window keeps working meanwhile.
+settings-update-downloading = Downloading ThinkTerm { $version }…
+settings-update-download-progress = { $done } of { $total } · { $percent }%
+settings-update-seconds-left = about { $count } s left
+settings-update-minutes-left = about { $count } min left
+settings-update-installing-title = Installing ThinkTerm { $version }…
+settings-update-installed = ThinkTerm { $version } is installed.
+settings-update-installed-detail = Restart ThinkTerm to start using it.
+settings-update-installer-started = The installer is running.
+settings-update-installer-started-detail = It closes ThinkTerm, installs { $version } and opens it again.
+settings-update-install-failed-title = The update could not be installed.
+settings-update-failed-detail = What went wrong is shown below.
+settings-update-install-note = Install Update replaces the files in place; ThinkTerm keeps running the current version until it restarts.
settings-update-method-script = Installed by the install script ({ $variant } variant).
settings-update-method-macapp = ThinkTerm.app installed by hand at { $path }; installing an update replaces it there and adds the command-line tools under ~/.local/bin.
settings-update-method-appimage = This is an AppImage: update it with AppImageUpdate, or download the new AppImage from the releases page.
diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftl
index 17070726..06e42294 100644
--- a/thinkterm-i18n/i18n/fr-FR.ftl
+++ b/thinkterm-i18n/i18n/fr-FR.ftl
@@ -703,7 +703,10 @@ settings-update-unknown = Aucune vérification n’a encore eu lieu.
settings-update-unknown-detail = ThinkTerm { $version }
settings-update-check-now = Rechercher les mises à jour
settings-update-checked = Vérifié
-settings-update-automatic = Mises à jour automatiques
+settings-update-checking = Vérification…
+settings-update-checking-title = Recherche de mises à jour…
+settings-update-check-failed = Impossible de vérifier les mises à jour.
+settings-update-automatic = Vérification automatique
settings-update-frequency = Fréquence de vérification
settings-update-frequency-off = Désactivé
settings-update-frequency-daily = Chaque jour
@@ -745,10 +748,20 @@ settings-sidebar-snippets-description = Commandes et textes enregistrés, à col
update-toast-title = Mise à jour de ThinkTerm disponible
update-toast-body = Cliquez pour voir les nouveautés
settings-update-install = Installer la mise à jour
-settings-update-installing = Installation… cette fenêtre reste utilisable pendant le remplacement des fichiers.
-settings-update-installed = ThinkTerm { $version } est installé. Quittez et rouvrez ThinkTerm pour l'utiliser.
-settings-update-install-failed = La mise à jour n'a pas pu être installée : { $error }
-settings-update-install-note = Installer la mise à jour remplace les fichiers sur place ; ThinkTerm continue d'exécuter la version actuelle jusqu'à sa réouverture.
+settings-update-preparing = Préparation de l'installation de ThinkTerm { $version }…
+settings-update-installing = Cette fenêtre reste utilisable pendant ce temps.
+settings-update-downloading = Téléchargement de ThinkTerm { $version }…
+settings-update-download-progress = { $done } sur { $total } · { $percent } %
+settings-update-seconds-left = environ { $count } s restantes
+settings-update-minutes-left = environ { $count } min restantes
+settings-update-installing-title = Installation de ThinkTerm { $version }…
+settings-update-installed = ThinkTerm { $version } est installé.
+settings-update-installed-detail = Redémarrez ThinkTerm pour utiliser la nouvelle version.
+settings-update-installer-started = Le programme d'installation est en cours.
+settings-update-installer-started-detail = Il ferme ThinkTerm, installe { $version } puis le rouvre.
+settings-update-install-failed-title = La mise à jour n'a pas pu être installée.
+settings-update-failed-detail = Le détail de l'erreur figure ci-dessous.
+settings-update-install-note = Installer la mise à jour remplace les fichiers sur place ; ThinkTerm continue d'exécuter la version actuelle jusqu'à son redémarrage.
settings-update-method-script = Installé par le script d'installation (variante { $variant }).
settings-update-method-macapp = ThinkTerm.app installé manuellement dans { $path } ; la mise à jour le remplace à cet endroit et ajoute les outils en ligne de commande dans ~/.local/bin.
settings-update-method-appimage = Ceci est une AppImage : mettez-la à jour avec AppImageUpdate ou téléchargez la nouvelle AppImage depuis la page des versions.
diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftl
index dca8124c..163a671b 100644
--- a/thinkterm-i18n/i18n/ja-JP.ftl
+++ b/thinkterm-i18n/i18n/ja-JP.ftl
@@ -691,7 +691,10 @@ settings-update-unknown = まだ確認していません。
settings-update-unknown-detail = ThinkTerm { $version }
settings-update-check-now = アップデートを確認
settings-update-checked = 確認しました
-settings-update-automatic = 自動アップデート
+settings-update-checking = 確認中…
+settings-update-checking-title = アップデートを確認中…
+settings-update-check-failed = アップデートを確認できませんでした。
+settings-update-automatic = アップデートを自動確認
settings-update-frequency = 確認の頻度
settings-update-frequency-off = オフ
settings-update-frequency-daily = 毎日
@@ -733,10 +736,20 @@ settings-sidebar-snippets-description = 保存したコマンドやテキスト
update-toast-title = ThinkTerm の新しいバージョンがあります
update-toast-body = クリックして更新内容を表示
settings-update-install = アップデートをインストール
-settings-update-installing = インストール中… ファイルの置き換え中もこのウィンドウは使えます。
-settings-update-installed = ThinkTerm { $version } をインストールしました。ThinkTerm を終了して開き直すと新しいバージョンになります。
-settings-update-install-failed = アップデートをインストールできませんでした: { $error }
-settings-update-install-note = 「アップデートをインストール」はファイルをその場で置き換えます。開き直すまで ThinkTerm は現在のバージョンのまま動作します。
+settings-update-preparing = ThinkTerm { $version } のインストールを準備中…
+settings-update-installing = その間もこのウィンドウは使えます。
+settings-update-downloading = ThinkTerm { $version } をダウンロード中…
+settings-update-download-progress = { $done } / { $total } · { $percent }%
+settings-update-seconds-left = 残り約 { $count } 秒
+settings-update-minutes-left = 残り約 { $count } 分
+settings-update-installing-title = ThinkTerm { $version } をインストール中…
+settings-update-installed = ThinkTerm { $version } をインストールしました。
+settings-update-installed-detail = ThinkTerm を再起動すると新しいバージョンを使えます。
+settings-update-installer-started = インストーラーを実行中です。
+settings-update-installer-started-detail = ThinkTerm を終了し、{ $version } をインストールしてから再び開きます。
+settings-update-install-failed-title = アップデートをインストールできませんでした。
+settings-update-failed-detail = 詳細は下に表示されています。
+settings-update-install-note = 「アップデートをインストール」はファイルをその場で置き換えます。再起動するまで ThinkTerm は現在のバージョンのまま動作します。
settings-update-method-script = インストールスクリプトでインストールされています({ $variant } 版)。
settings-update-method-macapp = { $path } に手動でインストールされた ThinkTerm.app です。アップデートはその場所で置き換え、コマンドラインツールを ~/.local/bin に追加します。
settings-update-method-appimage = これは AppImage です。AppImageUpdate で更新するか、リリースページから新しい AppImage をダウンロードしてください。
diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftl
index eff43e1e..9cd40a95 100644
--- a/thinkterm-i18n/i18n/zh-CN.ftl
+++ b/thinkterm-i18n/i18n/zh-CN.ftl
@@ -691,7 +691,10 @@ settings-update-unknown = 尚未检查过更新。
settings-update-unknown-detail = ThinkTerm { $version }
settings-update-check-now = 检查更新
settings-update-checked = 已检查
-settings-update-automatic = 自动更新
+settings-update-checking = 正在检查…
+settings-update-checking-title = 正在检查更新…
+settings-update-check-failed = 无法检查更新。
+settings-update-automatic = 自动检查更新
settings-update-frequency = 检查频率
settings-update-frequency-off = 关闭
settings-update-frequency-daily = 每天
@@ -733,10 +736,20 @@ settings-sidebar-snippets-description = 保存的命令和文本,可以粘贴
update-toast-title = ThinkTerm 有新版本
update-toast-body = 点击查看更新内容
settings-update-install = 安装更新
-settings-update-installing = 正在安装……替换文件期间本窗口可以继续使用。
-settings-update-installed = 已安装 ThinkTerm { $version }。退出并重新打开 ThinkTerm 即可使用新版本。
-settings-update-install-failed = 更新安装失败:{ $error }
-settings-update-install-note = "安装更新"会原地替换文件;在你重新打开之前,ThinkTerm 仍运行当前版本。
+settings-update-preparing = 正在准备安装 ThinkTerm { $version }…
+settings-update-installing = 期间本窗口可以继续使用。
+settings-update-downloading = 正在下载 ThinkTerm { $version }…
+settings-update-download-progress = { $done } / { $total } · { $percent }%
+settings-update-seconds-left = 约 { $count } 秒
+settings-update-minutes-left = 约 { $count } 分钟
+settings-update-installing-title = 正在安装 ThinkTerm { $version }…
+settings-update-installed = ThinkTerm { $version } 已安装。
+settings-update-installed-detail = 重启后开始使用新版本。
+settings-update-installer-started = 安装程序正在运行。
+settings-update-installer-started-detail = 它会关闭 ThinkTerm,安装 { $version } 后再重新打开。
+settings-update-install-failed-title = 更新安装失败。
+settings-update-failed-detail = 原因见下方。
+settings-update-install-note = "安装更新"会原地替换文件;在重启之前,ThinkTerm 仍运行当前版本。
settings-update-method-script = 由安装脚本安装({ $variant } 版本)。
settings-update-method-macapp = 手动安装在 { $path } 的 ThinkTerm.app;安装更新会在原位置替换它,并把命令行工具放到 ~/.local/bin。
settings-update-method-appimage = 这是 AppImage:用 AppImageUpdate 更新,或从发布页下载新的 AppImage。
diff --git a/thinkterm-update/Cargo.toml b/thinkterm-update/Cargo.toml
index 4c4e19f4..b1825e50 100644
--- a/thinkterm-update/Cargo.toml
+++ b/thinkterm-update/Cargo.toml
@@ -14,9 +14,7 @@ sha2.workspace = true
hex.workspace = true
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
+tempfile.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
plist.workspace = true
-
-[dev-dependencies]
-tempfile.workspace = true
diff --git a/thinkterm-update/src/lib.rs b/thinkterm-update/src/lib.rs
index 7645b2ca..28ca18fd 100644
--- a/thinkterm-update/src/lib.rs
+++ b/thinkterm-update/src/lib.rs
@@ -10,7 +10,9 @@
use anyhow::{anyhow, Context};
use serde::{Deserialize, Serialize};
+use std::io::Write;
use std::path::{Path, PathBuf};
+use std::time::{Duration, Instant};
pub mod manifest;
pub mod method;
@@ -102,25 +104,177 @@ impl Asset {
}
}
-/// Download one release asset and verify it against GitHub's digest when
-/// there is one. A missing digest is reported, not treated as a failure.
-pub fn download_asset(asset: &Asset) -> anyhow::Result<(Vec<u8>, bool)> {
+/// How far an install has got, for whoever is showing it.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InstallProgress {
+ /// Fetching the release archive or the Windows installer: bytes so far,
+ /// of the size GitHub recorded for the asset.
+ Downloading { done: u64, total: u64 },
+ /// The download is in and verified; the installer has taken over.
+ Installing,
+}
+
+/// The longest a download goes without telling its watcher how far it is.
+const PROGRESS_INTERVAL: Duration = Duration::from_millis(100);
+
+/// "63.1 MB": binary megabytes, or gigabytes past 1024 of them, the way
+/// Settings shows every size.
+pub fn format_size(bytes: u64) -> String {
+ let mib = bytes as f64 / 1024.0 / 1024.0;
+ if mib >= 1024.0 {
+ format!("{:.2} GB", mib / 1024.0)
+ } else {
+ format!("{mib:.1} MB")
+ }
+}
+
+/// Where a GET's body goes. A redirect's own body is thrown away, so the
+/// sink has to be able to start over.
+trait BodySink: Write {
+ fn restart(&mut self) -> std::io::Result<()>;
+}
+
+impl BodySink for Vec<u8> {
+ fn restart(&mut self) -> std::io::Result<()> {
+ self.clear();
+ Ok(())
+ }
+}
+
+/// A download on its way to disk, hashed and counted as it arrives, with
+/// the count reported at most every `interval`.
+struct DownloadSink<'a> {
+ file: std::fs::File,
+ hasher: sha2::Sha256,
+ done: u64,
+ total: u64,
+ progress: &'a mut dyn FnMut(u64, u64),
+ interval: Duration,
+ reported: Option<Instant>,
+}
+
+impl Write for DownloadSink<'_> {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ use sha2::Digest;
+ self.file.write_all(buf)?;
+ self.hasher.update(buf);
+ self.done += buf.len() as u64;
+ if self
+ .reported
+ .map_or(true, |at| at.elapsed() >= self.interval)
+ {
+ self.reported = Some(Instant::now());
+ (self.progress)(self.done, self.total);
+ }
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> std::io::Result<()> {
+ self.file.flush()
+ }
+}
+
+impl BodySink for DownloadSink<'_> {
+ fn restart(&mut self) -> std::io::Result<()> {
+ use sha2::Digest;
+ use std::io::{Seek, SeekFrom};
+ self.file.set_len(0)?;
+ self.file.seek(SeekFrom::Start(0))?;
+ self.hasher = sha2::Sha256::new();
+ self.done = 0;
+ self.reported = None;
+ Ok(())
+ }
+}
+
+/// How many times a download is tried before giving up, as curl's --retry
+/// did when install.sh fetched the archive itself.
+const DOWNLOAD_ATTEMPTS: u64 = 3;
+
+/// Download one release asset to `dest`, reporting `(bytes so far, size)`
+/// as it arrives, and verify it against GitHub's digest when there is one.
+/// Returns whether it was verified: a missing digest is reported, not
+/// treated as a failure. A failed or mismatched download leaves no file.
+pub fn download_asset_to(
+ asset: &Asset,
+ dest: &Path,
+ progress: &mut dyn FnMut(u64, u64),
+) -> anyhow::Result<bool> {
use sha2::Digest;
- let body = http_get(&asset.browser_download_url)
- .with_context(|| format!("downloading {}", asset.name))?;
+ // With a token the repository may be private, and then only the API
+ // serves the bytes; install.sh downloads from there in that case too.
+ let (url, accept) = match update_token() {
+ Some(_) => (asset.url.as_str(), Some("application/octet-stream")),
+ None => (asset.browser_download_url.as_str(), None),
+ };
+ let file =
+ std::fs::File::create(dest).with_context(|| format!("creating {}", dest.display()))?;
+ let mut sink = DownloadSink {
+ file,
+ hasher: sha2::Sha256::new(),
+ done: 0,
+ total: asset.size as u64,
+ progress,
+ interval: PROGRESS_INTERVAL,
+ reported: None,
+ };
+ let mut attempt = 1;
+ let fetched = loop {
+ let mut result = http_get_into(url, accept, &mut sink);
+ if result.is_ok() {
+ result = sink.flush().map_err(anyhow::Error::from);
+ }
+ // http_req ends a body at the first read error instead of failing,
+ // so a dropped connection arrives as a short file: count the bytes.
+ if result.is_ok() && sink.total > 0 && sink.done != sink.total {
+ result = Err(anyhow!(
+ "the download stopped at {} of {} bytes",
+ sink.done,
+ sink.total
+ ));
+ }
+ match result {
+ Err(err)
+ if attempt < DOWNLOAD_ATTEMPTS
+ && !err.chain().any(|cause| cause.is::<Refused>()) =>
+ {
+ log::warn!("downloading {} (attempt {attempt}): {err:#}", asset.name);
+ std::thread::sleep(Duration::from_secs(attempt));
+ attempt += 1;
+ if let Err(err) = sink.restart() {
+ break Err(err.into());
+ }
+ }
+ result => break result,
+ }
+ }
+ .with_context(|| format!("downloading {}", asset.name));
+ let DownloadSink {
+ hasher,
+ done,
+ total,
+ progress,
+ ..
+ } = sink;
+ if let Err(err) = fetched {
+ let _ = std::fs::remove_file(dest);
+ return Err(err);
+ }
+ progress(done, total);
match asset.sha256() {
Some(expected) => {
- let got = hex::encode(sha2::Sha256::digest(&body));
+ let got = hex::encode(hasher.finalize());
if got != expected {
+ let _ = std::fs::remove_file(dest);
anyhow::bail!(
"checksum mismatch for {}: expected {expected}, got {got}; \
the download is corrupt or has been tampered with",
asset.name
);
}
- Ok((body, true))
+ Ok(true)
}
- None => Ok((body, false)),
+ None => Ok(false),
}
}
@@ -132,7 +286,10 @@ pub fn download_asset(asset: &Asset) -> anyhow::Result<(Vec<u8>, bool)> {
/// skips the "this will install" prompt; the two APPLICATIONS switches let
/// the installer stop and restart a running ThinkTerm rather than fail on a
/// locked file. Elevation is the installer's own UAC prompt.
-pub fn run_windows_installer(release: &Release) -> anyhow::Result<()> {
+pub fn run_windows_installer(
+ release: &Release,
+ progress: &mut dyn FnMut(InstallProgress),
+) -> anyhow::Result<()> {
let version = release.tag_name.trim_start_matches('v');
let wanted = format!("ThinkTerm-{version}-setup.exe");
let asset = release
@@ -141,16 +298,16 @@ pub fn run_windows_installer(release: &Release) -> anyhow::Result<()> {
.find(|a| a.name.eq_ignore_ascii_case(&wanted))
.ok_or_else(|| anyhow!("release {version} has no {wanted}; see {}", release.html_url))?;
- println!("downloading {} ({} bytes)...", asset.name, asset.size);
- let (body, verified) = download_asset(asset)?;
- if !verified {
- println!("note: GitHub recorded no checksum for this asset; the download was not verified");
- }
-
let dir = std::env::temp_dir().join("thinkterm-update");
std::fs::create_dir_all(&dir)?;
let path = dir.join(&asset.name);
- std::fs::write(&path, &body).with_context(|| format!("writing {}", path.display()))?;
+ let verified = download_asset_to(asset, &path, &mut |done, total| {
+ progress(InstallProgress::Downloading { done, total })
+ })?;
+ if !verified {
+ println!("note: GitHub recorded no checksum for this asset; the download was not verified");
+ }
+ progress(InstallProgress::Installing);
println!("starting the installer: {}", path.display());
std::process::Command::new(&path)
@@ -168,40 +325,128 @@ fn get_github_release_info(uri: &str) -> anyhow::Result<Release> {
}
/// One HTTP GET, whole body in memory. The releases API answers are small
-/// and the installer script is a few dozen kilobytes; nothing here streams.
+/// and the installer script is a few dozen kilobytes; downloads of release
+/// assets go through `download_asset_to` instead.
pub fn http_get(uri: &str) -> anyhow::Result<Vec<u8>> {
+ let mut body = Vec::new();
+ http_get_into(uri, None, &mut body)?;
+ Ok(body)
+}
+
+/// A token lifts the anonymous API rate limit and is what makes a private
+/// repository reachable at all. It has to be one meant for this: the GUI
+/// runs its check on its own, and a GITHUB_TOKEN the user exported for
+/// other tools must not be sent anywhere by it.
+fn update_token() -> Option<String> {
+ std::env::var("THINKTERM_UPDATE_TOKEN")
+ .ok()
+ .map(|token| token.trim().to_string())
+ .filter(|token| !token.is_empty())
+}
+
+/// How many redirects a GET follows. GitHub sends every asset download
+/// through one, to signed storage; http_req does not follow them itself.
+const MAX_REDIRECTS: usize = 5;
+
+fn http_get_into<S: BodySink>(
+ uri: &str,
+ accept: Option<&str>,
+ sink: &mut S,
+) -> anyhow::Result<()> {
use http_req::request::{HttpVersion, Request};
use http_req::uri::Uri;
use std::convert::TryFrom;
- let parsed = Uri::try_from(uri)?;
- let mut body = Vec::new();
- let mut request = Request::new(&parsed);
- request
- .version(HttpVersion::Http10)
- .header("User-Agent", &format!("thinkterm/{}", config::wezterm_version()));
- // A token lifts the anonymous API rate limit and is what makes a
- // private repository reachable at all. It has to be one meant for
- // this: the GUI runs this check on its own, and a GITHUB_TOKEN the
- // user exported for other tools must not be sent anywhere by it.
- let auth = std::env::var("THINKTERM_UPDATE_TOKEN")
+ let auth = update_token().map(|token| format!("Bearer {token}"));
+
+ let mut current = uri.to_string();
+ for _ in 0..=MAX_REDIRECTS {
+ // Name the host that answered when a redirect led to another one.
+ let what = match host_of(&current).filter(|_| !same_host(uri, &current)) {
+ Some(host) => format!("{uri} (redirected to {host})"),
+ None => uri.to_string(),
+ };
+ let parsed = Uri::try_from(current.as_str())?;
+ let mut request = Request::new(&parsed);
+ request
+ .version(HttpVersion::Http10)
+ .header("User-Agent", &format!("thinkterm/{}", config::wezterm_version()));
+ if let Some(accept) = accept {
+ request.header("Accept", accept);
+ }
+ // Only to the host the token was meant for: the storage a download
+ // is redirected to is signed already and must not see it.
+ if let Some(auth) = auth.as_ref().filter(|_| same_host(uri, &current)) {
+ request.header("Authorization", auth);
+ }
+ let res = request
+ .send(sink)
+ .map_err(|e| anyhow!("fetching {what}: {e}"))?;
+ let status = res.status_code();
+ if status.is_redirect() {
+ let Some(location) = res.headers().get("Location") else {
+ return Err(Refused(format!("fetching {what}: HTTP {status} without a Location")).into());
+ };
+ current = redirect_target(&current, location)
+ .map_err(|err| Refused(format!("fetching {what}: {err:#}")))?;
+ sink.restart()?;
+ continue;
+ }
+ if !status.is_success() {
+ let message = format!("fetching {what}: HTTP {status} {}", res.reason());
+ // A timeout or a rate limit is worth another try; no other 4xx is.
+ let lasting = status.is_client_err() && !matches!(u16::from(status), 408 | 429);
+ return Err(if lasting {
+ Refused(message).into()
+ } else {
+ anyhow!(message)
+ });
+ }
+ return Ok(());
+ }
+ Err(Refused(format!("fetching {uri}: more than {MAX_REDIRECTS} redirects")).into())
+}
+
+/// An answer that asking again will not change: a 4xx other than a timeout
+/// or a rate limit, or a redirect this does not follow. Anything else -- the
+/// network, a 5xx, a short body -- may come out differently the next time.
+#[derive(Debug)]
+struct Refused(String);
+
+impl std::fmt::Display for Refused {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+impl std::error::Error for Refused {}
+
+fn host_of(uri: &str) -> Option<String> {
+ use http_req::uri::Uri;
+ use std::convert::TryFrom;
+ Uri::try_from(uri)
.ok()
- .filter(|t| !t.trim().is_empty())
- .map(|t| format!("Bearer {}", t.trim()));
- if let Some(auth) = &auth {
- request.header("Authorization", auth);
- }
- let res = request
- .send(&mut body)
- .map_err(|e| anyhow!("fetching {uri}: {e}"))?;
- if !res.status_code().is_success() {
- anyhow::bail!(
- "fetching {uri}: HTTP {} {}",
- res.status_code(),
- res.reason()
- );
+ .and_then(|uri| uri.host().map(str::to_ascii_lowercase))
+}
+
+fn same_host(a: &str, b: &str) -> bool {
+ matches!((host_of(a), host_of(b)), (Some(a), Some(b)) if a == b)
+}
+
+/// Where a redirect from `current` to `location` leads. Only https is
+/// followed: a download that finished over plain http could have been
+/// swapped on the way.
+fn redirect_target(current: &str, location: &str) -> anyhow::Result<String> {
+ let location = location.trim();
+ if location.starts_with("https://") {
+ return Ok(location.to_string());
}
- Ok(body)
+ if location.starts_with('/') && !location.starts_with("//") && current.starts_with("https://") {
+ let rest = &current["https://".len()..];
+ let origin_len = "https://".len() + rest.find('/').unwrap_or(rest.len());
+ return Ok(format!("{}{location}", &current[..origin_len]));
+ }
+ anyhow::bail!("refusing to follow a redirect to {location:?}")
}
pub fn get_latest_release_info() -> anyhow::Result<Release> {
@@ -322,39 +567,119 @@ pub fn takeover_command() -> String {
.to_string()
}
+/// The release archive `install.sh` installs for `variant` on this machine,
+/// named exactly as its `asset_name` names it; None where it has no build.
+pub fn install_asset_name(variant: &str, version: &str) -> Option<String> {
+ asset_name_for(std::env::consts::OS, std::env::consts::ARCH, variant, version)
+}
+
+fn asset_name_for(os: &str, arch: &str, variant: &str, version: &str) -> Option<String> {
+ match (os, arch, variant) {
+ ("linux", "x86_64" | "aarch64", "desktop") => {
+ Some(format!("thinkterm-{version}-linux-{arch}.tar.gz"))
+ }
+ ("linux", "x86_64" | "aarch64", "server") => {
+ Some(format!("thinkterm-server-{version}-linux-{arch}.tar.gz"))
+ }
+ // One bundle serves both variants, named the way uname -m names
+ // the architecture there.
+ ("macos", "aarch64", _) => Some(format!("ThinkTerm-macos-arm64-{version}.zip")),
+ ("macos", "x86_64", _) => Some(format!("ThinkTerm-macos-x86_64-{version}.zip")),
+ _ => None,
+ }
+}
+
/// Run `install.sh` on this machine for the install the manifest describes,
-/// asking it for release `tag`. The script is fetched fresh and fed to `sh`
-/// on stdin, exactly as the documented `curl | sh` does, so there is one
-/// installer to keep correct rather than two.
+/// installing `release`. The script is fetched fresh and fed to `sh` on
+/// stdin, exactly as the documented `curl | sh` does, so there is one
+/// installer to keep correct rather than two. The release archive is
+/// downloaded here first, so `progress` can follow it, and handed to the
+/// script with `--from`.
///
/// Returns once the script has finished; its own output goes straight to the
/// terminal, which is where a person running `thinkterm update` is looking.
-pub fn run_local_installer(manifest: &InstallManifest, tag: &str) -> anyhow::Result<()> {
- run_installer(manifest, tag, false).map(|_| ())
+pub fn run_local_installer(
+ manifest: &InstallManifest,
+ release: &Release,
+ progress: &mut dyn FnMut(InstallProgress),
+) -> anyhow::Result<()> {
+ run_installer(manifest, release, false, progress).map(|_| ())
}
/// The same, with the installer's output collected and returned instead of
/// written to the terminal: what a GUI that has no terminal shows in its
/// own window. On failure the output is in the error's message.
-pub fn run_local_installer_captured(manifest: &InstallManifest, tag: &str) -> anyhow::Result<String> {
- run_installer(manifest, tag, true)
+pub fn run_local_installer_captured(
+ manifest: &InstallManifest,
+ release: &Release,
+ progress: &mut dyn FnMut(InstallProgress),
+) -> anyhow::Result<String> {
+ run_installer(manifest, release, true, progress)
}
-fn run_installer(manifest: &InstallManifest, tag: &str, capture: bool) -> anyhow::Result<String> {
- use std::io::{Read, Write};
- use std::process::{Command, Stdio};
-
+fn run_installer(
+ manifest: &InstallManifest,
+ release: &Release,
+ capture: bool,
+ progress: &mut dyn FnMut(InstallProgress),
+) -> anyhow::Result<String> {
let script = http_get(INSTALL_SCRIPT_URL)
.with_context(|| format!("downloading the installer from {INSTALL_SCRIPT_URL}"))?;
+ // Only an archive GitHub recorded a checksum for is fetched here: it is
+ // checked against that before the script sees it, and the script checks
+ // nothing it is handed with --from. Without one, or without an archive
+ // under the name the script would fetch, the script finds, downloads and
+ // judges it itself, as it always has -- just without a progress report.
+ let version = release.tag_name.trim_start_matches('v');
+ let asset = install_asset_name(&manifest.variant, version)
+ .and_then(|name| release.assets.iter().find(|asset| asset.name == name))
+ .filter(|asset| asset.sha256().is_some());
+ // The directory, and the archive in it, go when this returns.
+ let staged = match asset {
+ Some(asset) => {
+ let dir = tempfile::Builder::new()
+ .prefix("thinkterm-update-")
+ .tempdir()
+ .context("creating a directory to download into")?;
+ let path = dir.path().join(&asset.name);
+ download_asset_to(asset, &path, &mut |done, total| {
+ progress(InstallProgress::Downloading { done, total })
+ })?;
+ Some((dir, path))
+ }
+ None => None,
+ };
+ progress(InstallProgress::Installing);
+ run_install_script(
+ manifest,
+ &release.tag_name,
+ staged.as_ref().map(|(_, path)| path.as_path()),
+ &script,
+ capture,
+ )
+}
+
+fn run_install_script(
+ manifest: &InstallManifest,
+ tag: &str,
+ from: Option<&Path>,
+ script: &[u8],
+ capture: bool,
+) -> anyhow::Result<String> {
+ use std::io::Read;
+ use std::process::{Command, Stdio};
+
let mut cmd = Command::new("sh");
cmd.arg("-s")
.arg("--")
- .arg(format!("--{}", manifest.variant))
- .arg("--version")
- .arg(tag)
- .arg("--prefix")
- .arg(&manifest.prefix);
+ .arg(format!("--{}", manifest.variant));
+ if let Some(archive) = from {
+ cmd.arg("--from").arg(archive);
+ }
+ // With --from the script looks nothing up; the version still names the
+ // install in the manifest it writes.
+ cmd.arg("--version").arg(tag).arg("--prefix").arg(&manifest.prefix);
if let Some(app) = &manifest.app {
if let Some(dir) = Path::new(app).parent() {
cmd.arg("--app-dir").arg(dir);
@@ -449,6 +774,109 @@ mod tests {
);
}
+ #[test]
+ fn redirects_are_followed_only_to_https() {
+ assert_eq!(
+ redirect_target(
+ "https://github.com/o/r/releases/download/1.0/a.zip",
+ "https://objects.example.com/a?sig=1"
+ )
+ .unwrap(),
+ "https://objects.example.com/a?sig=1"
+ );
+ assert_eq!(
+ redirect_target("https://api.github.com/repos/o/r/releases/latest", "/repositories/1/releases/latest")
+ .unwrap(),
+ "https://api.github.com/repositories/1/releases/latest"
+ );
+ assert!(redirect_target("https://github.com/a", "http://example.com/a").is_err());
+ assert!(redirect_target("https://github.com/a", "//example.com/a").is_err());
+ assert!(redirect_target("https://github.com/a", "a.zip").is_err());
+ }
+
+ #[test]
+ fn the_token_stays_on_its_own_host() {
+ assert!(same_host(
+ "https://api.github.com/repos/o/r/releases/latest",
+ "https://API.github.com/repositories/1/releases/latest"
+ ));
+ assert!(!same_host(
+ "https://github.com/o/r/releases/download/1.0/a.zip",
+ "https://objects.example.com/a?sig=1"
+ ));
+ }
+
+ #[test]
+ fn a_download_counts_hashes_and_starts_over() {
+ use sha2::Digest;
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("asset");
+ let mut reports = Vec::new();
+ let mut progress = |done: u64, total: u64| reports.push((done, total));
+ let mut sink = DownloadSink {
+ file: std::fs::File::create(&path).unwrap(),
+ hasher: sha2::Sha256::new(),
+ done: 0,
+ total: 11,
+ progress: &mut progress,
+ // Long enough that no pause in a busy test run reaches it.
+ interval: Duration::from_secs(3600),
+ reported: None,
+ };
+ sink.write_all(b"redirected").unwrap();
+ sink.restart().unwrap();
+ sink.write_all(b"hello ").unwrap();
+ sink.write_all(b"world").unwrap();
+ sink.flush().unwrap();
+ let DownloadSink { hasher, done, .. } = sink;
+ assert_eq!(done, 11);
+ assert_eq!(std::fs::read(&path).unwrap(), b"hello world");
+ assert_eq!(
+ hex::encode(hasher.finalize()),
+ hex::encode(sha2::Sha256::digest(b"hello world"))
+ );
+ // The first write reports at once, and so does the first after
+ // starting over; the rest wait out the interval.
+ assert_eq!(reports, vec![(10, 11), (6, 11)]);
+ }
+
+ /// The archive downloaded here is handed to install.sh by name, so the
+ /// names have to be the ones its own `asset_name` would fetch.
+ #[cfg(unix)]
+ #[test]
+ fn asset_names_match_the_installer() {
+ let script = std::fs::read_to_string(
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../install.sh"),
+ )
+ .unwrap();
+ let start = script.find("asset_name() {").expect("install.sh defines asset_name");
+ let end = start + script[start..].find("\n}\n").expect("asset_name ends") + 3;
+ let function = &script[start..end];
+ // (Rust's os and arch, install.sh's os and arch, variant)
+ let cases = [
+ ("linux", "x86_64", "linux", "x86_64", "desktop"),
+ ("linux", "aarch64", "linux", "aarch64", "server"),
+ ("macos", "aarch64", "macos", "arm64", "desktop"),
+ ("macos", "x86_64", "macos", "x86_64", "server"),
+ ];
+ for (os, arch, sh_os, sh_arch, variant) in cases {
+ let out = std::process::Command::new("sh")
+ .arg("-c")
+ .arg(format!(
+ "{function}os={sh_os}; arch={sh_arch}; variant={variant}; asset_name 1.2.3"
+ ))
+ .output()
+ .unwrap();
+ assert!(out.status.success());
+ assert_eq!(
+ asset_name_for(os, arch, variant, "1.2.3").as_deref(),
+ Some(String::from_utf8_lossy(&out.stdout).trim()),
+ "{os}/{arch}/{variant}"
+ );
+ }
+ assert_eq!(asset_name_for("windows", "x86_64", "desktop", "1.2.3"), None);
+ }
+
#[test]
fn glibc_versions_parse_from_getconf_output() {
assert_eq!(parse_glibc_version("glibc 2.31\n"), Some((2, 31)));
diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rs
index 24edebc2..894c78ba 100644
--- a/wezterm-gui/src/main.rs
+++ b/wezterm-gui/src/main.rs
@@ -1118,6 +1118,13 @@ impl Publish {
return Self::NoConnectNoPublish;
}
+ if RESTARTED.load(std::sync::atomic::Ordering::Relaxed) {
+ // Restarted from Settings, so the GUI found running is the one
+ // on its way out: handing it the window would lose both. Publish
+ // over it instead; it removes only a name still pointing at it.
+ return Self::NoConnectButPublish;
+ }
+
match wezterm_client::discovery::resolve_gui_sock_path(
&crate::termwindow::get_window_class(),
) {
@@ -1530,10 +1537,22 @@ fn terminate_with_error(err: anyhow::Error) -> ! {
terminate_with_error_message(&err_text)
}
+/// Set by a restart from Settings on the process it starts, which comes up
+/// while the old one is still quitting.
+pub(crate) const RESTARTED_ENV: &str = "THINKTERM_RESTARTED";
+static RESTARTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
fn main() {
#[cfg(feature = "dhat-heap")]
let _profiler = dhat::Profiler::new_heap();
+ // Read and cleared before any thread starts, so that the shells this
+ // process runs do not inherit it.
+ if std::env::var_os(RESTARTED_ENV).is_some() {
+ std::env::remove_var(RESTARTED_ENV);
+ RESTARTED.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+
config::designate_this_as_the_main_thread();
config::assign_error_callback(mux::connui::show_configuration_error_message);
notify_on_panic();
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index 0f5f3cae..1d04b139 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -359,17 +359,87 @@ pub(crate) fn follow_open_settings_window(
});
}
-fn settings_window_for_instance(instance_id: u64) -> Option<Rc<RefCell<SettingsWindow>>> {
+thread_local! {
+ /// The install started from Settings. Kept apart from any one Settings
+ /// window: closing and reopening Settings must not forget that it runs,
+ /// or a second press would start another installer over it.
+ static UPDATE_INSTALL: RefCell<Option<UpdateInstall>> = const { RefCell::new(None) };
+ /// A Check for Updates press, kept the same way for the same reason.
+ static UPDATE_CHECK: RefCell<Option<UpdateCheck>> = const { RefCell::new(None) };
+}
+
+fn update_install() -> Option<UpdateInstall> {
+ UPDATE_INSTALL.with(|install| install.borrow().clone())
+}
+
+fn set_update_install(install: Option<UpdateInstall>) {
+ UPDATE_INSTALL.with(|slot| *slot.borrow_mut() = install);
+}
+
+fn update_check() -> Option<UpdateCheck> {
+ UPDATE_CHECK.with(|check| check.borrow().clone())
+}
+
+fn set_update_check(check: Option<UpdateCheck>) {
+ UPDATE_CHECK.with(|slot| *slot.borrow_mut() = check);
+}
+
+/// Whichever Settings window is open now, of any instance: the one an
+/// install started from may have been closed and another opened since.
+fn open_settings_window() -> Option<Rc<RefCell<SettingsWindow>>> {
+ open_settings_window_with_id().map(|(_, settings)| settings)
+}
+
+fn open_settings_window_with_id() -> Option<(u64, Rc<RefCell<SettingsWindow>>)> {
SETTINGS_WINDOW.with(|slot| match &*slot.borrow() {
SettingsWindowSlot::Open {
- instance_id: current_id,
+ instance_id,
settings,
- } if *current_id == instance_id => Some(Rc::clone(settings)),
+ } => Some((*instance_id, Rc::clone(settings))),
SettingsWindowSlot::Closed | SettingsWindowSlot::Opening(_) => None,
- SettingsWindowSlot::Open { .. } => None,
})
}
+/// Whether restarting ends terminals: a shell this process runs itself -- in
+/// process, or over a direct SSH session -- goes with it, where one in the
+/// session server or another mux server is kept for the next GUI.
+fn restart_ends_terminals() -> bool {
+ let Some(mux) = mux::Mux::try_get() else {
+ return false;
+ };
+ mux.iter_panes().iter().any(|pane| {
+ mux.get_domain(pane.domain_id()).is_some_and(|domain| {
+ domain.downcast_ref::<mux::domain::LocalDomain>().is_some()
+ || domain.downcast_ref::<mux::ssh::RemoteSshDomain>().is_some()
+ })
+ })
+}
+
+/// Repaint the open Settings window for a change to the install. With
+/// `refresh`, first reread what the page knows about the installed copy,
+/// which a finished install has just changed.
+fn repaint_open_settings(refresh: bool) {
+ let Some(settings) = open_settings_window() else {
+ return;
+ };
+ let Ok(mut settings) = settings.try_borrow_mut() else {
+ return;
+ };
+ if refresh {
+ settings.ui.update_status = Some(crate::update::cached_update_status());
+ settings.ui.update_method = Some(thinkterm_update::InstallMethod::detect());
+ }
+ if let Some(window) = settings.window.as_ref() {
+ window.invalidate();
+ }
+}
+
+fn settings_window_for_instance(instance_id: u64) -> Option<Rc<RefCell<SettingsWindow>>> {
+ open_settings_window_with_id()
+ .filter(|(current_id, _)| *current_id == instance_id)
+ .map(|(_, settings)| settings)
+}
+
fn settings_window_pixel_size(
dpi: usize,
active_screen_size: Option<(usize, usize)>,
@@ -410,14 +480,33 @@ enum HeroBadge {
/// An install run from the Update page, from the click to its outcome.
#[derive(Debug, Clone)]
enum UpdateInstall {
+ /// `progress` is None until the installer first reports;
+ /// `download_started` is when the first download report came in, which
+ /// the time-left estimate counts from.
+ Running {
+ version: String,
+ progress: Option<thinkterm_update::InstallProgress>,
+ download_started: Option<Instant>,
+ },
+ Installed {
+ version: String,
+ },
+ Failed {
+ error: String,
+ },
+}
+
+/// A Check for Updates press still asking GitHub, or how it went wrong.
+#[derive(Debug, Clone)]
+enum UpdateCheck {
Running,
- Installed { version: String },
Failed { error: String },
}
-/// What the Update page's status card can say. Derived from the on-disk
-/// check cache rather than from a live query, which is why "up to date" is
-/// only ever claimed for a build that actually carries a release tag.
+/// What the last check found, as the Update page's status card says it.
+/// Read from the on-disk check cache, which the background checker and
+/// Check for Updates both write; "up to date" is only ever claimed for a
+/// build that actually carries a release tag.
#[derive(Debug, Clone)]
enum UpdateHero {
/// No usable result on disk: either no check has run, or the cache is
@@ -432,18 +521,6 @@ enum UpdateHero {
LocalBuild,
}
-/// Semantic accents for the status badges. They stay local rather than
-/// joining UiPalette because nothing else in the chrome carries a success or
-/// neutral status color, and a token would imply a system that does not
-/// exist. The action tint is not here: that one *is* the accent, so it reads
-/// `palette.accent`.
-fn status_tint_positive(appearance: Appearance) -> LinearRgba {
- match appearance {
- Appearance::Light | Appearance::LightHighContrast => rgba(52, 199, 89, 1.0),
- Appearance::Dark | Appearance::DarkHighContrast => rgba(48, 209, 88, 1.0),
- }
-}
-
/// Secondary text sits a step below the label. Clamped at 350 so a user who
/// already runs a light UI weight does not end up with hairline text.
fn settings_body_font_weight(label_weight: u16) -> u16 {
@@ -477,6 +554,27 @@ fn format_check_interval(seconds: u64) -> String {
}
}
+/// "about 12 s left", from the average rate since the download started;
+/// None until it has run for a second, when the rate means little.
+fn download_time_left(started: Instant, done: u64, total: u64) -> Option<String> {
+ let elapsed = started.elapsed().as_secs_f64();
+ if elapsed < 1.0 || done == 0 || done >= total {
+ return None;
+ }
+ let left = (total - done) as f64 / (done as f64 / elapsed);
+ Some(if left < 60.0 {
+ settings_tr(
+ "settings-update-seconds-left",
+ &[("count", (left.ceil() as u64).max(1).to_string())],
+ )
+ } else {
+ settings_tr(
+ "settings-update-minutes-left",
+ &[("count", ((left / 60.0).ceil() as u64).to_string())],
+ )
+ })
+}
+
/// "just now" / "N minutes ago" / "N hours ago" / a local date. The recent
/// cases get words because recency is what the user is checking for; older
/// than a day, the date is more useful than a growing hour count.
@@ -1906,8 +2004,8 @@ struct SettingsUiState {
confirm_stop_server: bool,
input_diagnostics_copied_until: Option<Instant>,
/// The Update page's view of the on-disk check cache. Read when the
- /// section is entered and when Check Now is clicked, never while
- /// painting: it stats and reads a file, and the paint path must not.
+ /// section is entered and when a check from the page finishes, never
+ /// while painting: it stats and reads a file, and the paint path must not.
update_status: Option<crate::update::CachedUpdateStatus>,
/// Set briefly after Check Now so the button can report that it ran even
/// when the cached answer is unchanged.
@@ -1916,9 +2014,6 @@ struct SettingsUiState {
/// install an update itself or only say who can. Read with the status:
/// it looks at the filesystem, so never on the paint path.
update_method: Option<thinkterm_update::InstallMethod>,
- /// The install started from this page, if any. Runs on its own thread
- /// and reports back through the instance id.
- update_install: Option<UpdateInstall>,
version_info_copied_until: Option<Instant>,
sidebar_scrollbar_visible_until: Option<Instant>,
content_scrollbar_visible_until: Option<Instant>,
@@ -2010,7 +2105,6 @@ impl SettingsUiState {
update_status: None,
update_checked_until: None,
update_method: None,
- update_install: None,
version_info_copied_until: None,
sidebar_scrollbar_visible_until: None,
content_scrollbar_visible_until: None,
@@ -2138,12 +2232,7 @@ impl RowCursor {
}
fn format_bytes(bytes: u64) -> String {
- let mib = bytes as f64 / 1024.0 / 1024.0;
- if mib >= 1024.0 {
- format!("{:.2} GB", mib / 1024.0)
- } else {
- format!("{mib:.1} MB")
- }
+ thinkterm_update::format_size(bytes)
}
fn capture_memory_snapshot(detailed: bool) -> MemorySnapshot {
@@ -4846,6 +4935,11 @@ impl SettingsWindow {
// another section.
self.ui.update_status = Some(crate::update::cached_update_status());
self.ui.update_method = Some(thinkterm_update::InstallMethod::detect());
+ // A failed check from an earlier visit says nothing about the
+ // cache just read, which a later check may have refreshed.
+ if matches!(update_check(), Some(UpdateCheck::Failed { .. })) {
+ set_update_check(None);
+ }
}
}
@@ -5152,6 +5246,11 @@ impl SettingsWindow {
}
SettingsAction::RestartApplication => {
self.ui.open_dropdown = None;
+ // Not while an install from the Update page runs: quitting
+ // would cut the installer off half way through its work.
+ if matches!(update_install(), Some(UpdateInstall::Running { .. })) {
+ return;
+ }
match Self::restart_application() {
Ok(()) => {
self.status = crate::i18n::tr("settings-status-restarting");
@@ -5715,19 +5814,51 @@ impl SettingsWindow {
}
SettingsAction::CheckForUpdates => {
self.ui.open_dropdown = None;
- // The live query is not wired up yet. Re-reading the cache the
- // background checker maintains is the same answer a check that
- // found nothing new would produce, and it costs one stat plus
- // one small read rather than a blocking HTTP request on the UI
- // thread. The live check replaces this call, not the button.
- self.ui.update_status = Some(crate::update::cached_update_status());
- self.ui.update_method = Some(thinkterm_update::InstallMethod::detect());
- self.ui.update_checked_until = Some(Instant::now() + Duration::from_millis(1400));
- self.schedule_copied_state_clear(window);
+ if matches!(update_check(), Some(UpdateCheck::Running)) {
+ return;
+ }
+ set_update_check(Some(UpdateCheck::Running));
+ // A new check is the next attempt after a failed install.
+ if matches!(update_install(), Some(UpdateInstall::Failed { .. })) {
+ set_update_install(None);
+ }
+ window.invalidate();
+
+ // A live query to GitHub: off the UI thread, with the answer
+ // posted back to whichever Settings window is open by then.
+ let spawned = std::thread::Builder::new()
+ .name("thinkterm-update-check".into())
+ .spawn(move || {
+ let result = crate::update::check_now();
+ promise::spawn::spawn_into_main_thread(async move {
+ let checked = result.is_ok();
+ set_update_check(result.err().map(|err| UpdateCheck::Failed {
+ error: format!("{err:#}"),
+ }));
+ repaint_open_settings(true);
+ // Let the button say it ran, even when the answer
+ // is the one already showing.
+ if let Some(settings) = open_settings_window().filter(|_| checked) {
+ if let Ok(mut settings) = settings.try_borrow_mut() {
+ settings.ui.update_checked_until =
+ Some(Instant::now() + Duration::from_millis(1400));
+ if let Some(window) = settings.window.clone() {
+ settings.schedule_copied_state_clear(&window);
+ }
+ }
+ }
+ })
+ .detach();
+ });
+ if let Err(err) = spawned {
+ set_update_check(Some(UpdateCheck::Failed {
+ error: err.to_string(),
+ }));
+ }
}
SettingsAction::InstallUpdate => {
self.ui.open_dropdown = None;
- if matches!(self.ui.update_install, Some(UpdateInstall::Running)) {
+ if matches!(update_install(), Some(UpdateInstall::Running { .. })) {
return;
}
let Some(release) = self
@@ -5743,25 +5874,77 @@ impl SettingsWindow {
.update_method
.clone()
.unwrap_or_else(thinkterm_update::InstallMethod::detect);
- self.ui.update_install = Some(UpdateInstall::Running);
+ let version = release.tag_name.trim_start_matches('v').to_string();
+ set_update_install(Some(UpdateInstall::Running {
+ version: version.clone(),
+ progress: None,
+ download_started: None,
+ }));
+ if matches!(update_check(), Some(UpdateCheck::Failed { .. })) {
+ set_update_check(None);
+ }
window.invalidate();
// The installer downloads and replaces files: off the UI
- // thread, with the outcome posted back to whichever settings
- // window instance asked, if it is still open.
- let instance_id = self.instance_id;
- let window = window.clone();
- std::thread::Builder::new()
+ // thread, with its progress and outcome posted back to
+ // whichever Settings window is open by then.
+ let spawned = std::thread::Builder::new()
.name("thinkterm-update-install".into())
.spawn(move || {
- let version = release.tag_name.trim_start_matches('v').to_string();
+ // A cache written by a build that did not keep
+ // GitHub's checksums lacks them: ask for the release
+ // again then, and settle for the cache if that fails.
+ let release = if release.assets.iter().any(|a| a.sha256().is_none()) {
+ thinkterm_update::get_release_by_tag(&release.tag_name)
+ .unwrap_or(release)
+ } else {
+ release
+ };
+ let mut progress = |progress| {
+ promise::spawn::spawn_into_main_thread(async move {
+ // Never over the outcome, should a report
+ // land after it.
+ let reported = UPDATE_INSTALL.with(|install| {
+ let mut install = install.borrow_mut();
+ let Some(UpdateInstall::Running {
+ progress: current,
+ download_started,
+ ..
+ }) = &mut *install
+ else {
+ return false;
+ };
+ use thinkterm_update::InstallProgress;
+ if let InstallProgress::Downloading { done, .. } = progress {
+ // A retry, or a redirect's body thrown
+ // away, starts the count over, and the
+ // rate is timed from there.
+ let restarted = matches!(
+ current,
+ Some(InstallProgress::Downloading { done: before, .. })
+ if done < *before
+ );
+ if download_started.is_none() || restarted {
+ *download_started = Some(Instant::now());
+ }
+ }
+ *current = Some(progress);
+ true
+ });
+ if reported {
+ repaint_open_settings(false);
+ }
+ })
+ .detach();
+ };
let result = if cfg!(windows) {
- thinkterm_update::run_windows_installer(&release).map(|_| ())
+ thinkterm_update::run_windows_installer(&release, &mut progress)
} else {
match method.manifest_for_install() {
Some(manifest) => thinkterm_update::run_local_installer_captured(
&manifest,
- &release.tag_name,
+ &release,
+ &mut progress,
)
.map(|_| ()),
None => Err(anyhow::anyhow!("{}", method.how_to_update())),
@@ -5774,19 +5957,16 @@ impl SettingsWindow {
},
};
promise::spawn::spawn_into_main_thread(async move {
- if let Some(settings) = settings_window_for_instance(instance_id) {
- let mut settings = settings.borrow_mut();
- settings.ui.update_install = Some(outcome);
- settings.ui.update_status =
- Some(crate::update::cached_update_status());
- settings.ui.update_method =
- Some(thinkterm_update::InstallMethod::detect());
- window.invalidate();
- }
+ set_update_install(Some(outcome));
+ repaint_open_settings(true);
})
.detach();
- })
- .ok();
+ });
+ if let Err(err) = spawned {
+ set_update_install(Some(UpdateInstall::Failed {
+ error: err.to_string(),
+ }));
+ }
}
SettingsAction::OpenLatestRelease => {
self.ui.open_dropdown = None;
@@ -13134,9 +13314,8 @@ impl SettingsWindow {
Ok(cursor_y + height - y)
}
- /// What the Update hero is currently able to say. Derived entirely from
- /// the cache the background checker writes; a live check will produce
- /// these same states once one is wired up.
+ /// What the last check found, from the cache every check writes. An
+ /// install or a check in flight is said over it; see `paint_update`.
fn update_hero(&self) -> UpdateHero {
let Some(status) = self.ui.update_status.as_ref() else {
return UpdateHero::Unknown;
@@ -13201,6 +13380,7 @@ impl SettingsWindow {
badge: HeroBadge,
headline: &str,
subline: &str,
+ progress: Option<f32>,
button: Option<(String, SettingsAction)>,
) -> anyhow::Result<f32> {
let palette = self.palette();
@@ -13237,7 +13417,15 @@ impl SettingsWindow {
let text_x = mark_x + mark + self.ui_px(24.0);
let text_width = (text_right - text_x).max(self.ui_px(120.0));
let line_gap = self.ui_px(12.0);
- let text_y = y + (height - (cell * 2.0 + line_gap)) / 2.0;
+ // A progress bar goes between the two lines, with air either side;
+ // the card keeps its height.
+ let bar_height = self.ui_px(6.0);
+ let bar_gap = self.ui_px(14.0);
+ let block = match progress {
+ Some(_) => cell * 2.0 + bar_gap * 2.0 + bar_height,
+ None => cell * 2.0 + line_gap,
+ };
+ let text_y = y + (height - block) / 2.0;
self.draw_text(
layers,
&title_font,
@@ -13247,11 +13435,41 @@ impl SettingsWindow {
palette.title,
text_width,
)?;
+ let subline_y = match progress {
+ Some(fraction) => {
+ let bar_y = text_y + cell + bar_gap;
+ let radius = bar_height / 2.0;
+ self.draw_rounded_rect(
+ layers,
+ 0,
+ text_x,
+ bar_y,
+ text_width,
+ bar_height,
+ palette.track_off,
+ radius,
+ )?;
+ if fraction > 0.0 {
+ self.draw_rounded_rect(
+ layers,
+ 0,
+ text_x,
+ bar_y,
+ (text_width * fraction.min(1.0)).max(bar_height),
+ bar_height,
+ self.chrome_palette.accent,
+ radius,
+ )?;
+ }
+ bar_y + bar_height + bar_gap
+ }
+ None => text_y + cell + line_gap,
+ };
self.draw_text(
layers,
&body_font,
text_x,
- text_y + cell + line_gap,
+ subline_y,
subline,
palette.secondary_text,
text_width,
@@ -13931,7 +14149,6 @@ impl SettingsWindow {
) -> anyhow::Result<()> {
let palette = self.palette();
let body_font = Rc::clone(&self.body_font);
- let appearance = self.effective_appearance();
let scroll = self.ui.content_scroll.offset;
let card_padding = self.ui_px(HERO_PADDING);
let row_x = x + card_padding;
@@ -13940,8 +14157,8 @@ impl SettingsWindow {
let hero = self.update_hero();
let version = self.running_version_label();
- // The app icon, as on About: the page is about ThinkTerm, and the
- // state is already in the headline.
+ // What the last check found; an install or a check in flight
+ // outranks it below.
let (headline, subline) = match &hero {
UpdateHero::UpToDate => (
crate::i18n::tr("settings-update-current"),
@@ -13971,25 +14188,39 @@ impl SettingsWindow {
.ui
.update_checked_until
.is_some_and(|until| Instant::now() < until);
- let check_label = if checked_recently {
+ let check = update_check();
+ let check_label = if matches!(check, Some(UpdateCheck::Running)) {
+ crate::i18n::tr("settings-update-checking")
+ } else if checked_recently {
crate::i18n::tr("settings-update-checked")
} else {
crate::i18n::tr("settings-update-check-now")
};
// The one button on the hero: install when there is something to
- // install and this copy is ours to replace, check otherwise. While
- // an install runs there is nothing to click.
+ // install and this copy is ours to replace, restart once it has been
+ // replaced, check otherwise. While an install runs there is nothing
+ // to click, and the Windows installer restarts ThinkTerm itself.
let self_updatable = self
.ui
.update_method
.as_ref()
.is_some_and(|method| method.self_updatable() || cfg!(windows));
- let hero_button = match (&hero, &self.ui.update_install) {
- (_, Some(UpdateInstall::Running)) => None,
- (UpdateHero::Available { .. }, Some(UpdateInstall::Installed { .. })) => {
- Some((check_label, SettingsAction::CheckForUpdates))
+ let install = update_install();
+ let hero_button = match (&hero, &install) {
+ (_, Some(UpdateInstall::Running { .. })) => None,
+ // Restart only where it ends no terminal: shells this process
+ // runs itself would go with it, so there the person quits and
+ // reopens when ready. The Windows installer restarts by itself.
+ (_, Some(UpdateInstall::Installed { .. }))
+ if !cfg!(windows) && !restart_ends_terminals() =>
+ {
+ Some((
+ crate::i18n::tr("settings-restart"),
+ SettingsAction::RestartApplication,
+ ))
}
+ (_, Some(UpdateInstall::Installed { .. })) => None,
(UpdateHero::Available { .. }, _) if self_updatable => Some((
crate::i18n::tr("settings-update-install"),
SettingsAction::InstallUpdate,
@@ -13997,6 +14228,96 @@ impl SettingsWindow {
_ => Some((check_label, SettingsAction::CheckForUpdates)),
};
+ // The card says what is happening now: an install or a check in
+ // flight, or how one went, before what the last check found.
+ use thinkterm_update::InstallProgress;
+ let (headline, subline, progress) =
+ match (&install, &check) {
+ (
+ Some(UpdateInstall::Running {
+ version,
+ progress: Some(InstallProgress::Downloading { done, total }),
+ download_started,
+ }),
+ _,
+ ) => {
+ let fraction = if *total > 0 {
+ (*done as f32 / *total as f32).clamp(0.0, 1.0)
+ } else {
+ 0.0
+ };
+ let mut detail = settings_tr(
+ "settings-update-download-progress",
+ &[
+ ("done", format_bytes(*done)),
+ ("total", format_bytes(*total)),
+ ("percent", ((fraction * 100.0).floor() as u32).to_string()),
+ ],
+ );
+ if let Some(left) = download_started
+ .and_then(|started| download_time_left(started, *done, *total))
+ {
+ detail = format!("{detail} · {left}");
+ }
+ (
+ settings_tr("settings-update-downloading", &[("version", version.clone())]),
+ detail,
+ Some(fraction),
+ )
+ }
+ // Looking the release up, fetching install.sh: nothing is
+ // being installed yet.
+ (
+ Some(UpdateInstall::Running {
+ version,
+ progress: None,
+ ..
+ }),
+ _,
+ ) => (
+ settings_tr("settings-update-preparing", &[("version", version.clone())]),
+ crate::i18n::tr("settings-update-installing"),
+ None,
+ ),
+ (Some(UpdateInstall::Running { version, .. }), _) => (
+ settings_tr(
+ "settings-update-installing-title",
+ &[("version", version.clone())],
+ ),
+ crate::i18n::tr("settings-update-installing"),
+ None,
+ ),
+ (Some(UpdateInstall::Installed { version }), _) if cfg!(windows) => (
+ crate::i18n::tr("settings-update-installer-started"),
+ settings_tr(
+ "settings-update-installer-started-detail",
+ &[("version", version.clone())],
+ ),
+ None,
+ ),
+ (Some(UpdateInstall::Installed { version }), _) => (
+ settings_tr("settings-update-installed", &[("version", version.clone())]),
+ crate::i18n::tr("settings-update-installed-detail"),
+ None,
+ ),
+ (Some(UpdateInstall::Failed { .. }), _) => (
+ crate::i18n::tr("settings-update-install-failed-title"),
+ crate::i18n::tr("settings-update-failed-detail"),
+ None,
+ ),
+ (None, Some(UpdateCheck::Running)) => (
+ crate::i18n::tr("settings-update-checking-title"),
+ subline,
+ None,
+ ),
+ (None, Some(UpdateCheck::Failed { .. })) => (
+ crate::i18n::tr("settings-update-check-failed"),
+ crate::i18n::tr("settings-update-failed-detail"),
+ None,
+ ),
+ (None, None) => (headline, subline, None),
+ };
+
let hero_y = self.ui_px(CONTENT_SECTION_Y) - scroll;
let hero_height = self.paint_hero(
layers,
@@ -14006,6 +14327,7 @@ impl SettingsWindow {
HeroBadge::AppIcon,
&headline,
&subline,
+ progress,
hero_button,
)?;
@@ -14014,6 +14336,8 @@ impl SettingsWindow {
let config = configuration();
let rows = [
(
+ SvgIcon::RefreshCw,
+ TileColor::Green,
crate::i18n::tr("settings-update-automatic"),
if config.check_for_updates {
crate::i18n::tr("common-on")
@@ -14022,10 +14346,14 @@ impl SettingsWindow {
},
),
(
+ SvgIcon::Calendar,
+ TileColor::Orange,
crate::i18n::tr("settings-update-frequency"),
format_check_interval(config.check_for_updates_interval_seconds),
),
(
+ SvgIcon::Timer,
+ TileColor::Blue,
crate::i18n::tr("settings-update-last-checked"),
self.ui
.update_status
@@ -14040,27 +14368,32 @@ impl SettingsWindow {
let row_step = self.compact_row_step();
let first_row_y = card_y + self.ui_px(12.0);
self.paint_group_card(layers, x, card_y, max_width, card_height)?;
- for (index, (label, value)) in rows.iter().enumerate() {
- self.paint_compact_row(
- layers,
- row_x,
- first_row_y + row_step * index as f32,
- row_width,
- label,
- value,
- index > 0,
- )?;
+ for (index, (icon, color, label, value)) in rows.iter().enumerate() {
+ let row_y = first_row_y + row_step * index as f32;
+ let (tx, tw) =
+ self.paint_band_tile(layers, row_x, row_y, row_step, row_width, *icon, *color)?;
+ self.paint_compact_row(layers, tx, row_y, tw, label, value, index > 0)?;
}
// One choice: what updating a remote server does to its sessions.
let toggle_card_y = card_y + card_height + gap;
let toggle_card_height = self.compact_card_height(1);
self.paint_group_card(layers, x, toggle_card_y, max_width, toggle_card_height)?;
- self.paint_toggle_setting_row_with_hint(
+ let toggle_row_y = toggle_card_y + self.ui_px(12.0);
+ let (tx, tw) = self.paint_band_tile(
layers,
row_x,
- toggle_card_y + self.ui_px(12.0),
+ toggle_row_y,
+ row_step,
row_width,
+ SvgIcon::Server,
+ TileColor::Slate,
+ )?;
+ self.paint_toggle_setting_row_with_hint(
+ layers,
+ tx,
+ toggle_row_y,
+ tw,
self.compact_row_step(),
&crate::i18n::tr("settings-remote-update-keep-sessions"),
"settings-remote-update-keep-sessions-description",
@@ -14068,30 +14401,25 @@ impl SettingsWindow {
SettingsAction::ToggleRemoteUpdateKeepsSessions,
)?;
- // Under the facts: what an install would do here, or why this page
- // cannot do one, and the outcome of the install just run.
+ // Under the facts: what went wrong, if something did -- the card
+ // above only has room to say that it did -- then what an install
+ // would do here, or why this page cannot do one.
let note_y = toggle_card_y + toggle_card_height + gap;
let line_step = self.metrics.cell_size.height as f32 + self.ui_px(6.0);
let mut notes: Vec<(String, LinearRgba)> = Vec::new();
- match &self.ui.update_install {
- Some(UpdateInstall::Running) => {
- notes.push((crate::i18n::tr("settings-update-installing"), palette.text));
- }
- Some(UpdateInstall::Installed { version }) => notes.push((
- settings_tr("settings-update-installed", &[("version", version.clone())]),
- status_tint_positive(appearance),
- )),
- Some(UpdateInstall::Failed { error }) => notes.push((
- settings_tr("settings-update-install-failed", &[("error", error.clone())]),
- self.chrome_palette.danger,
- )),
- None => {}
+ let failure = match (&install, &check) {
+ (Some(UpdateInstall::Failed { error }), _) => Some(error),
+ (None, Some(UpdateCheck::Failed { error })) => Some(error),
+ _ => None,
+ };
+ if let Some(error) = failure {
+ notes.push((error.clone(), self.chrome_palette.danger));
}
notes.push((
self.update_method_note(),
palette.secondary_text,
));
- if self_updatable && !matches!(self.ui.update_install, Some(UpdateInstall::Installed { .. })) {
+ if self_updatable && !matches!(install, Some(UpdateInstall::Installed { .. })) {
notes.push((
crate::i18n::tr("settings-update-install-note"),
palette.secondary_text,
@@ -14171,21 +14499,36 @@ impl SettingsWindow {
"settings-about-version-line",
&[("version", version.clone())],
),
+ None,
Some((copy_label, SettingsAction::CopyVersionInfo)),
)?;
// Build only earns a line when it says something Version does not: a
// release binary stamps both from the same tag.
let build = config::wezterm_version();
- let mut rows = vec![(crate::i18n::tr("settings-about-version"), version.clone())];
+ let mut rows = vec![(
+ SvgIcon::Package,
+ TileColor::Blue,
+ crate::i18n::tr("settings-about-version"),
+ version.clone(),
+ )];
if build != version {
- rows.push((crate::i18n::tr("settings-about-build"), build.to_string()));
+ rows.push((
+ SvgIcon::GitBranch,
+ TileColor::Indigo,
+ crate::i18n::tr("settings-about-build"),
+ build.to_string(),
+ ));
}
rows.push((
+ SvgIcon::Cpu,
+ TileColor::Teal,
crate::i18n::tr("settings-about-platform"),
config::wezterm_target_triple().to_string(),
));
rows.push((
+ SvgIcon::Scale,
+ TileColor::Orange,
crate::i18n::tr("settings-about-license"),
// Must match what the packages declare -- ci/deploy.sh and
// ci/make-winget-pr.sh both say GPL-3.0-only. "or-later" is a
@@ -14199,16 +14542,11 @@ impl SettingsWindow {
let row_step = self.compact_row_step();
let first_row_y = card_y + self.ui_px(12.0);
self.paint_group_card(layers, x, card_y, max_width, card_height)?;
- for (index, (label, value)) in rows.iter().enumerate() {
- self.paint_compact_row(
- layers,
- row_x,
- first_row_y + row_step * index as f32,
- row_width,
- label,
- value,
- index > 0,
- )?;
+ for (index, (icon, color, label, value)) in rows.iter().enumerate() {
+ let row_y = first_row_y + row_step * index as f32;
+ let (tx, tw) =
+ self.paint_band_tile(layers, row_x, row_y, row_step, row_width, *icon, *color)?;
+ self.paint_compact_row(layers, tx, row_y, tw, label, value, index > 0)?;
}
// Everything outbound sits in one wrapping row along the bottom
@@ -17497,9 +17835,20 @@ return config
fn restart_application() -> anyhow::Result<()> {
let exe = std::env::current_exe().context("resolve current executable")?;
+ // Once an update has replaced the binary, Linux names the running
+ // one "<path> (deleted)"; the new one is at the path itself.
+ #[cfg(target_os = "linux")]
+ let exe = match exe.to_str().and_then(|path| path.strip_suffix(" (deleted)")) {
+ Some(path) => PathBuf::from(path),
+ None => exe,
+ };
let args = std::env::args_os().skip(1).collect::<Vec<_>>();
let mut command = Command::new(exe);
command.args(args);
+ // The replacement starts while this process is still on its way
+ // out; told so, it publishes itself instead of handing this one the
+ // window to open, which would lose both.
+ command.env(crate::RESTARTED_ENV, "1");
if let Ok(cwd) = std::env::current_dir() {
command.current_dir(cwd);
}
diff --git a/wezterm-gui/src/update.rs b/wezterm-gui/src/update.rs
index 98142a69..d92e45d4 100644
--- a/wezterm-gui/src/update.rs
+++ b/wezterm-gui/src/update.rs
@@ -33,8 +33,9 @@ pub fn update_available() -> bool {
}
/// Record the flag; when it changes, ask every window to repaint so the dot
-/// appears or goes away. Only the checker thread calls this: it runs once
-/// the GUI is up, and spawning onto the main thread needs its scheduler.
+/// appears or goes away. Only the checker thread and a check asked for from
+/// Settings call this: both run once the GUI is up, and spawning onto the
+/// main thread needs its scheduler.
fn set_update_available(available: bool) {
let was = UPDATE_AVAILABLE.swap(available, Ordering::Relaxed);
if was != available {
@@ -140,6 +141,36 @@ mod update_version_tests {
}
+/// Ask GitHub now, as the background checker does on its schedule: record
+/// the answer where Settings reads it and set the dot. Blocks on the
+/// network, so callers run it off the UI thread. No toast: whoever asked is
+/// looking at the answer.
+pub fn check_now() -> anyhow::Result<()> {
+ let latest = get_latest_release_info()?;
+ let newer = is_newer_release(&latest.tag_name, &running_release_version());
+ set_update_available(newer || always_show_update_ui());
+ // Settings shows what it reads back from the cache: an answer that could
+ // not be kept there is, as far as the page can tell, no answer.
+ record_latest_release(&latest)
+}
+
+/// Persist the newest release seen; the file's mtime is the time of the
+/// check. Written beside it and renamed over it, so a reader -- Settings, or
+/// the other of the two threads that check -- never sees half a file.
+fn record_latest_release(latest: &Release) -> anyhow::Result<()> {
+ use anyhow::Context;
+ let update_file_name = config::DATA_DIR.join("check_update");
+ let dir = config::DATA_DIR.as_path();
+ let saved = config::create_user_owned_dirs(dir)
+ .and_then(|()| Ok(tempfile::NamedTempFile::new_in(dir)?))
+ .and_then(|mut file| {
+ serde_json::to_writer_pretty(&mut file, latest)?;
+ file.persist(&update_file_name)?;
+ Ok(())
+ });
+ saved.with_context(|| format!("saving the update check to {}", update_file_name.display()))
+}
+
/// Returns true if the provided socket path is dead.
fn update_checker() {
// Compute how long we should sleep for;
@@ -198,16 +229,8 @@ fn update_checker() {
}
}
- config::create_user_owned_dirs(update_file_name.parent().unwrap()).ok();
-
- // Record the time of this check
- if let Ok(f) = std::fs::OpenOptions::new()
- .write(true)
- .create(true)
- .truncate(true)
- .open(&update_file_name)
- {
- serde_json::to_writer_pretty(f, &latest).ok();
+ if let Err(err) = record_latest_release(&latest) {
+ log::warn!("{err:#}");
}
}
}
diff --git a/wezterm/src/main.rs b/wezterm/src/main.rs
index 4aa8b8fd..8526c880 100644
--- a/wezterm/src/main.rs
+++ b/wezterm/src/main.rs
@@ -842,7 +842,10 @@ impl UpdateCommand {
return Ok(());
}
}
- thinkterm_update::run_windows_installer(&target)?;
+ {
+ let mut progress = CliInstallProgress::new();
+ thinkterm_update::run_windows_installer(&target, &mut |p| progress.report(p))?;
+ }
println!("The installer is running; it finishes on its own.");
return Ok(());
}
@@ -882,7 +885,11 @@ impl UpdateCommand {
}
}
- if let Err(err) = thinkterm_update::run_local_installer(&manifest, &target.tag_name) {
+ let installed = {
+ let mut progress = CliInstallProgress::new();
+ thinkterm_update::run_local_installer(&manifest, &target, &mut |p| progress.report(p))
+ };
+ if let Err(err) = installed {
println!();
println!("The installer failed ({err:#}); nothing was changed.");
println!("If it refused this machine (glibc, musl, architecture), a release binary cannot run here.");
@@ -895,6 +902,75 @@ impl UpdateCommand {
}
}
+/// Download progress for `thinkterm update`: one line rewritten in place when
+/// a person is watching the terminal, the size once otherwise. The line is
+/// ended once the download is in, and when this is dropped with the line
+/// still open, so nothing printed afterwards -- a note, an error -- lands on
+/// the end of it.
+struct CliInstallProgress {
+ watched: bool,
+ announced: bool,
+ line_open: bool,
+ completed: bool,
+}
+
+impl CliInstallProgress {
+ fn new() -> Self {
+ use std::io::IsTerminal;
+ Self {
+ watched: std::io::stderr().is_terminal(),
+ announced: false,
+ line_open: false,
+ completed: false,
+ }
+ }
+
+ fn report(&mut self, progress: thinkterm_update::InstallProgress) {
+ use thinkterm_update::{format_size, InstallProgress};
+ match progress {
+ InstallProgress::Downloading { done, total } => {
+ if self.watched {
+ // The last report repeats the one that finished the line.
+ if done >= total && self.completed {
+ return;
+ }
+ // Cleared first: a retry restarts the count, and a
+ // shorter line would leave the old one's tail behind.
+ eprint!(
+ "\r\x1b[Kdownloading: {} of {}",
+ format_size(done),
+ format_size(total)
+ );
+ self.line_open = true;
+ self.completed = done >= total;
+ if self.completed {
+ self.end_line();
+ }
+ } else if !self.announced {
+ eprintln!("downloading {}...", format_size(total));
+ }
+ self.announced = true;
+ }
+ InstallProgress::Installing => {
+ self.end_line();
+ eprintln!("installing...");
+ }
+ }
+ }
+
+ fn end_line(&mut self) {
+ if std::mem::take(&mut self.line_open) {
+ eprintln!();
+ }
+ }
+}
+
+impl Drop for CliInstallProgress {
+ fn drop(&mut self) {
+ self.end_line();
+ }
+}
+
#[derive(Debug, Parser, Clone)]
struct ListFilesCommand {
/// The project folder.