diff --git a/Cargo.lock b/Cargo.lock index 1f496960..b22601e6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1181,7 +1181,7 @@ checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" [[package]] name = "draftcraft" -version = "2.0.1" +version = "2.0.2" dependencies = [ "chrono", "clap", @@ -1211,7 +1211,7 @@ dependencies = [ [[package]] name = "draftcraft-cli" -version = "2.0.1" +version = "2.0.2" dependencies = [ "clap", "clap_complete", @@ -1227,14 +1227,14 @@ dependencies = [ [[package]] name = "draftcraft-color" -version = "2.0.1" +version = "2.0.2" dependencies = [ "serde", ] [[package]] name = "draftcraft-constraints" -version = "2.0.1" +version = "2.0.2" dependencies = [ "draftcraft-doc", "draftcraft-geom", @@ -1244,7 +1244,7 @@ dependencies = [ [[package]] name = "draftcraft-doc" -version = "2.0.1" +version = "2.0.2" dependencies = [ "draftcraft-color", "draftcraft-geom", @@ -1255,7 +1255,7 @@ dependencies = [ [[package]] name = "draftcraft-dwg" -version = "2.0.1" +version = "2.0.2" dependencies = [ "acadrust", "log", @@ -1263,7 +1263,7 @@ dependencies = [ [[package]] name = "draftcraft-dxf" -version = "2.0.1" +version = "2.0.2" dependencies = [ "encoding_rs", "log", @@ -1272,7 +1272,7 @@ dependencies = [ [[package]] name = "draftcraft-engine" -version = "2.0.1" +version = "2.0.2" dependencies = [ "craft-docpath", "draftcraft-color", @@ -1293,7 +1293,7 @@ dependencies = [ [[package]] name = "draftcraft-fonts" -version = "2.0.1" +version = "2.0.2" dependencies = [ "draftcraft-geom", "encoding_rs", @@ -1305,14 +1305,14 @@ dependencies = [ [[package]] name = "draftcraft-geom" -version = "2.0.1" +version = "2.0.2" dependencies = [ "serde", ] [[package]] name = "draftcraft-io" -version = "2.0.1" +version = "2.0.2" dependencies = [ "acadrust", "craft-pdf", @@ -1334,7 +1334,7 @@ dependencies = [ [[package]] name = "draftcraft-mcp" -version = "2.0.1" +version = "2.0.2" dependencies = [ "clap", "draftcraft-engine", @@ -1348,7 +1348,7 @@ dependencies = [ [[package]] name = "draftcraft-render" -version = "2.0.1" +version = "2.0.2" dependencies = [ "draftcraft-color", "draftcraft-doc", @@ -1362,7 +1362,7 @@ dependencies = [ [[package]] name = "draftcraft-ui-egui" -version = "2.0.1" +version = "2.0.2" dependencies = [ "chrono", "craft-ui", @@ -1384,11 +1384,12 @@ dependencies = [ "serde", "serde_json", "web-time", + "zip", ] [[package]] name = "draftcraft-web" -version = "2.0.1" +version = "2.0.2" dependencies = [ "craft-web-host", "draftcraft-engine", @@ -5976,7 +5977,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "2.0.1" +version = "2.0.2" dependencies = [ "chrono", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index cc62d43c..599f056c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] # default-members [workspace.package] -version = "2.0.1" +version = "2.0.2" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/apps/draftcraft/src/main.rs b/apps/draftcraft/src/main.rs index 16160a0e..224387fd 100644 --- a/apps/draftcraft/src/main.rs +++ b/apps/draftcraft/src/main.rs @@ -314,6 +314,9 @@ fn main() -> eframe::Result { let launch = launch_args::parse(launch_args::command(), std::env::args_os().skip(1)).unwrap_or_else(|e| e.exit()); let vars = env::Env::read(); adopt_old_folders(vars.config_dir.as_deref()); + // What an in-app update left beside this copy (the old app, `*.old` files). + #[cfg(not(target_arch = "wasm32"))] + draftcraft_ui_egui::self_update::clean_leftovers(); let (control_port, sample, files) = (launch.control, launch.sample, launch.files); // The log file lives under the settings directory; opened after the arguments, so `--version` // leaves no file behind. Records logged until now are written to it first. @@ -387,7 +390,7 @@ fn main() -> eframe::Result { b.with_close_requested_on_terminate(true); })); } - eframe::run_native( + let result = eframe::run_native( "DraftCraft", options, Box::new(move |cc| { @@ -470,7 +473,11 @@ fn main() -> eframe::Result { movable: None, })) }), - ) + ); + // Restart Now after an in-app update: the new copy starts once this window has closed. + #[cfg(not(target_arch = "wasm32"))] + draftcraft_ui_egui::self_update::relaunch_if_scheduled(); + result } #[cfg(test)] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 52e9445f..89aef46c 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -31,6 +31,8 @@ web-time = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] craft-update = { workspace = true } +# Unpacks the Windows update zip (self_update.rs); the same version and features craft-update uses. +zip = { version = "9", default-features = false, features = ["deflate"] } [dev-dependencies] # Tests build the dock area as the desktop app does (headless contexts keep floats in-window). diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 0df17ba9..fdb23471 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1386,6 +1386,22 @@ menu Modify Edita Skip This Version Salta questa versione DraftCraft is up to date (version {version}). DraftCraft è aggiornato (versione {version}). Could not check for updates. Impossibile verificare gli aggiornamenti. + Do you want to install the update now? Vuoi installare l'aggiornamento adesso? + Update Now Aggiorna ora + Open the release page Apri la pagina della release + This copy of DraftCraft can't update itself. Questa copia di DraftCraft non può aggiornarsi da sola. + Updating DraftCraft Aggiornamento di DraftCraft + Update Failed Aggiornamento non riuscito + Installing DraftCraft {version} Installazione di DraftCraft {version} + Downloading: {done} of {total} MB Download: {done} di {total} MB + Installing… Installazione… + Starting the download… Avvio del download… + The connection dropped; trying again… Connessione interrotta; nuovo tentativo… + DraftCraft {version} is installed. DraftCraft {version} è installato. + Restart DraftCraft to use it. If you restart later, it opens the next time you start DraftCraft. Riavvia DraftCraft per usarlo. Se riavvii più tardi, si aprirà al prossimo avvio di DraftCraft. + Restart Now Riavvia ora + The update could not be installed. Impossibile installare l'aggiornamento. + You can download it from the release page instead. Puoi scaricarlo invece dalla pagina della release. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 968f0333..04d6c7aa 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1369,6 +1369,22 @@ Skip This Version 跳过此版本 DraftCraft is up to date (version {version}). DraftCraft 已是最新版本({version})。 Could not check for updates. 无法检查更新。 + Do you want to install the update now? 要立即安装更新吗? + Update Now 立即更新 + Open the release page 打开发布页面 + This copy of DraftCraft can't update itself. 此 DraftCraft 副本无法自行更新。 + Updating DraftCraft 正在更新 DraftCraft + Update Failed 更新失败 + Installing DraftCraft {version} 正在安装 DraftCraft {version} + Downloading: {done} of {total} MB 正在下载:{done} / {total} MB + Installing… 正在安装… + Starting the download… 正在开始下载… + The connection dropped; trying again… 连接中断,正在重试… + DraftCraft {version} is installed. DraftCraft {version} 已安装。 + Restart DraftCraft to use it. If you restart later, it opens the next time you start DraftCraft. 重新启动 DraftCraft 即可使用。如果稍后重启,下次启动 DraftCraft 时将打开新版本。 + Restart Now 立即重启 + The update could not be installed. 无法安装更新。 + You can download it from the release page instead. 您也可以从发布页面下载。 # Menu and command labels the October 2026 update missed (#1129). Align Multileaders 对齐多重引线 Analyze Usage 分析使用情况 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a8651bdd..7331d036 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -62,6 +62,8 @@ pub mod plotstyles; pub mod quick; pub mod ribbon; pub mod save_loss; +#[cfg(not(target_arch = "wasm32"))] +pub mod self_update; pub mod shortcut_menus; pub mod theme; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/self_update.rs b/crates/ui-egui/src/self_update.rs new file mode 100644 index 00000000..331510cb --- /dev/null +++ b/crates/ui-egui/src/self_update.rs @@ -0,0 +1,616 @@ +//! DraftCraft updating itself (desktop only): Update Now in the update window downloads the new +//! release, checks it against the release's `SHA256SUMS.txt`, puts it in place of the running copy +//! and starts it once this one has quit. +//! +//! | Installed as | Download | Put in place | +//! |---|---|---| +//! | macOS `DraftCraft.app` (bundle id `dev.skryx.draftcraft`) | `draftcraft-macos-arm64.dmg` | the new app copied out of the disk image beside the old one, then swapped in by renaming (fine while it runs) | +//! | Windows folder with `DraftCraft.exe` | `draftcraft-windows-{x64,arm64}.zip` | unzipped beside it; each running file renamed to `*.old` (Windows allows that) and the new one moved in | +//! | Linux AppImage (`$APPIMAGE`) | `draftcraft-linux-x86_64.AppImage` | renamed over the old one (fine while it runs) | +//! +//! Anything else (a build from source, a folder this account can't write, another system) gets the +//! release page instead, as before. The leftovers of a swap (the old app, `*.old` files) are deleted +//! at the next start ([`clean_leftovers`]). +//! +//! Downloading, resuming and the checksum are `craft_update::Http::download`; only files under +//! `https://github.com/SkryxDev/DraftCraft/releases/download/` are fetched. + +use std::path::{Path, PathBuf}; +use std::sync::Mutex; + +use craft_update::http::{Stop, Transfer}; +use craft_update::{Asset, Http, Release}; + +/// macOS bundle identifier of DraftCraft.app (`apps/draftcraft/Info.plist.in`). +const BUNDLE_ID: &str = "dev.skryx.draftcraft"; + +/// The largest download accepted (a release file is about 75 MB). +const MAX_DOWNLOAD: u64 = 600 * 1024 * 1024; + +/// The most files and bytes a Windows update zip may unpack to. +const MAX_ZIP_ENTRIES: usize = 500; +const MAX_ZIP_BYTES: u64 = 1024 * 1024 * 1024; + +/// How deep the folders of a Windows update may nest. +const MAX_DEPTH: usize = 8; + +/// Names beside the running copy that a swap leaves behind. +const MAC_STAGED: &str = ".DraftCraft-update.app"; +const MAC_OLD: &str = ".DraftCraft-old.app"; +const WIN_STAGING: &str = ".draftcraft-update"; +const OLD_SUFFIX: &str = ".old"; +const LINUX_STAGED: &str = ".draftcraft-update.AppImage"; + +/// How the running copy was installed, when it can replace itself. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Install { + /// macOS: the `DraftCraft.app` bundle. + MacApp(PathBuf), + /// Windows: the folder holding `DraftCraft.exe`. + WindowsFolder(PathBuf), + /// Linux: the AppImage file. + AppImage(PathBuf), +} + +impl Install { + /// The release file this install updates from, on this processor. + pub fn asset_name(&self) -> Option<&'static str> { + match self { + Self::MacApp(_) => cfg!(target_arch = "aarch64").then_some("draftcraft-macos-arm64.dmg"), + Self::WindowsFolder(_) => Some(if cfg!(target_arch = "aarch64") { "draftcraft-windows-arm64.zip" } else { "draftcraft-windows-x64.zip" }), + Self::AppImage(_) => cfg!(target_arch = "x86_64").then_some("draftcraft-linux-x86_64.AppImage"), + } + } + + /// What to start after the update. + fn program(&self) -> PathBuf { + match self { + Self::MacApp(bundle) => bundle.clone(), + Self::WindowsFolder(dir) => dir.join("DraftCraft.exe"), + Self::AppImage(path) => path.clone(), + } + } +} + +/// How this running copy can update itself; `None` when it can't (the release page is offered). +pub fn detect() -> Option { + let exe = std::env::current_exe().ok()?; + let exe = exe.canonicalize().unwrap_or(exe); + if is_development_build(&exe) { + return None; + } + let install = detect_at(&exe, std::env::var_os("APPIMAGE").map(PathBuf::from))?; + install.asset_name()?; + writable(container(&install)?).then_some(install) +} + +/// [`detect`] for a known executable and `$APPIMAGE`, without the writability check. +fn detect_at(exe: &Path, appimage: Option) -> Option { + if cfg!(target_os = "macos") { + let bundle = exe.ancestors().find(|p| p.extension().is_some_and(|e| e == "app"))?; + return (bundle_value(bundle, "CFBundleIdentifier").as_deref() == Some(BUNDLE_ID)).then(|| Install::MacApp(bundle.to_path_buf())); + } + if cfg!(windows) { + let named = exe.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.eq_ignore_ascii_case("DraftCraft.exe")); + return named.then(|| exe.parent().map(|d| Install::WindowsFolder(d.to_path_buf()))).flatten(); + } + if cfg!(target_os = "linux") { + return appimage.filter(|p| p.is_file()).map(Install::AppImage); + } + None +} + +/// The folder the swap writes in. +fn container(install: &Install) -> Option<&Path> { + match install { + Install::MacApp(bundle) | Install::AppImage(bundle) => bundle.parent(), + Install::WindowsFolder(dir) => Some(dir), + } +} + +/// Whether this account can create files in `dir`. +fn writable(dir: &Path) -> bool { + let probe = dir.join(format!(".draftcraft-write-test-{}", std::process::id())); + let ok = std::fs::write(&probe, b"").is_ok(); + let _ = std::fs::remove_file(&probe); + ok +} + +/// Whether `exe` runs from a Cargo build folder (a build from source updates through git). +fn is_development_build(exe: &Path) -> bool { + exe.ancestors().skip(1).any(|d| d.join(".rustc_info.json").is_file() || d.join("CACHEDIR.TAG").is_file()) +} + +/// A value from a macOS bundle's Info.plist, read with `plutil`. +fn bundle_value(bundle: &Path, key: &str) -> Option { + let plist = bundle.join("Contents/Info.plist"); + let out = std::process::Command::new("/usr/bin/plutil").args(["-extract", key, "raw", "-o", "-"]).arg(&plist).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()) +} + +/// What an update reports while it works. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Progress { + /// Bytes downloaded of the total. + Downloading { done: u64, total: u64 }, + /// The connection dropped; trying again. + Reconnecting { done: u64, total: u64 }, + /// Downloaded and checked; putting it in place. + Installing, +} + +/// The release file `install` updates from, checked: one of this repository's downloads, with a +/// size and a SHA-256. +fn pick(release: &Release, install: &Install) -> Result { + let name = install.asset_name().ok_or("this release has no build for this computer")?; + let asset = release.assets.iter().find(|a| a.name == name).ok_or_else(|| format!("the release has no {name}"))?; + if !craft_update::release::download_url_under(&asset.url, &craft_update::release::download_prefix(crate::UPDATE_APP.repo)) { + return Err(format!("{name} isn't one of DraftCraft's own downloads")); + } + if asset.size == 0 || asset.size > MAX_DOWNLOAD { + return Err(format!("{name} has an unexpected size ({} bytes)", asset.size)); + } + if !asset.sha256.as_deref().is_some_and(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit())) { + return Err(format!("the release publishes no checksum for {name}")); + } + Ok(asset.clone()) +} + +/// Fill in the release's checksums from its `SHA256SUMS.txt`, when GitHub didn't give them. +fn add_checksums(http: &Http, release: &mut Release) -> Result<(), String> { + if release.assets.iter().all(|a| a.sha256.is_some()) { + return Ok(()); + } + let Some(sums) = release.sums_asset() else { return Ok(()) }; + if !craft_update::release::download_url_under(&sums.url, &craft_update::release::download_prefix(crate::UPDATE_APP.repo)) { + return Err("the release's checksum file isn't one of DraftCraft's own downloads".into()); + } + let text = http.get_text(&sums.url)?.ok_or("the release's checksum file is missing")?; + release.apply_sums(&craft_update::release::parse_sha256sums(&text)); + Ok(()) +} + +/// Where downloads wait until they are installed. +fn downloads_dir() -> PathBuf { + draftcraft_engine::settings_dir::current().map_or_else(|| std::env::temp_dir().join("draftcraft-updates"), |d| d.join("updates")) +} + +/// Download `release` for `install`, check it and put it in place. Returns what to start after +/// quitting. Runs on its own thread; `stop` cancels the download. +pub fn install(release: &Release, install: &Install, stop: &Stop, progress: &mut dyn FnMut(Progress)) -> Result { + let version = release.version_label(); + let http = Http::new(&format!("DraftCraft/{}", env!("CARGO_PKG_VERSION")))?; + let mut release = release.clone(); + add_checksums(&http, &mut release)?; + let asset = pick(&release, install)?; + let sha = asset.sha256.clone().unwrap_or_default(); + let dir = downloads_dir(); + std::fs::create_dir_all(&dir).map_err(|e| format!("couldn't create {} ({e})", dir.display()))?; + let file = dir.join(&asset.name); + http.download(&asset.url, &file, asset.size, &sha, stop, &mut |t| { + progress(match t { + Transfer::Bytes { done, total } => Progress::Downloading { done, total }, + Transfer::Reconnecting { done, total } => Progress::Reconnecting { done, total }, + }); + })?; + progress(Progress::Installing); + let placed = match install { + Install::MacApp(bundle) => install_mac(&file, bundle, &version), + Install::WindowsFolder(folder) => install_windows(&file, folder), + Install::AppImage(path) => install_appimage(&file, path), + }; + let _ = std::fs::remove_file(&file); + placed?; + log::info!("DraftCraft {version} installed at {}", install.program().display()); + Ok(install.program()) +} + +/// macOS: mount the disk image, copy its DraftCraft.app beside `bundle`, check it, swap it in. +fn install_mac(dmg: &Path, bundle: &Path, version: &str) -> Result<(), String> { + let parent = bundle.parent().ok_or("DraftCraft.app isn't in a folder")?; + let mount = downloads_dir().join("mount"); + let _ = std::fs::create_dir_all(&mount); + run( + "/usr/bin/hdiutil", + &[ + "attach".as_ref(), + "-readonly".as_ref(), + "-nobrowse".as_ref(), + "-noautoopen".as_ref(), + "-mountpoint".as_ref(), + mount.as_os_str(), + dmg.as_os_str(), + ], + )?; + let staged = parent.join(MAC_STAGED); + let copied = (|| { + let new = mount.join("DraftCraft.app"); + if bundle_value(&new, "CFBundleIdentifier").as_deref() != Some(BUNDLE_ID) { + return Err("the disk image doesn't hold DraftCraft".to_string()); + } + let found = bundle_value(&new, "CFBundleShortVersionString").unwrap_or_default(); + if found != version { + return Err(format!("the disk image holds DraftCraft {found}, not {version}")); + } + let _ = std::fs::remove_dir_all(&staged); + run("/usr/bin/ditto", &[new.as_os_str(), staged.as_os_str()]) + })(); + let _ = run("/usr/bin/hdiutil", &["detach".as_ref(), "-force".as_ref(), mount.as_os_str()]); + if let Err(e) = copied { + let _ = std::fs::remove_dir_all(&staged); + return Err(e); + } + swap_in(&staged, bundle, &parent.join(MAC_OLD)) +} + +/// Put `new` at `target`, moving what is there to `old` first, and back if the move fails. +fn swap_in(new: &Path, target: &Path, old: &Path) -> Result<(), String> { + remove_any(old); + if target.exists() { + std::fs::rename(target, old).map_err(|e| format!("couldn't move the old {} aside ({e})", target.display()))?; + } + if let Err(e) = std::fs::rename(new, target) { + let _ = std::fs::rename(old, target); + return Err(format!("couldn't put the new {} in place ({e})", target.display())); + } + Ok(()) +} + +fn remove_any(path: &Path) { + if path.is_dir() { + let _ = std::fs::remove_dir_all(path); + } else { + let _ = std::fs::remove_file(path); + } +} + +/// Windows: unzip beside the running copy, then move each file in, renaming the one it replaces +/// to `*.old` (a running program can be renamed, not overwritten). +fn install_windows(zip: &Path, folder: &Path) -> Result<(), String> { + let staging = folder.join(WIN_STAGING); + remove_any(&staging); + let done = unzip(zip, &staging).and_then(|()| { + if !staging.join("DraftCraft.exe").is_file() { + return Err("the download doesn't hold DraftCraft.exe".to_string()); + } + move_in(&staging, folder, 0) + }); + remove_any(&staging); + done +} + +/// Unpack `zip` into `dest`, dropping the archive's top `DraftCraft/` folder. Entries that would +/// land outside `dest`, too many entries or too many bytes are refused. +fn unzip(zip: &Path, dest: &Path) -> Result<(), String> { + let file = std::fs::File::open(zip).map_err(|e| format!("couldn't open the download ({e})"))?; + let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("the download isn't a zip ({e})"))?; + if archive.len() > MAX_ZIP_ENTRIES { + return Err("the download holds too many files".into()); + } + let mut total = 0u64; + for i in 0..archive.len() { + let mut entry = archive.by_index(i).map_err(|e| format!("unreadable zip entry ({e})"))?; + let Some(name) = entry.enclosed_name() else { return Err("a file in the download would land outside its folder".to_string()) }; + let rel: PathBuf = name.components().skip_while(|c| c.as_os_str().eq_ignore_ascii_case("DraftCraft")).take(MAX_DEPTH + 1).collect(); + if rel.as_os_str().is_empty() { + continue; + } + if rel.components().count() > MAX_DEPTH { + return Err("the download's folders nest too deep".into()); + } + let out = dest.join(&rel); + if entry.is_dir() { + std::fs::create_dir_all(&out).map_err(|e| format!("couldn't create {} ({e})", out.display()))?; + continue; + } + total = total.saturating_add(entry.size()); + if total > MAX_ZIP_BYTES { + return Err("the download unpacks to too much".into()); + } + if let Some(dir) = out.parent() { + std::fs::create_dir_all(dir).map_err(|e| format!("couldn't create {} ({e})", dir.display()))?; + } + let mut f = std::fs::File::create(&out).map_err(|e| format!("couldn't write {} ({e})", out.display()))?; + let mut limited = std::io::Read::take(&mut entry, MAX_ZIP_BYTES); + std::io::copy(&mut limited, &mut f).map_err(|e| format!("couldn't unpack {} ({e})", rel.display()))?; + } + Ok(()) +} + +/// Move every file of `from` into `to` (same folders), renaming each file it replaces to +/// `.old` (or `.old2`, … when an earlier one is still in use). +fn move_in(from: &Path, to: &Path, depth: usize) -> Result<(), String> { + if depth > MAX_DEPTH { + return Err("the download's folders nest too deep".into()); + } + let entries = std::fs::read_dir(from).map_err(|e| format!("couldn't read {} ({e})", from.display()))?; + for entry in entries { + let entry = entry.map_err(|e| format!("couldn't read {} ({e})", from.display()))?; + let src = entry.path(); + let dst = to.join(entry.file_name()); + if src.is_dir() { + std::fs::create_dir_all(&dst).map_err(|e| format!("couldn't create {} ({e})", dst.display()))?; + move_in(&src, &dst, depth + 1)?; + continue; + } + if dst.exists() { + let aside = old_name(&dst).ok_or_else(|| format!("couldn't move the old {} aside", dst.display()))?; + std::fs::rename(&dst, &aside).map_err(|e| format!("couldn't move the old {} aside ({e})", dst.display()))?; + } + std::fs::rename(&src, &dst).map_err(|e| format!("couldn't put the new {} in place ({e})", dst.display()))?; + } + Ok(()) +} + +/// A free `.old` name for `file`, deleting an earlier one when it can. +fn old_name(file: &Path) -> Option { + let name = file.file_name()?.to_str()?; + for n in 1..=20u32 { + let suffix = if n == 1 { OLD_SUFFIX.to_string() } else { format!("{OLD_SUFFIX}{n}") }; + let candidate = file.with_file_name(format!("{name}{suffix}")); + if !candidate.exists() || std::fs::remove_file(&candidate).is_ok() { + return Some(candidate); + } + } + None +} + +/// Linux: copy the new AppImage beside the old one and rename it over. +fn install_appimage(file: &Path, appimage: &Path) -> Result<(), String> { + let staged = appimage.with_file_name(LINUX_STAGED); + std::fs::copy(file, &staged).map_err(|e| format!("couldn't copy the new AppImage ({e})"))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + if let Err(e) = std::fs::set_permissions(&staged, std::fs::Permissions::from_mode(0o755)) { + let _ = std::fs::remove_file(&staged); + return Err(format!("couldn't make the new AppImage executable ({e})")); + } + } + std::fs::rename(&staged, appimage).map_err(|e| { + let _ = std::fs::remove_file(&staged); + format!("couldn't put the new AppImage in place ({e})") + }) +} + +/// Run a system tool; its error output on failure. +fn run(program: &str, args: &[&std::ffi::OsStr]) -> Result<(), String> { + let out = std::process::Command::new(program).args(args).output().map_err(|e| format!("couldn't run {program} ({e})"))?; + if out.status.success() { Ok(()) } else { Err(format!("{program} failed: {}", String::from_utf8_lossy(&out.stderr).trim())) } +} + +/// The program to start once this one has quit. +static RELAUNCH: Mutex> = Mutex::new(None); + +/// Start `program` after this run of DraftCraft ends ([`relaunch_if_scheduled`]); `None` cancels. +pub fn relaunch_after_exit(program: Option) { + if let Ok(mut slot) = RELAUNCH.lock() { + *slot = program; + } +} + +/// Called by the app once its window has closed: start the updated DraftCraft, if an update asked. +pub fn relaunch_if_scheduled() { + let Some(program) = RELAUNCH.lock().ok().and_then(|mut slot| slot.take()) else { return }; + let mut cmd = if cfg!(target_os = "macos") { + let mut open = std::process::Command::new("/usr/bin/open"); + open.arg("-n").arg(&program); + open + } else { + std::process::Command::new(&program) + }; + // A pretend version (for trying the update) lasts one run. + cmd.env_remove("DRAFTCRAFT_PRETEND_VERSION"); + if let Err(e) = cmd.spawn() { + log::warn!("couldn't start the updated DraftCraft ({}): {e}", program.display()); + } +} + +/// At start: delete what an earlier update left beside this copy, and its downloads. +pub fn clean_leftovers() { + let Some(exe) = std::env::current_exe().ok().map(|e| e.canonicalize().unwrap_or(e)) else { return }; + if let Some(install) = detect_at(&exe, std::env::var_os("APPIMAGE").map(PathBuf::from)) { + clean_beside(&install); + } + remove_any(&downloads_dir().join("mount")); +} + +fn clean_beside(install: &Install) { + match install { + Install::MacApp(bundle) => { + if let Some(parent) = bundle.parent() { + remove_any(&parent.join(MAC_OLD)); + remove_any(&parent.join(MAC_STAGED)); + } + } + Install::WindowsFolder(dir) => { + remove_any(&dir.join(WIN_STAGING)); + remove_old_files(dir, 0); + } + Install::AppImage(path) => remove_any(&path.with_file_name(LINUX_STAGED)), + } +} + +/// Delete the `*.old`, `*.old2`, … files a Windows update renamed. +fn remove_old_files(dir: &Path, depth: usize) { + let Ok(entries) = std::fs::read_dir(dir) else { return }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + if depth < MAX_DEPTH { + remove_old_files(&path, depth + 1); + } + } else if is_old_name(&path) { + let _ = std::fs::remove_file(&path); + } + } +} + +fn is_old_name(path: &Path) -> bool { + let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false }; + let Some(pos) = name.rfind(OLD_SUFFIX) else { return false }; + pos > 0 && name.get(pos + OLD_SUFFIX.len()..).is_some_and(|n| n.bytes().all(|b| b.is_ascii_digit())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn release(assets: &[(&str, &str, u64, Option<&str>)]) -> Release { + Release { + tag: "v9.0.0".into(), + version: craft_update::parse_version("9.0.0"), + assets: assets + .iter() + .map(|(name, url, size, sha)| Asset { name: (*name).into(), url: (*url).into(), size: *size, sha256: sha.map(Into::into) }) + .collect(), + ..Release::default() + } + } + + const SHA: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + + fn ours(name: &str) -> String { + format!("https://github.com/SkryxDev/DraftCraft/releases/download/v9.0.0/{name}") + } + + #[test] + fn only_our_checked_downloads_are_picked() { + let install = Install::WindowsFolder(PathBuf::from("C:/DraftCraft")); + let name = install.asset_name().unwrap(); + let url = ours(name); + assert_eq!(pick(&release(&[(name, &url, 10, Some(SHA))]), &install).unwrap().name, name); + // Another repository, a path that climbs out, no checksum, no size, too big, missing. + for (u, size, sha) in [ + ("https://github.com/someone/else/releases/download/v9.0.0/x.zip", 10, Some(SHA)), + ("https://github.com/SkryxDev/DraftCraft/releases/download/../../../x/y/releases/download/v1/z", 10, Some(SHA)), + (url.as_str(), 10, None), + (url.as_str(), 10, Some("abc")), + (url.as_str(), 0, Some(SHA)), + (url.as_str(), MAX_DOWNLOAD + 1, Some(SHA)), + ] { + assert!(pick(&release(&[(name, u, size, sha)]), &install).is_err(), "{u} {size} {sha:?}"); + } + assert!(pick(&release(&[]), &install).is_err()); + } + + #[test] + fn each_install_updates_from_its_own_file() { + let win = Install::WindowsFolder(PathBuf::from("C:/DraftCraft")).asset_name().unwrap(); + assert!(win == "draftcraft-windows-x64.zip" || win == "draftcraft-windows-arm64.zip"); + let mac = Install::MacApp(PathBuf::from("/Applications/DraftCraft.app")); + assert_eq!(mac.asset_name().is_some(), cfg!(target_arch = "aarch64")); + assert_eq!(mac.program(), PathBuf::from("/Applications/DraftCraft.app")); + let linux = Install::AppImage(PathBuf::from("/home/me/DraftCraft.AppImage")); + assert_eq!(linux.asset_name().is_some(), cfg!(target_arch = "x86_64")); + } + + #[test] + fn a_cargo_build_is_a_development_build() { + let dir = tempdir(); + std::fs::create_dir_all(dir.join("target/release")).unwrap(); + std::fs::write(dir.join("target/.rustc_info.json"), "{}").unwrap(); + assert!(is_development_build(&dir.join("target/release/draftcraft"))); + assert!(!is_development_build(&dir.join("DraftCraft/DraftCraft.exe"))); + } + + #[test] + fn swap_in_moves_the_old_copy_aside_and_back_on_failure() { + let dir = tempdir(); + let (new, target, old) = (dir.join("new.app"), dir.join("DraftCraft.app"), dir.join("old.app")); + std::fs::create_dir_all(&new).unwrap(); + std::fs::write(new.join("v"), "2").unwrap(); + std::fs::create_dir_all(&target).unwrap(); + std::fs::write(target.join("v"), "1").unwrap(); + swap_in(&new, &target, &old).unwrap(); + assert_eq!(std::fs::read_to_string(target.join("v")).unwrap(), "2"); + assert_eq!(std::fs::read_to_string(old.join("v")).unwrap(), "1"); + // Nothing new to move in: the old copy comes back. + let missing = dir.join("missing.app"); + assert!(swap_in(&missing, &target, &old).is_err()); + assert_eq!(std::fs::read_to_string(target.join("v")).unwrap(), "2"); + } + + fn write_zip(path: &Path, files: &[(&str, &[u8])]) { + let mut w = zip::ZipWriter::new(std::fs::File::create(path).unwrap()); + for (name, bytes) in files { + w.start_file(*name, zip::write::SimpleFileOptions::default()).unwrap(); + std::io::Write::write_all(&mut w, bytes).unwrap(); + } + w.finish().unwrap(); + } + + #[test] + fn a_windows_update_replaces_files_and_keeps_the_old_ones_aside() { + let dir = tempdir(); + let folder = dir.join("DraftCraft"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(folder.join("DraftCraft.exe"), "old").unwrap(); + std::fs::write(folder.join("settings.txt"), "mine").unwrap(); + let zip = dir.join("draftcraft-windows-x64.zip"); + write_zip(&zip, &[("DraftCraft/DraftCraft.exe", b"new"), ("DraftCraft/draftcraft-cli.exe", b"cli"), ("DraftCraft/docs/NOTICE", b"n")]); + install_windows(&zip, &folder).unwrap(); + assert_eq!(std::fs::read_to_string(folder.join("DraftCraft.exe")).unwrap(), "new"); + assert_eq!(std::fs::read_to_string(folder.join("DraftCraft.exe.old")).unwrap(), "old"); + assert_eq!(std::fs::read_to_string(folder.join("draftcraft-cli.exe")).unwrap(), "cli"); + assert_eq!(std::fs::read_to_string(folder.join("docs/NOTICE")).unwrap(), "n"); + assert_eq!(std::fs::read_to_string(folder.join("settings.txt")).unwrap(), "mine"); + assert!(!folder.join(WIN_STAGING).exists()); + // The next start deletes what the swap left. + clean_beside(&Install::WindowsFolder(folder.clone())); + assert!(!folder.join("DraftCraft.exe.old").exists()); + assert!(folder.join("DraftCraft.exe").exists() && folder.join("settings.txt").exists()); + } + + #[test] + fn a_hostile_zip_is_refused() { + let dir = tempdir(); + let folder = dir.join("DraftCraft"); + std::fs::create_dir_all(&folder).unwrap(); + std::fs::write(folder.join("DraftCraft.exe"), "old").unwrap(); + let zip = dir.join("evil.zip"); + write_zip(&zip, &[("../../outside.txt", b"x"), ("DraftCraft/DraftCraft.exe", b"new")]); + assert!(install_windows(&zip, &folder).is_err()); + assert!(!dir.join("outside.txt").exists()); + assert_eq!(std::fs::read_to_string(folder.join("DraftCraft.exe")).unwrap(), "old"); + // A zip without the program changes nothing. + write_zip(&zip, &[("DraftCraft/readme.txt", b"x")]); + assert!(install_windows(&zip, &folder).is_err()); + assert!(!folder.join("readme.txt").exists()); + } + + #[test] + fn old_names_are_recognised() { + for (name, old) in [("DraftCraft.exe.old", true), ("a.old2", true), ("a.old12", true), ("a.older", false), (".old", false), ("a.txt", false)] + { + assert_eq!(is_old_name(Path::new(name)), old, "{name}"); + } + } + + #[test] + fn an_appimage_is_replaced_in_place() { + let dir = tempdir(); + let (app, new) = (dir.join("DraftCraft.AppImage"), dir.join("download")); + std::fs::write(&app, "old").unwrap(); + std::fs::write(&new, "new").unwrap(); + install_appimage(&new, &app).unwrap(); + assert_eq!(std::fs::read_to_string(&app).unwrap(), "new"); + assert!(!dir.join(LINUX_STAGED).exists()); + } + + #[test] + fn a_relaunch_can_be_cancelled() { + relaunch_after_exit(Some(PathBuf::from("/nonexistent/DraftCraft"))); + relaunch_after_exit(None); + assert!(RELAUNCH.lock().unwrap().is_none()); + } + + fn tempdir() -> PathBuf { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + let dir = std::env::temp_dir().join(format!("draftcraft-self-update-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } +} diff --git a/crates/ui-egui/src/updates_ui.rs b/crates/ui-egui/src/updates_ui.rs index cb110da0..16122f84 100644 --- a/crates/ui-egui/src/updates_ui.rs +++ b/crates/ui-egui/src/updates_ui.rs @@ -1,17 +1,22 @@ //! The update check (desktop only; the web build is always the latest). Once at startup, and again //! from Help ▸ Check for Updates…, a background thread asks GitHub for the newest release of //! DraftCraft (`SkryxDev/DraftCraft`). When it is newer than this build, a window offers it: -//! Download opens the release page, Later closes the window until the next start, and Skip This -//! Version stops the startup check offering that version. Nothing is downloaded or installed here. +//! Update Now downloads and installs it and offers to restart ([`crate::self_update`], when this +//! copy can replace itself), Download opens the release page, Later closes the window until the +//! next start, and Skip This Version stops the startup check offering that version. //! The asking and comparing are `craft_update::check_for_update`; `DRAFTCRAFT_PRETEND_VERSION` //! makes this build count as another version (to try the prompt). +use std::path::PathBuf; use std::sync::Arc; use std::sync::mpsc::{Receiver, TryRecvError, channel}; +use craft_update::http::Stop; + use egui::{RichText, vec2}; use crate::CadApp; +use crate::self_update::{self, Install, Progress}; use crate::theme::Tokens; /// The version this build reports to the update check. @@ -32,6 +37,38 @@ pub struct Offer { pub url: String, /// Its release notes (Markdown, capped). pub notes: String, + /// The release as GitHub described it (its files), for Update Now; `None` in tests. + pub release: Option, +} + +/// What Update Now is doing. +#[derive(Default)] +enum Job { + #[default] + Idle, + /// Downloading or installing `version` on its own thread. + Working { version: String, progress: Option, stop: Arc, rx: Receiver }, + /// `version` is in place; `program` starts it. + Installed { version: String, program: PathBuf }, + /// The update failed; the release page is offered instead. + Failed { message: String, url: String }, +} + +/// What the update thread reports. +enum Msg { + Progress(Progress), + Done(Result), +} + +/// After Restart Now: whether the quit is waiting on the unsaved-changes prompt. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Restart { + #[default] + No, + /// The window was asked to close. + Asked, + /// The unsaved-changes prompt is open. + Prompted, } /// Where a check gets the newest release (tests stand in for GitHub with one). @@ -56,6 +93,10 @@ pub struct Runtime { /// The version Skip This Version skipped. skipped: Option, source: Option, + /// How this copy can replace itself, looked up when a release is offered. + install: Option>, + job: Job, + restart: Restart, } impl CadApp { @@ -80,7 +121,12 @@ pub fn check_now(app: &mut CadApp) { fn from_github() -> Result, String> { let http = craft_update::Http::new(&format!("DraftCraft/{VERSION}"))?; let release = craft_update::check_for_update(&crate::UPDATE_APP, &http, VERSION)?; - Ok(release.map(|r| Offer { version: r.version_label(), url: r.html_url, notes: r.notes.chars().take(NOTES_MAX).collect() })) + Ok(release.map(|r| Offer { + version: r.version_label(), + url: r.html_url.clone(), + notes: r.notes.chars().take(NOTES_MAX).collect(), + release: Some(r), + })) } /// The version this build counts as: [`VERSION`], or `DRAFTCRAFT_PRETEND_VERSION` when it is set @@ -170,6 +216,7 @@ fn tick(app: &mut CadApp, ctx: &egui::Context) { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Choice { None, + UpdateNow, Download, Later, Skip, @@ -178,8 +225,14 @@ enum Choice { /// Run the checks, and draw the update window while there is something to say. pub fn show(app: &mut CadApp, ctx: &egui::Context) { tick(app, ctx); + job_tick(app, ctx); if let Some(offer) = app.updates_rt.offer.clone() { - match offer_window(ctx, &offer) { + let can_update = offer.release.is_some() && app.updates_rt.install.get_or_insert_with(self_update::detect).is_some(); + match offer_window(ctx, &offer, can_update) { + Choice::UpdateNow => { + app.updates_rt.offer = None; + start_update(app, ctx, &offer); + } Choice::Download => { ctx.open_url(egui::OpenUrl::new_tab(&offer.url)); app.updates_rt.offer = None; @@ -213,7 +266,168 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { } } -fn offer_window(ctx: &egui::Context, offer: &Offer) -> Choice { +/// Update Now: download and install `offer` on its own thread. +fn start_update(app: &mut CadApp, ctx: &egui::Context, offer: &Offer) { + let fail = |message: String| Job::Failed { message, url: offer.url.clone() }; + let (Some(release), Some(Some(install))) = (offer.release.clone(), app.updates_rt.install.clone()) else { + app.updates_rt.job = fail(crate::tl!("This copy of DraftCraft can't update itself.").to_string()); + return; + }; + let stop = Arc::new(Stop::default()); + let (tx, rx) = channel(); + let (thread_stop, ctx2) = (Arc::clone(&stop), ctx.clone()); + let spawned = std::thread::Builder::new().name("self-update".into()).spawn(move || { + let progress_tx = tx.clone(); + let progress_ctx = ctx2.clone(); + let result = self_update::install(&release, &install, &thread_stop, &mut |p| { + let _ = progress_tx.send(Msg::Progress(p)); + progress_ctx.request_repaint(); + }); + let _ = tx.send(Msg::Done(result)); + ctx2.request_repaint(); + }); + app.updates_rt.job = match spawned { + Ok(_) => Job::Working { version: offer.version.clone(), progress: None, stop, rx }, + Err(e) => fail(format!("the update could not start: {e}")), + }; +} + +/// Collect the update thread's reports, follow a restart through the unsaved-changes prompt, and +/// draw the update's window. +fn job_tick(app: &mut CadApp, ctx: &egui::Context) { + if let Job::Working { version, progress, rx, .. } = &mut app.updates_rt.job { + let mut done = None; + loop { + match rx.try_recv() { + Ok(Msg::Progress(p)) => *progress = Some(p), + Ok(Msg::Done(result)) => { + done = Some(result); + break; + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + done = Some(Err("the update stopped".to_string())); + break; + } + } + } + if let Some(result) = done { + let version = version.clone(); + app.updates_rt.job = match result { + Ok(program) => Job::Installed { version, program }, + Err(e) => { + log::warn!("update to DraftCraft {version} failed: {e}"); + let url = format!("https://github.com/{}/releases/tag/v{version}", crate::UPDATE_APP.repo); + Job::Failed { message: e, url } + } + }; + } + } + // A restart that waits on the unsaved-changes prompt: cancelling it keeps this copy open, and + // the new version then starts next time instead. + match app.updates_rt.restart { + Restart::Asked if app.closing.is_some() => app.updates_rt.restart = Restart::Prompted, + Restart::Prompted if app.closing.is_none() && !app.quit_confirmed => { + self_update::relaunch_after_exit(None); + app.updates_rt.restart = Restart::No; + } + _ => {} + } + job_window(app, ctx); +} + +fn job_window(app: &mut CadApp, ctx: &egui::Context) { + let t = Tokens::get(); + let (mut close, mut cancel, mut restart, mut download) = (false, false, None, None); + let title = match &app.updates_rt.job { + Job::Idle => return, + Job::Working { .. } | Job::Installed { .. } => crate::tl!("Updating DraftCraft"), + Job::Failed { .. } => crate::tl!("Update Failed"), + }; + egui::Window::new(title) + .id(egui::Id::unique("rd_update_job")) + .collapsible(false) + .resizable(false) + .anchor(egui::Align2::CENTER_TOP, vec2(0.0, 120.0)) + .show(ctx, |ui| { + ui.set_width(380.0); + match &app.updates_rt.job { + Job::Idle => {} + Job::Working { version, progress, .. } => { + ui.label(RichText::new(crate::tf!("Installing DraftCraft {version}", version = version)).strong()); + ui.add_space(4.0); + let (fraction, text) = match progress { + Some(Progress::Downloading { done, total }) | Some(Progress::Reconnecting { done, total }) => { + let fraction = if *total == 0 { 0.0 } else { (*done as f64 / *total as f64).clamp(0.0, 1.0) as f32 }; + let text = crate::tf!("Downloading: {done} of {total} MB", done = mb(*done), total = mb(*total)); + (fraction, text) + } + Some(Progress::Installing) => (1.0, crate::tl!("Installing…").to_string()), + None => (0.0, crate::tl!("Starting the download…").to_string()), + }; + ui.add(egui::ProgressBar::new(fraction).text(text)); + if matches!(progress, Some(Progress::Reconnecting { .. })) { + ui.label(RichText::new(crate::tl!("The connection dropped; trying again…")).color(t.text_dim)); + } + ui.add_space(6.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + let installing = matches!(progress, Some(Progress::Installing)); + cancel = ui.add_enabled(!installing, egui::Button::new(crate::tl!("Cancel"))).clicked(); + }); + } + Job::Installed { version, program } => { + ui.label(RichText::new(crate::tf!("DraftCraft {version} is installed.", version = version)).strong()); + ui.label( + RichText::new(crate::tl!("Restart DraftCraft to use it. If you restart later, it opens the next time you start DraftCraft.")) + .color(t.text_dim), + ); + ui.add_space(6.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.add(egui::Button::new(RichText::new(crate::tl!("Restart Now")).strong())).clicked() { + restart = Some(program.clone()); + } + close = ui.button(crate::tl!("Later")).clicked(); + }); + } + Job::Failed { message, url } => { + ui.label(crate::tl!("The update could not be installed.")); + ui.label(RichText::new(message).color(t.text_dim)); + ui.add_space(4.0); + ui.label(crate::tl!("You can download it from the release page instead.")); + ui.add_space(6.0); + ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(crate::tl!("Download")).clicked() { + download = Some(url.clone()); + } + close = ui.button(crate::tl!("Close")).clicked(); + }); + } + } + }); + if cancel && let Job::Working { stop, .. } = &app.updates_rt.job { + stop.cancel(); + } + if let Some(url) = download { + ctx.open_url(egui::OpenUrl::new_tab(&url)); + close = true; + } + if let Some(program) = restart { + self_update::relaunch_after_exit(Some(program)); + app.updates_rt.restart = Restart::Asked; + app.updates_rt.job = Job::Idle; + ctx.send_viewport_cmd(egui::ViewportCommand::Close); + } + if close { + app.updates_rt.job = Job::Idle; + } +} + +/// Bytes as megabytes, one decimal. +fn mb(bytes: u64) -> String { + format!("{:.1}", bytes as f64 / (1024.0 * 1024.0)) +} + +fn offer_window(ctx: &egui::Context, offer: &Offer, can_update: bool) -> Choice { let t = Tokens::get(); let mut choice = Choice::None; egui::Window::new(crate::tl!("Update Available")) @@ -226,7 +440,11 @@ fn offer_window(ctx: &egui::Context, offer: &Offer) -> Choice { ui.label(RichText::new(crate::tf!("DraftCraft {version} is available.", version = offer.version)).strong().size(15.0)); ui.label(RichText::new(crate::tf!("You have version {version}.", version = running_version())).color(t.text_dim)); ui.add_space(4.0); - ui.label(crate::tl!("Do you want to download the update?")); + ui.label(if can_update { + crate::tl!("Do you want to install the update now?") + } else { + crate::tl!("Do you want to download the update?") + }); if !offer.notes.trim().is_empty() { ui.add_space(4.0); ui.collapsing(crate::tl!("What's new"), |ui| { @@ -237,7 +455,14 @@ fn offer_window(ctx: &egui::Context, offer: &Offer) -> Choice { } ui.add_space(6.0); ui.allocate_ui_with_layout(vec2(ui.available_width(), 0.0), egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button(crate::tl!("Download")).clicked() { + if can_update { + if ui.add(egui::Button::new(RichText::new(crate::tl!("Update Now")).strong())).clicked() { + choice = Choice::UpdateNow; + } + if ui.button(crate::tl!("Download")).on_hover_text(crate::tl!("Open the release page")).clicked() { + choice = Choice::Download; + } + } else if ui.button(crate::tl!("Download")).clicked() { choice = Choice::Download; } if ui.button(crate::tl!("Later")).clicked() { @@ -256,7 +481,12 @@ mod tests { use super::*; fn offer(v: &str) -> Offer { - Offer { version: v.into(), url: format!("https://github.com/SkryxDev/DraftCraft/releases/tag/v{v}"), notes: "Conic arcs".into() } + Offer { + version: v.into(), + url: format!("https://github.com/SkryxDev/DraftCraft/releases/tag/v{v}"), + notes: "Conic arcs".into(), + release: None, + } } fn app_with(answer: Result, String>) -> CadApp { diff --git a/docs/releasing.md b/docs/releasing.md index c524bf89..50625888 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -34,6 +34,16 @@ newest. The workflow creates the GitHub Release `DraftCraft v` with the made on a macOS 26 runner, whose Xcode compiles the app icon. The workflow can also be started by hand (**Actions › Release › Run workflow**) for an existing tag. +### In-app updates depend on these names + +From 2.0.2, **Update Now** in the app's update window downloads the new release and installs it +([`crates/ui-egui/src/self_update.rs`](../crates/ui-egui/src/self_update.rs)): `DraftCraft.app` from +`draftcraft-macos-arm64.dmg`, a Windows folder from `draftcraft-windows-{x64,arm64}.zip` (whose top +folder is `DraftCraft/`), the AppImage from `draftcraft-linux-x86_64.AppImage`. Each file is checked +against `SHA256SUMS.txt`, and the DMG's app must have the bundle id `dev.skryx.draftcraft` and the +release's version. Keep those names, that folder and `SHA256SUMS.txt`, or installed copies can no +longer update themselves (they then offer the release page instead). + ## 3. A macOS build on your own Mac The release doesn't need it, but the same script makes the DMG locally (Apple-silicon Mac with Xcode):