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

+1
View File
@@ -2,6 +2,7 @@ import {
"moonbitlang/core/builtin",
"chandra/desktop/compositor/scene" @scene,
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/sys" @sys,
"chandra/desktop/interface/chandra/host/raster" @hostraster,
}
+23
View File
@@ -10,3 +10,26 @@ pub fn submit(_scene : @scene.SceneGraph) -> Unit {
pub fn read_frame(_width : Int, _height : Int) -> @renderer.Pixmap {
abort("the host rasteriser is only available to the wasm compositor")
}
///| Images already loaded, by path (0: it failed, don't try again).
let loaded_images : Map[String, UInt] = {}
///| Load the image file at `path` for `Image` draw ops: a handle, or 0 when it can't be decoded.
/// The software renderer only reads PNG (an SVG icon gets 0, and the caller's fallback).
pub fn load_image(path : String) -> UInt {
match loaded_images.get(path) {
Some(h) => h
None => {
let h = if path.has_suffix(".png") {
match @renderer.decode_png(@sys.read_file_bytes(path)) {
Some(p) => @renderer.add_image(p)
None => 0U
}
} else {
0U
}
loaded_images.set(path, h)
h
}
}
}
+16
View File
@@ -36,6 +36,7 @@ fn conv_op(op : @scene.DrawOp) -> @hostraster.Op {
DrawText({ x, y, text, size, color: conv_color(c), align: conv_align(align), bold, mono: true })
PushClip(r) => PushClip(conv_rect(r))
PopClip => PopClip
Image(r, image) => DrawImage({ area: conv_rect(r), image })
}
}
@@ -95,3 +96,18 @@ pub fn read_frame(width : Int, height : Int) -> @renderer.Pixmap {
let data = @hostraster.read_frame()
{ width, height, data }
}
///| Images already loaded, by path (0: it failed, don't ask the host again).
let loaded_images : Map[String, UInt] = {}
///| Have the host load the PNG or SVG file at `path` for `Image` draw ops: a handle, or 0.
pub fn load_image(path : String) -> UInt {
match loaded_images.get(path) {
Some(h) => h
None => {
let h = @hostraster.load_image(path)
loaded_images.set(path, h)
h
}
}
}
+88
View File
@@ -0,0 +1,88 @@
///| Images the compositor loaded (app icons) and the `Image` draw op that shows them.
///| Loaded images; handle `i + 1` is `images[i]` (0 means "no image").
let images : Array[Pixmap] = []
///| Each image scaled to the sizes it has been drawn at, by (handle, w, h).
let scaled : Map[(UInt, Int, Int), Pixmap] = {}
///| Keep `p` for `Image` ops and return its handle (never 0).
pub fn add_image(p : Pixmap) -> UInt {
images.push(p)
images.length().reinterpret_as_uint()
}
///| Scale `src` to `w`x`h`: each target pixel averages the source pixels it covers (alpha
/// weighted, so transparent edges don't darken), or takes the nearest one when enlarging.
pub fn scale_pixmap(src : Pixmap, w : Int, h : Int) -> Pixmap {
let out = Pixmap::new(w, h)
for y = 0; y < h; y = y + 1 {
let y0 = y * src.height / h
let y1 = { let e = (y + 1) * src.height / h; if e > y0 { e } else { y0 + 1 } }
for x = 0; x < w; x = x + 1 {
let x0 = x * src.width / w
let x1 = { let e = (x + 1) * src.width / w; if e > x0 { e } else { x0 + 1 } }
let mut r = 0
let mut g = 0
let mut b = 0
let mut a = 0
let mut n = 0
for sy = y0; sy < y1; sy = sy + 1 {
for sx = x0; sx < x1; sx = sx + 1 {
let o = (sy * src.width + sx) * 4
let pa = src.data[o + 3].to_int()
r = r + src.data[o].to_int() * pa
g = g + src.data[o + 1].to_int() * pa
b = b + src.data[o + 2].to_int() * pa
a = a + pa
n = n + 1
}
}
let o = (y * w + x) * 4
if a > 0 {
out.data[o] = (r / a).to_byte()
out.data[o + 1] = (g / a).to_byte()
out.data[o + 2] = (b / a).to_byte()
out.data[o + 3] = (a / n).to_byte()
}
}
}
out
}
///| Draw image `handle` scaled into `r` (unknown handles draw nothing).
fn draw_image(dst : Pixmap, handle : UInt, r : @scene.Rect, clip : @scene.Rect?) -> Unit {
let i = handle.reinterpret_as_int() - 1
if i < 0 || i >= images.length() || r.w <= 0 || r.h <= 0 || r.w > 1024 || r.h > 1024 {
return
}
let key = (handle, r.w, r.h)
let img = match scaled.get(key) {
Some(p) => p
None => {
let src = images[i]
let p = if src.width == r.w && src.height == r.h {
src
} else {
scale_pixmap(src, r.w, r.h)
}
scaled.set(key, p)
p
}
}
for y = 0; y < r.h; y = y + 1 {
for x = 0; x < r.w; x = x + 1 {
let o = (y * r.w + x) * 4
blend_pixel(
dst,
r.x + x,
r.y + y,
img.data[o].to_int(),
img.data[o + 1].to_int(),
img.data[o + 2].to_int(),
img.data[o + 3].to_int(),
clip,
)
}
}
}
+6
View File
@@ -6,8 +6,12 @@ import {
}
// Values
pub fn add_image(Pixmap) -> UInt32
pub fn blit_shm_surface(Pixmap, @scene.ShmBufferSnapshot, @scene.Rect) -> Unit
pub fn decode_png(Bytes) -> Pixmap?
pub fn draw_ops(Pixmap, Array[@scene.DrawOp], Int32, Int32) -> Unit
pub fn encode_png(Pixmap) -> Bytes
@@ -16,6 +20,8 @@ pub fn encode_ppm(Pixmap) -> Bytes
pub fn render_scene(@scene.SceneGraph) -> Pixmap
pub fn scale_pixmap(Pixmap, Int32, Int32) -> Pixmap
pub fn set_glyph_source((Int32, Int32, Bool, Bool) -> Glyph) -> Unit
pub fn text_width(String, Int32, Bool, Bool) -> Int32
+434
View File
@@ -0,0 +1,434 @@
///| A small PNG decoder for app icons (the native build has no image library). Handles what icon
/// themes ship: 8-bit grey, grey+alpha, RGB, RGBA (16-bit read as 8), palettes of 1-8 bits with
/// tRNS alpha. Interlaced images and anything over 1024 px a side are refused.
///|
priv suberror PngError
///| Inflate (RFC 1951) state over a zlib stream's deflate data.
priv struct Inflate {
src : Bytes
mut pos : Int
mut bitbuf : Int
mut bitcnt : Int
out : Array[Byte]
}
///|
fn Inflate::bits(self : Inflate, need : Int) -> Int raise PngError {
let mut val = self.bitbuf
while self.bitcnt < need {
if self.pos >= self.src.length() {
raise PngError
}
val = val | (self.src[self.pos].to_int() << self.bitcnt)
self.pos = self.pos + 1
self.bitcnt = self.bitcnt + 8
}
self.bitbuf = val >> need
self.bitcnt = self.bitcnt - need
val & ((1 << need) - 1)
}
///| A canonical Huffman code: how many codes of each length, and the symbols in code order.
priv struct Huffman {
count : FixedArray[Int]
symbol : FixedArray[Int]
}
///|
fn Huffman::build(lengths : FixedArray[Int], start : Int, n : Int) -> Huffman raise PngError {
let count = FixedArray::make(16, 0)
let symbol = FixedArray::make(n, 0)
for i = 0; i < n; i = i + 1 {
count[lengths[start + i]] = count[lengths[start + i]] + 1
}
let mut left = 1
for len = 1; len < 16; len = len + 1 {
left = (left << 1) - count[len]
if left < 0 {
raise PngError
}
}
let offs = FixedArray::make(16, 0)
for len = 1; len < 15; len = len + 1 {
offs[len + 1] = offs[len] + count[len]
}
for i = 0; i < n; i = i + 1 {
let l = lengths[start + i]
if l != 0 {
symbol[offs[l]] = i
offs[l] = offs[l] + 1
}
}
{ count, symbol }
}
///|
fn Inflate::decode(self : Inflate, h : Huffman) -> Int raise PngError {
let mut code = 0
let mut first = 0
let mut index = 0
for len = 1; len < 16; len = len + 1 {
code = code | self.bits(1)
let c = h.count[len]
if code - c < first {
return h.symbol[index + (code - first)]
}
index = index + c
first = (first + c) << 1
code = code << 1
}
raise PngError
}
///|
let len_base : FixedArray[Int] = [
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83,
99, 115, 131, 163, 195, 227, 258,
]
///|
let len_extra : FixedArray[Int] = [
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
5, 0,
]
///|
let dist_base : FixedArray[Int] = [
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025,
1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
]
///|
let dist_extra : FixedArray[Int] = [
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
12, 12, 13, 13,
]
///| Decode one compressed block's symbols until end-of-block; `limit` caps the output size.
fn Inflate::codes(
self : Inflate,
lencode : Huffman,
distcode : Huffman,
limit : Int,
) -> Unit raise PngError {
while true {
let sym = self.decode(lencode)
if sym < 256 {
self.out.push(sym.to_byte())
} else if sym == 256 {
return
} else {
let s = sym - 257
if s >= 29 {
raise PngError
}
let len = len_base[s] + self.bits(len_extra[s])
let ds = self.decode(distcode)
if ds >= 30 {
raise PngError
}
let dist = dist_base[ds] + self.bits(dist_extra[ds])
let n = self.out.length()
if dist > n || n + len > limit {
raise PngError
}
for k = 0; k < len; k = k + 1 {
self.out.push(self.out[n - dist + k])
}
}
if self.out.length() > limit {
raise PngError
}
}
}
///|
fn Inflate::stored(self : Inflate) -> Unit raise PngError {
self.bitbuf = 0
self.bitcnt = 0
if self.pos + 4 > self.src.length() {
raise PngError
}
let len = self.src[self.pos].to_int() | (self.src[self.pos + 1].to_int() << 8)
let nlen = self.src[self.pos + 2].to_int() | (self.src[self.pos + 3].to_int() << 8)
self.pos = self.pos + 4
if len != (nlen ^ 0xFFFF) || self.pos + len > self.src.length() {
raise PngError
}
for k = 0; k < len; k = k + 1 {
self.out.push(self.src[self.pos + k])
}
self.pos = self.pos + len
}
///|
fn Inflate::fixed(self : Inflate, limit : Int) -> Unit raise PngError {
let l = FixedArray::make(288 + 30, 5)
for i = 0; i < 288; i = i + 1 {
l[i] = if i < 144 { 8 } else if i < 256 { 9 } else if i < 280 { 7 } else { 8 }
}
self.codes(Huffman::build(l, 0, 288), Huffman::build(l, 288, 30), limit)
}
///|
let code_order : FixedArray[Int] = [
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
]
///|
fn Inflate::dynamic(self : Inflate, limit : Int) -> Unit raise PngError {
let nlen = self.bits(5) + 257
let ndist = self.bits(5) + 1
let ncode = self.bits(4) + 4
if nlen > 286 || ndist > 30 {
raise PngError
}
let lengths = FixedArray::make(320, 0)
for i = 0; i < ncode; i = i + 1 {
lengths[code_order[i]] = self.bits(3)
}
let lencode = Huffman::build(lengths, 0, 19)
let mut idx = 0
while idx < nlen + ndist {
let sym = self.decode(lencode)
if sym < 16 {
lengths[idx] = sym
idx = idx + 1
} else {
let mut len = 0
let rep = if sym == 16 {
if idx == 0 {
raise PngError
}
len = lengths[idx - 1]
3 + self.bits(2)
} else if sym == 17 {
3 + self.bits(3)
} else {
11 + self.bits(7)
}
if idx + rep > nlen + ndist {
raise PngError
}
for k = 0; k < rep; k = k + 1 {
lengths[idx] = len
idx = idx + 1
}
}
}
if lengths[256] == 0 {
raise PngError
}
let lc = Huffman::build(lengths, 0, nlen)
let dc = Huffman::build(lengths, nlen, ndist)
self.codes(lc, dc, limit)
}
///| Inflate a zlib stream (header checked, checksum ignored), refusing output beyond `limit`.
fn zlib_inflate(src : Bytes, limit : Int) -> Array[Byte] raise PngError {
if src.length() < 2 || (src[0].to_int() & 0x0F) != 8 ||
((src[0].to_int() << 8) | src[1].to_int()) % 31 != 0 {
raise PngError
}
let s : Inflate = { src, pos: 2, bitbuf: 0, bitcnt: 0, out: [] }
while true {
let last = s.bits(1)
match s.bits(2) {
0 => s.stored()
1 => s.fixed(limit)
2 => s.dynamic(limit)
_ => raise PngError
}
if s.out.length() > limit {
raise PngError
}
if last == 1 {
break
}
}
s.out
}
///|
fn be32(b : Bytes, o : Int) -> Int {
(b[o].to_int() << 24) | (b[o + 1].to_int() << 16) | (b[o + 2].to_int() << 8) |
b[o + 3].to_int()
}
///|
fn paeth(a : Int, b : Int, c : Int) -> Int {
let p = a + b - c
let pa = (p - a).abs()
let pb = (p - b).abs()
let pc = (p - c).abs()
if pa <= pb && pa <= pc {
a
} else if pb <= pc {
b
} else {
c
}
}
///| Decode a PNG file into an RGBA pixmap; None when it is not a PNG this decoder handles.
pub fn decode_png(data : Bytes) -> Pixmap? {
decode_png_inner(data) catch {
_ => None
}
}
///|
fn decode_png_inner(data : Bytes) -> Pixmap? raise PngError {
let sig : FixedArray[Int] = [137, 80, 78, 71, 13, 10, 26, 10]
if data.length() < 33 {
return None
}
for i = 0; i < 8; i = i + 1 {
if data[i].to_int() != sig[i] {
return None
}
}
let mut w = 0
let mut h = 0
let mut depth = 0
let mut ctype = 0
let mut interlace = 0
let mut palette : Array[Byte] = []
let mut trns : Array[Byte] = []
let idat : Array[Byte] = []
let mut pos = 8
while pos + 8 <= data.length() {
let len = be32(data, pos)
if len < 0 || pos + 12 + len > data.length() {
return None
}
let kind = data[pos + 4:pos + 8].to_bytes()
let body = pos + 8
if kind == b"IHDR" && len >= 13 {
w = be32(data, body)
h = be32(data, body + 4)
depth = data[body + 8].to_int()
ctype = data[body + 9].to_int()
interlace = data[body + 12].to_int()
} else if kind == b"PLTE" {
palette = data[body:body + len].to_bytes().to_array()
} else if kind == b"tRNS" {
trns = data[body:body + len].to_bytes().to_array()
} else if kind == b"IDAT" {
for k = 0; k < len; k = k + 1 {
idat.push(data[body + k])
}
} else if kind == b"IEND" {
break
}
pos = body + len + 4
}
if w <= 0 || h <= 0 || w > 1024 || h > 1024 || interlace != 0 {
return None
}
let channels = match ctype {
0 => 1
2 => 3
3 => 1
4 => 2
6 => 4
_ => return None
}
let ok_depth = match ctype {
0 | 3 => depth == 1 || depth == 2 || depth == 4 || depth == 8 || (ctype == 0 && depth == 16)
_ => depth == 8 || depth == 16
}
if !ok_depth {
return None
}
let bits_pp = channels * depth
let bpp = if bits_pp < 8 { 1 } else { bits_pp / 8 }
let stride = (w * bits_pp + 7) / 8
let raw = zlib_inflate(Bytes::from_array(idat), h * (stride + 1))
if raw.length() < h * (stride + 1) {
return None
}
// Undo the per-row filters in place, into `cur` rows of `stride` bytes.
let px = FixedArray::make(h * stride, b'\x00')
for y = 0; y < h; y = y + 1 {
let f = raw[y * (stride + 1)].to_int()
let src = y * (stride + 1) + 1
let row = y * stride
for x = 0; x < stride; x = x + 1 {
let a = if x >= bpp { px[row + x - bpp].to_int() } else { 0 }
let b = if y > 0 { px[row - stride + x].to_int() } else { 0 }
let c = if x >= bpp && y > 0 { px[row - stride + x - bpp].to_int() } else { 0 }
let v = raw[src + x].to_int()
let out = match f {
0 => v
1 => v + a
2 => v + b
3 => v + (a + b) / 2
4 => v + paeth(a, b, c)
_ => raise PngError
}
px[row + x] = (out & 0xFF).to_byte()
}
}
let img = Pixmap::new(w, h)
// Sample `i` (0-based within the row) of `n` bits, for 1/2/4/8-bit rows.
let sample = fn(row : Int, i : Int) -> Int {
if depth == 8 {
px[row + i].to_int()
} else if depth == 16 {
px[row + i * 2].to_int()
} else {
let bit = i * depth
let byte = px[row + bit / 8].to_int()
(byte >> (8 - depth - bit % 8)) & ((1 << depth) - 1)
}
}
let scale = fn(v : Int) -> Int {
match depth {
1 => v * 255
2 => v * 85
4 => v * 17
_ => v
}
}
for y = 0; y < h; y = y + 1 {
let row = y * stride
for x = 0; x < w; x = x + 1 {
let (r, g, b, a) = match ctype {
0 => {
let v = scale(sample(row, x))
(v, v, v, 255)
}
2 => (sample(row, x * 3), sample(row, x * 3 + 1), sample(row, x * 3 + 2), 255)
3 => {
let i = sample(row, x)
if i * 3 + 2 >= palette.length() {
(0, 0, 0, 0)
} else {
let a = if i < trns.length() { trns[i].to_int() } else { 255 }
(palette[i * 3].to_int(), palette[i * 3 + 1].to_int(), palette[i * 3 + 2].to_int(), a)
}
}
4 => {
let v = sample(row, x * 2)
(v, v, v, sample(row, x * 2 + 1))
}
_ =>
(
sample(row, x * 4),
sample(row, x * 4 + 1),
sample(row, x * 4 + 2),
sample(row, x * 4 + 3),
)
}
let o = (y * w + x) * 4
img.data[o] = r.to_byte()
img.data[o + 1] = g.to_byte()
img.data[o + 2] = b.to_byte()
img.data[o + 3] = a.to_byte()
}
}
Some(img)
}
+71
View File
@@ -0,0 +1,71 @@
///|
fn px(p : Pixmap, x : Int, y : Int) -> (Int, Int, Int, Int) {
let o = (y * p.width + x) * 4
(p.data[o].to_int(), p.data[o + 1].to_int(), p.data[o + 2].to_int(), p.data[o + 3].to_int())
}
///|
test "decode_png: RGBA rows using all five filters (fixed Huffman)" {
let p = decode_png(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x03\x00\x00\x00\x05\x08\x06\x00\x00\x00\x80\x71\x56\xa2\x00\x00\x00\x3e\x49\x44\x41\x54\x78\xda\x63\x60\x60\x60\xf8\xaf\xc1\xc0\x70\x38\x80\x81\xa1\x9d\x91\xdd\x08\xc4\x91\x3b\x02\xc2\x4c\x40\x0e\x03\xbb\x91\x1c\x10\xdb\x30\x30\xf3\xa5\x30\x34\x48\x48\xda\x3c\x92\x90\xf4\x7e\xc4\x02\x96\x61\x00\xca\x30\xd8\x30\x00\x00\x9a\x17\x0b\x5d\x72\xb0\x16\x16\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82").unwrap()
assert_eq((p.width, p.height), (3, 5))
for y = 0; y < 5; y = y + 1 {
for x = 0; x < 3; x = x + 1 {
assert_eq(px(p, x, y), ((x * 40 + y * 7) & 255, (y * 50) & 255, (x * y * 30) & 255, 255 - x * 60))
}
}
}
///|
test "decode_png: RGB with dynamic Huffman blocks" {
let p = decode_png(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x28\x00\x00\x00\x28\x08\x02\x00\x00\x00\x03\x9c\x2f\x3a\x00\x00\x00\x33\x49\x44\x41\x54\x78\xda\xed\xcd\xc1\x09\x00\x20\x0c\x00\xb1\x03\xa5\xfb\x8f\xec\x16\x0a\x12\xc8\x3f\xbb\x9a\xd6\x7d\xbb\x59\xf5\x80\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\xf8\xc7\xf8\x00\xd3\x7b\x15\x32\x6b\xd7\xe3\x22\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82").unwrap()
assert_eq((p.width, p.height), (40, 40))
for y = 0; y < 40; y = y + 1 {
for x = 0; x < 40; x = x + 1 {
assert_eq(px(p, x, y), (x * 6, y * 6, (x + y) * 3, 255))
}
}
}
///|
test "decode_png: 2-bit palette with tRNS, and stored grey+alpha" {
let p = decode_png(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x03\x00\x00\x00\x02\x02\x03\x00\x00\x00\xe0\x1a\x8e\x89\x00\x00\x00\x0c\x50\x4c\x54\x45\xff\x00\x00\x00\xff\x00\x00\x00\xff\x09\x09\x09\x5c\x71\x7e\x86\x00\x00\x00\x03\x74\x52\x4e\x53\xff\x80\x00\x7f\x6d\x68\x78\x00\x00\x00\x0c\x49\x44\x41\x54\x78\xda\x63\x90\x60\x7c\x02\x00\x01\x32\x00\xfe\x06\xf2\x6e\x18\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82").unwrap()
assert_eq(px(p, 0, 0), (255, 0, 0, 255))
assert_eq(px(p, 1, 0), (0, 255, 0, 128))
assert_eq(px(p, 2, 0), (0, 0, 255, 0))
assert_eq(px(p, 0, 1), (9, 9, 9, 255))
assert_eq(px(p, 2, 1), (0, 255, 0, 128))
let g = decode_png(b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x02\x00\x00\x00\x01\x08\x04\x00\x00\x00\x5e\x2b\xb7\x01\x00\x00\x00\x10\x49\x44\x41\x54\x78\x01\x01\x05\x00\xfa\xff\x00\x0a\x14\x1e\x28\x00\xcd\x00\x65\x7b\x27\x54\xba\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82").unwrap()
assert_eq(px(g, 0, 0), (10, 10, 10, 20))
assert_eq(px(g, 1, 0), (30, 30, 30, 40))
}
///|
test "decode_png refuses what isn't a PNG it can read" {
assert_true(decode_png(b"not a png at all, not a png at all, nope").is_empty())
assert_true(decode_png(b"").is_empty())
// a truncated file
let cut = b"\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\x00\x00\x28\x00\x00\x00\x28\x08\x02\x00\x00\x00\x03\x9c\x2f\x3a\x00\x00\x00\x33\x49\x44\x41\x54\x78\xda\xed\xcd\xc1\x09\x00\x20\x0c\x00\xb1\x03\xa5\xfb\x8f\xec\x16\x0a\x12\xc8\x3f\xbb\x9a\xd6\x7d\xbb\x59\xf5\x80\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16"
assert_true(decode_png(cut).is_empty())
}
///|
test "scale_pixmap averages down and draw_image blends the icon into the frame" {
let src = Pixmap::new(4, 4)
for i = 0; i < 16; i = i + 1 {
src.data[i * 4] = b'\xff'
src.data[i * 4 + 3] = if i % 2 == 0 { b'\xff' } else { b'\x00' }
}
let s = scale_pixmap(src, 2, 2)
// half the source pixels are opaque red: the result is red at half alpha
assert_eq(px(s, 0, 0), (255, 0, 0, 127))
let h = add_image(src)
assert_true(h != 0U)
let dst = Pixmap::new(10, 10)
draw_ops(dst, [Image({ x: 2, y: 2, w: 4, h: 4 }, h)], 0, 0)
assert_eq(px(dst, 2, 2), (255, 0, 0, 255))
assert_eq(px(dst, 3, 2).3, 0)
assert_eq(px(dst, 0, 0), (0, 0, 0, 0))
// unknown handles draw nothing
draw_ops(dst, [Image({ x: 0, y: 0, w: 2, h: 2 }, 9999U)], 0, 0)
assert_eq(px(dst, 0, 0), (0, 0, 0, 0))
}
+2
View File
@@ -668,6 +668,8 @@ pub fn draw_ops(
PushClip(r) =>
clip_stack.push(@scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h))
PopClip => if clip_stack.length() > 0 { ignore(clip_stack.pop()) }
Image(r, handle) =>
draw_image(dst, handle, @scene.Rect::new(r.x + ox, r.y + oy, r.w, r.h), cur_clip)
}
}
}
+2
View File
@@ -32,6 +32,7 @@ pub(all) enum DrawOp {
MonoText(Int32, Int32, String, Int32, Rgba, TextAlign, Bool)
PushClip(Rect)
PopClip
Image(Rect, UInt32)
}
pub(all) struct PanelWidgetNode {
@@ -113,6 +114,7 @@ pub(all) struct ThemeTokens {
panel_height : Int32
}
pub fn ThemeTokens::from_json_string(String) -> Self
pub fn ThemeTokens::moon_day() -> Self
pub fn ThemeTokens::moon_night() -> Self
pub(all) struct WindowSceneNode {
+2
View File
@@ -253,6 +253,8 @@ pub(all) enum DrawOp {
MonoText(Int, Int, String, Int, Rgba, TextAlign, Bool)
PushClip(Rect)
PopClip
/// A loaded image (`@renderer.add_image` / `raster.load-image` handle) scaled into the rect.
Image(Rect, UInt)
}
///|
+10 -1
View File
@@ -10,6 +10,8 @@ priv struct DesktopApp {
command : String
/// StartupWMClass: the app id its windows carry when that is not the desktop file's name.
wm_class : String
/// Icon=: an icon theme name ("firefox") or an absolute path.
icon : String
}
///| Directories scanned, lowest priority first (later ones override by file name).
@@ -66,6 +68,7 @@ fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp
let mut terminal = false
let mut kind = "Application"
let mut wm_class = ""
let mut icon = ""
for raw in text.split("\n") {
let line = raw.trim(chars=" \r\t").to_string()
if line.length() == 0 || line.has_prefix("#") {
@@ -93,6 +96,7 @@ fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp
"NoDisplay" | "Hidden" => if val == "true" { hidden = true }
"Terminal" => terminal = val == "true"
"StartupWMClass" => wm_class = val
"Icon" => icon = val
_ => ()
}
}
@@ -113,7 +117,7 @@ fn parse_desktop(id : String, text : String, have_terminal : Bool) -> DesktopApp
_ => "Other"
}
let comment = if comment.length() > 0 { comment } else { generic }
Some({ id, name, comment, category, command, wm_class })
Some({ id, name, comment, category, command, wm_class, icon })
}
///| Scan every applications dir; later dirs override earlier ones, result sorted by name.
@@ -169,6 +173,11 @@ test "parse_desktop keeps StartupWMClass" {
Some(a) => assert_eq(a.wm_class, "Code")
None => fail("expected entry")
}
let t2 = "[Desktop Entry]\nType=Application\nName=Files\nExec=nautilus\nIcon=org.gnome.Nautilus\n[Desktop Action w]\nIcon=other\n"
match parse_desktop("org.gnome.Nautilus", t2, true) {
Some(a) => assert_eq(a.icon, "org.gnome.Nautilus")
None => fail("expected entry")
}
}
///|
+145
View File
@@ -0,0 +1,145 @@
///| App icons for panel modules (the `icons` capability): a window's app id is matched to its
/// .desktop file (`resolve_app_id`), whose Icon= key is looked up in the freedesktop icon themes
/// (a simplified icon theme spec lookup), and the file is loaded for `Image` draw ops.
///| Base directories icon themes live in, highest priority first.
fn icon_base_dirs() -> Array[String] {
let home = @sys.getenv("HOME")
let data_home = {
let x = @sys.getenv("XDG_DATA_HOME")
if x.length() > 0 { x } else { home + "/.local/share" }
}
let dirs = [data_home + "/icons", home + "/.icons"]
let xdg = @sys.getenv("XDG_DATA_DIRS")
let list = if xdg.length() > 0 { xdg } else { "/usr/local/share:/usr/share" }
for p in list.split(":") {
if p.length() > 0 {
dirs.push(p.to_string() + "/icons")
}
}
dirs.push(home + "/.local/share/flatpak/exports/share/icons")
dirs.push("/var/lib/flatpak/exports/share/icons")
dirs
}
///| Themes searched: hicolor is where apps install their icons; the others cover apps whose icon
/// only ships with a desktop theme.
let icon_themes : Array[String] = ["hicolor", "Adwaita", "breeze"]
///| Fixed-size directories, best first for a ~22-48 px icon (scaled down well); the scalable SVG
/// goes after the first three when the host can draw SVG.
let icon_sizes : Array[String] = [
"48x48", "64x64", "32x32", "96x96", "128x128", "256x256", "24x24", "22x22", "16x16",
"512x512",
]
///| Candidate files for icon `name` (an Icon= value), in lookup order. `svg_ok`: whether the
/// image loader can read SVG (the host does; the native software renderer only reads PNG).
fn icon_candidates(
name : String,
svg_ok : Bool,
bases : Array[String],
pixmaps : Array[String],
) -> Array[String] {
if name.length() == 0 {
return []
}
if name.has_prefix("/") {
return if name.has_suffix(".png") || (svg_ok && name.has_suffix(".svg")) {
[name]
} else {
[]
}
}
// Icon=foo.png is not allowed by the spec but common: look it up as "foo".
let stem = if name.has_suffix(".png") || name.has_suffix(".svg") || name.has_suffix(".xpm") {
name[:name.length() - 4].to_string()
} else {
name
}
let out : Array[String] = []
for theme in icon_themes {
for base in bases {
let dir = base + "/" + theme
for i = 0; i < icon_sizes.length(); i = i + 1 {
if i == 3 && svg_ok {
out.push(dir + "/scalable/apps/" + stem + ".svg")
}
out.push(dir + "/" + icon_sizes[i] + "/apps/" + stem + ".png")
}
}
}
for p in pixmaps {
out.push(p + "/" + stem + ".png")
if svg_ok {
out.push(p + "/" + stem + ".svg")
}
}
out
}
///| The icon file for Icon= value `name`, or None when no theme has it.
fn find_icon_file(name : String, svg_ok : Bool) -> String? {
let pixmaps = ["/usr/share/pixmaps"]
for path in icon_candidates(name, svg_ok, icon_base_dirs(), pixmaps) {
if @sys.read_file_bytes(path).length() > 0 {
return Some(path)
}
}
None
}
///| The image handle of the icon for windows carrying `app_id` (0: none). Cached per app id,
/// so each app's themes are searched once.
fn DesktopShell::app_icon(self : DesktopShell, app_id : String) -> UInt {
match self.icon_handles.get(app_id) {
Some(h) => return h
None => ()
}
let icon = match resolve_app_id(app_id, self.exec, self.wm_classes) {
Some(id) => self.icon_names.get(id).unwrap_or("")
None => ""
}
// No desktop file: many apps' icons are named after their app id anyway.
let name = if icon.length() > 0 { icon } else { app_id }
let h = match find_icon_file(name, @sys.host_raster()) {
Some(path) => @raster.load_image(path)
None => 0U
}
self.icon_handles.set(app_id, h)
h
}
///| Publish the icons table (app id -> image handle) for the windows' apps.
fn DesktopShell::publish_icons(self : DesktopShell) -> Unit {
let t = @wasm.Table::new()
let seen : Map[String, Bool] = {}
for w in self.win_list {
if w.app_id.length() > 0 && !seen.contains(w.app_id) {
seen.set(w.app_id, true)
let h = self.app_icon(w.app_id)
if h != 0U {
t.str(w.app_id)
t.int(h.reinterpret_as_int())
t.end_row()
}
}
}
@wasm.publish(Icons, t)
}
///|
test "icon lookup tries the themes' sized PNGs, then scalable SVG when it can, then pixmaps" {
let c = icon_candidates("firefox", true, ["/u/icons"], ["/p"])
assert_eq(c[0], "/u/icons/hicolor/48x48/apps/firefox.png")
assert_eq(c[3], "/u/icons/hicolor/scalable/apps/firefox.svg")
assert_eq(c[c.length() - 2], "/p/firefox.png")
assert_true(c.contains("/u/icons/breeze/16x16/apps/firefox.png"))
// The software renderer reads PNG only.
assert_false(icon_candidates("firefox", false, ["/u/icons"], ["/p"]).iter().any(p => p.has_suffix(".svg")))
// Icon=foo.png means foo; absolute paths are taken as they are.
assert_eq(icon_candidates("foo.png", false, ["/b"], [])[0], "/b/hicolor/48x48/apps/foo.png")
assert_eq(icon_candidates("/opt/app/icon.png", false, ["/b"], []), ["/opt/app/icon.png"])
assert_eq(icon_candidates("/opt/app/icon.svg", false, ["/b"], []), [])
assert_eq(icon_candidates("", true, ["/b"], []), [])
}
+1
View File
@@ -14,6 +14,7 @@ import {
"jqlssg/moonedn" @edn,
"chandra/desktop/compositor/sys" @sys,
"chandra/desktop/compositor/renderer" @renderer,
"chandra/desktop/compositor/raster" @raster,
"chandra/desktop/compositor/wasm" @wasm,
}
+14
View File
@@ -108,6 +108,7 @@ fn translate(
}
PushClip(r) => out.push(@scene.DrawOp::PushClip(rect(r)))
PopClip => out.push(@scene.DrawOp::PopClip)
Image(i) => out.push(@scene.DrawOp::Image(rect(i.rect), i.image))
}
}
}
@@ -184,6 +185,10 @@ pub(all) struct DesktopShell {
exec : Map[String, String]
/// Lower-cased StartupWMClass -> desktop file id, for apps whose windows' app id differs.
wm_classes : Map[String, String]
/// Desktop file id -> its Icon= value, and the image handle found for each window app id
/// (0: no icon), for the `icons` capability.
icon_names : Map[String, String]
icon_handles : Map[String, UInt]
/// Wayland socket handed to launched apps as WAYLAND_DISPLAY.
display : String
/// Panel modules in panel order; a module with `stretch` splits the panel into a left and a right group.
@@ -266,7 +271,11 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
let apps : Array[@types.AppEntry] = []
let exec : Map[String, String] = {}
let wm_classes : Map[String, String] = {}
let icon_names : Map[String, String] = {}
for a in scan_desktop_apps() {
if a.icon.length() > 0 {
icon_names.set(a.id, a.icon)
}
if a.wm_class.length() > 0 {
wm_classes.set(a.wm_class.to_lower(), a.id)
}
@@ -282,6 +291,8 @@ pub fn DesktopShell::new(display : String) -> DesktopShell {
apps,
exec,
wm_classes,
icon_names,
icon_handles: {},
display,
widgets: [],
next_slot: 1,
@@ -785,6 +796,9 @@ pub fn DesktopShell::render(
self.sampler.refresh()
@wasm.set_windows(self.win_list)
}
if self.widgets.iter().any(w => w.has_cap("icons")) {
self.publish_icons()
}
let bg : Array[@scene.DrawOp] = []
translate(@libshell.render_wallpaper(@ui.size(w, h), tokens, self.wallpaper_sel), 0, 0, bg)
self.wallpaper_len = bg.length()
+3
View File
@@ -233,6 +233,8 @@ pub(all) enum HostTable {
Instances
Wallpapers
SessionSettings
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
Icons
}
///|
@@ -254,6 +256,7 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
Instances => 4U
Wallpapers => 5U
SessionSettings => 6U
Icons => 7U
}
@hostpl.publish_table(id, out)
}
+4
View File
@@ -435,6 +435,7 @@ fn Plasmoid::decode_ops(self : Plasmoid, base : Int, n : Int, out : Array[@types
}),
)
5 => out.push(PushClip(rect(o + 4)))
7 => out.push(Image({ rect: rect(o + 4), image: rd32(b, o + 20).reinterpret_as_uint() }))
_ => out.push(PopClip)
}
}
@@ -609,6 +610,8 @@ pub(all) enum HostTable {
Instances
Wallpapers
SessionSettings
/// App id -> image handle (`raster.load-image`), served by `icons.app-icon`.
Icons
}
///| Publish `t` as the data behind `which` for every module's next call.
@@ -621,6 +624,7 @@ pub fn publish(which : HostTable, t : Table) -> Unit {
Instances => 4
Wallpapers => 5
SessionSettings => 6
Icons => 7
}
let out : Array[Byte] = []
for k = 0; k < 4; k = k + 1 {
+31 -2
View File
@@ -48,13 +48,14 @@ enum {
K_OTHER, K_TOKENS, K_CLOCK, K_APPS, K_LAUNCH, K_WINDOWS, K_FOCUS, K_LAYOUTS, K_LAYOUT_CUR, K_SET_LAYOUT,
K_INSPECT_IS_ON, K_INSPECT_SET, K_MOD_AVAILABLE, K_MOD_LOADED, K_MOD_LOAD, K_MOD_UNLOAD, K_MOD_BROWSE,
K_SYSTEM_READ, K_WIN_ALL, K_WIN_FOCUS_ID, K_LOGOUT, K_WALLPAPERS, K_WALLPAPER_CUR, K_SET_WALLPAPER,
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET
K_SESSION_SETTINGS, K_SESSION_IS_ON, K_SESSION_SET,
K_APP_ICON
};
typedef struct Env { Inst *inst; int kind; } Env;
/* ---- host data the shell publishes before calling a guest ----
* A table is [u32 rows] then rows of fields, each field a LE i32 ('i') or a u32 byte length + UTF-8 ('s'). */
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_N };
enum { T_APPS, T_WINDOWS, T_LAYOUTS, T_MODULES, T_INSTANCES, T_WALLPAPERS, T_SESSION_SETTINGS, T_ICONS, T_N };
typedef struct { uint8_t *data; size_t len; } Blob;
static Blob tables[T_N];
static int32_t host_ints[4]; /* 0 layout mode, 1 inspector on, 2 current wallpaper, 3 session settings on (bit i: row i) */
@@ -226,6 +227,25 @@ static int table_has_id(int t, const char *spec, const char *id) {
return 0;
}
/* The image handle table T_ICONS ("si": app id, handle) holds for `id`, or 0. */
static int32_t icon_for(const char *id) {
Blob *b = &tables[T_ICONS];
uint32_t n = b->len >= 4 ? rd_u32(b->data) : 0;
size_t pos = 4, idl = strlen(id);
for (uint32_t r = 0; r < n; r++) {
if (pos + 4 > b->len) return 0;
uint32_t sl = rd_u32(b->data + pos);
pos += 4;
if (pos + sl + 4 > b->len) return 0;
int hit = sl == idl && memcmp(b->data + pos, id, sl) == 0;
pos += sl;
int32_t h = (int32_t)rd_u32(b->data + pos);
pos += 4;
if (hit) return h;
}
return 0;
}
static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_vec_t *results) {
Env *e = (Env *)env;
Inst *in = e->inst;
@@ -305,6 +325,14 @@ static wasm_trap_t *host_import(void *env, const wasm_val_vec_t *args, wasm_val_
free(id);
break;
}
case K_APP_ICON: {
/* app-icon(app-id) -> u32; (ptr, len) */
char *id = guest_str(in, a0, a1);
int32_t h = id ? icon_for(id) : 0;
free(id);
if (results->size >= 1) results->data[0] = (wasm_val_t)WASM_I32_VAL(h);
break;
}
case K_SYSTEM_READ:
if (args->size >= 1) mem_write(in, a0, g_system, 64);
break;
@@ -414,6 +442,7 @@ static int classify_import(const wasm_name_t *m, const wasm_name_t *f) {
if (!strcmp(iface, "windows") && !strcmp(fn, "all")) return K_WIN_ALL;
if (!strcmp(iface, "windows") && !strcmp(fn, "focus")) return K_WIN_FOCUS_ID;
if (!strcmp(iface, "system") && !strcmp(fn, "read")) return K_SYSTEM_READ;
if (!strcmp(iface, "icons") && !strcmp(fn, "app-icon")) return K_APP_ICON;
if (!strcmp(iface, "session") && !strcmp(fn, "logout")) return K_LOGOUT;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "wallpapers")) return K_WALLPAPERS;
if (!strcmp(iface, "wallpaper") && !strcmp(fn, "current-wallpaper")) return K_WALLPAPER_CUR;
+38
View File
@@ -121,6 +121,44 @@ test "task list module draws the host's windows and asks to focus one" {
p.unload()
}
///|
test "task list draws the host's icon for an app it has one for, the letter tile otherwise" {
let p = load_module("tasks")
assert_true(p.imports().contains("icons"))
let t = Table::new()
for w in [(3, "Firefox"), (4, "foot")] {
t.int(w.0)
t.str(w.1)
t.int(0)
t.int(0)
t.end_row()
}
publish(Windows, t)
set_windows([
{ id: 3UL, title: "Firefox", app_id: "firefox", focused: false },
{ id: 4UL, title: "foot", app_id: "foot", focused: false },
])
let icons = Table::new()
icons.str("firefox")
icons.int(42)
icons.end_row()
publish(Icons, icons)
let ops = p.render(400, 36, test_tokens())
let images = ops.filter_map(op => match op {
Image(i) => Some(i)
_ => None
})
// Firefox: the icon (handle 42, a 22px square centred in the bar), no glyph; foot: the tile.
assert_eq(images.length(), 1)
assert_eq(images[0].image, 42U)
assert_eq((images[0].rect.w, images[0].rect.h), (22U, 22U))
assert_eq(images[0].rect.y, 7)
assert_eq(texts_of(ops), ["Firefox", "F", "foot"])
publish(Icons, Table::new())
set_windows([])
p.unload()
}
///|
test "layout module is a tile/float toggle" {
let p = load_module("layout")