Updates: opt-in launch check, Check for Updates…, install after a normal quit, from the Gitea release; dmgs carry an Applications link (UPD-1, REL-1)

This commit is contained in:
ZacharyZhang-NY committed 2026-10-09 16:34:32 -04:00
1 parent fa273aff13
commit b03c9f2853
28 files changed
+896 -16

No files matched your search

+6
View File
@@ -68,6 +68,12 @@ pub trait Closing: Host {
});
}
/// A close or quit stopped: no update installs on it.
fn close_stopped(&mut self, cx: &mut Context<Self>) {
ely_ui::updates::quit_stopped(cx);
self.close_cancelled(cx);
}
fn no_document(&self, cx: &mut Context<Self>) {
let text = text(cx, "command.blocked.no_document", &[]);
self.toast(text, Severity::Warning, cx);
+3 -3
View File
@@ -87,7 +87,7 @@ pub trait Dialogs: Host {
// Cancel stops the whole close.
let cancelled = move |window: &mut Window, cx: &mut App| {
owner.update(cx, |host, cx| {
host.close_cancelled(cx);
host.close_stopped(cx);
host.dialog_done(window, cx)
})
};
@@ -119,7 +119,7 @@ pub trait Dialogs: Host {
let cancelled = move |window: &mut Window, cx: &mut App| {
owner.update(cx, |host, cx| {
if then.is_some() {
host.close_cancelled(cx);
host.close_stopped(cx);
}
host.dialog_done(window, cx)
})
@@ -135,7 +135,7 @@ pub trait Dialogs: Host {
move |host, _, cx| {
// Reloading ends the close that waited.
if then.is_some() {
host.close_cancelled(cx);
host.close_stopped(cx);
}
host.reload(tab, cx)
},
+2 -2
View File
@@ -190,7 +190,7 @@ pub trait Saving: Host {
}
// No save: a close that waited on it stops.
if then.is_some() {
host.close_cancelled(cx);
host.close_stopped(cx);
}
})
})
@@ -419,7 +419,7 @@ pub trait Saving: Host {
failed => {
self.report(id, failed, cx);
if then.is_some() {
self.close_cancelled(cx);
self.close_stopped(cx);
}
}
}
+160
View File
@@ -0,0 +1,160 @@
//! Puts a downloaded release in place of the running app.
use std::{
io,
path::{Path, PathBuf},
process::{Command, Stdio},
};
/// The `.app` running this process; none in dev builds.
pub fn running_bundle() -> io::Result<Option<PathBuf>> {
let exe = std::env::current_exe()?;
Ok(bundle_of(&exe).map(Path::to_path_buf))
}
fn bundle_of(exe: &Path) -> Option<&Path> {
exe.ancestors().find(|dir| dir.extension().is_some_and(|ext| ext == "app"))
}
/// Replaces `bundle` with the same-named app inside `dmg`.
#[cfg(target_os = "macos")]
pub fn install(dmg: &Path, bundle: &Path) -> io::Result<()> {
let name = bundle.file_name().ok_or_else(|| io::Error::other("the app has no name"))?;
let parent = bundle.parent().ok_or_else(|| io::Error::other("the app has no folder"))?;
let mount = tempfile::tempdir()?;
run(Command::new("hdiutil").args(["attach", "-nobrowse", "-readonly", "-noautoopen", "-mountpoint"]).arg(mount.path()).arg(dmg))?;
let copied = stage(&mount.path().join(name), parent, name);
let detached = run(Command::new("hdiutil").args(["detach", "-force"]).arg(mount.path()));
let staged = copied?;
detached?;
swap(&staged, bundle)
}
#[cfg(not(target_os = "macos"))]
pub fn install(_dmg: &Path, _bundle: &Path) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "installing updates is not built for this platform"))
}
/// Copies the new app beside the old, hidden.
#[cfg(target_os = "macos")]
fn stage(from: &Path, parent: &Path, name: &std::ffi::OsStr) -> io::Result<PathBuf> {
if !from.is_dir() {
return Err(io::Error::new(io::ErrorKind::NotFound, format!("the download holds no {}", name.to_string_lossy())));
}
let staged = parent.join(format!(".{}.new", name.to_string_lossy()));
if staged.exists() {
std::fs::remove_dir_all(&staged)?;
}
run(Command::new("ditto").arg(from).arg(&staged))?;
Ok(staged)
}
/// Puts `staged` at `bundle`; on failure the old returns.
fn swap(staged: &Path, bundle: &Path) -> io::Result<()> {
let name = bundle.file_name().ok_or_else(|| io::Error::other("the app has no name"))?;
let old = bundle.with_file_name(format!(".{}.old", name.to_string_lossy()));
if old.exists() {
std::fs::remove_dir_all(&old)?;
}
std::fs::rename(bundle, &old)?;
if let Err(error) = std::fs::rename(staged, bundle) {
std::fs::rename(&old, bundle)?;
return Err(error);
}
log::info!("install: {} replaced", bundle.display());
// Installed: an old copy left behind is only untidy.
if let Err(error) = std::fs::remove_dir_all(&old) {
log::warn!("install: the old copy at {} stays: {error}", old.display());
}
Ok(())
}
/// Returns once process `pid` has ended.
#[cfg(unix)]
pub fn wait_for_exit(pid: u32) {
while unsafe { libc::kill(pid as libc::pid_t, 0) } == 0 {
std::thread::sleep(std::time::Duration::from_millis(200));
}
}
#[cfg(not(unix))]
pub fn wait_for_exit(_pid: u32) {}
/// Opens `bundle` as a fresh launch.
#[cfg(target_os = "macos")]
pub fn reopen(bundle: &Path) -> io::Result<()> {
run(Command::new("open").arg(bundle))
}
#[cfg(not(target_os = "macos"))]
pub fn reopen(_bundle: &Path) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::Unsupported, "reopening after an update is not built for this platform"))
}
/// Runs `command`; a failure carries what it said.
#[cfg(target_os = "macos")]
fn run(command: &mut Command) -> io::Result<()> {
let out = command.stdin(Stdio::null()).output()?;
if out.status.success() {
return Ok(());
}
let said = String::from_utf8_lossy(&out.stderr);
Err(io::Error::other(format!("{:?} failed ({}): {}", command.get_program(), out.status, said.trim())))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_bundle_is_the_nearest_app_folder() {
let exe = Path::new("/Applications/ElyDoc.app/Contents/MacOS/ely-doc");
assert_eq!(bundle_of(exe), Some(Path::new("/Applications/ElyDoc.app")));
assert_eq!(bundle_of(Path::new("/repo/target/debug/ely-doc")), None);
}
#[test]
fn a_swap_replaces_the_app_and_leaves_no_copy() {
let dir = tempfile::tempdir().expect("a temp dir");
let (bundle, staged) = (dir.path().join("ElyDoc.app"), dir.path().join(".ElyDoc.app.new"));
std::fs::create_dir_all(bundle.join("old")).expect("the old app");
std::fs::create_dir_all(staged.join("new")).expect("the new app");
swap(&staged, &bundle).expect("swaps");
assert!(bundle.join("new").exists() && !bundle.join("old").exists());
assert_eq!(std::fs::read_dir(dir.path()).expect("lists").count(), 1, "nothing else is left");
}
#[cfg(target_os = "macos")]
#[test]
fn an_old_copy_that_will_not_go_leaves_the_install_done() {
let dir = tempfile::tempdir().expect("a temp dir");
let (bundle, staged) = (dir.path().join("ElyDoc.app"), dir.path().join(".ElyDoc.app.new"));
std::fs::create_dir_all(&bundle).expect("the old app");
std::fs::write(bundle.join("version"), "old").expect("marks it");
std::fs::create_dir_all(&staged).expect("the new app");
std::fs::write(staged.join("version"), "new").expect("marks it");
run(Command::new("chflags").arg("uchg").arg(bundle.join("version"))).expect("locks a file");
swap(&staged, &bundle).expect("installed although the old copy stays");
assert_eq!(std::fs::read_to_string(bundle.join("version")).expect("reads"), "new");
let old = dir.path().join(".ElyDoc.app.old");
run(Command::new("chflags").arg("nouchg").arg(old.join("version"))).expect("unlocks");
}
#[cfg(target_os = "macos")]
#[test]
fn a_dmg_installs_over_the_app() {
let dir = tempfile::tempdir().expect("a temp dir");
let source = dir.path().join("src");
std::fs::create_dir_all(source.join("ElyDoc.app/Contents")).expect("the new app");
std::fs::write(source.join("ElyDoc.app/Contents/version"), "new").expect("marks it");
let dmg = dir.path().join("ElyDoc.dmg");
run(Command::new("hdiutil").args(["create", "-quiet", "-fs", "HFS+", "-srcfolder"]).arg(&source).arg(&dmg)).expect("a dmg");
let bundle = dir.path().join("Applications/ElyDoc.app");
std::fs::create_dir_all(bundle.join("Contents")).expect("the old app");
std::fs::write(bundle.join("Contents/version"), "old").expect("marks it");
install(&dmg, &bundle).expect("installs");
assert_eq!(std::fs::read_to_string(bundle.join("Contents/version")).expect("reads"), "new");
let empty = dir.path().join("Applications/Other.app");
assert!(install(&dmg, &empty).is_err(), "a dmg without that app is refused");
}
}
+2
View File
@@ -7,12 +7,14 @@ mod dirs;
pub mod env;
pub mod git;
pub mod graphics;
pub mod install;
pub mod instance;
pub mod locale;
pub mod lock;
pub mod logging;
pub mod media;
pub mod print;
pub mod release;
pub mod settings;
pub mod startup;
pub mod storage;
+46
View File
@@ -0,0 +1,46 @@
//! The newest release's files, as the release server lists them.
use anyhow::{Context, Result, bail};
use serde::Deserialize;
#[derive(Deserialize)]
struct Latest {
tag_name: String,
assets: Vec<Asset>,
}
#[derive(Deserialize)]
struct Asset {
name: String,
browser_download_url: String,
}
/// Where the latest release at `api` keeps the file `name`.
pub fn asset_url(api: &str, name: &str) -> Result<String> {
let text = crate::update::fetch(&crate::update::manifest_agent(), api)?
.body_mut()
.with_config()
.limit(1 << 20)
.read_to_string()
.context("cannot read the latest release")?;
asset_in(&text, name)
}
fn asset_in(text: &str, name: &str) -> Result<String> {
let latest: Latest = serde_json::from_str(text).context("the latest release is not valid")?;
match latest.assets.into_iter().find(|asset| asset.name == name) {
Some(asset) => Ok(asset.browser_download_url),
None => bail!("release {} has no {name}", latest.tag_name),
}
}
#[cfg(test)]
mod tests {
#[test]
fn the_named_file_is_found_or_said_missing() {
let text = r#"{"tag_name":"v0.1.2","assets":[{"name":"ely-doc.json","browser_download_url":"https://h/d.json"}]}"#;
assert_eq!(super::asset_in(text, "ely-doc.json").unwrap(), "https://h/d.json");
let missing = super::asset_in(text, "ely-tree.json").unwrap_err().to_string();
assert_eq!(missing, "release v0.1.2 has no ely-tree.json");
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ use serde_json::{Map, Value};
use crate::{AppId, lock::FileLock};
mod shared;
pub use shared::{APPEARANCE, AUTHOR, Appearance, LANGUAGE, Language, MOTION, Motion, OMARCHY_SYNC, Shared, word};
pub use shared::{APPEARANCE, AUTHOR, Appearance, CHECK_UPDATES, LANGUAGE, Language, MOTION, Motion, OMARCHY_SYNC, Shared, word};
/// The layout this build reads and writes.
pub const VERSION: u64 = 1;
@@ -38,6 +38,7 @@ pub const LANGUAGE: &str = "language";
pub const MOTION: &str = "motion";
pub const OMARCHY_SYNC: &str = "omarchy_sync";
pub const AUTHOR: &str = "author";
pub const CHECK_UPDATES: &str = "check_updates";
/// The shared settings; absent fields take their defaults.
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -48,6 +49,8 @@ pub struct Shared {
pub omarchy_sync: bool,
/// Signs comments and changes; empty means the account name.
pub author: String,
/// Asks for a newer release at launch; off unless chosen.
pub check_updates: bool,
}
impl Default for Shared {
@@ -58,6 +61,7 @@ impl Default for Shared {
motion: Motion::System,
omarchy_sync: true,
author: String::new(),
check_updates: false,
}
}
}
@@ -92,6 +96,11 @@ impl Shared {
appearance: pick(fields, APPEARANCE, &Appearance::ALL)?.unwrap_or(defaults.appearance),
language: pick(fields, LANGUAGE, &Language::ALL)?.unwrap_or(defaults.language),
motion: pick(fields, MOTION, &Motion::ALL)?.unwrap_or(defaults.motion),
check_updates: match fields.get(CHECK_UPDATES) {
None => defaults.check_updates,
Some(Value::Bool(on)) => *on,
Some(other) => return Err(wrong(CHECK_UPDATES, other)),
},
omarchy_sync: match fields.get(OMARCHY_SYNC) {
None => defaults.omarchy_sync,
Some(Value::Bool(on)) => *on,
+3 -2
View File
@@ -63,14 +63,15 @@ fn shared_fields_type_strictly_and_default_when_absent() {
let fields = |text: &str| serde_json::from_str::<serde_json::Map<_, _>>(text).unwrap();
assert_eq!(Shared::from_fields(&fields("{}")).unwrap(), Shared::default());
let read = Shared::from_fields(&fields(
r#"{"appearance":"dark","language":"zh-CN","motion":"reduce","omarchy_sync":false,"author":" Ana "}"#,
r#"{"appearance":"dark","language":"zh-CN","motion":"reduce","omarchy_sync":false,"author":" Ana ","check_updates":true}"#,
))
.unwrap();
assert!(read.check_updates && !Shared::default().check_updates, "asked for, never by default");
assert_eq!(
(read.appearance, read.language, read.motion, read.omarchy_sync, read.author.as_str()),
(Appearance::Dark, Language::Chinese, Motion::Reduced, false, "Ana")
);
for bad in [r#"{"appearance":"blue"}"#, r#"{"omarchy_sync":"yes"}"#, r#"{"author":3}"#] {
for bad in [r#"{"appearance":"blue"}"#, r#"{"omarchy_sync":"yes"}"#, r#"{"author":3}"#, r#"{"check_updates":1}"#] {
assert!(Shared::from_fields(&fields(bad)).is_err(), "{bad}");
}
}
+2 -2
View File
@@ -305,7 +305,7 @@ fn secure_host(url: &str) -> Result<String> {
}
/// GETs `url`, following redirects only to places `secure_host` accepts.
fn fetch(agent: &Agent, url: &str) -> Result<Response<Body>> {
pub(crate) fn fetch(agent: &Agent, url: &str) -> Result<Response<Body>> {
let mut url = url.to_string();
for _ in 0..=MAX_REDIRECTS {
secure_host(&url)?;
@@ -335,7 +335,7 @@ fn fetch(agent: &Agent, url: &str) -> Result<Response<Body>> {
bail!("too many redirects")
}
fn manifest_agent() -> Agent {
pub(crate) fn manifest_agent() -> Agent {
Agent::config_builder()
.timeout_global(Some(MANIFEST_TIMEOUT))
.max_redirects(0)
+1
View File
@@ -13,6 +13,7 @@ ely-platform.workspace = true
gpui.workspace = true
directories.workspace = true
futures.workspace = true
semver.workspace = true
gpui_platform.workspace = true
log.workspace = true
notify.workspace = true
+6 -1
View File
@@ -18,6 +18,7 @@ actions!(
CloseTab,
ToggleCommandPalette,
OpenSettings,
CheckForUpdates,
Quit
]
);
@@ -43,7 +44,7 @@ pub fn bind_quit(cx: &mut App) {
}
/// Quits through the main window's route, if one is set.
fn quit(cx: &mut App) {
pub(crate) fn quit(cx: &mut App) {
match cx.try_global::<QuitRoute>().map(|route| Rc::clone(&route.0)) {
Some(route) => route(cx),
None => cx.quit(),
@@ -171,6 +172,10 @@ pub fn menus(
first.push(MenuItem::separator());
}
first.push(MenuItem::action(i18n::text(cx, "menu.app.settings", &[]), OpenSettings));
// Only an installed app can update itself.
if crate::updates::updater(cx).is_some() {
first.push(MenuItem::action(i18n::text(cx, "menu.app.updates", &[]), CheckForUpdates));
}
first.push(MenuItem::separator());
first.push(MenuItem::action(i18n::text(cx, "menu.app.quit", &[("app", app.name())]), Quit));
let mut menus = vec![
+6
View File
@@ -24,6 +24,9 @@ use gpui::{App, SharedString};
const EN: &[(&str, &str)] = &[
("menu.app.quit", "Quit {app}"),
("updates.failed", "The update did not finish: {error}"),
("updates.latest", "{app} {version} is the latest version."),
("menu.app.updates", "Check for Updates…"),
("menu.app.switch", "Open Ely App"),
("toast.open", "Open"),
("toast.open_failed", "The file did not open: {error}"),
@@ -76,6 +79,9 @@ const EN: &[(&str, &str)] = &[
const ZH_CN: &[(&str, &str)] = &[
("menu.app.quit", "退出 {app}"),
("updates.failed", "更新没有完成:{error}"),
("updates.latest", "{app} {version} 已是最新版本。"),
("menu.app.updates", "检查更新…"),
("menu.app.switch", "打开 Ely 应用"),
("toast.open", "打开"),
("toast.open_failed", "文件没能打开:{error}"),
+10
View File
@@ -9,6 +9,11 @@ pub(super) const EN: &[(&str, &str)] = &[
("settings.appearance.light", "Light"),
("settings.appearance.dark", "Dark"),
("settings.omarchy", "Follow Omarchy"),
("settings.updates", "Check for updates at launch"),
(
"settings.updates.hint",
"Off, Ely asks its release server for a newer version only when you choose Check for Updates.",
),
("settings.language", "Language"),
("settings.language.system", "System"),
("settings.language.next", "Applies the next time each app starts"),
@@ -64,6 +69,11 @@ pub(super) const ZH_CN: &[(&str, &str)] = &[
("settings.appearance.light", "浅色"),
("settings.appearance.dark", "深色"),
("settings.omarchy", "跟随 Omarchy"),
("settings.updates", "启动时检查更新"),
(
"settings.updates.hint",
"关闭时,只在你选择“检查更新”时才向发布服务器询问新版本。",
),
("settings.language", "语言"),
("settings.language.system", "跟随系统"),
("settings.language.next", "各应用下次启动时生效"),
+1
View File
@@ -6,6 +6,7 @@ pub mod settings;
mod shell;
pub mod tasks;
mod theme;
pub mod updates;
pub use opening::{launch_files, on_open};
pub use run::run;
+6
View File
@@ -15,6 +15,10 @@ pub fn run<V: Render>(
app: AppId,
root: impl FnOnce(AppId, &mut Window, &mut App) -> Entity<V> + 'static,
) {
// As the installer after an update, nothing else runs.
if let Some(code) = crate::updates::installer(app) {
std::process::exit(code);
}
// Before the log: a second copy must not trim it.
if let Err(error) = ely_platform::instance::hold(app) {
startup::fail(app, &format!("{error}"));
@@ -77,6 +81,8 @@ fn open<V: Render>(
}
theme::install(cx);
crate::i18n::install(cx);
crate::updates::install(app, cx);
cx.on_action(|_: &crate::commands::CheckForUpdates, cx| crate::updates::check_now(cx));
crate::commands::bind_keys(cx);
crate::commands::bind_quit(cx);
cx.on_action(move |_: &crate::commands::OpenSettings, cx| crate::settings::open(app, cx));
+10 -2
View File
@@ -9,7 +9,7 @@ use ely_gpui_component::{
};
use ely_platform::{
AppId,
settings::{APPEARANCE, AUTHOR, Appearance, LANGUAGE, Language, MOTION, Motion, OMARCHY_SYNC, Store, word},
settings::{APPEARANCE, AUTHOR, Appearance, CHECK_UPDATES, LANGUAGE, Language, MOTION, Motion, OMARCHY_SYNC, Store, word},
};
use gpui::{
AppContext as _, Context, Entity, FocusHandle, Global, IntoElement, ParentElement, Render, SharedString, Styled,
@@ -222,7 +222,7 @@ impl SettingsView {
Motion::Reduced => text(cx, "settings.motion.reduce", &[]),
Motion::Full => text(cx, "settings.motion.full", &[]),
}, MOTION, cx);
let mut section = SettingsSection::new(text(cx, "settings.general", &[]))
let section = SettingsSection::new(text(cx, "settings.general", &[]))
.row(SettingsRow::new(text(cx, "settings.appearance", &[])).control(theme))
.row(
SettingsRow::new(text(cx, "settings.language", &[]))
@@ -230,6 +230,14 @@ impl SettingsView {
.control(language),
)
.row(SettingsRow::new(text(cx, "settings.motion", &[])).control(motion));
let updates = Switch::new("settings-updates", shared.check_updates)
.name(text(cx, "settings.updates", &[]))
.on_change(|on, _, cx| set(CHECK_UPDATES, Value::Bool(on), cx));
let mut section = section.row(
SettingsRow::new(text(cx, "settings.updates", &[]))
.description(text(cx, "settings.updates.hint", &[]))
.control(updates),
);
// Only where Omarchy is installed.
if ely_platform::omarchy_current_dir().is_some() {
let follow = Switch::new("settings-omarchy", shared.omarchy_sync)
+1
View File
@@ -124,6 +124,7 @@ impl RenderOnce for Shell {
.flex()
.flex_col()
.child(TitleBar::new("titlebar").title(self.title))
.children(crate::updates::updater(cx))
.children(menu_bar(cx))
.children(self.tabs);
// Panels give way so the content keeps its room.
+27
View File
@@ -102,6 +102,33 @@ fn build(
if !document {
window.focus(&focus, cx);
}
if let Some(updates) = crate::updates::updater(cx) {
cx.subscribe(
&updates,
|root: &mut Root, _, news: &crate::updates::UpdateNews, cx| match news {
crate::updates::UpdateNews::Failed(error) => {
let text = crate::i18n::text(cx, "updates.failed", &[("error", error)]);
root.toast(text, Severity::Danger, cx);
}
crate::updates::UpdateNews::Latest => {
let args = [
("app", root.app.name()),
("version", env!("CARGO_PKG_VERSION")),
];
let text = crate::i18n::text(cx, "updates.latest", &args);
root.toast(text, Severity::Success, cx);
}
},
)
.detach();
// A failed install from the last quit says why.
if let Some(note) = updates.update(cx, |updates, _| updates.note.take()) {
let text = crate::i18n::text(cx, "updates.failed", &[("error", &note)]);
cx.defer_in(window, move |root: &mut Root, _, cx| {
root.toast(text, Severity::Danger, cx)
});
}
}
Root {
app,
focus,
+428
View File
@@ -0,0 +1,428 @@
//! A newer release: offered, downloaded, installed after quitting.
use std::{
io,
path::{Path, PathBuf},
process::{Command, Stdio},
sync::atomic::AtomicBool,
};
use ely_gpui_component::shell::{UpdateBanner, UpdateState};
use ely_platform::{
AppId,
update::{self, Check, Release},
};
use futures::{StreamExt as _, channel::mpsc};
use gpui::{
App, AppContext as _, Context, Entity, EventEmitter, Global, IntoElement, Render, Window, div,
};
/// The release server's newest release, listed by its API.
const LATEST: &str = "https://git.zacharyzhang.com/api/v1/repos/ZacharyZhang-NY/ElyOffice/releases/latest";
/// The argument that runs this binary as the installer.
const INSTALL: &str = "--ely-install-update";
#[derive(Clone, Debug, PartialEq)]
enum Phase {
Offered,
Fetching(f32),
Fetched(PathBuf),
}
pub struct Updates {
app: AppId,
bundle: PathBuf,
offer: Option<(Release, Phase)>,
dismissed: bool,
/// The download to install once the app has quit.
pending: Option<PathBuf>,
/// Why the last install failed, for the window to say.
pub note: Option<String>,
}
/// What an update says to the window.
pub enum UpdateNews {
Failed(String),
/// A check the user asked for found nothing newer.
Latest,
}
impl EventEmitter<UpdateNews> for Updates {}
struct Updater(Entity<Updates>);
impl Global for Updater {}
/// The app's updater, if it runs from an installed bundle.
pub fn updater(cx: &App) -> Option<Entity<Updates>> {
cx.try_global::<Updater>().map(|updater| updater.0.clone())
}
/// Checks now, as the user asked from the menu.
pub fn check_now(cx: &mut App) {
if let Some(updates) = updater(cx) {
updates.update(cx, |updates, cx| updates.check(true, cx));
}
}
/// The quit an update asked for stopped: install nothing.
pub fn quit_stopped(cx: &mut App) {
if let Some(updates) = updater(cx) {
updates.update(cx, |updates, _| {
if updates.pending.take().is_some() {
log::info!("update: the quit stopped; nothing installs");
}
});
}
}
/// Run as the installer: waits, installs, reopens; the exit code.
pub fn installer(app: AppId) -> Option<i32> {
let args: Vec<String> = std::env::args().collect();
let [_, flag, dmg, bundle, pid] = args.as_slice() else {
return None;
};
if flag != INSTALL {
return None;
}
let Ok(pid) = pid.parse() else {
eprintln!("update: {pid} is not a process number");
return Some(2);
};
ely_platform::install::wait_for_exit(pid);
let installed = ely_platform::install::install(Path::new(dmg), Path::new(bundle));
if let Err(error) = &installed {
// To the app's log; the reopened app shows it.
eprintln!("update: the install failed: {error}");
let note = ely_platform::data_dir(app)
.map_err(io::Error::other)
.and_then(|dir| {
std::fs::create_dir_all(dir.join("updates"))?;
std::fs::write(dir.join("updates/failed.txt"), error.to_string())
});
if let Err(lost) = note {
eprintln!("update: the failure note was not written: {lost}");
}
}
// Last: the note is written before the app reads it.
if let Err(error) = ely_platform::install::reopen(Path::new(bundle)) {
eprintln!("update: the app did not reopen: {error}");
return Some(1);
}
Some(i32::from(installed.is_err()))
}
/// An installed app's updater; checks at launch if chosen.
pub(crate) fn install(app: AppId, cx: &mut App) {
let bundle = match ely_platform::install::running_bundle() {
Ok(Some(bundle)) => bundle,
Ok(None) => return log::info!("update: a dev build; no check"),
Err(error) => return log::warn!("update: the running app is not found: {error}"),
};
match update::install_policy() {
Ok(update::InstallPolicy::SelfManaged) => {}
Ok(update::InstallPolicy::PackageManager) => {
return log::info!("update: the package manager updates this app");
}
Err(error) => return log::warn!("update: {error:#}"),
}
let note = ely_platform::data_dir(app)
.ok()
.map(|dir| dir.join("updates/failed.txt"));
let note = note.and_then(|path| {
std::fs::read_to_string(&path)
.ok()
.inspect(|_| drop(std::fs::remove_file(&path)))
});
let updates = cx.new(|cx| {
cx.on_app_quit(|this: &mut Updates, _| {
this.start_installer();
async {}
})
.detach();
Updates {
app,
bundle,
offer: None,
dismissed: false,
pending: None,
note,
}
});
cx.set_global(Updater(updates.clone()));
// Off by default: no request unless the user chose it.
if crate::settings::current(cx).check_updates {
updates.update(cx, |updates, cx| updates.check(false, cx));
} else {
log::info!("update: no check at launch; it is off in settings");
}
}
/// The app's manifest in the newest release, or the test's.
fn manifest(app: AppId) -> anyhow::Result<String> {
match std::env::var("ELY_UPDATE_MANIFEST") {
Ok(url) => Ok(url),
Err(_) => ely_platform::release::asset_url(LATEST, &format!("{}.json", app.slug())),
}
}
impl Updates {
/// Asks for a newer release; `asked` reports every outcome.
fn check(&mut self, asked: bool, cx: &mut Context<Self>) {
// A download under way or done stays the offer.
if matches!(
self.offer,
Some((_, Phase::Fetching(_) | Phase::Fetched(_)))
) {
log::info!("update: a release is already on its way");
if asked {
self.dismissed = false;
cx.notify();
}
return;
}
let app = self.app;
let current =
semver::Version::parse(env!("CARGO_PKG_VERSION")).expect("the build's version");
// The lookup is a request too: off the window's thread.
let checked = cx.background_spawn(async move { manifest(app).and_then(|url| update::check(&current, &url)) });
cx.spawn(async move |this, cx| {
let checked = checked.await;
this.update(cx, |this, cx| match checked {
Ok(Check::Available(_))
if matches!(
this.offer,
Some((_, Phase::Fetching(_) | Phase::Fetched(_)))
) => {}
Ok(Check::Available(release)) => {
(this.offer, this.dismissed) = (Some((release, Phase::Offered)), false);
cx.notify();
}
Ok(Check::Current) if asked => cx.emit(UpdateNews::Latest),
// At launch a failure only logs; offline is normal.
Err(error) if asked => cx.emit(UpdateNews::Failed(format!("{error:#}"))),
Err(error) => log::warn!("update: the launch check failed: {error:#}"),
Ok(Check::Current) => log::info!("update: nothing newer at launch"),
})
.ok();
})
.detach();
}
fn later(&mut self, cx: &mut Context<Self>) {
self.dismissed = true;
cx.notify();
}
fn download(&mut self, cx: &mut Context<Self>) {
let Some((release, phase)) = self
.offer
.as_mut()
.filter(|(_, phase)| *phase == Phase::Offered)
else {
return;
};
*phase = Phase::Fetching(0.0);
cx.notify();
let (release, app) = (release.clone(), self.app);
let (sender, mut progress) = mpsc::unbounded();
let fetching = release.clone();
let fetched = cx.background_spawn(async move {
let dir = ely_platform::data_dir(app)
.map_err(|error| format!("{error:#}"))?
.join("updates");
if dir.exists() {
std::fs::remove_dir_all(&dir).map_err(|error| error.to_string())?;
}
std::fs::create_dir_all(&dir).map_err(|error| error.to_string())?;
let cancel = AtomicBool::new(false);
let mut tell = |done: u64, total: Option<u64>| {
let part = total
.filter(|total| *total > 0)
.map_or(0.0, |total| done as f32 / total as f32);
sender.unbounded_send(part).ok();
};
let file = update::download(&fetching, &dir, &cancel, update::IDLE_TIMEOUT, &mut tell)
.map_err(|error| format!("{error:#}"))?
.ok_or("the download stopped")?;
update::verify_file(&file, &fetching.sha256).map_err(|error| format!("{error:#}"))?;
Ok::<PathBuf, String>(file)
});
cx.spawn(async move |this, cx| {
while let Some(part) = progress.next().await {
this.update(cx, |this, cx| this.fetching(part, cx)).ok();
}
let fetched = fetched.await;
this.update(cx, |this, cx| this.fetched(&release, fetched, cx))
.ok();
})
.detach();
}
fn fetching(&mut self, part: f32, cx: &mut Context<Self>) {
if let Some((_, phase @ Phase::Fetching(_))) = self.offer.as_mut() {
*phase = Phase::Fetching(part);
cx.notify();
}
}
/// A finished download counts only for the release it fetched.
fn fetched(
&mut self,
release: &Release,
fetched: Result<PathBuf, String>,
cx: &mut Context<Self>,
) {
let Some((offered, phase)) = self
.offer
.as_mut()
.filter(|(offered, _)| offered == release)
else {
return log::warn!("update: a download for another release was dropped");
};
match fetched {
Ok(file) => *phase = Phase::Fetched(file),
Err(error) => {
*phase = Phase::Offered;
cx.emit(UpdateNews::Failed(error));
}
}
log::info!("update: {} is {:?}", offered.version, phase);
cx.notify();
}
/// Quits as usual: unsaved work is asked about first.
fn restart(&mut self, cx: &mut Context<Self>) {
let Some((_, Phase::Fetched(file))) = self.offer.as_ref() else {
return;
};
self.pending = Some(file.clone());
crate::commands::quit(cx);
}
/// At the real quit: the installer waits for this process.
fn start_installer(&mut self) {
let Some(file) = self.pending.take() else {
return;
};
let started = std::env::current_exe().and_then(|exe| {
let mut command = Command::new(exe);
command
.arg(INSTALL)
.arg(&file)
.arg(&self.bundle)
.arg(std::process::id().to_string());
// Its words go to the app's log.
let log = ely_platform::logging::path()
.map(|path| std::fs::OpenOptions::new().append(true).open(path));
let said = match log {
Some(file) => Stdio::from(file?),
None => Stdio::null(),
};
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(said);
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
command.spawn()
});
match started {
Ok(_) => log::info!("update: installs after this quit"),
Err(error) => log::error!("update: the installer did not start: {error}"),
}
}
}
impl Render for Updates {
/// The bar under the title while a release is offered.
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let this = cx.entity();
let Some((release, phase)) = self.offer.as_ref().filter(|_| !self.dismissed) else {
return div().into_any_element();
};
let state = match phase {
Phase::Offered => UpdateState::Available,
Phase::Fetching(done) => UpdateState::Downloading(*done),
Phase::Fetched(_) => UpdateState::Ready,
};
let (download, restart, later) = (this.clone(), this.clone(), this);
let banner = UpdateBanner::new("update-banner", release.version.to_string(), state)
.on_download(move |_, cx| download.update(cx, |this, cx| this.download(cx)))
.on_later(move |_, cx| later.update(cx, |this, cx| this.later(cx)));
match phase {
Phase::Fetched(_) => banner
.on_restart(move |_, cx| restart.update(cx, |this, cx| this.restart(cx)))
.into_any_element(),
_ => banner.into_any_element(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn release(version: &str, url: &str) -> Release {
Release {
version: semver::Version::parse(version).expect("a version"),
url: url.into(),
sha256: String::new(),
}
}
#[gpui::test]
fn a_check_brings_back_a_dismissed_download(cx: &mut gpui::TestAppContext) {
let updates = cx.new(|_| Updates {
app: AppId::Tree,
bundle: PathBuf::from("/Applications/ElyTree.app"),
offer: Some((
release("9.0.0", "https://b"),
Phase::Fetched(PathBuf::from("B.dmg")),
)),
dismissed: true,
pending: None,
note: None,
});
updates.update(cx, |updates, cx| updates.check(true, cx));
updates.read_with(cx, |updates, _| {
assert!(!updates.dismissed, "the bar shows again");
assert_eq!(
updates.offer.as_ref().map(|(_, phase)| phase.clone()),
Some(Phase::Fetched(PathBuf::from("B.dmg")))
);
});
}
#[gpui::test]
fn a_download_for_an_older_offer_is_dropped(cx: &mut gpui::TestAppContext) {
let updates = cx.new(|_| Updates {
app: AppId::Tree,
bundle: PathBuf::from("/Applications/ElyTree.app"),
offer: Some((release("9.0.0", "https://b"), Phase::Fetching(0.5))),
dismissed: false,
pending: None,
note: None,
});
updates.update(cx, |updates, cx| {
updates.fetched(
&release("8.0.0", "https://a"),
Ok(PathBuf::from("A.dmg")),
cx,
);
assert_eq!(
updates.offer.as_ref().map(|(_, phase)| phase.clone()),
Some(Phase::Fetching(0.5))
);
updates.fetched(
&release("9.0.0", "https://b"),
Ok(PathBuf::from("B.dmg")),
cx,
);
assert_eq!(
updates.offer.as_ref().map(|(_, phase)| phase.clone()),
Some(Phase::Fetched(PathBuf::from("B.dmg")))
);
});
}
}