///| 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) }