Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

feat: startup update prompt modal and direct self-updating (#4654)

Dylan M. Taylor86a4120ae093
diff --git a/Cargo.lock b/Cargo.lock
index 0a7e03a82..947dfb0c8 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1181,6 +1181,31 @@ dependencies = [
"serde",
]
+[[package]]
+name = "craft-update"
+version = "0.1.0"
+source = "git+https://github.com/storytold/craft-libs?rev=db19c373c8d59a545972ca340987aecfb3611a4b#db19c373c8d59a545972ca340987aecfb3611a4b"
+dependencies = [
+ "chrono",
+ "dunce",
+ "egui",
+ "flate2",
+ "getrandom 0.3.4",
+ "log",
+ "plist",
+ "semver",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "tar",
+ "tempfile",
+ "ureq",
+ "verifysign",
+ "winreg",
+ "winsafe",
+ "zip",
+]
+
[[package]]
name = "craft-winprint-gdi"
version = "0.1.0"
@@ -1895,7 +1920,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -3327,7 +3352,7 @@ dependencies = [
"objc2-foundation 0.3.2",
"png 0.18.1",
"thiserror 2.0.21",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -3404,6 +3429,18 @@ dependencies = [
"jni-sys 0.3.1",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "nohash-hasher"
version = "0.2.0"
@@ -3876,7 +3913,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -3971,6 +4008,7 @@ version = "0.14.0"
dependencies = [
"chrono",
"craft-quit",
+ "craft-update",
"eframe",
"egui",
"fmv-macos-events",
@@ -3979,10 +4017,8 @@ dependencies = [
"pdfcraft-ui-egui",
"pollster 1.0.1",
"raw-window-handle",
- "rustls-native-certs",
"serde_json",
"uds_windows",
- "ureq",
"wayland-client",
"wayland-protocols",
"windows",
@@ -4407,6 +4443,7 @@ dependencies = [
"chrono",
"craft-quit",
"craft-ui",
+ "craft-update",
"eframe",
"egui",
"egui_extras",
@@ -5014,7 +5051,7 @@ dependencies = [
"once_cell",
"socket2",
"tracing",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -5551,7 +5588,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.4.15",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -5564,7 +5601,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -5634,7 +5671,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -5763,6 +5800,10 @@ name = "semver"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+dependencies = [
+ "serde",
+ "serde_core",
+]
[[package]]
name = "send_wrapper"
@@ -6295,7 +6336,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -6517,7 +6558,7 @@ dependencies = [
"getrandom 0.4.3",
"once_cell",
"rustix 1.1.5",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -6877,6 +6918,12 @@ dependencies = [
"rustc-hash 2.1.3",
]
+[[package]]
+name = "typed-path"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e"
+
[[package]]
name = "typeid"
version = "1.0.3"
@@ -6897,7 +6944,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
dependencies = [
"memoffset",
"tempfile",
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -6970,10 +7017,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc"
dependencies = [
"base64 0.23.1",
+ "flate2",
"log",
"percent-encoding",
"rustls",
"rustls-pki-types",
+ "rustls-platform-verifier",
"ureq-proto",
"utf8-zero",
]
@@ -7125,6 +7174,16 @@ dependencies = [
"vello_common 0.2.0",
]
+[[package]]
+name = "verifysign"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6acfcc42a8d44f340d001193d97ef56bf33210b51ad760ae8308c97d5241ca51"
+dependencies = [
+ "core-foundation 0.10.1",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "version_check"
version = "0.9.5"
@@ -7611,7 +7670,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.60.2",
]
[[package]]
@@ -7735,6 +7794,15 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets 0.52.6",
+]
+
[[package]]
name = "windows-sys"
version = "0.60.2"
@@ -7971,6 +8039,16 @@ dependencies = [
"xml",
]
+[[package]]
+name = "winreg"
+version = "0.55.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "winresource"
version = "0.1.31"
@@ -8384,6 +8462,23 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "zip"
+version = "9.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2886b00003a72c4ccee3f42cfc34908d33b2508a74d827dc2a4244706475c704"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "getrandom 0.4.3",
+ "indexmap",
+ "memchr",
+ "nix",
+ "typed-path",
+ "windows-sys 0.61.2",
+ "zopfli",
+]
+
[[package]]
name = "zlib-rs"
version = "0.6.8"
@@ -8396,6 +8491,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+[[package]]
+name = "zopfli"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
[[package]]
name = "zune-core"
version = "0.5.3"
diff --git a/Cargo.toml b/Cargo.toml
index cb69da41a..39d11d1ea 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -20,6 +20,7 @@ craft-quit = { git = "https://github.com/storytold/craft-libs", version = "0.1.0
craft-print = { git = "https://github.com/storytold/craft-libs", version = "0.1.0", rev = "42e30cd5b3f4b114270dd053fccbc33bedc47f68" }
# Whether a path stored in a document may be opened (GoToR link targets).
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "82a24b006eefa036b43c09a67fb9a3fbd17ffe63" }
+craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "db19c373c8d59a545972ca340987aecfb3611a4b", features = ["egui"] }
# internal
pdfcraft-geom = { path = "crates/geom", version = "0.14.0" }
pdfcraft-filters = { path = "crates/filters", version = "0.14.0" }
diff --git a/apps/pdfcraft/Cargo.toml b/apps/pdfcraft/Cargo.toml
index 02d6bc56c..15ec5d6f6 100644
--- a/apps/pdfcraft/Cargo.toml
+++ b/apps/pdfcraft/Cargo.toml
@@ -11,8 +11,6 @@ workspace = true
[dependencies]
# Help ▸ Check for updates (issue #28): one HTTPS request to GitHub, over rustls with the OS's
# trusted roots. No bundled root list (webpki-roots and webpki-root-certs are CDLA-licensed).
-ureq = { version = "3.4", default-features = false, features = ["rustls-no-provider", "_ring"] }
-rustls-native-certs = "0.8"
pdfcraft-ui-egui = { workspace = true }
# `build_info`: the version and compile-time build label for `--version` and the log.
pdfcraft-engine = { workspace = true }
@@ -71,3 +69,6 @@ uds_windows = "=1.2.1"
[build-dependencies]
# Icon + VERSIONINFO for pdfcraft.exe; build.rs only uses it when targeting Windows.
winresource = "0.1"
+
+[target.'cfg(windows)'.dependencies]
+craft-update = { workspace = true }
diff --git a/apps/pdfcraft/src/main.rs b/apps/pdfcraft/src/main.rs
index 8bc4d32f7..ab6ebf830 100644
--- a/apps/pdfcraft/src/main.rs
+++ b/apps/pdfcraft/src/main.rs
@@ -41,7 +41,6 @@ mod reopen;
mod settings;
mod single_instance;
mod text_scale;
-mod updates;
#[cfg(test)]
#[path = "windows_manifest.rs"]
mod windows_manifest;
@@ -195,6 +194,11 @@ fn rejoin_split_paths(args: Vec<String>, exists: impl Fn(&str) -> bool) -> Vec<S
}
fn main() -> eframe::Result {
+ // Windows: the update helper is a copy of this program started with `--finish-update`.
+ #[cfg(windows)]
+ if let Some(result) = craft_update::self_update::finish(&craft_update::suite::PDFCRAFT, &std::env::args_os().skip(1).collect::<Vec<_>>()) {
+ std::process::exit(i32::from(result.is_err()));
+ }
// First, so the panic hook and every start-up warning are recorded (`logging`).
let logger = logging::install();
// Last-resort guard (AGENTS.md §4): commands, edits, opens and saves catch panics and report
@@ -419,7 +423,7 @@ fn app_creator<'a>(
{
app.motion.source = Some(motion::source());
}
- app.update_source = Some(std::sync::Arc::new(updates::latest_release));
+ app.set_startup_update_check(true);
app.printer_source = Some(pdfcraft_ui_egui::system_printers());
app.os_key_store_ids = cfg!(any(target_os = "macos", target_os = "windows"));
#[cfg(target_os = "macos")]
diff --git a/apps/pdfcraft/src/updates.rs b/apps/pdfcraft/src/updates.rs
deleted file mode 100644
index 686c8cee8..000000000
--- a/apps/pdfcraft/src/updates.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-//! Asks GitHub for the latest PdfCraft release (Help ▸ Check for updates, issue #28).
-
-use std::time::Duration;
-
-use pdfcraft_ui_egui::updates::{RELEASES_PAGE, Release};
-
-const LATEST: &str = "https://api.github.com/repos/storytold/pdfcraft/releases/latest";
-
-/// The latest release. The answer is untrusted: its size is capped, and only a page under
-/// [`RELEASES_PAGE`] is ever offered for download (anything else falls back to that list).
-pub fn latest_release() -> Result<Release, String> {
- let agent = ureq::Agent::config_builder()
- .timeout_global(Some(Duration::from_secs(10)))
- .tls_config(ureq::tls::TlsConfig::builder().root_certs(os_roots()?).build())
- .build()
- .new_agent();
- let mut response = agent
- .get(LATEST)
- .header("Accept", "application/vnd.github+json")
- .header("User-Agent", concat!("PdfCraft/", env!("CARGO_PKG_VERSION")))
- // Read error statuses ourselves: a 403 from GitHub usually means its anonymous
- // rate limit ran out, and the retry time rides along in a response header.
- .config()
- .http_status_as_error(false)
- .build()
- .call()
- .map_err(|e| format!("couldn't reach GitHub ({e})"))?;
- let status = response.status().as_u16();
- if status == 403 {
- let reset = response.headers().get("x-ratelimit-reset").and_then(|v| v.to_str().ok());
- return Err(rate_limited(reset, now_unix()));
- }
- if !(200..300).contains(&status) {
- return Err(format!("couldn't reach GitHub (http status: {status})"));
- }
- let body = response.body_mut().with_config().limit(1 << 20).read_to_string().map_err(|e| format!("unreadable answer ({e})"))?;
- parse(&body)
-}
-
-/// The certificate authorities the operating system trusts.
-fn os_roots() -> Result<ureq::tls::RootCerts, String> {
- let found = rustls_native_certs::load_native_certs();
- let certs: Vec<ureq::tls::Certificate<'static>> = found.certs.iter().map(|c| ureq::tls::Certificate::from_der(c.as_ref()).to_owned()).collect();
- if certs.is_empty() {
- return Err("no trusted certificates found on this system".into());
- }
- Ok(ureq::tls::RootCerts::new_with_certs(&certs))
-}
-
-/// The current Unix time in seconds (0 when the clock gives nothing usable).
-fn now_unix() -> u64 {
- std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
-}
-
-/// What to tell the user when GitHub answers 403: its anonymous quota (60 checks an hour,
-/// shared by everyone behind the same address) ran out. `reset` is the `x-ratelimit-reset`
-/// header, the Unix time the quota refills; `now` is the current Unix time. Anything
-/// surprising (no header, not a number, already past) falls back to asking for patience.
-fn rate_limited(reset: Option<&str>, now: u64) -> String {
- const FALLBACK: &str = "GitHub is limiting update checks for now (shared hourly quota); try again later";
- let wait = reset.and_then(|r| r.trim().parse::<u64>().ok()).and_then(|reset| reset.checked_sub(now)).filter(|&wait| wait > 0);
- match wait {
- Some(wait) => {
- let minutes = wait.div_ceil(60).max(1);
- let plural = if minutes == 1 { "" } else { "s" };
- format!("GitHub is limiting update checks for now (shared hourly quota); try again in about {minutes} minute{plural}")
- }
- None => FALLBACK.into(),
- }
-}
-
-fn parse(body: &str) -> Result<Release, String> {
- let v: serde_json::Value = serde_json::from_str(body).map_err(|e| format!("unreadable answer ({e})"))?;
- let version = v["tag_name"].as_str().filter(|t| !t.is_empty() && t.len() <= 64).ok_or("no release found")?.to_string();
- let url = v["html_url"]
- .as_str()
- .filter(|u| u.strip_prefix(RELEASES_PAGE).is_some_and(|rest| rest.starts_with('/') && !rest.contains(['?', '#', '\\'])))
- .unwrap_or(RELEASES_PAGE)
- .to_string();
- Ok(Release { version, url })
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn answers_are_read_and_only_our_release_pages_are_offered() {
- let r = parse(r#"{"tag_name":"v0.2.0","html_url":"https://github.com/storytold/pdfcraft/releases/tag/v0.2.0"}"#).unwrap();
- assert_eq!(r, Release { version: "v0.2.0".into(), url: "https://github.com/storytold/pdfcraft/releases/tag/v0.2.0".into() });
- for elsewhere in ["https://example.com/pdfcraft.exe", "https://github.com/storytold/pdfcraft/releases.evil/x", "javascript:alert(1)"] {
- let r = parse(&format!(r#"{{"tag_name":"v9.9.9","html_url":"{elsewhere}"}}"#)).unwrap();
- assert_eq!(r.url, RELEASES_PAGE, "{elsewhere}");
- }
- assert!(parse(r#"{"message":"Not Found"}"#).is_err());
- assert!(parse("<html>").is_err());
- }
-
- #[test]
- fn rate_limit_messages_name_the_wait() {
- let limited = "GitHub is limiting update checks for now (shared hourly quota); try again in about 20 minutes";
- assert_eq!(rate_limited(Some("1800001200"), 1800000000), limited);
- // Rounds up: 61 seconds out reads as 2 minutes.
- assert_eq!(
- rate_limited(Some("1800000061"), 1800000000),
- "GitHub is limiting update checks for now (shared hourly quota); try again in about 2 minutes"
- );
- assert_eq!(
- rate_limited(Some("1800000060"), 1800000000),
- "GitHub is limiting update checks for now (shared hourly quota); try again in about 1 minute"
- );
- // No header, not a number, or already past: ask for patience instead of a time.
- let later = "GitHub is limiting update checks for now (shared hourly quota); try again later";
- for bad in [None, Some(""), Some("soon"), Some("1799999999"), Some("1800000000")] {
- assert_eq!(rate_limited(bad, 1800000000), later);
- }
- }
-
- /// Live: asks GitHub over TLS with the OS's roots (`cargo test -p pdfcraft -- --ignored`).
- #[test]
- #[ignore = "needs network access"]
- fn github_answers_with_the_latest_release() {
- let r = latest_release().unwrap();
- assert!(pdfcraft_ui_egui::updates::is_newer(&r.version, "0.0.0"), "{r:?}");
- assert!(r.url.starts_with(RELEASES_PAGE), "{r:?}");
- }
-}
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index b155d117b..c09625499 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -42,6 +42,7 @@ unicode-bidi = "0.3"
skrifa = "0.44"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+craft-update = { workspace = true }
# Control-channel tokens.
getrandom = "0.4"
# Create ▸ Clipboard (images; already in the tree through egui-winit).
@@ -83,6 +84,7 @@ js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "HtmlIFrameElement", "HtmlImageElement", "HtmlCollection", "Node", "EventTarget", "Navigator"] }
[dev-dependencies]
+craft-update = { workspace = true }
pdfcraft-xfa = { workspace = true }
egui_kittest = { workspace = true, features = ["eframe", "wgpu"] }
# Tests draw PdfCraft text without a system provider: the bundled and monochrome emoji faces must
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index d4ee683d4..79f46bee7 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -700,7 +700,6 @@ pub struct PdfCraftApp {
pub fill_text_size: f64,
pub dialog: Option<Dialog>,
/// How to ask for the latest release (the desktop app sets it; see `updates`).
- pub update_source: Option<updates::UpdateSource>,
pub(crate) updates: updates::Updates,
/// Lists the Print dialog's printers in the background (the desktop app sets it; see
/// [`PrinterSource`]).
@@ -1137,7 +1136,6 @@ impl PdfCraftApp {
flatten_fill_sign_on_save: false,
fill_text_size: fill_sign::TEXT_SIZE,
dialog: None,
- update_source: None,
updates: updates::Updates::default(),
printer_source: None,
options_source: None,
diff --git a/crates/ui-egui/src/updates.rs b/crates/ui-egui/src/updates.rs
index 4e7957e15..fa59f9a89 100644
--- a/crates/ui-egui/src/updates.rs
+++ b/crates/ui-egui/src/updates.rs
@@ -1,12 +1,8 @@
-//! Help ▸ Check for updates (issue #28): ask for the latest release and offer its download page.
-//!
-//! The desktop app supplies how to ask ([`PdfCraftApp::update_source`]), so this crate has no
-//! network code; without a source (the web build, tests) the command opens the releases page.
-//! PdfCraft never downloads or installs anything itself: the user downloads the new version.
-//! It asks only when the user does: there is no check at start (the owner's decision).
-
-use std::sync::Arc;
+//! Help ▸ Check for updates and the check at start, through `craft_update`: the flow itself is its
+//! `Updater`; this module supplies the suite, the quit path and the status dialog.
+#[cfg(not(target_arch = "wasm32"))]
+use craft_update::updater::{Action, CheckSource, Status, Updater};
use egui::{Align, Layout};
use crate::{PdfCraftApp, theme, widgets};
@@ -14,108 +10,102 @@ use crate::{PdfCraftApp, theme, widgets};
/// Where every PdfCraft release is listed.
pub const RELEASES_PAGE: &str = "https://github.com/storytold/pdfcraft/releases";
-/// The latest published release.
-#[derive(Clone, Debug, PartialEq, Eq)]
-pub struct Release {
- /// Its version tag, such as `v0.2.0`.
- pub version: String,
- /// Its page on [`RELEASES_PAGE`], where the downloads are.
- pub url: String,
-}
-
-/// Asks for the latest release (blocking; it runs on its own thread).
-pub type UpdateSource = Arc<dyn Fn() -> Result<Release, String> + Send + Sync>;
+/// Stands in for the network in tests.
+#[cfg(not(target_arch = "wasm32"))]
+pub type UpdateSource = CheckSource;
-/// Whether release `latest` (a tag such as `v0.2.0`) is newer than version `current` (`0.1.1`).
-/// Pre-release and build suffixes are ignored; a version that doesn't parse is never newer.
-pub fn is_newer(latest: &str, current: &str) -> bool {
- matches!((parse(latest), parse(current)), (Some(l), Some(c)) if l > c)
+pub(crate) struct Updates {
+ #[cfg(not(target_arch = "wasm32"))]
+ updater: Updater,
+ /// The Updates dialog is showing.
+ pub(crate) open: bool,
+ /// Ask for a newer release at start; the desktop app turns it on, so tests never reach the network.
+ #[cfg(not(target_arch = "wasm32"))]
+ startup_check: bool,
+ #[cfg(not(target_arch = "wasm32"))]
+ check_requested: bool,
}
-fn parse(v: &str) -> Option<(u64, u64, u64)> {
- let v = v.trim().trim_start_matches(['v', 'V']);
- let core = v.split(['-', '+']).next()?;
- let mut parts = core.split('.');
- let mut next = |required: bool| match parts.next() {
- Some(p) => p.parse::<u64>().ok(),
- None if required => None,
- None => Some(0),
- };
- let version = (next(true)?, next(false)?, next(false)?);
- parts.next().is_none().then_some(version)
+impl Default for Updates {
+ fn default() -> Self {
+ Self {
+ #[cfg(not(target_arch = "wasm32"))]
+ updater: Updater::new(&craft_update::suite::PDFCRAFT, env!("CARGO_PKG_VERSION")),
+ open: false,
+ #[cfg(not(target_arch = "wasm32"))]
+ startup_check: false,
+ #[cfg(not(target_arch = "wasm32"))]
+ check_requested: false,
+ }
+ }
}
-/// Where a check is.
-#[derive(Default)]
-pub(crate) enum Check {
- #[default]
- Idle,
+impl PdfCraftApp {
+ /// Whether the app asks for a newer release on its first frame (off until the desktop app turns it on).
#[cfg(not(target_arch = "wasm32"))]
- Running(std::sync::mpsc::Receiver<Result<Release, String>>),
- Done(Result<Release, String>),
-}
+ pub fn set_startup_update_check(&mut self, on: bool) {
+ self.updates.startup_check = on;
+ }
-#[derive(Default)]
-pub(crate) struct Updates {
- pub(crate) check: Check,
- /// The Updates dialog is showing.
- pub(crate) open: bool,
-}
+ /// Replaces the network with `source` (tests).
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn set_update_source(&mut self, source: UpdateSource) {
+ self.updates.updater = Updater::new(&craft_update::suite::PDFCRAFT, env!("CARGO_PKG_VERSION")).with_source(source);
+ }
-impl PdfCraftApp {
/// Help ▸ Check for updates: ask for the latest release and show the outcome.
pub fn check_for_updates(&mut self) {
- let Some(source) = self.update_source.clone() else {
- self.open_url(RELEASES_PAGE);
- return;
- };
#[cfg(not(target_arch = "wasm32"))]
{
self.updates.open = true;
- if matches!(self.updates.check, Check::Running(_)) {
- return;
- }
- let (tx, rx) = std::sync::mpsc::channel();
- let ctx = self.ctx.clone();
- std::thread::spawn(move || {
- // The receiver may be gone (the app quit): nothing to report to then.
- let _ = tx.send(source());
- if let Some(ctx) = ctx {
- ctx.request_repaint();
- }
- });
- self.updates.check = Check::Running(rx);
+ self.updates.check_requested = true;
}
#[cfg(target_arch = "wasm32")]
{
- let _ = source;
self.open_url(RELEASES_PAGE);
}
}
- /// Pick up a finished check (each frame).
+ /// Starts the checks and picks up their answers (each frame).
pub(crate) fn poll_updates(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
- if let Check::Running(rx) = &self.updates.check {
- let result = match rx.try_recv() {
- Ok(r) => r,
- Err(std::sync::mpsc::TryRecvError::Empty) => return,
- Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("the update check stopped unexpectedly".into()),
- };
- self.updates.check = Check::Done(result);
+ {
+ let Some(ctx) = self.ctx.clone() else { return };
+ let updates = &mut self.updates;
+ if std::mem::take(&mut updates.check_requested) {
+ updates.updater.check_now(&ctx);
+ } else if updates.startup_check {
+ updates.updater.check_at_start(&ctx);
+ }
+ updates.updater.tick(&ctx);
}
}
}
-/// The Updates dialog.
+/// The startup prompt, and the Updates dialog that answers Help ▸ Check for updates.
pub(crate) fn dialog(app: &mut PdfCraftApp, ctx: &egui::Context) {
+ #[cfg(not(target_arch = "wasm32"))]
+ {
+ // The restart helper is scheduled before the app closes, so no update starts over unsaved work.
+ let clean = app.first_dirty().is_none();
+ match app.updates.updater.show_if(ctx, clean) {
+ Action::None => {}
+ Action::OpenUrl(url) => app.open_url(&url),
+ Action::Close => {
+ app.request_quit(ctx);
+ }
+ }
+ // A requested check that found a release is answered by the prompt, not by this dialog.
+ if app.updates.open && !app.updates.check_requested && matches!(app.updates.updater.status(), Status::Idle) {
+ app.updates.open = false;
+ }
+ }
if !app.updates.open {
return;
}
let t = theme::Tokens::get(ctx);
let current = env!("CARGO_PKG_VERSION");
let mut close = false;
- let mut download: Option<String> = None;
let modal = crate::widgets::show_modal(ctx, "updates", |ui| {
ui.set_width(420.0);
ui.horizontal(|ui| {
@@ -123,34 +113,25 @@ pub(crate) fn dialog(app: &mut PdfCraftApp, ctx: &egui::Context) {
ui.label(egui::RichText::new(tl!("Check for updates")).font(theme::semibold(16.0)));
});
ui.add_space(8.0);
- match &app.updates.check {
- Check::Idle => {
- ui.label(tl!("No check has run yet."));
- }
- #[cfg(not(target_arch = "wasm32"))]
- Check::Running(_) => {
+ #[cfg(not(target_arch = "wasm32"))]
+ match app.updates.updater.status() {
+ Status::Idle => {
ui.horizontal(|ui| {
ui.spinner();
ui.label(tl!("Checking for a newer version…"));
});
}
- Check::Done(Ok(r)) if is_newer(&r.version, current) => {
- let version = r.version.trim_start_matches(['v', 'V']);
- ui.label(egui::RichText::new(crate::i18n::fmt(tl!("PdfCraft {v} is available."), &[("v", version)])).strong());
- ui.label(
- egui::RichText::new(crate::i18n::fmt(
- tl!("You have version {c}. Download the new version from its release page."),
- &[("c", current)],
- ))
- .color(t.text_muted),
- );
- download = Some(r.url.clone());
+ Status::Checking => {
+ ui.horizontal(|ui| {
+ ui.spinner();
+ ui.label(tl!("Checking for a newer version…"));
+ });
}
- Check::Done(Ok(_)) => {
+ Status::UpToDate => {
ui.label(crate::i18n::fmt(tl!("PdfCraft {c} is up to date."), &[("c", current)]));
}
- Check::Done(Err(e)) => {
- ui.label(crate::i18n::fmt(tl!("Couldn't check for updates: {e}"), &[("e", &e.to_string())]));
+ Status::Failed(e) => {
+ ui.label(crate::i18n::fmt(tl!("Couldn't check for updates: {e}"), &[("e", e)]));
ui.label(
egui::RichText::new(crate::i18n::fmt(
tl!("You have version {c}. All releases are listed at {page}."),
@@ -160,32 +141,21 @@ pub(crate) fn dialog(app: &mut PdfCraftApp, ctx: &egui::Context) {
);
}
}
+ #[cfg(target_arch = "wasm32")]
+ let _ = (&t, current);
ui.add_space(10.0);
- ui.label(
- egui::RichText::new(tl!("Asks GitHub for the latest release. Nothing is downloaded or installed automatically."))
- .color(t.text_muted)
- .small(),
- );
- ui.add_space(12.0);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
- if let Some(url) = download.take() {
- let get = widgets::pill_button(ui, tl!("Download"), true).clicked();
- let later = widgets::pill_button(ui, tl!("Later"), false).clicked();
- close = get || later;
- download = get.then_some(url);
- } else if widgets::pill_button(ui, tl!("Close"), true).clicked() {
+ if widgets::pill_button(ui, tl!("Close"), true).clicked() {
close = true;
}
});
});
if modal.should_close() {
close = true;
- download = None;
}
if close {
app.updates.open = false;
- if let Some(url) = download {
- app.open_url(&url);
- }
+ #[cfg(not(target_arch = "wasm32"))]
+ app.updates.updater.dismiss_status();
}
}
diff --git a/crates/ui-egui/tests/it/updates.rs b/crates/ui-egui/tests/it/updates.rs
index a8ecb31c5..d2eaa7c66 100644
--- a/crates/ui-egui/tests/it/updates.rs
+++ b/crates/ui-egui/tests/it/updates.rs
@@ -5,18 +5,28 @@ use std::sync::Arc;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use pdfcraft_ui_egui::PdfCraftApp;
-use pdfcraft_ui_egui::updates::{Release, UpdateSource, is_newer};
+use pdfcraft_ui_egui::updates::UpdateSource;
-fn source(answer: Result<&str, &str>) -> UpdateSource {
- let answer = answer.map(str::to_string).map_err(str::to_string);
- Arc::new(move || answer.clone().map(|v| Release { url: format!("https://github.com/storytold/pdfcraft/releases/tag/{v}"), version: v }))
+fn release(tag: &str) -> craft_update::Release {
+ craft_update::Release {
+ tag: tag.to_string(),
+ version: craft_update::parse_version(tag),
+ html_url: format!("https://github.com/storytold/pdfcraft/releases/tag/{tag}"),
+ ..Default::default()
+ }
+}
+
+/// `Ok(Some(tag))` is a newer release, `Ok(None)` is up to date.
+fn source(answer: Result<Option<&str>, &str>) -> UpdateSource {
+ let answer = answer.map(|tag| tag.map(release)).map_err(str::to_string);
+ Arc::new(move || answer.clone())
}
-fn harness(answer: Result<&str, &str>) -> Harness<'static, PdfCraftApp> {
+fn harness(answer: Result<Option<&str>, &str>) -> Harness<'static, PdfCraftApp> {
Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
let mut app = PdfCraftApp::new();
app.set_option("language", "en").unwrap();
- app.update_source = Some(source(answer));
+ app.set_update_source(source(answer));
app
})
}
@@ -37,34 +47,21 @@ fn settle(h: &mut Harness<'static, PdfCraftApp>) {
h.run_steps(2);
}
-#[test]
-fn versions_compare_by_number() {
- assert!(is_newer("v0.2.0", "0.1.1"));
- assert!(is_newer("v0.1.10", "0.1.9"));
- assert!(is_newer("1", "0.9.9"));
- assert!(!is_newer("v0.1.1", "0.1.1"));
- assert!(!is_newer("v0.1.0", "0.1.1"));
- assert!(!is_newer("v0.1.1-beta.2", "0.1.1"), "suffixes are ignored");
- assert!(!is_newer("nightly", "0.1.1"), "a tag that isn't a version is never newer");
- assert!(!is_newer("v1.2.3.4", "0.1.1"));
- assert!(!is_newer("v99999999999999999999.0.0", "0.1.1"), "out of range");
-}
-
#[test]
fn a_newer_release_is_offered_for_download() {
- let mut h = harness(Ok("v99.0.0"));
+ let mut h = harness(Ok(Some("v99.0.0")));
h.state_mut().execute("help.check_updates");
settle(&mut h);
h.get_by_label_contains("PdfCraft 99.0.0 is available");
- h.get_by_label("Download");
- h.get_by_label("Later").click();
+ h.get_by_label("DOWNLOAD");
+ h.get_by_label("LATER").click();
h.run_steps(3);
assert!(h.query_by_label_contains("is available").is_none(), "Later closes the dialog");
}
#[test]
fn an_up_to_date_or_failed_check_says_so() {
- let mut h = harness(Ok(concat!("v", env!("CARGO_PKG_VERSION"))));
+ let mut h = harness(Ok(None));
h.state_mut().execute("help.check_updates");
settle(&mut h);
h.get_by_label_contains("is up to date");
@@ -78,7 +75,7 @@ fn an_up_to_date_or_failed_check_says_so() {
#[test]
fn nothing_is_asked_until_the_user_checks() {
- // No check at start (the owner's decision): the source is only called from the command.
+ // The check at start is opt-in (the desktop app turns it on): the source is only called from the command.
let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let counted = calls.clone();
let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(move |_cc| {
@@ -87,9 +84,9 @@ fn nothing_is_asked_until_the_user_checks() {
// Settings from a build that had the startup option are ignored.
app.restore(r#"{"check_updates_at_start": true}"#);
let counted = counted.clone();
- app.update_source = Some(Arc::new(move || {
+ app.set_update_source(Arc::new(move || {
counted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
- Ok(Release { version: "v99.0.0".into(), url: "https://github.com/storytold/pdfcraft/releases/tag/v99.0.0".into() })
+ Ok(Some(release("v99.0.0")))
}));
app
});
@@ -101,3 +98,23 @@ fn nothing_is_asked_until_the_user_checks() {
assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
h.get_by_label_contains("PdfCraft 99.0.0 is available");
}
+
+#[test]
+fn the_check_at_start_offers_the_prompt_and_later_dismisses_it() {
+ let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_eframe(|_cc| {
+ let mut app = PdfCraftApp::new();
+ app.set_option("language", "en").unwrap();
+ app.set_update_source(source(Ok(Some("v99.0.0"))));
+ app.set_startup_update_check(true);
+ app
+ });
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
+ while h.query_by_label_contains("is available").is_none() {
+ h.run_steps(2);
+ assert!(std::time::Instant::now() < deadline, "timed out waiting for the startup prompt");
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ h.get_by_label("LATER").click();
+ h.run_steps(3);
+ assert!(h.query_by_label_contains("is available").is_none(), "Later closes the prompt");
+}
diff --git a/parity/acrobat-features.toml b/parity/acrobat-features.toml
index 8d2f3ecf6..cbbb96da6 100644
--- a/parity/acrobat-features.toml
+++ b/parity/acrobat-features.toml
@@ -1778,8 +1778,8 @@ milestone = "M3"
status = "partial"
commands = ["help.check_updates"]
tools = []
-evidence = ["crates/ui-egui/tests/it/updates.rs::a_newer_release_is_offered_for_download", "crates/ui-egui/tests/it/updates.rs::nothing_is_asked_until_the_user_checks", "apps/pdfcraft/src/updates.rs::answers_are_read_and_only_our_release_pages_are_offered"]
-notes = "asks GitHub Releases on request and offers the release page. By the owner's decision there is no check at start and no in-place install (Acrobat has both)"
+evidence = ["crates/ui-egui/tests/it/updates.rs::a_newer_release_is_offered_for_download", "crates/ui-egui/tests/it/updates.rs::an_up_to_date_or_failed_check_says_so", "crates/ui-egui/tests/it/updates.rs::the_check_at_start_offers_the_prompt_and_later_dismisses_it", "crates/ui-egui/tests/it/updates.rs::nothing_is_asked_until_the_user_checks"]
+notes = "asks GitHub Releases through craft-update at start (desktop app only) and on request, offers the release page, and updates and restarts in place where the install type allows it; an install waits while documents are unsaved"
[[feature]]
id = "view.single-key-accelerators"