Skip to content

Commit ca6b092

Browse files
committed
craft-update: the startup prompt shows the app's icon and accent colour
The update prompt drew the app name's first letter in a blue square and used that blue for its buttons and highlights. App gains accent, and the prompt now draws: - App::icon_png (decoded once per context, PNG only, at most 1024 px a side and never past the renderer's texture limit), keeping the letter badge for an app without a usable icon; - App::accent for its buttons, badge and highlights, with white text, or black where white falls under 3:1 on the accent; the UPDATE tag and the What's new link take the accent too. No accent keeps the default blue. - its own backgrounds for unfilled buttons (LATER, DISMISS) when hovered and pressed: the host app's widget style can hover in a colour its dark text doesn't read on (a light theme's dark hover). Apps opt in by passing their own App, e.g. App { icon_png: Some(include_bytes!("…128x128…png")), accent: Some([0x3f, 0x5f, 0xe0]), ..suite::WORDCRAFT }.
1 parent 733a038 commit ca6b092

4 files changed

Lines changed: 214 additions & 23 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/update/Cargo.toml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,13 @@ workspace = true
1212

1313
[features]
1414
default = []
15-
egui = ["dep:egui"]
15+
egui = ["dep:egui", "dep:image"]
1616
local-mirror = []
1717

1818
[dependencies]
1919
egui = { workspace = true, optional = true }
20+
# Decodes the app icon the startup prompt shows (`App::icon_png`); PNG only.
21+
image = { version = "0.25", default-features = false, features = ["png"], optional = true }
2022
serde = { workspace = true }
2123
serde_json = { workspace = true }
2224
log = "0.4"

‎crates/update/src/app.rs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@ pub struct App {
1717
pub former_names: &'static [&'static str],
1818
/// Its 128 px PNG icon, for the menu entry written beside an AppImage. `None`: no icon.
1919
pub icon_png: Option<&'static [u8]>,
20+
/// Its accent colour (sRGB), for the update prompt's buttons and highlights: the app's brand
21+
/// colour, as ArtCraft Launcher shows it. `None`: the default blue.
22+
pub accent: Option<[u8; 3]>,
2023
}
2124

2225
impl App {
2326
/// An app with no former names and no icon.
2427
pub const fn new(id: &'static str, name: &'static str, tagline: &'static str, repo: &'static str) -> Self {
25-
Self { id, name, tagline, repo, former_ids: &[], former_names: &[], icon_png: None }
28+
Self { id, name, tagline, repo, former_ids: &[], former_names: &[], icon_png: None, accent: None }
2629
}
2730

2831
/// `ai.storyteller.<id>`: macOS bundle id, Flatpak id and Linux desktop-file id.

‎crates/update/src/dialog.rs‎

Lines changed: 206 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ impl StartupPrompt {
6161
let border_color = if is_dark { Color32::from_rgb(52, 52, 56) } else { Color32::from_rgb(215, 215, 220) };
6262
let text_primary = if is_dark { Color32::from_rgb(245, 245, 248) } else { Color32::from_rgb(20, 20, 25) };
6363
let text_muted = if is_dark { Color32::from_rgb(150, 150, 160) } else { Color32::from_rgb(105, 105, 115) };
64-
let accent_color = Color32::from_rgb(52, 120, 246);
64+
let fill = self.app.accent.map_or(DEFAULT_ACCENT, |[r, g, b]| Color32::from_rgb(r, g, b));
65+
let on_fill = ink_on(fill);
6566

6667
egui::Area::new(egui::Id::unique("craft_update.startup_prompt"))
6768
.anchor(Align2::CENTER_CENTER, Vec2::ZERO)
@@ -74,22 +75,36 @@ impl StartupPrompt {
7475
.inner_margin(egui::Margin::symmetric(20, 18))
7576
.show(ui, |ui| {
7677
ui.set_width(400.0);
78+
// The host app's widget style isn't ours to rely on (a light theme's hover can be
79+
// dark under this card's dark text), so the prompt's buttons get their own states.
80+
let widgets = &mut ui.visuals_mut().widgets;
81+
let (hover_bg, press_bg) = button_states(is_dark);
82+
for (state, bg) in [(&mut widgets.inactive, card_bg), (&mut widgets.hovered, hover_bg), (&mut widgets.active, press_bg)] {
83+
state.weak_bg_fill = bg;
84+
state.bg_fill = bg;
85+
state.bg_stroke = egui::Stroke::new(1.0, border_color);
86+
}
7787
ui.spacing_mut().item_spacing = Vec2::new(8.0, 6.0);
7888

79-
// Header row: App badge + title + close
89+
// Header row: app icon (or its initial in a badge) + title + close
8090
ui.horizontal(|ui| {
8191
let (badge_rect, _) = ui.allocate_exact_size(Vec2::new(34.0, 34.0), egui::Sense::hover());
82-
ui.painter().rect_filled(badge_rect, egui::CornerRadius::ZERO, accent_color);
83-
let initial = self.app.name.chars().next().map(|c| c.to_string()).unwrap_or_else(|| "A".to_string());
84-
ui.painter().text(badge_rect.center(), Align2::CENTER_CENTER, initial, egui::FontId::monospace(18.0), Color32::WHITE);
92+
if let Some(icon) = icon_texture(ui.ctx(), self.app) {
93+
let uv = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
94+
ui.painter().image(icon.id(), badge_rect, uv, Color32::WHITE);
95+
} else {
96+
ui.painter().rect_filled(badge_rect, egui::CornerRadius::ZERO, fill);
97+
let initial = self.app.name.chars().next().map(|c| c.to_string()).unwrap_or_else(|| "A".to_string());
98+
ui.painter().text(badge_rect.center(), Align2::CENTER_CENTER, initial, egui::FontId::monospace(18.0), on_fill);
99+
}
85100

86101
ui.add_space(4.0);
87102

88103
ui.vertical(|ui| {
89104
ui.spacing_mut().item_spacing.y = 2.0;
90105
ui.horizontal(|ui| {
91106
ui.label(RichText::new(self.app.name).size(15.0).strong().color(text_primary));
92-
ui.label(RichText::new("UPDATE").size(10.0).monospace().color(accent_color));
107+
ui.label(RichText::new("UPDATE").size(10.0).monospace().color(fill));
93108
});
94109
// ASCII only, like the rest of the card: an app whose fonts lack a glyph may panic
95110
// instead of drawing a box, and this prompt shows up unasked.
@@ -147,10 +162,8 @@ impl StartupPrompt {
147162

148163
// Footer actions
149164
ui.horizontal(|ui| {
150-
let what_new = egui::Hyperlink::from_label_and_url(
151-
RichText::new("What's new").size(11.5).color(accent_color),
152-
&self.release.html_url,
153-
);
165+
let what_new =
166+
egui::Hyperlink::from_label_and_url(RichText::new("What's new").size(11.5).color(fill), &self.release.html_url);
154167
ui.add(what_new);
155168

156169
ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
@@ -164,21 +177,19 @@ impl StartupPrompt {
164177
}
165178
} else {
166179
if self.is_self_updating {
167-
let update_btn = egui::Button::new(
168-
RichText::new("UPDATE AND RESTART").size(10.5).strong().monospace().color(Color32::WHITE),
169-
)
170-
.fill(accent_color)
171-
.corner_radius(egui::CornerRadius::ZERO)
172-
.min_size(Vec2::new(140.0, 26.0));
180+
let update_btn =
181+
egui::Button::new(RichText::new("UPDATE AND RESTART").size(10.5).strong().monospace().color(on_fill))
182+
.fill(fill)
183+
.corner_radius(egui::CornerRadius::ZERO)
184+
.min_size(Vec2::new(140.0, 26.0));
173185
if ui.add(update_btn).clicked() {
174186
response = StartupPromptResponse::UpdateAndRestart;
175187
}
176188
} else {
177-
let dl_btn =
178-
egui::Button::new(RichText::new("DOWNLOAD").size(10.5).strong().monospace().color(Color32::WHITE))
179-
.fill(accent_color)
180-
.corner_radius(egui::CornerRadius::ZERO)
181-
.min_size(Vec2::new(90.0, 26.0));
189+
let dl_btn = egui::Button::new(RichText::new("DOWNLOAD").size(10.5).strong().monospace().color(on_fill))
190+
.fill(fill)
191+
.corner_radius(egui::CornerRadius::ZERO)
192+
.min_size(Vec2::new(90.0, 26.0));
182193
if ui.add(dl_btn).clicked() {
183194
response = StartupPromptResponse::Download;
184195
}
@@ -205,6 +216,71 @@ impl StartupPrompt {
205216
}
206217
}
207218

219+
/// Backgrounds of an unfilled button (LATER, DISMISS) when hovered and when pressed: a step from
220+
/// the card, so its text keeps the contrast it has at rest.
221+
fn button_states(is_dark: bool) -> (Color32, Color32) {
222+
if is_dark {
223+
(Color32::from_rgb(44, 44, 48), Color32::from_rgb(58, 58, 64))
224+
} else {
225+
(Color32::from_rgb(236, 236, 241), Color32::from_rgb(222, 222, 230))
226+
}
227+
}
228+
229+
/// The prompt's blue for an app that names no accent ([`App::accent`]).
230+
const DEFAULT_ACCENT: Color32 = Color32::from_rgb(52, 120, 246);
231+
232+
/// WCAG relative luminance of `c`: 0 for black to 1 for white.
233+
fn luminance(c: Color32) -> f32 {
234+
let channel = |v: u8| {
235+
let v = f32::from(v) / 255.0;
236+
if v <= 0.04045 { v / 12.92 } else { ((v + 0.055) / 1.055).powf(2.4) }
237+
};
238+
0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
239+
}
240+
241+
/// WCAG contrast ratio of two colours: 1 (none) to 21 (black on white).
242+
fn contrast(a: Color32, b: Color32) -> f32 {
243+
let (a, b) = (luminance(a), luminance(b));
244+
(a.max(b) + 0.05) / (a.min(b) + 0.05)
245+
}
246+
247+
/// Text for a label on `fill`: white, or black where white falls under 3:1 (WCAG's minimum for
248+
/// bold text and controls), as on an amber or mint accent.
249+
fn ink_on(fill: Color32) -> Color32 {
250+
if contrast(fill, Color32::WHITE) >= 3.0 { Color32::WHITE } else { Color32::BLACK }
251+
}
252+
253+
/// The largest icon the prompt decodes, a side; app icons are 128 px.
254+
const ICON_MAX_SIDE: u32 = 1024;
255+
256+
/// `app`'s icon as a texture, decoded once per context and app; `None` when the app has none or
257+
/// it doesn't decode, and the prompt shows the app's initial instead.
258+
fn icon_texture(ctx: &egui::Context, app: &App) -> Option<egui::TextureHandle> {
259+
let png = app.icon_png?;
260+
let id = egui::Id::unique(("craft_update.icon", app.id));
261+
if let Some(cached) = ctx.data(|d| d.get_temp::<Option<egui::TextureHandle>>(id)) {
262+
return cached;
263+
}
264+
// The renderer's own limit too: load_texture panics (debug) on a texture larger than it takes.
265+
let max_side = u32::try_from(ctx.input(|i| i.max_texture_side)).unwrap_or(u32::MAX).min(ICON_MAX_SIDE);
266+
let texture =
267+
decode_icon(png, max_side).map(|image| ctx.load_texture(format!("craft_update.icon.{}", app.id), image, egui::TextureOptions::LINEAR));
268+
ctx.data_mut(|d| d.insert_temp(id, texture.clone()));
269+
texture
270+
}
271+
272+
/// A PNG as an RGBA image, or `None` when it doesn't decode or is over `max_side` a side.
273+
fn decode_icon(png: &[u8], max_side: u32) -> Option<egui::ColorImage> {
274+
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(png), image::ImageFormat::Png);
275+
let mut limits = image::Limits::default();
276+
limits.max_image_width = Some(max_side);
277+
limits.max_image_height = Some(max_side);
278+
reader.limits(limits);
279+
let rgba = reader.decode().ok()?.to_rgba8();
280+
let size = [usize::try_from(rgba.width()).ok()?, usize::try_from(rgba.height()).ok()?];
281+
Some(egui::ColorImage::from_rgba_unmultiplied(size, rgba.as_raw()))
282+
}
283+
208284
#[cfg(test)]
209285
mod tests {
210286
use super::*;
@@ -290,6 +366,115 @@ mod tests {
290366
fills
291367
}
292368

369+
/// A `width` x `height` PNG of one opaque color.
370+
fn png(width: u32, height: u32, color: [u8; 4]) -> Vec<u8> {
371+
let mut out = std::io::Cursor::new(Vec::new());
372+
image::RgbaImage::from_pixel(width, height, image::Rgba(color)).write_to(&mut out, image::ImageFormat::Png).unwrap();
373+
out.into_inner()
374+
}
375+
376+
/// The textured meshes painted this frame (the app icon; text is drawn as `Shape::Text`).
377+
fn textured_meshes(output: &FullOutput) -> Vec<egui::TextureId> {
378+
fn collect(shape: &egui::Shape, out: &mut Vec<egui::TextureId>) {
379+
match shape {
380+
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect(s, out)),
381+
egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => out.push(mesh.texture_id),
382+
_ => {}
383+
}
384+
}
385+
let mut ids = Vec::new();
386+
for clipped in &output.shapes {
387+
collect(&clipped.shape, &mut ids);
388+
}
389+
ids
390+
}
391+
392+
#[test]
393+
fn icons_decode_and_bad_ones_are_refused() {
394+
let image = decode_icon(&png(3, 2, [10, 20, 30, 255]), ICON_MAX_SIDE).unwrap();
395+
assert_eq!(image.size, [3, 2]);
396+
assert_eq!(image.pixels[0], Color32::from_rgb(10, 20, 30));
397+
assert!(decode_icon(b"\x89PNG\r\n\x1a\nnot really", ICON_MAX_SIDE).is_none(), "a corrupt PNG must not decode");
398+
assert!(decode_icon(&png(ICON_MAX_SIDE + 1, 1, [0, 0, 0, 255]), ICON_MAX_SIDE).is_none(), "an oversized icon must not decode");
399+
// A renderer that takes smaller textures than the icon: no texture, so the initial is shown.
400+
assert!(decode_icon(&png(3, 2, [0, 0, 0, 255]), 2).is_none(), "an icon over the renderer's limit must not decode");
401+
}
402+
403+
#[test]
404+
fn prompt_shows_the_app_icon_or_else_its_initial() {
405+
static ICON_APP: std::sync::OnceLock<App> = std::sync::OnceLock::new();
406+
let icon_png: &'static [u8] = Box::leak(png(128, 128, [200, 40, 40, 255]).into_boxed_slice());
407+
let with_icon: &'static App = ICON_APP.get_or_init(|| App { icon_png: Some(icon_png), ..PHOTOCRAFT });
408+
let ctx = dark_context();
409+
let mut prompt = StartupPrompt { app: with_icon, ..prompt_for(false) };
410+
frame(&ctx, &mut prompt, Vec::new());
411+
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
412+
assert_eq!(textured_meshes(&output).len(), 1, "the app icon is drawn");
413+
let badge = rect_fills(&output).iter().any(|(rect, fill)| *fill == DEFAULT_ACCENT && rect.width() == 34.0);
414+
assert!(!badge, "no letter badge beside the icon");
415+
assert!(!painted_text(&output).lines().any(|l| l == "P"), "no initial beside the icon");
416+
417+
// No icon (or one that won't decode): the initial in the accent badge, as before.
418+
let ctx = dark_context();
419+
let mut prompt = prompt_for(false);
420+
frame(&ctx, &mut prompt, Vec::new());
421+
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
422+
assert!(textured_meshes(&output).is_empty());
423+
assert!(painted_text(&output).lines().any(|l| l == "P"), "the initial stands in for a missing icon");
424+
}
425+
426+
#[test]
427+
fn an_apps_accent_fills_the_buttons_with_readable_text() {
428+
// An amber accent: its buttons take it, with black text (white is under 3:1 on it).
429+
static AMBER: std::sync::OnceLock<App> = std::sync::OnceLock::new();
430+
let amber: &'static App = AMBER.get_or_init(|| App { accent: Some([0xf2, 0xa5, 0x16]), ..PHOTOCRAFT });
431+
let ctx = dark_context();
432+
let mut prompt = StartupPrompt { app: amber, ..prompt_for(false) };
433+
frame(&ctx, &mut prompt, Vec::new());
434+
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
435+
let fill = Color32::from_rgb(0xf2, 0xa5, 0x16);
436+
assert!(rect_fills(&output).iter().any(|(_, f)| *f == fill), "the accent fills the button and badge");
437+
assert!(!rect_fills(&output).iter().any(|(_, f)| *f == DEFAULT_ACCENT), "no default blue beside an accent");
438+
assert_eq!(ink_on(fill), Color32::BLACK);
439+
// The default blue keeps its white text; a dark accent does too.
440+
assert_eq!(ink_on(DEFAULT_ACCENT), Color32::WHITE);
441+
assert_eq!(ink_on(Color32::from_rgb(0x3f, 0x5f, 0xe0)), Color32::WHITE);
442+
assert!((contrast(Color32::BLACK, Color32::WHITE) - 21.0).abs() < 0.01);
443+
}
444+
445+
#[test]
446+
fn hovering_later_uses_the_prompts_own_background_not_the_hosts() {
447+
// A host whose light theme hovers in black: LATER's dark text would vanish on it.
448+
let ctx = Context::default();
449+
ctx.set_theme(egui::ThemePreference::Light);
450+
ctx.global_style_mut(|style| {
451+
style.animation_time = 0.0;
452+
style.visuals.widgets.hovered.weak_bg_fill = Color32::BLACK;
453+
style.visuals.widgets.hovered.bg_fill = Color32::BLACK;
454+
});
455+
let mut prompt = prompt_for(false);
456+
frame(&ctx, &mut prompt, Vec::new());
457+
let (_, output) = frame(&ctx, &mut prompt, Vec::new());
458+
let later = text_pos(&output, "LATER").expect("LATER is painted");
459+
frame(&ctx, &mut prompt, vec![Event::PointerMoved(later)]);
460+
let (_, hovered) = frame(&ctx, &mut prompt, vec![Event::PointerMoved(later)]);
461+
let fills = rect_fills(&hovered);
462+
assert!(fills.iter().any(|(r, f)| *f == button_states(false).0 && r.contains(later)), "LATER hovers in the prompt's grey: {fills:?}");
463+
assert!(!fills.iter().any(|(r, f)| *f == Color32::BLACK && r.contains(later)), "not in the host's black");
464+
}
465+
466+
/// Where the frame painted `text` (inside its galley, so a pointer there is over it).
467+
fn text_pos(output: &FullOutput, text: &str) -> Option<egui::Pos2> {
468+
fn find(shape: &egui::Shape, text: &str) -> Option<egui::Pos2> {
469+
match shape {
470+
egui::Shape::Vec(shapes) => shapes.iter().find_map(|s| find(s, text)),
471+
egui::Shape::Text(t) if t.galley.text() == text => Some(t.pos + t.galley.rect.center().to_vec2()),
472+
_ => None,
473+
}
474+
}
475+
output.shapes.iter().find_map(|c| find(&c.shape, text))
476+
}
477+
293478
#[test]
294479
fn creates_startup_prompt_dialog() {
295480
let release = Release { version: crate::version::parse("0.2.0"), tag: "v0.2.0".to_string(), ..Release::default() };

0 commit comments

Comments
 (0)