craft-update: the prompt's own messages are translated when it draws; fill keeps unknown placeholders whole (review)

The installed, save-your-work-first, can't-auto-update and couldn't-start messages were
translated when set, so a language change while the prompt showed one left it in the old
language. They are now a Note (English text and values) in StartupPrompt::status_note,
translated each time the prompt draws; errors from elsewhere stay in status_message as they
came. set_note/set_message/clear_message keep only one; message() is what the prompt shows.

fill keeps an unknown placeholder through its closing brace (`{bad {app}` stays), the rule
craft_i18n::fmt follows.
This commit is contained in:
cdhdt committed 2026-11-02 11:17:00 +01:00
1 parent a9e5afebf8
commit 493bdb9b1c
3 files changed
+117 -32

No files matched your search

+31 -2
View File
@@ -4,7 +4,7 @@ use egui::{Align, Align2, Color32, Layout, RichText, Vec2};
use crate::app::App;
use crate::release::Release;
use crate::translate::{Translate, button, english};
use crate::translate::{Note, Translate, button, english};
use crate::updater::Status;
/// What the user chose in the startup update prompt.
@@ -28,7 +28,11 @@ pub struct StartupPrompt {
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; shown instead of
/// `status_message`. [`StartupPrompt::set_note`] and [`StartupPrompt::set_message`] keep one.
pub status_note: Option<Note>,
pub is_installing: bool,
/// Puts the card's words in the interface language ([`crate::translate`]); English by default.
pub translate: Translate,
@@ -45,11 +49,35 @@ impl StartupPrompt {
is_self_updating,
open: true,
status_message: None,
status_note: None,
is_installing: 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.
pub fn message(&self) -> Option<String> {
self.status_note.as_ref().map(|note| note.translated(self.translate)).or_else(|| self.status_message.clone())
}
/// The prompt with its words in the interface language ([`crate::translate`]).
#[must_use]
pub fn with_translator(mut self, translate: Translate) -> Self {
@@ -95,7 +123,7 @@ impl StartupPrompt {
ui.add_space(8.0);
if let Some(msg) = &self.status_message {
if let Some(msg) = self.message() {
let alert_bg = if is_dark { Color32::from_rgb(50, 30, 20) } else { Color32::from_rgb(255, 242, 235) };
let alert_color = Color32::from_rgb(225, 95, 30);
egui::Frame::new()
@@ -538,6 +566,7 @@ mod tests {
is_self_updating,
open: true,
status_message: None,
status_note: None,
is_installing: false,
translate: english,
}
+43 -15
View File
@@ -27,34 +27,57 @@ pub fn english(text: &str, args: &[(&str, &str)]) -> String {
fill(text, args)
}
/// `template` with each `{name}` in `args` replaced by its value. A placeholder that `args`
/// lacks stays as written. An inserted value is never read as a template, so a value containing
/// `{app}` stays intact.
/// `template` with each `{name}` in `args` replaced by its value, by the rules of
/// `craft_i18n::fmt` (without its bidi isolates): a placeholder runs from a `{` to the next `}`,
/// and one that `args` lacks stays as written, braces and all. An inserted value is never read as
/// a template, so a value containing `{app}` stays intact.
pub fn fill(template: &str, args: &[(&str, &str)]) -> String {
let mut out = String::with_capacity(template.len());
let mut rest = template;
while let Some(open) = rest.find('{') {
let (before, from_brace) = rest.split_at(open);
while let Some((before, after_open)) = rest.split_once('{') {
out.push_str(before);
let value = from_brace.find('}').and_then(|close| {
let name = from_brace.get(1..close)?;
args.iter().find(|(key, _)| *key == name).map(|(_, value)| (*value, close))
});
match value {
Some((value, close)) => {
out.push_str(value);
rest = from_brace.get(close + 1..).unwrap_or("");
}
let Some((name, after_close)) = after_open.split_once('}') else {
out.push('{');
rest = after_open;
break;
};
match args.iter().find(|(key, _)| *key == name) {
Some((_, value)) => out.push_str(value),
None => {
out.push('{');
rest = from_brace.get(1..).unwrap_or("");
out.push_str(name);
out.push('}');
}
}
rest = after_close;
}
out.push_str(rest);
out
}
/// One of the crate's own messages in the startup prompt ("The update is installed…"), kept as
/// its English text and values so it is translated each time the prompt draws: a change of
/// interface language while it shows changes it too.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Note {
/// The English text, the lookup key.
pub text: &'static str,
/// The values of its `{name}` placeholders.
pub args: Vec<(&'static str, String)>,
}
impl Note {
pub fn new(text: &'static str, args: &[(&'static str, &str)]) -> Self {
Self { text, args: args.iter().map(|(k, v)| (*k, (*v).to_owned())).collect() }
}
/// The note in the interface language.
pub fn translated(&self, translate: Translate) -> String {
let args: Vec<(&str, &str)> = self.args.iter().map(|(k, v)| (*k, v.as_str())).collect();
translate(self.text, &args)
}
}
/// A button label: `label` (title case, the lookup key) translated, then in capitals, as the card
/// draws its buttons.
pub(crate) fn button(translate: Translate, label: &str) -> String {
@@ -72,6 +95,9 @@ mod tests {
assert_eq!(fill("{version}: {app}", &[("app", "A"), ("version", "1")]), "1: A");
// Unknown and unclosed placeholders stay; a value holding a placeholder stays as it is.
assert_eq!(fill("{nope} and {app", &[("app", "X")]), "{nope} and {app");
// An unknown candidate stays whole through its closing brace, as craft_i18n::fmt keeps it.
assert_eq!(fill("{bad {app}", &[("app", "X")]), "{bad {app}");
assert_eq!(fill("{bad} {app}", &[("app", "X")]), "{bad} X");
assert_eq!(fill("by {developer}", &[("developer", "{developer}")]), "by {developer}");
assert_eq!(fill("é {app} ü", &[("app", "日本")]), "é 日本 ü");
assert_eq!(fill("", &[]), "");
@@ -86,5 +112,7 @@ mod tests {
fill(if text == "Later" { "Plus tard" } else { text }, args)
}
assert_eq!(button(french, "Later"), "PLUS TARD");
let note = Note::new("Close {app} to finish", &[("app", "PdfCraft")]);
assert_eq!(note.translated(english), "Close PdfCraft to finish");
}
}
+43 -15
View File
@@ -15,7 +15,7 @@ use std::time::Duration;
use crate::dialog::{StartupPrompt, StartupPromptResponse};
use crate::pins::{Choice, Pins};
use crate::release::Release;
use crate::translate::{Translate, english};
use crate::translate::{Note, Translate, english};
use crate::{App, Http, Paths, Platform, Stop, check_for_update, self_update};
/// Asks for the newest release (blocking; it runs on its own thread). Tests stand in for the network
@@ -105,9 +105,9 @@ impl Updater {
StartupPrompt::new(self.app, release, self.version.clone()).with_translator(self.translate)
}
/// "The update is installed…", in the interface language.
fn installed_message(&self) -> String {
(self.translate)("The update is installed. Close {app} to finish; it restarts by itself.", &[("app", self.app.name)])
/// "The update is installed…", translated when the prompt draws.
fn installed_note(&self) -> Note {
Note::new("The update is installed. Close {app} to finish; it restarts by itself.", &[("app", self.app.name)])
}
/// Replaces the network with `source` (tests).
@@ -275,10 +275,10 @@ impl Updater {
Ok(()) => {
self.installed = true;
self.restart = true;
let message = self.installed_message();
let note = self.installed_note();
if let Some(prompt) = &mut self.prompt {
prompt.is_installing = false;
prompt.status_message = Some(message);
prompt.set_note(note);
}
}
Err(e) => {
@@ -291,7 +291,7 @@ impl Updater {
}
if let Some(prompt) = &mut self.prompt {
prompt.is_installing = false;
prompt.status_message = Some(e);
prompt.set_message(e);
}
}
}
@@ -338,7 +338,7 @@ impl Updater {
if can_start {
self.start_install(ctx);
} else if let Some(prompt) = &mut self.prompt {
prompt.status_message = Some((self.translate)("Save or close your open work first; the update restarts the app.", &[]));
prompt.set_note(Note::new("Save or close your open work first; the update restarts the app.", &[]));
}
}
@@ -347,19 +347,19 @@ impl Updater {
if self.install.is_none() && !self.installed && self.read_choice() {
return;
}
let (installed_message, t) = (self.installed_message(), self.translate);
let installed_note = self.installed_note();
let Some(prompt) = &mut self.prompt else { return };
if self.installed {
prompt.status_message = Some(installed_message);
prompt.set_note(installed_note);
return;
}
let Some(installed) = self_update::current(self.app) else {
prompt.status_message = Some(t("Cannot auto-update this installation type. Please download manually.", &[]));
prompt.set_note(Note::new("Cannot auto-update this installation type. Please download manually.", &[]));
prompt.is_installing = false;
return;
};
prompt.is_installing = true;
prompt.status_message = None;
prompt.clear_message();
let (tx, rx) = channel();
let (app, version, ctx, release) = (self.app, self.version.clone(), ctx.clone(), prompt.release.clone());
let worker_release = release.clone();
@@ -374,7 +374,7 @@ impl Updater {
Ok(_) => self.install = Some((rx, release)),
Err(e) => {
prompt.is_installing = false;
prompt.status_message = Some(format!("couldn't start the update ({e})"));
prompt.set_note(Note::new("Couldn't start the update ({error})", &[("error", &e.to_string())]));
}
}
}
@@ -561,7 +561,7 @@ mod tests {
u.install = Some((rx, newer()));
drop(tx);
u.tick(&ctx);
assert!(u.prompt.as_ref().is_some_and(|p| p.status_message.is_some()));
assert!(u.prompt.as_ref().is_some_and(|p| p.message().is_some()));
}
#[test]
@@ -587,7 +587,35 @@ mod tests {
u.offer(newer());
u.request_install(&ctx, false);
assert!(u.install.is_none(), "nothing is scheduled while there is unsaved work");
assert!(u.prompt.as_ref().is_some_and(|p| !p.is_installing && p.status_message.is_some()));
assert!(u.prompt.as_ref().is_some_and(|p| !p.is_installing && p.message().is_some()));
}
/// The updater's own messages follow the interface language while the prompt shows them:
/// they are translated when it draws, not when they are set.
#[test]
fn the_prompts_own_messages_follow_a_language_change() {
use std::sync::atomic::{AtomicBool, Ordering};
static FRENCH: AtomicBool = AtomicBool::new(false);
fn translate(text: &str, args: &[(&str, &str)]) -> String {
let text = if FRENCH.load(Ordering::Relaxed) { format!("FR {text}") } else { text.to_owned() };
crate::translate::fill(&text, args)
}
let ctx = egui::Context::default();
let mut u = updater(Ok(None)).with_translator(translate);
u.offer(newer());
u.request_install(&ctx, false);
let message = |u: &Updater| u.prompt.as_ref().and_then(StartupPrompt::message).unwrap_or_default();
assert!(message(&u).starts_with("Save or close"), "{}", message(&u));
FRENCH.store(true, Ordering::Relaxed);
assert!(message(&u).starts_with("FR Save or close"), "{}", message(&u));
// An installed update names the app, in the language of the moment.
let (tx, rx) = channel();
u.install = Some((rx, newer()));
assert!(tx.send(Ok(())).is_ok());
u.tick(&ctx);
assert!(message(&u).starts_with("FR The update is installed. Close PhotoCraft"), "{}", message(&u));
FRENCH.store(false, Ordering::Relaxed);
assert!(message(&u).starts_with("The update is installed."), "{}", message(&u));
}
/// One frame with the updater's prompt drawn.