Task manager: draw each app's real icon from its .desktop file
CI / test (push) Failing after 16s

Each pill now shows the icon the app's .desktop file names (Icon=), looked up in the
freedesktop icon themes, instead of the letter tile. The tile stays as the fallback for
windows with no app id, no desktop file or no icon the host can read.

- WIT: a new `icons` capability (`app-icon(app-id) -> u32`, a handle, never a path or pixels)
  and an `image(image-op)` draw op (appended, so existing modules keep their ABI).
  taskbar-widget and plasmoid-host import `icons`. Host raster gains `load-image(path)` and a
  `draw-image` op; the plasmoids host gets an icons table (6: app id, handle).
- Compositor (shell/icons.mbt): window app id -> desktop file (resolve_app_id, so StartupWMClass
  and last-dotted-part matches work) -> Icon= -> theme lookup (XDG data dirs, ~/.icons,
  flatpak exports; hicolor, Adwaita, breeze; 48/64/32 px PNG first, then scalable SVG when the
  host can draw it, then other sizes, then /usr/share/pixmaps). Absolute Icon= paths are used as
  they are. Results are cached per app id; the table is published only when a module imports
  `icons`.
- wasm host (host-wasm): PNG via the png crate, SVG via resvg (rendered sharp at each size),
  PNGs area-averaged to the drawn size; loads cached by path.
- Native build: a small PNG decoder (compositor/renderer/png.mbt: inflate + filters, 1-16 bit,
  palettes with tRNS) and the Image op in the software renderer. SVG-only icons fall back to the
  tile there. The wasmer stub serves `icons.app-icon` from the same table.
- Tests: PNG decoder fixtures (all filters, fixed/dynamic/stored blocks, palette), image scaling
  and drawing, icon lookup order, Icon= parsing, task module icon-or-tile (native and wasmtime),
  host raster PNG+SVG loading and drawing. Checked end to end with the wasm host: foot's
  hicolor icon shows on its pill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hhmtDt52EjaW8jevGU
This commit is contained in:
Claude committed 2026-11-25 18:52:58 +00:00
1 parent 0e6a1257e1
commit f2e870c251
53 files changed
+2284 -473

No files matched your search

+201 -5
View File
@@ -8,6 +8,7 @@
use crate::chandra::host::raster as wt;
use ab_glyph::{Font, FontVec, OutlineCurve};
use ab_glyph_rasterizer::{point, Rasterizer};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
@@ -416,8 +417,170 @@ fn draw_text(c: &mut Canvas, fonts: &mut Fonts, t: &wt::Label, ox: i32, oy: i32,
}
}
// ---------------------------------------------------------------- images
/// An image loaded with `load-image` (an app icon). An SVG keeps its tree, so it is rendered sharp at
/// each size it is drawn at; a PNG is kept as RGBA8888 and scaled.
enum ImageSrc {
Pixels { w: i32, h: i32, rgba: Vec<u8> },
Svg(resvg::usvg::Tree),
}
/// Loaded images by handle (`index + 1`), the handle of each path, and each image at the sizes it
/// has been drawn at (RGBA8888, not premultiplied).
#[derive(Default)]
pub struct Images {
srcs: Vec<ImageSrc>,
by_path: HashMap<String, u32>,
sized: RefCell<HashMap<(u32, i32, i32), Rc<Vec<u8>>>>,
}
/// Biggest image side accepted from a file, and drawn.
const MAX_IMAGE: i32 = 1024;
fn decode_png(bytes: &[u8]) -> Option<ImageSrc> {
let mut dec = png::Decoder::new(std::io::Cursor::new(bytes));
// Palette, grey and 16-bit images come out as 8-bit grey/GA/RGB/RGBA.
dec.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16);
let mut reader = dec.read_info().ok()?;
let (w, h) = (reader.info().width as i32, reader.info().height as i32);
if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE {
return None;
}
let mut buf = vec![0u8; reader.output_buffer_size()];
let info = reader.next_frame(&mut buf).ok()?;
let n = (w * h) as usize;
let mut rgba = Vec::with_capacity(n * 4);
let px = &buf[..info.buffer_size()];
match info.color_type {
png::ColorType::Rgba => rgba.extend_from_slice(&px[..n * 4]),
png::ColorType::Rgb => px.chunks_exact(3).take(n).for_each(|p| rgba.extend_from_slice(&[p[0], p[1], p[2], 255])),
png::ColorType::GrayscaleAlpha => px.chunks_exact(2).take(n).for_each(|p| rgba.extend_from_slice(&[p[0], p[0], p[0], p[1]])),
png::ColorType::Grayscale => px.iter().take(n).for_each(|&v| rgba.extend_from_slice(&[v, v, v, 255])),
png::ColorType::Indexed => return None,
}
(rgba.len() == n * 4).then_some(ImageSrc::Pixels { w, h, rgba })
}
fn decode_svg(bytes: &[u8]) -> Option<ImageSrc> {
let tree = resvg::usvg::Tree::from_data(bytes, &resvg::usvg::Options::default()).ok()?;
let s = tree.size();
(s.width() > 0.0 && s.height() > 0.0).then_some(ImageSrc::Svg(tree))
}
/// Scale RGBA `src` (`sw` x `sh`) to `w` x `h`: each target pixel averages the source pixels it
/// covers (alpha weighted), or takes the nearest one when enlarging. Same as the software renderer.
fn scale_rgba(src: &[u8], sw: i32, sh: i32, w: i32, h: i32) -> Vec<u8> {
let mut out = vec![0u8; (w * h * 4) as usize];
for y in 0..h {
let y0 = y * sh / h;
let y1 = ((y + 1) * sh / h).max(y0 + 1);
for x in 0..w {
let x0 = x * sw / w;
let x1 = ((x + 1) * sw / w).max(x0 + 1);
let (mut r, mut g, mut b, mut a, mut n) = (0i64, 0i64, 0i64, 0i64, 0i64);
for sy in y0..y1 {
for sx in x0..x1 {
let o = ((sy * sw + sx) * 4) as usize;
let pa = src[o + 3] as i64;
r += src[o] as i64 * pa;
g += src[o + 1] as i64 * pa;
b += src[o + 2] as i64 * pa;
a += pa;
n += 1;
}
}
if a > 0 {
let o = ((y * w + x) * 4) as usize;
out[o] = (r / a) as u8;
out[o + 1] = (g / a) as u8;
out[o + 2] = (b / a) as u8;
out[o + 3] = (a / n) as u8;
}
}
}
out
}
/// Render an SVG tree into a `w` x `h` RGBA8888 (not premultiplied) buffer, aspect kept and centred.
fn render_svg(tree: &resvg::usvg::Tree, w: i32, h: i32) -> Option<Vec<u8>> {
let mut pm = resvg::tiny_skia::Pixmap::new(w as u32, h as u32)?;
let s = tree.size();
let k = (w as f32 / s.width()).min(h as f32 / s.height());
let (dx, dy) = ((w as f32 - s.width() * k) / 2.0, (h as f32 - s.height() * k) / 2.0);
let t = resvg::tiny_skia::Transform::from_row(k, 0.0, 0.0, k, dx, dy);
resvg::render(tree, t, &mut pm.as_mut());
let mut out = pm.take();
for p in out.chunks_exact_mut(4) {
let a = p[3] as u32;
if a > 0 && a < 255 {
for c in &mut p[..3] {
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
}
Some(out)
}
impl Images {
/// Load the PNG or SVG at `path`; the same path gives the same handle. 0 on failure.
pub fn load(&mut self, path: &str) -> u32 {
if let Some(h) = self.by_path.get(path) {
return *h;
}
let src = std::fs::read(path).ok().and_then(|b| {
if b.starts_with(b"\x89PNG") {
decode_png(&b)
} else if path.ends_with(".svg") || path.ends_with(".svgz") {
decode_svg(&b)
} else {
None
}
});
let h = match src {
Some(s) => {
self.srcs.push(s);
self.srcs.len() as u32
}
None => 0,
};
self.by_path.insert(path.to_string(), h);
h
}
/// Image `handle` at `w` x `h` (cached), or None for an unknown handle or a silly size.
fn sized(&self, handle: u32, w: i32, h: i32) -> Option<Rc<Vec<u8>>> {
if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE {
return None;
}
let src = self.srcs.get((handle as usize).checked_sub(1)?)?;
if let Some(px) = self.sized.borrow().get(&(handle, w, h)) {
return Some(px.clone());
}
let px = Rc::new(match src {
ImageSrc::Pixels { w: sw, h: sh, rgba } if *sw == w && *sh == h => rgba.clone(),
ImageSrc::Pixels { w: sw, h: sh, rgba } => scale_rgba(rgba, *sw, *sh, w, h),
ImageSrc::Svg(tree) => render_svg(tree, w, h)?,
});
self.sized.borrow_mut().insert((handle, w, h), px.clone());
Some(px)
}
}
fn draw_image(c: &mut Canvas, imgs: &Images, p: &wt::Picture, ox: i32, oy: i32, clip: Clip) {
let (w, h) = (p.area.w, p.area.h);
let Some(px) = imgs.sized(p.image, w, h) else { return };
let (x0, y0) = (p.area.x + ox, p.area.y + oy);
for y in 0..h {
for x in 0..w {
let o = ((y * w + x) * 4) as usize;
blend_pixel(c, x0 + x, y0 + y, px[o] as i32, px[o + 1] as i32, px[o + 2] as i32, px[o + 3] as i32, clip);
}
}
}
/// Draw `ops` offset by (ox, oy), with the clip stack they push and pop.
fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, ops: &[wt::Op], ox: i32, oy: i32) {
fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, imgs: &Images, ops: &[wt::Op], ox: i32, oy: i32) {
let mut stack: Vec<R> = Vec::new();
for op in ops {
let clip = stack.last().copied();
@@ -437,6 +600,7 @@ fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, ops: &[wt::Op], ox: i32, oy: i32)
wt::Op::PopClip => {
stack.pop();
}
wt::Op::DrawImage(p) => draw_image(c, imgs, p, ox, oy, clip),
}
}
}
@@ -531,6 +695,8 @@ pub struct Raster {
wallpaper: Option<(Vec<wt::Op>, i32, i32, Vec<u8>)>,
surfaces: HashMap<u32, Surface>,
next_id: u32,
/// Images for `draw-image` ops (app icons).
pub images: Images,
}
impl Raster {
@@ -569,6 +735,7 @@ impl Raster {
self.fb.fill(0);
}
let surfaces = &self.surfaces;
let imgs = &self.images;
let mut c = Canvas { w, h, data: &mut self.fb };
// 1. Wallpaper: drawn once, copied back while unchanged.
@@ -578,7 +745,7 @@ impl Raster {
if cached {
c.data.copy_from_slice(&self.wallpaper.as_ref().unwrap().3);
} else {
draw_ops(&mut c, fonts, ops, 0, 0);
draw_ops(&mut c, fonts, imgs, ops, 0, 0);
self.wallpaper = Some((ops.clone(), w, h, c.data.to_vec()));
}
}
@@ -590,7 +757,7 @@ impl Raster {
}
}
}
draw_ops(&mut c, fonts, &f.background, 0, 0);
draw_ops(&mut c, fonts, imgs, &f.background, 0, 0);
// 2. Windows, bottom to top.
for win in &f.windows {
@@ -611,7 +778,7 @@ impl Raster {
for s in strips {
fill_rounded_rect(&mut c, shadow, col, 8, Some(s));
}
draw_ops(&mut c, fonts, &win.deco, outer_x, outer_y);
draw_ops(&mut c, fonts, imgs, &win.deco, outer_x, outer_y);
}
match surfaces.get(&win.surface) {
Some(s) => blit_surface(&mut c, s, g),
@@ -620,7 +787,7 @@ impl Raster {
}
// 3. Panel (and its popups, menus and notices), then 4. client popups above everything.
draw_ops(&mut c, fonts, &f.panel, 0, 0);
draw_ops(&mut c, fonts, imgs, &f.panel, 0, 0);
for p in &f.popups {
if let Some(s) = surfaces.get(&p.surface) {
blit_surface(&mut c, s, R::from(p.area));
@@ -784,4 +951,33 @@ mod tests {
r.submit(&f, &mut Fonts::default());
assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]);
}
#[test]
fn images_load_once_by_path_and_draw_scaled_png_and_svg() {
let dir = std::env::temp_dir().join(format!("chandra-img-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let png_path = dir.join("half.png");
std::fs::write(&png_path, b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x04\x00\x00\x00\x04\x08\x06\x00\x00\x00\xa9\xf1\x9e\x7e\x00\x00\x00\x13\x49\x44\x41\x54\x78\x9c\x63\xf8\xcf\xc0\xf0\x1f\x84\x19\x60\x80\x74\x01\x00\x5e\x02\x0f\xf1\x64\xf6\x7e\x7c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82").unwrap();
let svg_path = dir.join("blue.svg");
std::fs::write(&svg_path, br##"<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="#0000ff"/></svg>"##).unwrap();
let mut r = Raster::default();
let p = r.images.load(png_path.to_str().unwrap());
assert!(p != 0);
assert_eq!(r.images.load(png_path.to_str().unwrap()), p);
let s = r.images.load(svg_path.to_str().unwrap());
assert!(s != 0 && s != p);
assert_eq!(r.images.load("/nonexistent/icon.png"), 0);
let pic = |x: i32, w: i32, image: u32| wt::Op::DrawImage(wt::Picture { area: rect(x, 0, w, w), image });
let mut f = frame(40, 20);
f.panel = vec![pic(0, 8, p), pic(10, 20, s), pic(30, 4, 999)];
r.submit(&f, &mut Fonts::default());
// The PNG doubled: left half red, right half untouched.
assert_eq!(px(&r, 1, 1), [255, 0, 0, 255]);
assert_eq!(px(&r, 6, 1), [0, 0, 0, 0]);
// The SVG rendered at 20px fills its square.
assert_eq!(px(&r, 20, 10), [0, 0, 255, 255]);
// An unknown handle draws nothing.
assert_eq!(px(&r, 31, 1), [0, 0, 0, 0]);
let _ = std::fs::remove_dir_all(&dir);
}
}