Files
craft-libs/crates/update/src/dialog.rs
T
.CooCoo 5a93050c9f update: integration of the open fixes to craft-update (#763)
* update: an unsigned Windows copy gets Download instead of Update and Restart

The update helper installs nothing for an unsigned copy, so the prompt's
Update and Restart button on a local or unsigned build downloaded the
release and then stopped with "this copy isn't signed". is_self_updating
now answers false for an unsigned copy on Windows, and the prompt offers
Download. CRAFT_UPDATE_DEV still offers the update.

* update: check that a Windows copy can install before downloading

windows_precheck ran after the download, so a copy that could not install
downloaded the whole release first. The checks that do not depend on the
download now run before it; a new MSI's signature is checked after it.
The cache folder is created first, so a first update passes the check.

* update: a failure recorded before the running program is not reported

take_outcome reported any recorded failure at the next start, so a copy
put in place after an update had failed still opened with "The update
could not be installed". A failure record older than the running program
is now removed without being reported. A failure recorded after the
program was put in place, such as a failed helper's, is still reported.

* update: a Cargo build with a separate build directory is a development build

With build.build-dir set, Cargo keeps .rustc_info.json and the profile's
.fingerprint, deps and build folders in the build directory, and the
program's own folder has only its lock file. Such a build counted as an
installed copy and was offered Update and Restart. A profile folder with
Cargo's .cargo-lock under a target root with CACHEDIR.TAG is now a
development build, and gets the download link.

* update: a cache folder that can't be created is reported as that

same_cache_as_helper ignored the error from creating the folder, so a
failure read as a cache in the wrong place. It now names the folder and
the error.

* craft-update: a slow macOS signature check is not reported as a bad signature

`signed_by` gave `codesign` 120 seconds and treated every failure as a bad
signature, so a Mac that could not finish in time was told the app "isn't
signed by its developer".

The check now has 10 minutes and checks one bundle at a time. A job waiting
for its turn reports `JobPhase::Waiting` and can be canceled. A timeout, a
`codesign` that cannot start or is stopped by a signal, and any exit other
than 1 or 3 report that the signature couldn't be checked. Exit 3 refuses the
app as not signed by its developer. Exit 1 refuses it with `codesign`'s own
reason, because `codesign` also exits 1 for a bundle it cannot read. The app
is not installed in any of these cases.

On macOS, an install or uninstall now stops when `pgrep` gives no answer,
where a timeout used to read as "not running". `pgrep` has 30 seconds. An
install looks again after the signature check, which can wait behind other
apps' checks, and does not replace an app opened during the wait. A
self-update skips that second look.

* craft-update: a copy that cannot be replaced gets Download

A macOS bundle, an AppImage or a Linux standalone program was offered
Update and Restart even when the update could not replace it, so the
update failed only after the whole download.

`current_at` now leaves out such a copy when `access(2)` refuses what
the update needs. On macOS that is adding a subdirectory to the parent,
and adding a subdirectory to and deleting the bundle. On Linux it is
writing and searching the folder. A macOS copy under App Translocation
is also left out. Any other error from the check leaves the update on
offer, and `CRAFT_UPDATE_DEV` still offers it.

* craft-update: a macOS standalone copy that cannot be replaced gets Download

macOS `detect` returns `Install::Standalone` for a loose program, and
the update replaces it by writing beside it, as on Linux. `can_replace`
now checks that folder on macOS too, so a copy in a folder the user
cannot write gets Download instead of failing after the download.
`CRAFT_UPDATE_DEV` still offers the update.

* craft-update: a standalone copy whose share files cannot be replaced gets Download

The update replaces a standalone copy's files under `share` as well as
the program when the app's `share/<id>` folder sits next to `bin`. The
offer now also checks those folders, the `applications` and
`icons/hicolor` folders a release writes to, and the nearest existing
parent of one that doesn't exist yet.

* craft-update: a standalone macOS program without a release tarball gets Download

On macOS a program outside an app bundle counts as a standalone copy, and
the self-update replaces it from a macOS .tar.gz. Releases carry a disk
image and a command-line zip for macOS and no .tar.gz, so the prompt showed
Update and Restart and the update stopped with "has no Tarball (.tar.gz)
for macOS".

The prompt now also asks release_installs, which on macOS offers Update and
Restart to a standalone program only when the release lists that asset.
Without it the prompt shows Download. A release whose file list was not
loaded keeps the offer, because the install fetches the full release first.
CRAFT_UPDATE_DEV still offers the update. Other platforms and other kinds of
install are not checked against the release.

* craft-update: CRAFT_UPDATE_DEV no longer skips the release check

A standalone macOS program run with CRAFT_UPDATE_DEV was still offered
Update and Restart for a release without a macOS .tar.gz, and that update
failed. release_installs now checks the release for that copy too.

release_installs_at takes the executable, the opt-in setting and the
platform, and a new test checks a loose program in a temporary folder
against releases with and without the .tar.gz. The tests use SoundCraft's
release files, since craft-launcher ships no command-line zip.

* craft-update: a failed self-update keeps its download for the next try

On macOS, Linux and FreeBSD, prepare_update removed the downloaded
release file whether or not the install succeeded, so every retry after
a failed copy, signature check, package install or swap downloaded the
whole release again. A failed install now keeps the file, as install_at
already does, and the next try reuses it through Http::download, which
checks it against the published SHA-256 first and fetches it again when
it does not match.

- The cache folder's self-update-download.txt records the name and size
  of the release file before the download starts. A self-update for a
  different release file removes the finished and partial download that
  the record names, so each app keeps the files of one release at most.
- An install that succeeds removes the file and the record. So does a
  failed install whose record could not be written, since nothing would
  remove that file later.
- On macOS, when hdiutil cannot attach the disk image, the file is still
  removed: an image left attached by an install that ended part way
  makes hdiutil refuse the same file with "Resource busy", while a new
  download of it attaches.
- Windows is unchanged: its update helper removes the download after
  the app exits.

* craft-update: a macOS install that stopped partway no longer blocks the next install

When a macOS install ends before it finishes (the app quits or
crashes), the copy it was making stays beside the app and the update's
disk image stays attached. The next attach of the same file fails with
"Resource busy".

- Each staging folder's name now carries the installing process's id,
  and the folder holds an empty marker file. Before it stages a copy, an
  install removes the marked staging folders of processes that are no
  longer running, and their empty unmarked ones. It also removes a
  staging folder from earlier launcher versions when it holds only the
  app's bundle and has not changed for a day. Backup folders and other
  apps' folders are left alone.
- Before it attaches an image, an install detaches the images that
  earlier installs of the same app left at their mount points in the
  cache, when their process has ended or, in this process, when no
  install uses them any more.
- When the attach fails, the install detaches its image if it is
  attached with no volume mounted and no other attach of the same file
  is running.
- A staging folder that can't be removed, or an image that stays
  attached, is logged, and the error of a failed install says so after
  its reason.

* craft-update: the kept-download test accepts either signature refusal

An unsigned bundle is refused as "isn't signed" today and as a failed signature check once codesign's exit status is read, so the test checks that the install stopped on its signature.

* craft-update: the share check covers nested and pixmaps folders

A standalone copy in a prefix gets Update and Restart only when the
update can write every `share` folder it replaces files in. The check
covered `share/<id>`, `share/applications` and `share/icons/hicolor`
only, but the update writes a copy of each file next to its
destination first. A folder inside `share/<id>` (such as `models`), an
icon folder such as `icons/hicolor/256x256/apps`, or `share/pixmaps`
(where an older flat release puts its icon) that the user can't write
stopped the update after the whole download.

The check now also takes in every folder inside `share/<id>`, each
`icons/hicolor/<size>/apps` folder that holds the app's icon, and
`share/pixmaps`. Icon folders of other packages and other themes are
not checked. A linked folder is checked but not walked. The walk reads
at most 4,096 folder entries, so a large tree does not slow every
start; a folder past that is reported by the install as before.

The same check runs for a standalone copy on Linux, so a Linux copy
whose nested share folder or `share/pixmaps` it can't write now gets
the download link too.

* craft-update: a release folder that can't be read stops a standalone update

A standalone update in a prefix copies every file under the release's
`share` folder. The walk skipped any folder it could not list, and the
archive keeps each folder's mode, so a folder that nobody may list left
its files out while the update reported success. An error reading an
entry of the release's `bin` folder was dropped the same way.

These are now errors that name the folder, and the update stops before
any installed file changes. A release without a `share` folder still
updates.

A release whose `share` or `bin` is a link was followed, so the update
copied files from outside the release into the prefix. A `share` or
`bin` that is a link, or a `share` that is a file, now stops the update.
Links further down under `share` are still skipped.

The unpacked release is removed after a failed update even when it holds
a folder that its owner can't list. Before, such a folder stayed in the
cache.

* craft-update: the share check covers doc, metainfo and mime, and follows links

The share check for a standalone copy in a prefix now also takes in
`share/doc/<id>` and every folder inside it, `share/metainfo` and
`share/mime/packages`. Release archives such as VectorCraft's Linux and
FreeBSD ones put files in all three.

The walk now follows links, as the update's writes do. A copy whose
`share/<id>` is itself a link had none of its folders checked, and a
folder behind a link inside `share/<id>` was not checked either. A
folder the walk reaches twice is read once.

When `doc/<id>`, `metainfo`, `mime/packages` or `pixmaps` is missing,
the check no longer falls back to `share` itself. A copy whose `share`
the user can't write, but whose app, `applications` and `icons/hicolor`
folders exist, gets Update and Restart again, as it did before the
previous commit.

The entry limit of 4,096 now applies to each of `share/<id>`,
`doc/<id>` and `icons/hicolor` separately, and it counts files and
folders. A large app folder no longer turns off the icon folder check.

In a folder with the sticky bit, such as `/tmp`, the user can rename
over a file only when the user owns the file or the folder. A copy now
gets the download link when such a folder holds one of the app's files
that another user owns: the program itself, its other programs
(`<id>-<name>`, such as `<id>-cli`), anything in `share/<id>` or
`share/doc/<id>`, or a `share` file named `<id>.<ext>` or
`<bundle id>.<ext>`.

An icon size that the installed copy doesn't have yet is still not
checked, and a read-only folder that the user added under `share/<id>`
does count. Linux runs the same checks for a standalone copy, and the
sticky check on the program file for an AppImage.

* craft-update: the app-program check has its own name

The check for the app's programs in a bin folder was named is_program, the name of the Windows check for an MZ header, so the crate did not build on Windows. It is now is_app_program.

* craft-update: a missing doc, metainfo or mime folder is checked through share

A Linux release writes files into `share/doc/<id>`, `share/metainfo`
and `share/mime/packages`, and the update creates each of these
folders when it is missing. When one was missing, the share check took
its nearest existing parent inside `share` and never `share` itself. A
copy whose `share` the user can't write and that lacked one of these
folders was offered Update and Restart, and the update failed after
the whole download.

For a missing `doc/<id>`, `metainfo` or `mime/packages`, the check now
takes the nearest existing parent with `share` included, as it already
did for `applications`. Only the old flat release layout writes to
`share/pixmaps`, so a missing `pixmaps` is still checked inside
`share` only, and a copy whose `share` the user can't write keeps
Update and Restart when every other release folder exists.

A folder in the app's folder or in `doc/<id>` that the user can't
read is still checked against its own permissions, as before. The
copy gets Download when the user can't write and search that folder.
The check can't list the folders inside it and does not check them.
A new test keeps this rule, and the check does not refuse a copy only
because a folder in it can't be read.

* craft-update: the staging cleanup's doc says which folders it removes

A marked staging folder is removed once its process has ended,
whichever app that install was for: the folder's name does not record
the app. Only staging folders of earlier launcher versions are checked
for the app's bundle.

* craft-update: a failed attach leaves its image attached when pgrep gives no answer

detach_unmounted, from #766, checked for another attach of the same
image file with is_running, which reads a pgrep that gives no answer as
"not running", and then force-detached the image's unmounted
attachments. It now uses process::running, from #753, and detaches only
when the check answers that nothing is running.
2026-11-11 00:07:01 -05:00

1254 lines
63 KiB
Rust

//! Startup update prompt dialog for egui frontends.
use egui::{Align, Align2, Color32, Layout, RichText, Vec2};
use crate::app::App;
use crate::release::Release;
use crate::translate::{Note, Translate, button, english};
use crate::updater::Status;
/// What the user chose in the startup update prompt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StartupPromptResponse {
/// Dialog is still open and waiting for user input.
Pending,
/// User chose to update and restart now.
UpdateAndRestart,
/// User chose to download manually via browser.
Download,
/// User dismissed the dialog for now.
Later,
}
/// State for the startup update prompt dialog.
#[derive(Clone, Debug)]
pub struct StartupPrompt {
pub app: &'static App,
pub release: Release,
pub running_version: String,
pub is_self_updating: bool,
pub open: bool,
/// A message shown as it is: an error from the network or the installer.
pub status_message: Option<String>,
/// One of the crate's own messages, translated each time the prompt draws. `status_message`
/// wins when both are set, so an error written straight to it shows.
/// [`StartupPrompt::set_note`] and [`StartupPrompt::set_message`] keep only one.
pub status_note: Option<Note>,
pub is_installing: bool,
/// The update is ready and waits for the app to close: the main button reads "Restart to
/// Update" and answers [`StartupPromptResponse::UpdateAndRestart`].
pub is_ready: bool,
/// Puts the card's words in the interface language ([`crate::translate`]); English by default.
pub translate: Translate,
}
impl StartupPrompt {
/// Creates a new prompt dialog state for the given app and newly discovered release.
pub fn new(app: &'static App, release: Release, running_version: impl Into<String>) -> Self {
let is_self_updating = crate::self_update::is_self_updating(app) && crate::self_update::release_installs(app, &release);
Self {
app,
release,
running_version: running_version.into(),
is_self_updating,
open: true,
status_message: None,
status_note: None,
is_installing: false,
is_ready: false,
translate: english,
}
}
/// Shows one of the crate's own messages, in the interface language whenever it draws.
pub fn set_note(&mut self, note: Note) {
self.status_note = Some(note);
self.status_message = None;
}
/// Shows `message` as it is (an error from elsewhere).
pub fn set_message(&mut self, message: String) {
self.status_note = None;
self.status_message = Some(message);
}
/// Clears the message.
pub fn clear_message(&mut self) {
self.status_note = None;
self.status_message = None;
}
/// The message the prompt shows, in the interface language: `status_message` (an error
/// written to it), else the note.
pub fn message(&self) -> Option<String> {
self.status_message.clone().or_else(|| self.status_note.as_ref().map(|note| note.translated(self.translate)))
}
/// The prompt with its words in the interface language ([`crate::translate`]).
#[must_use]
pub fn with_translator(mut self, translate: Translate) -> Self {
self.translate = translate;
self
}
/// Renders the modal window on the given egui context.
pub fn show(&mut self, ctx: &egui::Context) -> StartupPromptResponse {
if !self.open {
return StartupPromptResponse::Later;
}
let mut response = StartupPromptResponse::Pending;
backdrop(ctx);
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
response = StartupPromptResponse::Later;
}
let pal = Palette::new(ctx, self.app);
let Palette { card_bg, border_color, text_primary, text_muted, fill, on_fill, alert, alert_bg, .. } = pal;
let t = self.translate;
let version = self.release.version_label();
egui::Area::new(egui::Id::unique("craft_update.startup_prompt"))
.anchor(Align2::CENTER_CENTER, Vec2::ZERO)
.order(egui::Order::Foreground)
.show(ctx, |ui| {
egui::Frame::new()
.fill(card_bg)
.stroke(egui::Stroke::new(1.0, border_color))
.corner_radius(egui::CornerRadius::ZERO)
.inner_margin(egui::Margin::symmetric(20, 18))
.show(ui, |ui| {
ui.set_width(400.0);
style_card(ui, &pal);
let version_line = t("v{from} to {to}", &[("from", &self.running_version), ("to", &version)]);
if card_header(ui, self.app, &pal, t, true, &version_line) {
response = StartupPromptResponse::Later;
}
ui.add_space(8.0);
if let Some(msg) = self.message() {
egui::Frame::new()
.fill(alert_bg)
.stroke(egui::Stroke::new(1.0, alert))
.corner_radius(egui::CornerRadius::ZERO)
.inner_margin(egui::Margin::symmetric(10, 6))
.show(ui, |ui| {
ui.set_width(ui.available_width());
bounded(ui, "craft_update.prompt_message", |ui| {
ui.label(RichText::new(msg).size(12.0).color(alert));
});
});
ui.add_space(4.0);
}
if self.is_installing {
ui.horizontal(|ui| {
ui.spinner();
ui.label(RichText::new(t("Downloading and installing update…", &[])).size(12.0).color(text_primary));
});
} else {
let desc = t(
"{app} {version} is available with the latest features and bug fixes.",
&[("app", self.app.name), ("version", &version)],
);
ui.label(RichText::new(desc).size(12.5).color(text_muted));
}
ui.add_space(10.0);
let (hairline_rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 1.0), egui::Sense::hover());
ui.painter().hline(hairline_rect.x_range(), hairline_rect.top(), egui::Stroke::new(1.0, border_color));
ui.add_space(8.0);
// Footer actions: a row as tall as the buttons, everything centred in it, so the link
// lines up with them (a plain horizontal row puts it at the top).
ui.with_layout(Layout::left_to_right(Align::Center), |ui| {
ui.set_min_height(26.0);
// Body text, so it reads on any card; the underline carries the accent.
let whats_new = t("What's new", &[]);
let link = ui.add(egui::Label::new(RichText::new(&whats_new).size(11.5).color(text_primary)).sense(egui::Sense::click()));
link.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Link, true, &whats_new));
let y = link.rect.bottom() - 0.5;
ui.painter()
.line_segment([egui::pos2(link.rect.left(), y), egui::pos2(link.rect.right(), y)], egui::Stroke::new(1.0, fill));
// Keyboard focus (Tab, then Enter or Space opens it): the buttons' 2 px ring.
if link.has_focus() {
let ring = egui::Stroke::new(2.0, text_primary);
ui.painter().rect_stroke(link.rect.expand(2.0), egui::CornerRadius::ZERO, ring, egui::StrokeKind::Outside);
}
// `Release`'s fields are public: an app may build one from its own feed or
// cache, so the link is checked here too, not only when parsed from GitHub.
if link.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() && crate::release::safe_web_link(&self.release.html_url)
{
ui.ctx().open_url(egui::OpenUrl::new_tab(&self.release.html_url));
}
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
if self.is_installing {
let dismiss_btn = egui::Button::new(RichText::new(button(t, "Dismiss")).size(10.5).monospace().color(text_muted))
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(72.0, 26.0));
if ui.add(dismiss_btn).clicked() {
response = StartupPromptResponse::Later;
}
} else {
if self.is_self_updating || self.is_ready {
let label = if self.is_ready { "Restart to Update" } else { "Update and Restart" };
let update_btn =
egui::Button::new(RichText::new(button(t, label)).size(10.5).strong().monospace().color(on_fill))
.fill(fill)
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(140.0, 26.0));
if ui.add(update_btn).clicked() {
response = StartupPromptResponse::UpdateAndRestart;
}
} else {
let dl_btn =
egui::Button::new(RichText::new(button(t, "Download")).size(10.5).strong().monospace().color(on_fill))
.fill(fill)
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(90.0, 26.0));
if ui.add(dl_btn).clicked() {
response = StartupPromptResponse::Download;
}
}
let later_btn = egui::Button::new(RichText::new(button(t, "Later")).size(10.5).monospace().color(text_primary))
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(65.0, 26.0));
if ui.add(later_btn).clicked() {
response = StartupPromptResponse::Later;
}
}
});
});
});
});
if response == StartupPromptResponse::Later {
self.open = false;
}
response
}
}
/// The card's colours for the current theme and app.
#[derive(Clone, Copy)]
struct Palette {
is_dark: bool,
card_bg: Color32,
border_color: Color32,
text_primary: Color32,
text_muted: Color32,
/// The app's accent.
fill: Color32,
/// Text on `fill`.
on_fill: Color32,
/// Errors and failure reasons, on the card and on `alert_bg`.
alert: Color32,
/// The box around a message in the prompt.
alert_bg: Color32,
}
impl Palette {
fn new(ctx: &egui::Context, app: &App) -> Self {
let is_dark = ctx.theme() == egui::Theme::Dark;
let fill = app.accent.map_or(DEFAULT_ACCENT, |[r, g, b]| Color32::from_rgb(r, g, b));
Self {
is_dark,
card_bg: if is_dark { Color32::from_rgb(26, 26, 28) } else { Color32::from_rgb(255, 255, 255) },
border_color: if is_dark { Color32::from_rgb(52, 52, 56) } else { Color32::from_rgb(215, 215, 220) },
text_primary: if is_dark { Color32::from_rgb(245, 245, 248) } else { Color32::from_rgb(20, 20, 25) },
text_muted: if is_dark { Color32::from_rgb(150, 150, 160) } else { Color32::from_rgb(105, 105, 115) },
fill,
on_fill: ink_on(fill),
alert: if is_dark { Color32::from_rgb(225, 95, 30) } else { Color32::from_rgb(184, 66, 8) },
alert_bg: if is_dark { Color32::from_rgb(44, 26, 18) } else { Color32::from_rgb(255, 242, 235) },
}
}
}
/// The dimmed modal backdrop; it senses clicks so they don't reach widgets underneath. True when
/// it was clicked (a click outside the card).
fn backdrop(ctx: &egui::Context) -> bool {
let screen_rect = ctx.content_rect();
egui::Area::new(egui::Id::unique("craft_update_backdrop"))
.order(egui::Order::Middle)
.fixed_pos(screen_rect.min)
.show(ctx, |ui| {
let (rect, response) = ui.allocate_exact_size(screen_rect.size(), egui::Sense::click_and_drag());
ui.painter().rect_filled(rect, 0.0, Color32::from_black_alpha(150));
response.clicked()
})
.inner
}
/// The host app's widget style isn't ours to rely on (a light theme's hover can be dark under
/// this card's dark text), so the card's buttons get their own states.
fn style_card(ui: &mut egui::Ui, pal: &Palette) {
let widgets = &mut ui.visuals_mut().widgets;
let (hover_bg, press_bg) = button_states(pal.is_dark);
for (state, bg) in [(&mut widgets.inactive, pal.card_bg), (&mut widgets.hovered, hover_bg), (&mut widgets.active, press_bg)] {
state.weak_bg_fill = bg;
state.bg_fill = bg;
state.bg_stroke = egui::Stroke::new(1.0, pal.border_color);
}
// egui draws a focused button (and a pressed one) in the active state: its border is
// the focus ring, in the body text colour so it shows on the card and around a fill.
widgets.active.bg_stroke = egui::Stroke::new(2.0, pal.text_primary);
ui.spacing_mut().item_spacing = Vec2::new(8.0, 6.0);
}
/// Header row: app icon (or its initial in a badge), name, developer, `second_line` and a close
/// button, worded by `t`. `update_pill` adds the "UPDATE" chip. True when the close button was clicked.
fn card_header(ui: &mut egui::Ui, app: &App, pal: &Palette, t: Translate, update_pill: bool, second_line: &str) -> bool {
let Palette { text_primary, text_muted, fill, on_fill, .. } = *pal;
let mut closed = false;
ui.horizontal(|ui| {
let (badge_rect, _) = ui.allocate_exact_size(Vec2::new(34.0, 34.0), egui::Sense::hover());
if let Some(icon) = icon_texture(ui.ctx(), app) {
let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
ui.painter().image(icon.id(), badge_rect, uv, Color32::WHITE);
} else {
ui.painter().rect_filled(badge_rect, egui::CornerRadius::ZERO, fill);
let initial = app.name.chars().next().map(|c| c.to_string()).unwrap_or_else(|| "A".to_string());
ui.painter().text(badge_rect.center(), Align2::CENTER_CENTER, initial, egui::FontId::monospace(18.0), on_fill);
}
ui.add_space(4.0);
ui.vertical(|ui| {
ui.spacing_mut().item_spacing.y = 2.0;
ui.horizontal(|ui| {
ui.label(RichText::new(app.name).size(15.0).strong().color(text_primary));
ui.label(RichText::new(t("by {developer}", &[("developer", app.developer)])).size(11.5).color(text_muted));
if update_pill {
// A chip, not accent-coloured text: small accent text misses WCAG's 4.5:1 for
// several apps (PdfCraft's red on the dark card, amber on the light one).
egui::Frame::new().fill(fill).inner_margin(egui::Margin::symmetric(4, 1)).show(ui, |ui| {
ui.label(RichText::new(button(t, "Update")).size(10.0).monospace().color(on_fill));
});
}
});
// ASCII only, like the rest of the card: an app whose fonts lack a glyph may panic
// instead of drawing a box, and the startup prompt shows up unasked.
ui.label(RichText::new(second_line).size(11.0).monospace().color(text_muted));
});
ui.with_layout(Layout::right_to_left(Align::Min), |ui| {
// Two strokes, not a "✕" glyph: none of the bundled faces has U+2715.
let (rect, close) = ui.allocate_exact_size(Vec2::splat(18.0), egui::Sense::click());
close.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, t("Close", &[])));
let color = if close.hovered() { text_primary } else { text_muted };
let (center, reach) = (rect.center(), 4.5);
let stroke = egui::Stroke::new(1.5, color);
ui.painter().line_segment([center + Vec2::new(-reach, -reach), center + Vec2::new(reach, reach)], stroke);
ui.painter().line_segment([center + Vec2::new(-reach, reach), center + Vec2::new(reach, -reach)], stroke);
if close.on_hover_cursor(egui::CursorIcon::PointingHand).clicked() {
closed = true;
}
});
});
closed
}
/// What the user chose in the result dialog of a manual update check.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CheckResultResponse {
/// Dialog is still open and waiting for user input.
None,
/// OK, the close button, Esc or a click outside: the app stops showing the dialog.
Close,
/// Failed states only: the app starts another requested check.
CheckAgain,
/// Ready state only: the app calls `Updater::restart_to_update`, which asks it to close.
RestartToUpdate,
}
/// The result of a manual "Check for Updates", in the same card as [`StartupPrompt`]: a spinner
/// while checking, "newest version" when up to date, the error and a retry when it failed, an
/// update installing or ready, and the launcher's choice when it manages the version. It also
/// shows what the last update came to at the first start after it.
///
/// An app shows it while a requested check is in view: open it when the user starts a check
/// (`Updater::check_now`) or when `updater.status()` is not [`Status::Idle`] after the check at
/// start, call [`show`](Self::show) every frame with `updater.status()` until it returns
/// [`CheckResultResponse::Close`], then call `Updater::dismiss_status` and stop calling it. On
/// [`CheckResultResponse::CheckAgain`] start another requested check and keep showing it; on
/// [`CheckResultResponse::RestartToUpdate`] call `Updater::restart_to_update`. An available update
/// goes to [`StartupPrompt`] instead; the app closes this dialog when the prompt opens.
#[derive(Clone, Copy, Debug)]
pub struct CheckResultDialog {
app: &'static App,
running_version: &'static str,
translate: Translate,
}
impl CheckResultDialog {
/// A dialog for `app`, which is running `running_version`.
pub fn new(app: &'static App, running_version: &'static str) -> Self {
Self { app, running_version, translate: english }
}
/// The dialog with its words in the interface language ([`crate::translate`]).
#[must_use]
pub fn with_translator(mut self, translate: Translate) -> Self {
self.translate = translate;
self
}
/// Draws the card for `status` and returns what the user chose. [`Status::Idle`] draws
/// nothing and returns [`CheckResultResponse::None`]. The card is modal except for
/// [`Status::Updated`], a notice that leaves the app usable behind it.
pub fn show(&self, ctx: &egui::Context, status: &Status) -> CheckResultResponse {
if matches!(status, Status::Idle) {
return CheckResultResponse::None;
}
let mut response = CheckResultResponse::None;
if !matches!(status, Status::Updated(_)) && backdrop(ctx) {
response = CheckResultResponse::Close;
}
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) {
response = CheckResultResponse::Close;
}
let pal = Palette::new(ctx, self.app);
let Palette { card_bg, border_color, text_primary, text_muted, fill, on_fill, alert, .. } = pal;
let t = self.translate;
egui::Area::new(egui::Id::unique("craft_update.check_result")).anchor(Align2::CENTER_CENTER, Vec2::ZERO).order(egui::Order::Foreground).show(
ctx,
|ui| {
egui::Frame::new()
.fill(card_bg)
.stroke(egui::Stroke::new(1.0, border_color))
.corner_radius(egui::CornerRadius::ZERO)
.inner_margin(egui::Margin::symmetric(20, 18))
.show(ui, |ui| {
ui.set_width(400.0);
style_card(ui, &pal);
if card_header(ui, self.app, &pal, t, false, &format!("v{}", self.running_version)) {
response = CheckResultResponse::Close;
}
ui.add_space(8.0);
match status {
Status::Checking => {
ui.horizontal(|ui| {
ui.spinner();
ui.label(RichText::new(t("Checking for updates…", &[])).size(12.5).color(text_primary));
});
}
Status::Installing => {
ui.horizontal(|ui| {
ui.spinner();
ui.label(RichText::new(t("Installing update…", &[])).size(12.5).color(text_primary));
});
}
Status::Ready => {
let text = t(crate::updater::READY_TEXT, &[("app", self.app.name)]);
ui.label(RichText::new(text).size(12.5).color(text_primary));
}
Status::Managed => {
let text = t(
"{app} {version} follows the version chosen in the launcher, so it does not update itself.",
&[("app", self.app.name), ("version", self.running_version)],
);
ui.label(RichText::new(text).size(12.5).color(text_muted));
}
Status::Updated(version) => {
let text = t("{app} updated to {version}.", &[("app", self.app.name), ("version", version)]);
ui.label(RichText::new(text).size(12.5).color(text_primary));
}
Status::InstallFailed(reason) => {
let text = t("The update could not be installed: {reason}", &[("reason", reason)]);
bounded(ui, "craft_update.install_failure", |ui| {
ui.add(egui::Label::new(RichText::new(text).size(12.5).color(alert)).selectable(true));
});
}
Status::UpToDate => {
let text = t(
"{app} {version} is the newest version available.",
&[("app", self.app.name), ("version", self.running_version)],
);
ui.label(RichText::new(text).size(12.5).color(text_muted));
}
Status::Failed(error) => {
ui.label(RichText::new(t("Could not check for updates.", &[])).size(12.5).strong().color(alert));
bounded(ui, "craft_update.check_failure", |ui| {
ui.add(egui::Label::new(RichText::new(error).size(12.0).color(text_muted)).selectable(true));
});
ui.label(
RichText::new(t("All releases are listed at {url}", &[("url", &self.app.releases_url())]))
.size(11.5)
.color(text_muted),
);
}
Status::Idle => {}
}
if !matches!(status, Status::Checking) {
ui.add_space(10.0);
let (hairline_rect, _) = ui.allocate_exact_size(Vec2::new(ui.available_width(), 1.0), egui::Sense::hover());
ui.painter().hline(hairline_rect.x_range(), hairline_rect.top(), egui::Stroke::new(1.0, border_color));
ui.add_space(8.0);
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
ui.set_min_height(26.0);
let ok = egui::Button::new(RichText::new(button(t, "OK")).size(10.5).strong().monospace().color(on_fill))
.fill(fill)
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(65.0, 26.0));
if ui.add(ok).clicked() {
response = CheckResultResponse::Close;
}
if matches!(status, Status::Failed(_) | Status::InstallFailed(_)) {
let again = egui::Button::new(RichText::new(button(t, "Check Again")).size(10.5).monospace().color(text_primary))
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(100.0, 26.0));
if ui.add(again).clicked() {
response = CheckResultResponse::CheckAgain;
}
}
if matches!(status, Status::Ready) {
let restart =
egui::Button::new(RichText::new(button(t, "Restart to Update")).size(10.5).monospace().color(text_primary))
.corner_radius(egui::CornerRadius::ZERO)
.min_size(Vec2::new(130.0, 26.0));
if ui.add(restart).clicked() {
response = CheckResultResponse::RestartToUpdate;
}
}
});
}
});
},
);
response
}
}
/// The tallest an error or failure reason draws in a card; a longer one scrolls, so the card's
/// buttons stay on screen.
const REASON_MAX_HEIGHT: f32 = 160.0;
/// Draws `add_contents` (an error or a failure reason) at most [`REASON_MAX_HEIGHT`] tall,
/// scrolling the rest.
fn bounded(ui: &mut egui::Ui, id: &str, add_contents: impl FnOnce(&mut egui::Ui)) {
egui::ScrollArea::vertical().id_salt(id).max_height(REASON_MAX_HEIGHT).auto_shrink([false, true]).show(ui, add_contents);
}
/// Backgrounds of an unfilled button (LATER, DISMISS) when hovered and when pressed: a step from
/// the card, so its text keeps the contrast it has at rest.
fn button_states(is_dark: bool) -> (Color32, Color32) {
if is_dark {
(Color32::from_rgb(44, 44, 48), Color32::from_rgb(58, 58, 64))
} else {
(Color32::from_rgb(236, 236, 241), Color32::from_rgb(222, 222, 230))
}
}
/// The prompt's blue for an app that names no accent ([`App::accent`]).
const DEFAULT_ACCENT: Color32 = Color32::from_rgb(52, 120, 246);
/// WCAG relative luminance of `c`: 0 for black to 1 for white.
fn luminance(c: Color32) -> f32 {
let channel = |v: u8| {
let v = f32::from(v) / 255.0;
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
};
0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
}
/// WCAG contrast ratio of two colours: 1 (none) to 21 (black on white).
fn contrast(a: Color32, b: Color32) -> f32 {
let (a, b) = (luminance(a), luminance(b));
(a.max(b) + 0.05) / (a.min(b) + 0.05)
}
/// Text for a label on `fill`: white or black, whichever contrasts more. Every Craft app accent
/// then reaches WCAG AA's 4.5:1 for the prompt's small labels (5:1 at the least).
fn ink_on(fill: Color32) -> Color32 {
if contrast(fill, Color32::WHITE) >= contrast(fill, Color32::BLACK) { Color32::WHITE } else { Color32::BLACK }
}
/// The largest icon the prompt decodes, a side; app icons are 128 px.
const ICON_MAX_SIDE: u32 = 1024;
/// `app`'s icon as a texture, decoded once per context and app; `None` when the app has none or
/// it doesn't decode, and the prompt shows the app's initial instead.
fn icon_texture(ctx: &egui::Context, app: &App) -> Option<egui::TextureHandle> {
let png = app.icon_png?;
let id = egui::Id::unique(("craft_update.icon", app.id));
if let Some(cached) = ctx.data(|d| d.get_temp::<Option<egui::TextureHandle>>(id)) {
return cached;
}
// The renderer's own limit too: load_texture panics (debug) on a texture larger than it takes.
let max_side = u32::try_from(ctx.input(|i| i.max_texture_side)).unwrap_or(u32::MAX).min(ICON_MAX_SIDE);
let texture =
decode_icon(png, max_side).map(|image| ctx.load_texture(format!("craft_update.icon.{}", app.id), image, egui::TextureOptions::LINEAR));
ctx.data_mut(|d| d.insert_temp(id, texture.clone()));
texture
}
/// A PNG as an RGBA image, or `None` when it doesn't decode or is over `max_side` a side.
fn decode_icon(png: &[u8], max_side: u32) -> Option<egui::ColorImage> {
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(max_side);
limits.max_image_height = Some(max_side);
reader.limits(limits);
let rgba = reader.decode().ok()?.to_rgba8();
let size = [usize::try_from(rgba.width()).ok()?, usize::try_from(rgba.height()).ok()?];
Some(egui::ColorImage::from_rgba_unmultiplied(size, rgba.as_raw()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::suite::PHOTOCRAFT;
use egui::{Context, Event, FullOutput, Key, Modifiers, RawInput, Rect};
const DARK_CARD: Color32 = Color32::from_rgb(26, 26, 28);
const DARK_STATUS: Color32 = Color32::from_rgb(44, 26, 18);
fn screen() -> Rect {
Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0))
}
/// A dark, animation-free context so a single frame paints final (unfaded) colors.
fn dark_context() -> Context {
let ctx = Context::default();
ctx.set_theme(egui::ThemePreference::Dark);
ctx.global_style_mut(|style| style.animation_time = 0.0);
ctx
}
/// A prompt in a known installation mode, without probing the host for a real install.
fn prompt_for(is_self_updating: bool) -> StartupPrompt {
let release = Release { version: crate::version::parse("0.2.0"), tag: "v0.2.0".to_string(), ..Release::default() };
StartupPrompt {
app: &PHOTOCRAFT,
release,
running_version: "0.1.0".to_string(),
is_self_updating,
open: true,
status_message: None,
status_note: None,
is_installing: false,
is_ready: false,
translate: english,
}
}
fn frame(ctx: &Context, prompt: &mut StartupPrompt, events: Vec<Event>) -> (StartupPromptResponse, FullOutput) {
let mut response = StartupPromptResponse::Pending;
let mut output = ctx.run_ui(RawInput { screen_rect: Some(screen()), events, ..RawInput::default() }, |ui| {
response = prompt.show(ui.ctx());
});
output.textures_delta.clear(); // Headless test: no renderer consumes the font atlas.
(response, output)
}
fn collect_text(shape: &egui::Shape, out: &mut Vec<String>) {
match shape {
egui::Shape::Vec(shapes) => {
for shape in shapes {
collect_text(shape, out);
}
}
egui::Shape::Text(text) => out.push(text.galley.text().to_owned()),
_ => {}
}
}
/// Every string the frame actually painted, one per line.
fn painted_text(output: &FullOutput) -> String {
let mut texts = Vec::new();
for clipped in &output.shapes {
collect_text(&clipped.shape, &mut texts);
}
texts.join("\n")
}
/// The rectangle fills painted this frame, so the card and alert surfaces can be told apart.
fn rect_fills(output: &FullOutput) -> Vec<(Rect, Color32)> {
fn collect(shape: &egui::Shape, out: &mut Vec<(Rect, Color32)>) {
match shape {
egui::Shape::Vec(shapes) => {
for shape in shapes {
collect(shape, out);
}
}
egui::Shape::Rect(rect) => out.push((rect.rect, rect.fill)),
_ => {}
}
}
let mut fills = Vec::new();
for clipped in &output.shapes {
collect(&clipped.shape, &mut fills);
}
fills
}
/// A `width` x `height` PNG of one opaque color.
fn png(width: u32, height: u32, color: [u8; 4]) -> Vec<u8> {
let mut out = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(width, height, image::Rgba(color)).write_to(&mut out, image::ImageFormat::Png).unwrap();
out.into_inner()
}
/// The textured meshes painted this frame (the app icon; text is drawn as `Shape::Text`).
fn textured_meshes(output: &FullOutput) -> Vec<egui::TextureId> {
fn collect(shape: &egui::Shape, out: &mut Vec<egui::TextureId>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out)),
egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => out.push(mesh.texture_id),
_ => {}
}
}
let mut ids = Vec::new();
for clipped in &output.shapes {
collect(&clipped.shape, &mut ids);
}
ids
}
#[test]
fn icons_decode_and_bad_ones_are_refused() {
let image = decode_icon(&png(3, 2, [10, 20, 30, 255]), ICON_MAX_SIDE).unwrap();
assert_eq!(image.size, [3, 2]);
assert_eq!(image.pixels[0], Color32::from_rgb(10, 20, 30));
assert!(decode_icon(b"\x89PNG\r\n\x1a\nnot really", ICON_MAX_SIDE).is_none(), "a corrupt PNG must not decode");
assert!(decode_icon(&png(ICON_MAX_SIDE + 1, 1, [0, 0, 0, 255]), ICON_MAX_SIDE).is_none(), "an oversized icon must not decode");
// A renderer that takes smaller textures than the icon: no texture, so the initial is shown.
assert!(decode_icon(&png(3, 2, [0, 0, 0, 255]), 2).is_none(), "an icon over the renderer's limit must not decode");
}
#[test]
fn prompt_shows_the_app_icon_or_else_its_initial() {
static ICON_APP: std::sync::OnceLock<App> = std::sync::OnceLock::new();
let icon_png: &'static [u8] = Box::leak(png(128, 128, [200, 40, 40, 255]).into_boxed_slice());
let with_icon: &'static App = ICON_APP.get_or_init(|| App { icon_png: Some(icon_png), ..PHOTOCRAFT });
let ctx = dark_context();
let mut prompt = StartupPrompt { app: with_icon, ..prompt_for(false) };
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(textured_meshes(&output).len(), 1, "the app icon is drawn");
let badge = rect_fills(&output).iter().any(|(rect, fill)| *fill == DEFAULT_ACCENT && rect.width() == 34.0);
assert!(!badge, "no letter badge beside the icon");
assert!(!painted_text(&output).lines().any(|l| l == "P"), "no initial beside the icon");
// No icon (or one that won't decode): the initial in the accent badge, as before.
let ctx = dark_context();
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
assert!(textured_meshes(&output).is_empty());
assert!(painted_text(&output).lines().any(|l| l == "P"), "the initial stands in for a missing icon");
}
#[test]
fn an_apps_accent_fills_the_buttons_with_readable_text() {
// An amber accent: its buttons take it, with black text (white is under 3:1 on it).
static AMBER: std::sync::OnceLock<App> = std::sync::OnceLock::new();
let amber: &'static App = AMBER.get_or_init(|| App { accent: Some([0xf2, 0xa5, 0x16]), ..PHOTOCRAFT });
let ctx = dark_context();
let mut prompt = StartupPrompt { app: amber, ..prompt_for(false) };
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let fill = Color32::from_rgb(0xf2, 0xa5, 0x16);
assert!(rect_fills(&output).iter().any(|(_, f)| *f == fill), "the accent fills the button and badge");
assert!(!rect_fills(&output).iter().any(|(_, f)| *f == DEFAULT_ACCENT), "no default blue beside an accent");
assert_eq!(ink_on(fill), Color32::BLACK);
// Whichever of white and black contrasts more: black on the default blue, white on
// WordCraft's deeper blue and PdfCraft's red.
assert_eq!(ink_on(DEFAULT_ACCENT), Color32::BLACK);
assert_eq!(ink_on(Color32::from_rgb(0x3f, 0x5f, 0xe0)), Color32::WHITE);
assert_eq!(ink_on(Color32::from_rgb(0xb7, 0x02, 0x28)), Color32::WHITE);
// The accent underlines "What's new" (whose text is the body colour).
let underlined = line_strokes(&output).contains(&fill);
assert!(underlined, "the link's underline takes the accent");
assert!((contrast(Color32::BLACK, Color32::WHITE) - 21.0).abs() < 0.01);
}
#[test]
fn hovering_later_uses_the_prompts_own_background_not_the_hosts() {
// A host whose light theme hovers in black: LATER's dark text would vanish on it.
let ctx = Context::default();
ctx.set_theme(egui::ThemePreference::Light);
ctx.global_style_mut(|style| {
style.animation_time = 0.0;
style.visuals.widgets.hovered.weak_bg_fill = Color32::BLACK;
style.visuals.widgets.hovered.bg_fill = Color32::BLACK;
});
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let later = text_pos(&output, "LATER").expect("LATER is painted");
frame(&ctx, &mut prompt, vec![Event::PointerMoved(later)]);
let (_, hovered) = frame(&ctx, &mut prompt, vec![Event::PointerMoved(later)]);
let fills = rect_fills(&hovered);
assert!(fills.iter().any(|(r, f)| *f == button_states(false).0 && r.contains(later)), "LATER hovers in the prompt's grey: {fills:?}");
assert!(!fills.iter().any(|(r, f)| *f == Color32::BLACK && r.contains(later)), "not in the host's black");
}
/// The strokes of the rectangles painted this frame, with each rectangle.
fn rect_strokes(output: &FullOutput) -> Vec<(Rect, egui::Stroke)> {
fn collect(shape: &egui::Shape, out: &mut Vec<(Rect, egui::Stroke)>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out)),
egui::Shape::Rect(rect) => out.push((rect.rect, rect.stroke)),
_ => {}
}
}
let mut strokes = Vec::new();
for clipped in &output.shapes {
collect(&clipped.shape, &mut strokes);
}
strokes
}
#[test]
fn a_pressed_or_focused_button_shows_a_ring() {
// Focus and a press both draw the active state; its 2 px ring must show on LATER (whose
// border used to be fixed) and on the filled DOWNLOAD.
for label in ["LATER", "DOWNLOAD"] {
let ctx = dark_context();
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let at = text_pos(&output, label).expect("the button is painted");
let down = Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE };
frame(&ctx, &mut prompt, vec![Event::PointerMoved(at)]);
let (_, pressed) = frame(&ctx, &mut prompt, vec![down]);
let ring = rect_strokes(&pressed).iter().any(|(r, s)| r.contains(at) && s.width == 2.0 && s.color == Color32::from_rgb(245, 245, 248));
assert!(ring, "{label} shows the focus ring while pressed");
}
}
#[test]
fn a_focused_whats_new_link_shows_a_ring() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let link = text_pos(&output, "What's new").expect("the link is painted");
let tab = Event::Key { key: Key::Tab, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
let ringed = (0..8).any(|_| {
let (_, out) = frame(&ctx, &mut prompt, vec![tab.clone()]);
rect_strokes(&out).iter().any(|(r, s)| r.contains(link) && s.width == 2.0 && s.color == Color32::from_rgb(245, 245, 248))
});
assert!(ringed, "tabbing to the link shows the focus ring");
}
#[test]
fn whats_new_lines_up_with_the_buttons() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let link = text_pos(&output, "What's new").expect("the link is painted");
let button = text_pos(&output, "DOWNLOAD").expect("the button is painted");
assert!((link.y - button.y).abs() <= 1.0, "link centred at {} but the button at {}", link.y, button.y);
}
/// #391: the "What's new" link opens the release page only when it is a safe web link; an app
/// that builds its own `Release` (a feed, a cache) can't hand the browser anything else.
#[test]
fn whats_new_opens_only_a_safe_link() {
let opened = |url: &str| {
let ctx = dark_context();
let mut prompt = prompt_for(false);
prompt.release.html_url = url.to_string();
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let at = text_pos(&output, "What's new").expect("the link is painted");
let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
frame(&ctx, &mut prompt, vec![Event::PointerMoved(at)]);
frame(&ctx, &mut prompt, vec![button(true)]);
let (_, output) = frame(&ctx, &mut prompt, vec![button(false)]);
output.platform_output.commands.iter().find_map(|c| match c {
egui::OutputCommand::OpenUrl(u) => Some(u.url.clone()),
_ => None,
})
};
let page = "https://github.com/storytold/photocraft/releases/tag/v0.2.0";
assert_eq!(opened(page).as_deref(), Some(page));
for bad in ["", "file:///etc/passwd", "javascript:alert(1)", "https://evil.example/a&calc", "https://user@evil.example/"] {
assert_eq!(opened(bad), None, "{bad:?}");
}
}
#[test]
fn clicking_download_answers_download() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let at = text_pos(&output, "DOWNLOAD").expect("DOWNLOAD is painted");
let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE };
frame(&ctx, &mut prompt, vec![Event::PointerMoved(at)]);
frame(&ctx, &mut prompt, vec![button(true)]);
let (response, _) = frame(&ctx, &mut prompt, vec![button(false)]);
assert_eq!(response, StartupPromptResponse::Download);
}
/// The colours of the line segments painted this frame.
fn line_strokes(output: &FullOutput) -> Vec<Color32> {
fn collect(shape: &egui::Shape, out: &mut Vec<Color32>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out)),
egui::Shape::LineSegment { stroke, .. } => out.push(stroke.color),
_ => {}
}
}
let mut colors = Vec::new();
for clipped in &output.shapes {
collect(&clipped.shape, &mut colors);
}
colors
}
#[test]
fn every_craft_accent_reaches_aa_for_its_labels() {
// The 13 apps' accents (as ArtCraft Launcher shows them, PdfCraft's new red) and the default.
let accents = [
0x2f7bf5, 0xe8573f, 0x8b5cf6, 0xf2a516, 0xb70228, 0xe0368f, 0x7bb51c, 0x02da96, 0x3f5fe0, 0x1fa5c9, 0xf07a1e, 0x3ea6e8, 0x1f9d55,
0x3478f6,
];
for hex in accents {
let fill = Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8);
let ratio = contrast(fill, ink_on(fill));
assert!(ratio >= 4.5, "#{hex:06x}: {ratio:.2}:1");
}
}
/// Errors and failure reasons reach WCAG AA's 4.5:1 on the card and in the prompt's message
/// box, in both themes.
#[test]
fn failure_text_reaches_aa_in_both_themes() {
for theme in [egui::ThemePreference::Dark, egui::ThemePreference::Light] {
let ctx = Context::default();
ctx.set_theme(theme);
let pal = Palette::new(&ctx, &PHOTOCRAFT);
for (surface, bg) in [("card", pal.card_bg), ("message box", pal.alert_bg)] {
let ratio = contrast(pal.alert, bg);
assert!(ratio >= 4.5, "{theme:?} {surface}: {ratio:.2}:1");
}
}
}
/// A long error or failure reason scrolls inside the card, so the card's buttons stay on
/// screen.
#[test]
fn a_long_reason_keeps_the_buttons_on_screen() {
let long = "the installer reported an error. ".repeat(120);
let on_screen = |output: &FullOutput, label: &str| text_pos(output, label).is_some_and(|pos| screen().contains(pos));
let dialog = CheckResultDialog::new(&PHOTOCRAFT, "0.1.0");
for status in [Status::InstallFailed(long.clone()), Status::Failed(long.clone())] {
let ctx = dark_context();
let mut output = None;
// The first frame of an area only sizes it; the second paints.
for _ in 0..2 {
let mut out = ctx.run_ui(RawInput { screen_rect: Some(screen()), ..RawInput::default() }, |ui| {
dialog.show(ui.ctx(), &status);
});
out.textures_delta.clear();
output = Some(out);
}
let output = output.unwrap();
for label in ["OK", "CHECK AGAIN"] {
assert!(on_screen(&output, label), "{label} is off screen for a long {status:?}");
}
}
let ctx = dark_context();
let mut prompt = prompt_for(true);
prompt.set_message(long);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
for label in ["UPDATE AND RESTART", "LATER"] {
assert!(on_screen(&output, label), "{label} is off screen under a long message");
}
}
/// Where the frame painted `text` (inside its galley, so a pointer there is over it).
fn text_pos(output: &FullOutput, text: &str) -> Option<egui::Pos2> {
fn find(shape: &egui::Shape, text: &str) -> Option<egui::Pos2> {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)),
egui::Shape::Text(t) if t.galley.text() == text => Some(t.pos + t.galley.rect.center().to_vec2()),
_ => None,
}
}
output.shapes.iter().find_map(|c| find(&c.shape, text))
}
#[test]
fn the_prompt_names_the_developer() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
assert!(painted_text(&output).lines().any(|l| l == "by ArtCraft"), "every suite app is ArtCraft's by default");
// An app can name its own developer.
static OTHER: std::sync::OnceLock<App> = std::sync::OnceLock::new();
let other: &'static App = OTHER.get_or_init(|| App { developer: "Someone Else", ..PHOTOCRAFT });
let ctx = dark_context();
let mut prompt = StartupPrompt { app: other, ..prompt_for(false) };
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let painted = painted_text(&output);
assert!(painted.lines().any(|l| l == "by Someone Else") && !painted.contains("by ArtCraft"), "{painted}");
}
/// An error written straight to `status_message` shows even when a note was set before.
#[test]
fn a_literal_error_wins_over_a_stale_note() {
let mut prompt = prompt_for(false);
prompt.set_note(Note::new("Save or close your open work first; the update restarts the app.", &[]));
prompt.status_message = Some("disk full".into());
assert_eq!(prompt.message().as_deref(), Some("disk full"));
prompt.set_note(Note::new("Close {app}", &[("app", "PhotoCraft")]));
assert_eq!(prompt.message().as_deref(), Some("Close PhotoCraft"));
prompt.clear_message();
assert_eq!(prompt.message(), None);
}
#[test]
fn creates_startup_prompt_dialog() {
let release = Release { version: crate::version::parse("0.2.0"), tag: "v0.2.0".to_string(), ..Release::default() };
let prompt = StartupPrompt::new(&PHOTOCRAFT, release, "0.1.0");
assert_eq!(prompt.app.name, "PhotoCraft");
assert_eq!(prompt.running_version, "0.1.0");
assert!(prompt.open);
}
#[test]
fn download_prompt_paints_card_actions_and_stays_pending() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
// A new Area first measures itself invisibly; inspect the following visible frame.
let (sizing, _) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(sizing, StartupPromptResponse::Pending);
let (response, output) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(response, StartupPromptResponse::Pending);
assert!(prompt.open);
let painted = painted_text(&output);
for expected in [
"PhotoCraft",
"UPDATE",
"v0.1.0 to 0.2.0",
"PhotoCraft 0.2.0 is available with the latest features and bug fixes.",
"What's new",
"DOWNLOAD",
"LATER",
] {
assert!(painted.contains(expected), "missing {expected:?} in painted text {painted:?}");
}
assert!(!painted.contains("UPDATE AND RESTART"), "download branch must not offer the self-update button: {painted:?}");
// No glyph that a font might lack: apps that panic on a missing glyph would take the prompt down (#343).
assert!(painted.is_ascii(), "the prompt paints a non-ASCII character: {painted:?}");
let fills = rect_fills(&output);
let backdrop = fills.iter().any(|(rect, fill)| *fill == Color32::from_black_alpha(150) && rect.size() == screen().size());
assert!(backdrop, "modal backdrop missing: {fills:?}");
let card = fills.iter().any(|(_, fill)| *fill == DARK_CARD);
assert!(card, "dialog card missing: {fills:?}");
}
#[test]
fn self_updating_prompt_offers_update_and_restart() {
let ctx = dark_context();
let mut prompt = prompt_for(true);
// A new Area first measures itself invisibly; inspect the following visible frame.
let (sizing, _) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(sizing, StartupPromptResponse::Pending);
let (response, output) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(response, StartupPromptResponse::Pending);
assert!(prompt.open);
let painted = painted_text(&output);
assert!(painted.contains("UPDATE AND RESTART"), "self-update button missing: {painted:?}");
assert!(painted.contains("LATER"), "dismiss button missing: {painted:?}");
assert!(!painted.contains("DOWNLOAD"), "self-updating copy must not offer the manual download button: {painted:?}");
let card = rect_fills(&output).iter().any(|(_, fill)| *fill == DARK_CARD);
assert!(card, "dialog card missing");
}
#[test]
fn installing_prompt_paints_status_and_dismiss() {
let ctx = dark_context();
let mut prompt = prompt_for(true);
prompt.is_installing = true;
prompt.status_message = Some("Couldn't reach GitHub".to_string());
// A new Area first measures itself invisibly; inspect the following visible frame.
let (sizing, _) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(sizing, StartupPromptResponse::Pending);
let (response, output) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(response, StartupPromptResponse::Pending);
assert!(prompt.open);
let painted = painted_text(&output);
for expected in ["PhotoCraft", "Downloading and installing update…", "Couldn't reach GitHub", "DISMISS", "What's new"] {
assert!(painted.contains(expected), "missing {expected:?} in painted text {painted:?}");
}
for absent in ["LATER", "DOWNLOAD", "UPDATE AND RESTART"] {
assert!(!painted.contains(absent), "unexpected {absent:?} while installing: {painted:?}");
}
let fills = rect_fills(&output);
let alert = fills.iter().any(|(_, fill)| *fill == DARK_STATUS);
assert!(alert, "status alert frame missing: {fills:?}");
}
#[test]
fn escape_dismisses_open_prompt() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
let (first, _) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(first, StartupPromptResponse::Pending);
assert!(prompt.open);
let escape = Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
let (dismissed, dismissed_output) = frame(&ctx, &mut prompt, vec![escape]);
assert_eq!(dismissed, StartupPromptResponse::Later);
assert!(!prompt.open);
// The dismissing frame still paints the dialog; the closed state applies from the next frame on.
assert!(!painted_text(&dismissed_output).is_empty(), "dismissing frame should have painted the dialog");
let (later, closed_output) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(later, StartupPromptResponse::Later);
assert!(closed_output.shapes.is_empty(), "closed prompt painted {} shapes", closed_output.shapes.len());
}
#[test]
fn closed_prompt_returns_later_without_painting() {
let ctx = dark_context();
let mut prompt = prompt_for(false);
prompt.open = false;
let (response, output) = frame(&ctx, &mut prompt, Vec::new());
assert_eq!(response, StartupPromptResponse::Later);
assert!(!prompt.open);
assert!(output.shapes.is_empty(), "closed prompt painted {} shapes", output.shapes.len());
assert!(painted_text(&output).is_empty());
}
#[test]
fn check_result_paints_each_state_and_escape_closes() {
let dialog = CheckResultDialog::new(&PHOTOCRAFT, "0.1.0");
let run = |ctx: &Context, status: &Status, events: Vec<Event>| {
// The first frame of an area only sizes it; the second paints.
let mut frames = [Vec::new(), events].into_iter().map(|events| {
let mut response = CheckResultResponse::None;
let mut output = ctx.run_ui(RawInput { screen_rect: Some(screen()), events, ..RawInput::default() }, |ui| {
response = dialog.show(ui.ctx(), status);
});
output.textures_delta.clear();
(response, output)
});
frames.next();
frames.next().unwrap()
};
let ctx = dark_context();
let (_, checking) = run(&ctx, &Status::Checking, Vec::new());
assert!(painted_text(&checking).contains("Checking for updates…"));
assert!(!painted_text(&checking).contains("UPDATE"), "no update pill on a result");
let (_, up_to_date) = run(&ctx, &Status::UpToDate, Vec::new());
let text = painted_text(&up_to_date);
assert!(text.contains("PhotoCraft 0.1.0 is the newest version available.") && text.contains("OK"), "{text}");
let (response, failed) = run(&ctx, &Status::Failed("no network".into()), Vec::new());
let text = painted_text(&failed);
for want in ["Could not check for updates.", "no network", "All releases are listed at https://github.com/", "CHECK AGAIN", "OK"] {
assert!(text.contains(want), "{want} missing in {text}");
}
assert_eq!(response, CheckResultResponse::None);
let (_, idle) = run(&ctx, &Status::Idle, Vec::new());
assert!(painted_text(&idle).is_empty());
// An update under way, the launcher's choice, and what the last update came to.
let ready = crate::translate::fill(crate::updater::READY_TEXT, &[("app", "PhotoCraft")]);
let backdrop = Color32::from_black_alpha(150);
for (status, wants, modal) in [
(Status::Installing, vec!["Installing update…", "OK"], true),
(Status::Ready, vec![ready.as_str(), "RESTART TO UPDATE", "OK"], true),
(Status::Managed, vec!["PhotoCraft 0.1.0 follows the version chosen in the launcher, so it does not update itself.", "OK"], true),
(Status::Updated("0.2.0".into()), vec!["PhotoCraft updated to 0.2.0.", "OK"], false),
(Status::InstallFailed("disk full".into()), vec!["The update could not be installed: disk full", "CHECK AGAIN", "OK"], true),
] {
let (response, output) = run(&ctx, &status, Vec::new());
let text = painted_text(&output);
for want in wants {
assert!(text.contains(want), "{status:?}: {want} missing in {text}");
}
assert!(!text.contains("newest version"), "{status:?} is not called newest: {text}");
assert_eq!(response, CheckResultResponse::None);
assert_eq!(rect_fills(&output).iter().any(|(_, fill)| *fill == backdrop), modal, "{status:?} modal");
}
let escape = Event::Key { key: Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE };
assert_eq!(run(&dark_context(), &Status::UpToDate, vec![escape]).0, CheckResultResponse::Close);
}
/// A pseudo-language for the tests: every string bracketed, its values reordered first, so a
/// string the card draws without asking the app shows up as plain English.
fn pseudo(text: &str, args: &[(&str, &str)]) -> String {
let values: Vec<&str> = args.iter().map(|(_, value)| *value).collect();
format!("[{} | {}]", values.join(", "), text.split('{').next().unwrap_or(""))
}
/// Each painted line of a translated card is the app's (bracketed), or a value the card
/// doesn't translate (the badge initial, the app name, an error).
fn assert_all_translated(painted: &str, untranslated: &[&str]) {
for line in painted.lines() {
assert!(line.starts_with('[') || untranslated.contains(&line), "{line:?} is not translated in {painted:?}");
}
}
#[test]
fn the_prompt_draws_its_words_through_the_apps_translator() {
for (self_updating, installing, ready) in [(false, false, false), (true, false, false), (true, true, false), (true, false, true)] {
let ctx = dark_context();
let mut prompt = StartupPrompt { is_installing: installing, is_ready: ready, ..prompt_for(self_updating) }.with_translator(pseudo);
frame(&ctx, &mut prompt, Vec::new());
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
let painted = painted_text(&output);
assert_all_translated(&painted, &["P", "PhotoCraft"]);
// Values reach the translation; buttons are looked up in title case and drawn in capitals.
assert!(painted.contains("[0.1.0, 0.2.0 | v]") && painted.contains("[ArtCraft | by ]"), "{painted}");
let button = match (self_updating, installing, ready) {
(_, true, _) => "[ | DISMISS]",
(_, false, true) => "[ | RESTART TO UPDATE]",
(true, false, false) => "[ | UPDATE AND RESTART]",
(false, false, false) => "[ | DOWNLOAD]",
};
assert!(painted.contains(button) && painted.contains("[ | UPDATE]"), "{painted}");
}
}
#[test]
fn the_result_dialog_draws_its_words_through_the_apps_translator() {
let dialog = CheckResultDialog::new(&PHOTOCRAFT, "0.1.0").with_translator(pseudo);
for status in [
Status::Checking,
Status::UpToDate,
Status::Failed("no network".into()),
Status::Installing,
Status::Ready,
Status::Managed,
Status::Updated("0.2.0".into()),
Status::InstallFailed("no network".into()),
] {
let ctx = dark_context();
let mut output = None;
for _ in 0..2 {
let mut out = ctx.run_ui(RawInput { screen_rect: Some(screen()), ..RawInput::default() }, |ui| {
dialog.show(ui.ctx(), &status);
});
out.textures_delta.clear();
output = Some(out);
}
let painted = output.map(|o| painted_text(&o)).unwrap_or_default();
// The version line is a number, and a failure's reason comes from the network as it is.
assert_all_translated(&painted, &["P", "PhotoCraft", "v0.1.0", "no network"]);
assert!(painted.contains("[ArtCraft | by ]"), "{painted}");
}
}
}