S057: site colour from the favicon

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-11-14 07:21:33 -06:00
commit b458a6d9bc
14 changed files with 119 additions and 12 deletions

View file

@ -27,7 +27,7 @@ Bugs the user and S048/S056 found that are small but visible every day.
- [x] Wheel over floating egui surfaces scrolls them, never the page; Customize sheet scrolls to its last row; regression smoke (wheel over the sheet, assert scroll offset; page scroll unchanged).
- [x] Colour picker chips render (font fallback or no emoji).
- [x] beforeunload on window close / quit through Nacre's dialog; smoke with a page that sets it.
- [ ] Site colour from the favicon (dominant vivid colour, unit-tested on a few icons: red, blue, monochrome → none), applied when Colour source = Website; works on WebKit; `colours.txt` smoke updated; shots of two coloured sites and one monochrome site read.
- [x] Site colour from the favicon (dominant vivid colour, unit-tested on a few icons: red, blue, monochrome → none), applied when Colour source = Website; works on WebKit; `colours.txt` smoke updated; shots of two coloured sites and one monochrome site read.
- [ ] Hidden smokes launch, basics, input, chrome, newtab green; shots read.
- [ ] PROGRESS entry, INDEX line, tracker, commit `S057: …`, push.
@ -41,4 +41,4 @@ Bugs the user and S048/S056 found that are small but visible every day.
Which surfaces now take the wheel.
## Resume
Boxes 1-3 done (beforeunload: App::begin_shutdown/shutdown_answered/cancel_shutdown in app.rs, smoke unload-quit.txt). Next: box 4 favicon colour.
Boxes 1-4 done (favicon colour: theme::dominant_vivid, Tab.favicon_colour, smoke favicon-colour.txt needs the loopback server). Next: box 5 smokes, box 6 close out.

View file

@ -1601,7 +1601,7 @@ impl App {
match message.kind.as_str() {
"ready" => {},
"meta" => {
let color = crate::theme::parse_css_color(&s(&data, "theme_color")).or_else(|| crate::theme::parse_css_color(&s(&data, "background")));
let color = crate::theme::parse_css_color(&s(&data, "theme_color"));
let icon = data.get("icons").and_then(|v| v.as_array()).and_then(|a| a.first()).map(|i| s(i, "href")).unwrap_or_default();
let changed;
{
@ -1616,11 +1616,7 @@ impl App {
}
}
if changed && self.shared.settings.borrow().theme.source == crate::store::settings::ColourSource::Website && self.windows[&w].active == i {
if let Some(mut win) = self.windows.remove(&w) {
self.style_window(&mut win);
self.windows.insert(w, win);
}
self.redraw(w);
self.restyle(w);
}
},
"media" => {

View file

@ -635,6 +635,7 @@ impl App {
if host_changed {
tab.arrived_ms = util::now_ms();
tab.theme_color = None;
tab.favicon_colour = None;
tab.site_name.clear();
tab.favicon = None;
tab.favicon_png = None;
@ -898,6 +899,9 @@ impl App {
if rgba.len() != (width * height * 4) as usize || width == 0 {
return;
}
let colour = theme::dominant_vivid(&rgba);
let changed = tab.favicon_colour != colour;
tab.favicon_colour = colour;
let color = egui::ColorImage::from_rgba_unmultiplied([width as usize, height as usize], &rgba);
tab.favicon = Some(ctx.load_texture(format!("favicon-{}", tab.id), color, egui::TextureOptions::LINEAR));
let mut png = Vec::new();
@ -907,6 +911,18 @@ impl App {
tab.favicon_png = Some(png);
}
win.redraw();
if changed && self.shared.settings.borrow().theme.source == crate::store::settings::ColourSource::Website && self.windows[&w].active == i {
self.restyle(w);
}
}
/// Rebuilds a window's palette (the site colour changed).
pub fn restyle(&mut self, w: WindowId) {
if let Some(mut win) = self.windows.remove(&w) {
self.style_window(&mut win);
self.windows.insert(w, win);
}
self.redraw(w);
}
/// A pop-up opened as a tab next to its opener (WebKit already made its view, related to the opener's).

View file

@ -882,7 +882,7 @@ impl App {
"favicon": t.favicon.is_some(), "crashed": t.crashed, "can_back": t.can_go_back(), "can_forward": t.can_go_forward(),
"history_len": t.back_forward.len(), "find": [t.find.index, t.find.count], "prompts": t.prompts.len(),
"dialog": t.dialog.is_some(), "media": t.media.as_ref().map(|(m, _)| serde_json::json!({"title": m.title, "paused": m.paused, "duration": m.duration, "position": m.position})),
"theme_color": t.theme_color.map(crate::theme::to_hex), "pip": t.pip_size.is_some(),
"theme_color": t.theme_color.map(crate::theme::to_hex), "favicon_colour": t.favicon_colour.map(crate::theme::to_hex), "site_colour": t.site_colour().map(crate::theme::to_hex), "pip": t.pip_size.is_some(),
})
})
.collect()

View file

@ -186,8 +186,10 @@ pub struct Tab {
pub upgraded_from: Option<Url>,
/// The certificate warning on show; its "Open anyway" (`nacre://allowcert`) trusts this one.
pub cert_error: Option<crate::engine::CertError>,
/// Page details from META_JS.
/// Page details from META_JS: the `theme-color` meta.
pub theme_color: Option<egui::Color32>,
/// The icon's dominant vivid colour (`theme::dominant_vivid`).
pub favicon_colour: Option<egui::Color32>,
pub site_name: String,
pub page_image: String,
pub manifest: String,
@ -240,6 +242,7 @@ impl Tab {
upgraded_from: None,
cert_error: None,
theme_color: None,
favicon_colour: None,
site_name: String::new(),
page_image: String::new(),
manifest: String::new(),
@ -266,9 +269,10 @@ impl Tab {
self.page.is_some()
}
/// The colour the "Website" colour source follows: none on an internal page, even one shown over a web page.
/// The colour the "Website" colour source follows: the favicon's, else the page's `theme-color`; none on an
/// internal page, even one shown over a web page.
pub fn site_colour(&self) -> Option<egui::Color32> {
if self.is_internal() { None } else { self.theme_color }
if self.is_internal() { None } else { self.favicon_colour.or(self.theme_color) }
}
pub fn loading(&self) -> bool {
@ -333,6 +337,8 @@ mod tests {
tab.page = None;
tab.theme_color = Some(egui::Color32::from_rgb(0xDE, 0x58, 0x33));
assert_eq!(tab.site_colour(), tab.theme_color);
tab.favicon_colour = Some(egui::Color32::from_rgb(0x30, 0x60, 0xE0));
assert_eq!(tab.site_colour(), tab.favicon_colour);
tab.page = Some(Page::Settings(String::new()));
assert_eq!(tab.site_colour(), None);
}

View file

@ -30,6 +30,38 @@ pub fn parse_hex(text: &str) -> Option<Color32> {
}
}
/// The most common vivid colour of an icon (RGBA, not premultiplied), for the "Website" colour source: pixels that
/// are transparent, grey, near-white or near-black are skipped, the rest are counted in 12 hue buckets and the
/// winning bucket is averaged. None when too little of the icon is vivid (a monochrome icon has no colour).
pub fn dominant_vivid(rgba: &[u8]) -> Option<Color32> {
let mut buckets = [(0u32, [0u32; 3]); 12];
let mut opaque = 0u32;
for px in rgba.chunks_exact(4) {
if px[3] < 128 {
continue;
}
opaque += 1;
let (r, g, b) = (px[0] as f32 / 255.0, px[1] as f32 / 255.0, px[2] as f32 / 255.0);
let (max, min) = (r.max(g).max(b), r.min(g).min(b));
let delta = max - min;
if max < 0.25 || delta / max < 0.35 {
continue;
}
let hue = if max == r { ((g - b) / delta).rem_euclid(6.0) } else if max == g { (b - r) / delta + 2.0 } else { (r - g) / delta + 4.0 };
let bucket = &mut buckets[(hue * 2.0) as usize % 12];
bucket.0 += 1;
for (sum, c) in bucket.1.iter_mut().zip(&px[..3]) {
*sum += *c as u32;
}
}
let (count, sum) = buckets.iter().max_by_key(|b| b.0).copied()?;
// A few stray pixels (anti-aliasing) don't make a colour.
if count < 4 || count * 20 < opaque {
return None;
}
Some(Color32::from_rgb((sum[0] / count) as u8, (sum[1] / count) as u8, (sum[2] / count) as u8))
}
/// "rgb(1, 2, 3)", "rgba(...)" or "#abc" from CSS.
pub fn parse_css_color(text: &str) -> Option<Color32> {
let t = text.trim();
@ -611,6 +643,29 @@ pub fn visuals(p: &Palette, corner_radius: u8) -> Visuals {
#[cfg(test)]
mod tests {
fn icon(pixels: &[([u8; 4], usize)]) -> Vec<u8> {
pixels.iter().flat_map(|(px, n)| std::iter::repeat_n(*px, *n)).flatten().collect()
}
#[test]
fn favicon_colour_is_the_dominant_vivid_one() {
// Mostly red with some blue, white, black and transparent: red.
let red = icon(&[([220, 30, 30, 255], 60), ([30, 30, 220, 255], 10), ([255, 255, 255, 255], 20), ([0, 0, 0, 255], 20), ([0, 0, 0, 0], 40)]);
assert_eq!(dominant_vivid(&red), Some(Color32::from_rgb(220, 30, 30)));
let blue = icon(&[([30, 80, 230, 255], 50), ([220, 30, 30, 255], 10)]);
assert_eq!(dominant_vivid(&blue), Some(Color32::from_rgb(30, 80, 230)));
}
#[test]
fn monochrome_favicon_has_no_colour() {
let mono = icon(&[([0, 0, 0, 255], 50), ([255, 255, 255, 255], 40), ([128, 128, 128, 255], 30), ([200, 30, 30, 0], 99)]);
assert_eq!(dominant_vivid(&mono), None);
// A few coloured edge pixels in a grey icon don't count either.
let edges = icon(&[([120, 120, 120, 255], 200), ([220, 30, 30, 255], 3)]);
assert_eq!(dominant_vivid(&edges), None);
assert_eq!(dominant_vivid(&[]), None);
}
use super::*;
/// Laying out text renders glyphs (epaint 0.37.0 once panicked rasterizing them).

View file

@ -1,3 +1,4 @@
# S057: site colour is the favicon's dominant vivid colour, else this page's theme-color (tests/smoke/favicon-colour.txt covers icons).
# R1-11: colours still change after the welcome setup, also when Settings is typed into a web tab whose page has a
# theme-color. Hidden 1280x1100 layout (tap positions): SMOKE_SIZE=1280x1100, fresh outdir. Expect: site-* orange
# chrome (#DE5833 seed); s-website NOT orange (an internal page has no site colour); s-teal teal; back-site orange

View file

@ -0,0 +1,30 @@
# Site colour from the favicon (S057): Colour source "Website" follows the icon's dominant vivid colour; a
# monochrome icon gives none. Offline, pages from a loopback server (a file:// page gets no favicon):
# python3 -m http.server 8765 --bind 127.0.0.1 --directory tests/smoke/pages & then tools/smoke.sh <this script>
# Expect: shot-red chrome red, shot-blue chrome blue, shot-mono the default colour (System accent / palette, no tint).
wait 3
resize 1280 900
set /theme/source "website"
set /theme/mode "light"
open http://127.0.0.1:8765/favicon-red.html
waitload 30
wait 2
status red
expect /active/favicon_colour "#D62828"
expect /active/site_colour "#D62828"
shot shot-red
open http://127.0.0.1:8765/favicon-blue.html
waitload 30
wait 2
status blue
expect /active/favicon_colour "#1E5ADC"
shot shot-blue
open http://127.0.0.1:8765/favicon-mono.html
waitload 30
wait 2
status mono
expect /active/favicon_colour null
expect /active/site_colour null
shot shot-mono
status done
quit

View file

@ -0,0 +1 @@
<!doctype html><meta charset=utf-8><title>Favicon blue</title><link rel="icon" href="favicon-blue.png"><body style="background:#fff;font:20px sans-serif;padding:2em">Favicon test: blue

Binary file not shown.

After

Width:  |  Height:  |  Size: 172 B

View file

@ -0,0 +1 @@
<!doctype html><meta charset=utf-8><title>Favicon mono</title><link rel="icon" href="favicon-mono.png"><body style="background:#fff;font:20px sans-serif;padding:2em">Favicon test: mono

Binary file not shown.

After

Width:  |  Height:  |  Size: 182 B

View file

@ -0,0 +1 @@
<!doctype html><meta charset=utf-8><title>Favicon red</title><link rel="icon" href="favicon-red.png"><body style="background:#fff;font:20px sans-serif;padding:2em">Favicon test: red

Binary file not shown.

After

Width:  |  Height:  |  Size: 171 B