//! The host's rasteriser (`chandra:host/raster`). //! //! A direct port of compositor/renderer (the pure-MoonBit software renderer), so a frame comes out //! pixel for pixel the same, but native: the compositor component sends draw operations and window //! surface ids, and the pixels never cross the component boundary. Window buffers are copied out of //! the client's shared memory once, at commit (`capture`), converted to RGBA, and kept here. 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; // ---------------------------------------------------------------- fonts /// A rasterised glyph: an 8-bit coverage bitmap whose top-left sits at (`xoff`, `yoff`) from the /// pen on the baseline (y grows downward), and the pen advance. pub struct Glyph { pub w: i32, pub h: i32, pub xoff: i32, pub yoff: i32, pub advance: i32, pub coverage: Vec, } /// TTF faces loaded by the component (`font.load`), by slot, and a cache of their glyphs. #[derive(Default)] pub struct Fonts { faces: [Option; 4], cache: HashMap<(u32, u32, u32), Rc>, } impl Fonts { pub fn load(&mut self, slot: u32, path: &str) -> bool { if slot as usize >= self.faces.len() { return false; } match std::fs::read(path).ok().and_then(|d| FontVec::try_from_vec(d).ok()) { Some(f) => { self.faces[slot as usize] = Some(f); self.cache.retain(|k, _| k.0 != slot); true } None => false, } } fn has(&self, slot: u32) -> bool { self.faces.get(slot as usize).map_or(false, |f| f.is_some()) } /// Same maths as stb_truetype in the native build: the size is an em size in pixels, the glyph /// origin sits on the integer pixel grid, and the bitmap box is the outline's floor/ceil bounds. pub fn glyph(&mut self, slot: u32, cp: u32, size: u32) -> Rc { if let Some(g) = self.cache.get(&(slot, cp, size)) { return g.clone(); } let g = Rc::new(self.rasterise(slot, cp, size)); self.cache.insert((slot, cp, size), g.clone()); g } fn rasterise(&self, slot: u32, cp: u32, size: u32) -> Glyph { let blank = Glyph { w: 0, h: 0, xoff: 0, yoff: 0, advance: 0, coverage: Vec::new() }; let Some(Some(font)) = self.faces.get(slot as usize) else { return blank }; let ch = char::from_u32(cp).unwrap_or('\u{fffd}'); let id = font.glyph_id(ch); let s = size as f32 / font.units_per_em().unwrap_or(1000.0); let advance = (font.h_advance_unscaled(id) * s + 0.5) as i32; let Some(outline) = font.outline(id) else { return Glyph { advance, ..blank } }; // Font units grow upward, pixels downward; ab_glyph stores the outline's top edge as // `min.y` and its bottom edge as `max.y`, both in font units. let x0 = (outline.bounds.min.x * s).floor() as i32; let x1 = (outline.bounds.max.x * s).ceil() as i32; let y0 = (-outline.bounds.min.y * s).floor() as i32; let y1 = (-outline.bounds.max.y * s).ceil() as i32; let (w, h) = (x1 - x0, y1 - y0); if w <= 0 || h <= 0 { return Glyph { advance, ..blank }; } let tp = |p: ab_glyph::Point| point(p.x * s - x0 as f32, -p.y * s - y0 as f32); let mut r = Rasterizer::new(w as usize, h as usize); for c in &outline.curves { match c { OutlineCurve::Line(a, b) => r.draw_line(tp(*a), tp(*b)), OutlineCurve::Quad(a, b, c) => r.draw_quad(tp(*a), tp(*b), tp(*c)), OutlineCurve::Cubic(a, b, c, d) => r.draw_cubic(tp(*a), tp(*b), tp(*c), tp(*d)), } } let mut coverage = vec![0u8; (w * h) as usize]; r.for_each_pixel(|i, a| coverage[i] = (a.clamp(0.0, 1.0) * 255.0 + 0.5) as u8); Glyph { w, h, xoff: x0, yoff: y0, advance, coverage } } /// The glyph for `cp` in the face the UI uses for (bold, mono), and whether it must be /// emboldened (a face with no bold instance gets its glyphs drawn a pixel wider). /// Slots: 0 mono, 1 mono bold, 2 sans. None when no face is loaded at all. fn pick(&mut self, cp: u32, size: u32, bold: bool, mono: bool) -> Option<(Rc, bool)> { let has_mono = self.has(0); let has_sans = self.has(2); if !has_mono && !has_sans { return None; } let has_bold = has_mono && self.has(1); let (slot, embolden) = if mono && has_mono { if bold && has_bold { (1, false) } else { (0, bold) } } else if has_sans { (2, bold) } else { (0, bold) }; Some((self.glyph(slot, cp, size), embolden)) } } // ---------------------------------------------------------------- canvas /// What every drawing function paints on: an RGBA8888 buffer. pub struct Canvas<'a> { pub w: i32, pub h: i32, pub data: &'a mut [u8], } #[derive(Clone, Copy)] struct R { x: i32, y: i32, w: i32, h: i32, } impl From for R { fn from(r: wt::Rect) -> R { R { x: r.x, y: r.y, w: r.w, h: r.h } } } type Clip = Option; fn clamp_u8(v: i32) -> u8 { v.clamp(0, 255) as u8 } /// Blend one pixel; `clip` and the canvas bounds are checked. fn blend_pixel(c: &mut Canvas, x: i32, y: i32, r: i32, g: i32, b: i32, a: i32, clip: Clip) { if x < 0 || y < 0 || x >= c.w || y >= c.h || a <= 0 { return; } if let Some(k) = clip { if x < k.x || y < k.y || x >= k.x + k.w || y >= k.y + k.h { return; } } let off = ((y * c.w + x) * 4) as usize; let d = &mut c.data[off..off + 4]; if a >= 255 { d[0] = r as u8; d[1] = g as u8; d[2] = b as u8; d[3] = 0xff; return; } let inv = 255 - a; d[0] = ((r * a + d[0] as i32 * inv + 127) / 255) as u8; d[1] = ((g * a + d[1] as i32 * inv + 127) / 255) as u8; d[2] = ((b * a + d[2] as i32 * inv + 127) / 255) as u8; d[3] = clamp_u8(a + (d[3] as i32 * inv + 127) / 255); } /// Blend a colour over pixels [xa, xb) of row `y`; the span is already clipped. fn blend_span(c: &mut Canvas, y: i32, xa: i32, xb: i32, r: i32, g: i32, b: i32, a: i32) { if xa >= xb || a <= 0 { return; } let row = &mut c.data[((y * c.w + xa) * 4) as usize..((y * c.w + xb) * 4) as usize]; if a >= 255 { for p in row.chunks_exact_mut(4) { p[0] = r as u8; p[1] = g as u8; p[2] = b as u8; p[3] = 0xff; } return; } let inv = 255 - a; let (ra, ga, ba) = (r * a + 127, g * a + 127, b * a + 127); for p in row.chunks_exact_mut(4) { p[0] = ((ra + p[0] as i32 * inv) / 255) as u8; p[1] = ((ga + p[1] as i32 * inv) / 255) as u8; p[2] = ((ba + p[2] as i32 * inv) / 255) as u8; p[3] = clamp_u8(a + (p[3] as i32 * inv + 127) / 255); } } /// True when (px, py) is inside the rectangle whose corners have radius `rad`. fn in_rounded_rect(px: i32, py: i32, rx: i32, ry: i32, rw: i32, rh: i32, rad: i32) -> bool { if px < rx || py < ry || px >= rx + rw || py >= ry + rh { return false; } if rad <= 0 { return true; } let max_r = rw.min(rh) / 2; let r = rad.min(max_r); if r <= 0 { return true; } let (x_left, x_right) = (rx + r, rx + rw - r - 1); let (y_top, y_bot) = (ry + r, ry + rh - r - 1); let corner = |dx: i32, dy: i32| dx * dx + dy * dy <= r * r; if px < x_left && py < y_top { corner(x_left - px, y_top - py) } else if px > x_right && py < y_top { corner(px - x_right, y_top - py) } else if px < x_left && py > y_bot { corner(x_left - px, py - y_bot) } else if px > x_right && py > y_bot { corner(px - x_right, py - y_bot) } else { true } } /// The part of `rect` that is on the canvas and inside `clip`, as (x0, y0, x1, y1). fn visible(c: &Canvas, rect: R, clip: Clip) -> Option<(i32, i32, i32, i32)> { let (mut x0, mut y0) = (rect.x.max(0), rect.y.max(0)); let (mut x1, mut y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h)); if let Some(k) = clip { x0 = x0.max(k.x); y0 = y0.max(k.y); x1 = x1.min(k.x + k.w); y1 = y1.min(k.y + k.h); } if x0 >= x1 || y0 >= y1 { None } else { Some((x0, y0, x1, y1)) } } fn fill_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, radius: i32, clip: Clip) { if rect.w <= 0 || rect.h <= 0 || col.a == 0 { return; } let Some((x0, y0, x1, y1)) = visible(c, rect, clip) else { return }; let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32); if radius <= 0 { for y in y0..y1 { blend_span(c, y, x0, x1, cr, cg, cb, ca); } return; } let r = radius.min(rect.w.min(rect.h) / 2); let (x_left, x_right) = (rect.x + r, rect.x + rect.w - r - 1); let (y_top, y_bot) = (rect.y + r, rect.y + rect.h - r - 1); for y in y0..y1 { if y >= y_top && y <= y_bot { blend_span(c, y, x0, x1, cr, cg, cb, ca); continue; } let mut x = x0; while x < x1 && x < x_left { if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { blend_span(c, y, x, x + 1, cr, cg, cb, ca); } x += 1; } let (mid_a, mid_b) = (x_left.max(x0), (x_right + 1).min(x1)); blend_span(c, y, mid_a, mid_b, cr, cg, cb, ca); x = (x_right + 1).max(x0).max(mid_a); while x < x1 { if in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius) { blend_span(c, y, x, x + 1, cr, cg, cb, ca); } x += 1; } } } fn stroke_rounded_rect(c: &mut Canvas, rect: R, col: wt::Color, width: i32, radius: i32, clip: Clip) { if rect.w <= 0 || rect.h <= 0 || width <= 0 || col.a == 0 { return; } let (x0, y0) = (rect.x.max(0), rect.y.max(0)); let (x1, y1) = ((rect.x + rect.w).min(c.w), (rect.y + rect.h).min(c.h)); let (cr, cg, cb, ca) = (col.r as i32, col.g as i32, col.b as i32, col.a as i32); let (inner_x, inner_y) = (rect.x + width, rect.y + width); let (inner_w, inner_h) = (rect.w - width * 2, rect.h - width * 2); let inner_r = if radius > width { radius - width } else { 0 }; let (cx0, cx1, cy0, cy1) = match clip { Some(k) => (k.x, k.x + k.w, k.y, k.y + k.h), None => (0, c.w, 0, c.h), }; // Rows where the inner rectangle is full width only have the two side strips to draw. let (mid_a, mid_b) = (inner_y + inner_r, inner_y + inner_h - inner_r); for y in y0..y1 { if inner_w > 0 && inner_h > 0 && y >= mid_a && y < mid_b { if y >= cy0 && y < cy1 { let l0 = x0.max(cx0); let l1 = inner_x.min(x1).min(cx1); blend_span(c, y, l0, l1, cr, cg, cb, ca); let r0 = (inner_x + inner_w).max(x0).max(cx0); blend_span(c, y, r0, x1.min(cx1), cr, cg, cb, ca); } continue; } for x in x0..x1 { let in_outer = in_rounded_rect(x, y, rect.x, rect.y, rect.w, rect.h, radius); let in_inner = inner_w > 0 && inner_h > 0 && in_rounded_rect(x, y, inner_x, inner_y, inner_w, inner_h, inner_r); if in_outer && !in_inner { blend_pixel(c, x, y, cr, cg, cb, ca, clip); } } } } fn draw_line(c: &mut Canvas, s: &wt::Segment, ox: i32, oy: i32, clip: Clip) { let (cr, cg, cb, ca) = (s.color.r as i32, s.color.g as i32, s.color.b as i32, s.color.a as i32); let half = if s.width <= 1 { 0 } else { s.width / 2 }; let (mut x0, mut y0) = (s.x0 + ox, s.y0 + oy); let (x1, y1) = (s.x1 + ox, s.y1 + oy); let dx = (x1 - x0).abs(); let sx = if x0 < x1 { 1 } else { -1 }; let dy = -(y1 - y0).abs(); let sy = if y0 < y1 { 1 } else { -1 }; let mut err = dx + dy; loop { for oy2 in -half..=half { for ox2 in -half..=half { blend_pixel(c, x0 + ox2, y0 + oy2, cr, cg, cb, ca, clip); } } if x0 == x1 && y0 == y1 { break; } let e2 = 2 * err; if e2 >= dy { err += dy; x0 += sx; } if e2 <= dx { err += dx; y0 += sy; } } } fn draw_circle(c: &mut Canvas, d: &wt::Disc, ox: i32, oy: i32, clip: Clip) { if d.radius <= 0 { return; } let (cr, cg, cb, ca) = (d.color.r as i32, d.color.g as i32, d.color.b as i32, d.color.a as f64); let rad = d.radius as f64; let (cx, cy) = (d.cx + ox, d.cy + oy); for dy in (-d.radius - 1)..=(d.radius + 1) { for dx in (-d.radius - 1)..=(d.radius + 1) { let dist = ((dx * dx + dy * dy) as f64).sqrt(); let outer = rad + 0.5 - dist; let mut cov = if outer > 1.0 { 1.0 } else { outer }; if !d.filled { let inner = dist - (rad - 1.0 - 0.5); let ic = if inner > 1.0 { 1.0 } else { inner }; if ic < cov { cov = ic; } } if cov > 0.02 { blend_pixel(c, cx + dx, cy + dy, cr, cg, cb, (ca * cov).round() as i32, clip); } } } } fn draw_text(c: &mut Canvas, fonts: &mut Fonts, t: &wt::Label, ox: i32, oy: i32, clip: Clip) { if t.text.is_empty() || t.color.a == 0 { return; } let size = t.size.max(0) as u32; let mut glyphs: Vec<(Rc, bool)> = Vec::new(); let mut total_w = 0; for ch in t.text.chars() { match fonts.pick(ch as u32, size, t.bold, t.mono) { Some((g, e)) => { total_w += g.advance + if e { 1 } else { 0 }; glyphs.push((g, e)); } None => return, // no face loaded: nothing to draw with } } let x = t.x + ox; let start_x = match t.align { 1 => x - total_w / 2, 2 => x - total_w, _ => x, }; // `y` is the vertical centre of the text; centre the capital height ('H') on it. let Some((cap, _)) = fonts.pick(72, size, false, t.mono) else { return }; let baseline = t.y + oy + (-cap.yoff) / 2; let (cr, cg, cb, ca) = (t.color.r as i32, t.color.g as i32, t.color.b as i32, t.color.a as i32); let mut pen = start_x; for (g, embolden) in &glyphs { for row in 0..g.h { for col in 0..g.w { let cov = g.coverage[(row * g.w + col) as usize] as i32; if cov > 0 { let px = pen + g.xoff + col; let py = baseline + g.yoff + row; blend_pixel(c, px, py, cr, cg, cb, ca * cov / 255, clip); if *embolden { blend_pixel(c, px + 1, py, cr, cg, cb, ca * cov / 255, clip); } } } } pen += g.advance + if *embolden { 1 } else { 0 }; } } // ---------------------------------------------------------------- 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 }, 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, by_path: HashMap, sized: RefCell>>>, } /// Biggest image side accepted from a file, and drawn. const MAX_IMAGE: i32 = 1024; fn decode_png(bytes: &[u8]) -> Option { 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 { 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 { 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> { 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 } /// Store `w` x `h` RGBA pixels as an image: overwrite `reuse` when it is a handle from an earlier /// call (its cached sizes are dropped), else add a new one. Returns the handle. pub fn put_pixels(&mut self, reuse: u32, w: i32, h: i32, rgba: Vec) -> u32 { let src = ImageSrc::Pixels { w, h, rgba }; if reuse > 0 && (reuse as usize) <= self.srcs.len() && !self.by_path.values().any(|&v| v == reuse) { self.srcs[reuse as usize - 1] = src; self.sized.borrow_mut().retain(|k, _| k.0 != reuse); return reuse; } self.srcs.push(src); self.srcs.len() as u32 } /// 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>> { 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. /// The overlap of two clips (None: no clip). fn intersect(a: Clip, b: Clip) -> Clip { match (a, b) { (None, k) | (k, None) => k, (Some(a), Some(b)) => { let (x0, y0) = (a.x.max(b.x), a.y.max(b.y)); let (x1, y1) = ((a.x + a.w).min(b.x + b.w), (a.y + a.h).min(b.y + b.h)); Some(R { x: x0, y: y0, w: (x1 - x0).max(0), h: (y1 - y0).max(0) }) } } } /// Draw `ops` offset by (ox, oy). `base` limits everything (the frame's damaged area); a push-clip /// op replaces the clip within it. fn draw_ops(c: &mut Canvas, fonts: &mut Fonts, imgs: &Images, ops: &[wt::Op], ox: i32, oy: i32, base: Clip) { let mut stack: Vec = Vec::new(); for op in ops { let clip = match stack.last() { Some(k) => intersect(Some(*k), base), None => base, }; match op { wt::Op::FillRect(f) => { let r = R { x: f.area.x + ox, y: f.area.y + oy, w: f.area.w, h: f.area.h }; fill_rounded_rect(c, r, f.color, f.radius, clip); } wt::Op::StrokeRect(s) => { let r = R { x: s.area.x + ox, y: s.area.y + oy, w: s.area.w, h: s.area.h }; stroke_rounded_rect(c, r, s.color, s.width, s.radius, clip); } wt::Op::DrawLine(l) => draw_line(c, l, ox, oy, clip), wt::Op::DrawCircle(d) => draw_circle(c, d, ox, oy, clip), wt::Op::DrawText(t) => draw_text(c, fonts, t, ox, oy, clip), wt::Op::PushClip(r) => stack.push(R { x: r.x + ox, y: r.y + oy, w: r.w, h: r.h }), wt::Op::PopClip => { stack.pop(); } wt::Op::DrawImage(p) => draw_image(c, imgs, p, ox, oy, clip), } } } // ---------------------------------------------------------------- surfaces /// A client window buffer, copied out of its shared memory and converted to RGBA8888. pub struct Surface { w: i32, h: i32, rgba: Vec, /// Every pixel has alpha 255 (XRGB, or an ARGB buffer that happens to be solid): blits copy rows. opaque: bool, } impl Surface { /// Build one from `h` rows of `stride` bytes of little-endian B, G, R, A (or X) pixels. pub fn from_bgra(src: &[u8], stride: usize, w: i32, h: i32, xrgb: bool) -> Option { if w <= 0 || h <= 0 || stride < w as usize * 4 || src.len() < stride * (h as usize - 1) + w as usize * 4 { return None; } let mut rgba = vec![0u8; w as usize * h as usize * 4]; let mut opaque = true; for y in 0..h as usize { let s = &src[y * stride..y * stride + w as usize * 4]; let d = &mut rgba[y * w as usize * 4..(y + 1) * w as usize * 4]; for (sp, dp) in s.chunks_exact(4).zip(d.chunks_exact_mut(4)) { dp[0] = sp[2]; dp[1] = sp[1]; dp[2] = sp[0]; dp[3] = if xrgb { 0xff } else { sp[3] }; opaque &= dp[3] == 0xff; } } Some(Surface { w, h, rgba, opaque }) } } /// Draw a client surface into `dst`. While the client catches up with a resize its buffer is smaller /// than the window: the buffer's bottom-right colour is extended over the rest. fn blit_surface(c: &mut Canvas, s: &Surface, dst: R, clip: Clip) { if s.w <= 0 || s.h <= 0 || dst.w <= 0 || dst.h <= 0 { return; } if s.w < dst.w || s.h < dst.h { let o = ((s.h - 1) * s.w + (s.w - 1)) as usize * 4; let col = wt::Color { r: s.rgba[o], g: s.rgba[o + 1], b: s.rgba[o + 2], a: s.rgba[o + 3] }; fill_rounded_rect(c, dst, col, 0, clip); } let (copy_w, copy_h) = (s.w.min(dst.w), s.h.min(dst.h)); // Visible columns [c0, c1) and rows [r0, r1) of the buffer: on the canvas and inside the clip. let (mut c0, mut c1) = ((-dst.x).max(0), copy_w.min(c.w - dst.x)); let (mut r0, mut r1) = ((-dst.y).max(0), copy_h.min(c.h - dst.y)); if let Some(k) = clip { c0 = c0.max(k.x - dst.x); c1 = c1.min(k.x + k.w - dst.x); r0 = r0.max(k.y - dst.y); r1 = r1.min(k.y + k.h - dst.y); } if c0 >= c1 || r0 >= r1 { return; } for row in r0..r1 { let dy = dst.y + row; let src = &s.rgba[((row * s.w + c0) * 4) as usize..((row * s.w + c1) * 4) as usize]; let d0 = ((dy * c.w + dst.x + c0) * 4) as usize; let dst_row = &mut c.data[d0..d0 + src.len()]; if s.opaque { dst_row.copy_from_slice(src); } else { for (sp, dp) in src.chunks_exact(4).zip(dst_row.chunks_exact_mut(4)) { let a = sp[3] as i32; if a >= 255 { dp.copy_from_slice(sp); } else if a > 0 { // wl_shm ARGB8888 is premultiplied: the colour already carries its alpha. let inv = 255 - a; dp[0] = clamp_u8(sp[0] as i32 + (dp[0] as i32 * inv + 127) / 255); dp[1] = clamp_u8(sp[1] as i32 + (dp[1] as i32 * inv + 127) / 255); dp[2] = clamp_u8(sp[2] as i32 + (dp[2] as i32 * inv + 127) / 255); dp[3] = clamp_u8(a + (dp[3] as i32 * inv + 127) / 255); } } } } } // ---------------------------------------------------------------- the rasteriser /// The framebuffer, the wallpaper cache and the captured client surfaces. #[derive(Default)] pub struct Raster { pub w: i32, pub h: i32, /// RGBA8888, `w * h * 4` bytes. pub fb: Vec, wallpaper: Option<(Vec, i32, i32, Vec)>, surfaces: HashMap, next_id: u32, /// Images for `draw-image` ops (app icons). pub images: Images, /// The last frame drawn, to work out what the next one changes. prev: Option, /// Pixels redrawn by the last submit (for tests and profiling). pub last_drawn: usize, } /// Room around a window for its drop shadow (4 px right, 6 px down) and a little slack. const SHADOW_PAD: i32 = 8; /// What a window covers on screen: its decoration and drop shadow, or just itself when fullscreen. fn window_footprint(win: &wt::Window) -> R { let g = R::from(win.geometry); if win.fullscreen { return g; } R { x: g.x - win.inset_left - SHADOW_PAD, y: g.y - win.inset_top - SHADOW_PAD, w: g.w + win.inset_left + win.inset_right + 2 * SHADOW_PAD, h: g.h + win.inset_top + win.inset_bottom + 2 * SHADOW_PAD, } } /// The bounding box of two rectangles (an empty one counts for nothing). fn union(a: R, b: R) -> R { if a.w <= 0 || a.h <= 0 { return b; } if b.w <= 0 || b.h <= 0 { return a; } let (x0, y0) = (a.x.min(b.x), a.y.min(b.y)); let (x1, y1) = ((a.x + a.w).max(b.x + b.w), (a.y + a.h).max(b.y + b.h)); R { x: x0, y: y0, w: x1 - x0, h: y1 - y0 } } /// The part of the screen `f` changes over `prev`, as one rectangle; None when all of it must be /// redrawn. Only window changes are narrowed down (a client drawing, a window moving, focus moving): /// any change to the wallpaper, desktop card, panel or the set of windows redraws everything. fn damage(prev: &wt::Frame, f: &wt::Frame) -> Option { if prev.width != f.width || prev.height != f.height || prev.windows.len() != f.windows.len() { return None; } if f.background != prev.background || f.panel != prev.panel { return None; } if let Some(ops) = &f.wallpaper { if prev.wallpaper.as_ref() != Some(ops) { return None; } } let mut d = R { x: 0, y: 0, w: 0, h: 0 }; for (a, b) in prev.windows.iter().zip(f.windows.iter()) { if a == b { continue; } d = union(d, union(window_footprint(a), window_footprint(b))); } if prev.popups != f.popups { for p in prev.popups.iter().chain(f.popups.iter()) { d = union(d, R::from(p.area)); } } Some(d) } impl Raster { pub fn add_surface(&mut self, s: Surface) -> u32 { self.next_id = self.next_id.wrapping_add(1).max(1); self.surfaces.insert(self.next_id, s); self.next_id } pub fn release(&mut self, id: u32) { self.surfaces.remove(&id); } /// A `w` x `h` scaled copy of surface `id` as an image (see `Images::put_pixels` for `reuse`). /// 0 for an unknown surface or a silly size. pub fn thumbnail(&mut self, id: u32, w: i32, h: i32, reuse: u32) -> u32 { if w <= 0 || h <= 0 || w > MAX_IMAGE || h > MAX_IMAGE { return 0; } let Some(s) = self.surfaces.get(&id) else { return 0 }; let px = scale_rgba(&s.rgba, s.w, s.h, w, h); self.images.put_pixels(reuse, w, h, px) } pub fn surface_count(&self) -> usize { self.surfaces.len() } /// `submit_frame` for a borrowed frame (tests). #[cfg(test)] pub fn submit(&mut self, f: &wt::Frame, fonts: &mut Fonts) { self.submit_frame(f.clone(), fonts) } /// Draw a frame into the framebuffer: wallpaper (cached), background, windows bottom to top, /// panel, then client popups. The same layering as the software renderer's `render_scene`. /// Only the part that differs from the last frame is redrawn (see `damage`): a client drawing /// in its window costs that window's pixels, not the whole screen. pub fn submit_frame(&mut self, f: wt::Frame, fonts: &mut Fonts) { let (w, h) = (f.width.max(1), f.height.max(1)); let resized = w != self.w || h != self.h || self.fb.len() != (w * h * 4) as usize; if resized { self.w = w; self.h = h; self.fb = vec![0u8; (w * h * 4) as usize]; } // The frame starts from the cached backdrop (which covers every pixel), so the buffer is // only cleared when there is none: no point zeroing 8 MB that is overwritten at once. let backdrop_ready = match (&f.wallpaper, &self.wallpaper) { (None, Some((_, cw, ch, _))) => *cw == w && *ch == h, (Some(ops), Some((o, cw, ch, _))) => *cw == w && *ch == h && o == ops, _ => false, }; let clip: Clip = match (&self.prev, resized || !backdrop_ready) { (Some(prev), false) => match damage(prev, &f) { Some(d) => match intersect(Some(d), Some(R { x: 0, y: 0, w, h })) { Some(k) if k.w > 0 && k.h > 0 => Some(k), _ => { // Nothing on screen changed (a window off screen, say). self.last_drawn = 0; self.keep_prev(f); return; } }, None => None, }, _ => None, }; if !resized && !backdrop_ready { self.fb.fill(0); } self.last_drawn = match clip { Some(k) => (k.w * k.h) as usize, None => (w * h) as usize, }; 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 (only the damaged rows and columns). let copy_backdrop = |c: &mut Canvas, px: &[u8]| match clip { None => c.data.copy_from_slice(px), Some(k) => { for y in k.y..k.y + k.h { let a = ((y * w + k.x) * 4) as usize; let b = a + (k.w * 4) as usize; c.data[a..b].copy_from_slice(&px[a..b]); } } }; match &f.wallpaper { Some(ops) => { let cached = matches!(&self.wallpaper, Some((o, cw, ch, _)) if *cw == w && *ch == h && o == ops); if cached { copy_backdrop(&mut c, &self.wallpaper.as_ref().unwrap().3); } else { draw_ops(&mut c, fonts, imgs, ops, 0, 0, None); self.wallpaper = Some((ops.clone(), w, h, c.data.to_vec())); } } None => { if let Some((_, cw, ch, px)) = &self.wallpaper { if *cw == w && *ch == h { copy_backdrop(&mut c, px); } } } } draw_ops(&mut c, fonts, imgs, &f.background, 0, 0, clip); // 2. Windows, bottom to top. for win in &f.windows { let g = R::from(win.geometry); if let Some(k) = clip { if intersect(Some(window_footprint(win)), Some(k)).map_or(true, |r| r.w <= 0 || r.h <= 0) { continue; } } if !win.fullscreen { let (outer_x, outer_y) = (g.x - win.inset_left, g.y - win.inset_top); let outer_w = g.w + win.inset_left + win.inset_right; let outer_h = g.h + win.inset_top + win.inset_bottom; // Subtle drop shadow: only the strips that stick out from under the window (and the // part under the translucent title bar) are blended. let shadow = R { x: outer_x + 4, y: outer_y + 6, w: outer_w, h: outer_h }; let col = wt::Color { r: 0, g: 0, b: 0, a: 80 }; let strips = [ R { x: outer_x + outer_w, y: outer_y, w: 4, h: outer_h + 6 }, R { x: outer_x, y: outer_y + outer_h, w: outer_w + 4, h: 6 }, R { x: outer_x, y: outer_y, w: outer_w, h: win.inset_top + 2 }, ]; for s in strips { if let Some(k) = intersect(Some(s), clip) { if k.w > 0 && k.h > 0 { fill_rounded_rect(&mut c, shadow, col, 8, Some(k)); } } } draw_ops(&mut c, fonts, imgs, &win.deco, outer_x, outer_y, clip); } match surfaces.get(&win.surface) { Some(s) => blit_surface(&mut c, s, g, clip), None => fill_rounded_rect(&mut c, g, wt::Color { r: 0x1e, g: 0x29, b: 0x3b, a: 0xff }, 0, clip), } } // 3. Panel (and its popups, menus and notices), then 4. client popups above everything. draw_ops(&mut c, fonts, imgs, &f.panel, 0, 0, clip); for p in &f.popups { if let Some(s) = surfaces.get(&p.surface) { blit_surface(&mut c, s, R::from(p.area), clip); } } self.keep_prev(f); } /// Remember `f` as the last frame. Its wallpaper ops are kept from the frame that sent them, so /// a later frame that resends the same wallpaper still compares equal. fn keep_prev(&mut self, mut f: wt::Frame) { if f.wallpaper.is_none() { f.wallpaper = self.prev.as_mut().and_then(|p| p.wallpaper.take()); } self.prev = Some(f); } /// The framebuffer as little-endian ARGB8888 (B, G, R, A=255), `stride = w * 4`. pub fn to_argb8888(&self) -> Vec { let mut out = vec![0u8; self.fb.len()]; for (s, d) in self.fb.chunks_exact(4).zip(out.chunks_exact_mut(4)) { d[0] = s[2]; d[1] = s[1]; d[2] = s[0]; d[3] = 0xff; } out } } #[cfg(test)] mod tests { use super::*; fn color(r: u8, g: u8, b: u8, a: u8) -> wt::Color { wt::Color { r, g, b, a } } fn rect(x: i32, y: i32, w: i32, h: i32) -> wt::Rect { wt::Rect { x, y, w, h } } fn fill(x: i32, y: i32, w: i32, h: i32, c: wt::Color, radius: i32) -> wt::Op { wt::Op::FillRect(wt::Fill { area: rect(x, y, w, h), color: c, radius }) } fn frame(w: i32, h: i32) -> wt::Frame { wt::Frame { width: w, height: h, wallpaper: None, background: vec![], windows: vec![], panel: vec![], popups: vec![] } } fn px(r: &Raster, x: i32, y: i32) -> [u8; 4] { let o = ((y * r.w + x) * 4) as usize; [r.fb[o], r.fb[o + 1], r.fb[o + 2], r.fb[o + 3]] } #[test] fn fills_blend_with_the_same_arithmetic_as_the_software_renderer() { let mut r = Raster::default(); let mut f = frame(20, 10); f.background = vec![fill(0, 0, 20, 10, color(10, 20, 30, 255), 0), fill(2, 2, 6, 6, color(200, 100, 0, 128), 0)]; r.submit(&f, &mut Fonts::default()); assert_eq!(px(&r, 0, 0), [10, 20, 30, 255]); // (200*128 + 10*127 + 127) / 255 = 105, (100*128 + 20*127 + 127) / 255 = 60, (0 + 30*127 + 127) / 255 = 15 assert_eq!(px(&r, 3, 3), [105, 60, 15, 255]); } #[test] fn rounded_corners_leave_the_corner_pixel_untouched() { let mut r = Raster::default(); let mut f = frame(40, 40); f.background = vec![fill(4, 4, 30, 30, color(255, 255, 255, 255), 10)]; r.submit(&f, &mut Fonts::default()); assert_eq!(px(&r, 4, 4), [0, 0, 0, 0]); // outside the rounded corner assert_eq!(px(&r, 19, 19), [255, 255, 255, 255]); assert_eq!(px(&r, 19, 4), [255, 255, 255, 255]); // straight edge } #[test] fn stroke_draws_only_the_border() { let mut r = Raster::default(); let mut f = frame(30, 30); f.background = vec![wt::Op::StrokeRect(wt::Stroke { area: rect(2, 2, 20, 20), color: color(9, 9, 9, 255), width: 2, radius: 0 })]; r.submit(&f, &mut Fonts::default()); assert_eq!(px(&r, 2, 10), [9, 9, 9, 255]); assert_eq!(px(&r, 3, 10), [9, 9, 9, 255]); assert_eq!(px(&r, 4, 10), [0, 0, 0, 0]); // interior assert_eq!(px(&r, 21, 10), [9, 9, 9, 255]); assert_eq!(px(&r, 10, 21), [9, 9, 9, 255]); } #[test] fn clip_ops_limit_drawing() { let mut r = Raster::default(); let mut f = frame(20, 20); f.background = vec![ wt::Op::PushClip(rect(5, 5, 5, 5)), fill(0, 0, 20, 20, color(1, 2, 3, 255), 0), wt::Op::PopClip, fill(0, 0, 2, 2, color(7, 7, 7, 255), 0), ]; r.submit(&f, &mut Fonts::default()); assert_eq!(px(&r, 6, 6), [1, 2, 3, 255]); assert_eq!(px(&r, 2, 2), [0, 0, 0, 0]); assert_eq!(px(&r, 10, 10), [0, 0, 0, 0]); assert_eq!(px(&r, 1, 1), [7, 7, 7, 255]); } #[test] fn wallpaper_is_cached_and_reused_when_the_frame_says_unchanged() { let mut r = Raster::default(); let mut fonts = Fonts::default(); let mut f = frame(16, 16); f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(50, 60, 70, 255), 0)]); r.submit(&f, &mut fonts); assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]); let mut g = frame(16, 16); g.wallpaper = None; // unchanged: the cached pixels come back g.background = vec![fill(0, 0, 2, 2, color(1, 1, 1, 255), 0)]; r.submit(&g, &mut fonts); assert_eq!(px(&r, 8, 8), [50, 60, 70, 255]); assert_eq!(px(&r, 0, 0), [1, 1, 1, 255]); // A different wallpaper is drawn afresh. f.wallpaper = Some(vec![fill(0, 0, 16, 16, color(9, 8, 7, 255), 0)]); r.submit(&f, &mut fonts); assert_eq!(px(&r, 8, 8), [9, 8, 7, 255]); } #[test] fn windows_blit_their_surface_converted_from_bgra_and_shadow_only_sticks_out() { let mut r = Raster::default(); // A 4x2 XRGB buffer, every pixel B=10 G=20 R=30. let bgra: Vec = (0..8).flat_map(|_| [10u8, 20, 30, 0]).collect(); let id = r.add_surface(Surface::from_bgra(&bgra, 16, 4, 2, true).unwrap()); let mut f = frame(40, 30); f.background = vec![fill(0, 0, 40, 30, color(200, 200, 200, 255), 0)]; f.windows = vec![wt::Window { geometry: rect(10, 10, 4, 2), inset_top: 0, inset_right: 0, inset_bottom: 0, inset_left: 0, deco: vec![], fullscreen: false, surface: id, }]; r.submit(&f, &mut Fonts::default()); assert_eq!(px(&r, 10, 10), [30, 20, 10, 255]); // R, G, B order after conversion assert_eq!(px(&r, 13, 11), [30, 20, 10, 255]); // The shadow sits to the right of / below the window, not under it. // The shadow rectangle is the window moved by (4, 6): (14..18, 16..18) here. assert!(px(&r, 15, 17)[0] < 200, "shadow strip below and to the right"); assert_eq!(px(&r, 15, 12)[0], 200, "no shadow where the offset rectangle does not reach"); r.release(id); assert_eq!(r.surface_count(), 0); } /// A window with a title-bar decoration over a patterned backdrop and a panel. fn scene_window(r: &mut Raster, x: i32, y: i32, shade: u8, focused: bool) -> wt::Window { let bgra: Vec = (0..(30 * 20)).flat_map(|i| [shade, (i % 251) as u8, 40, if i % 7 == 0 { 90 } else { 255 }]).collect(); let id = r.add_surface(Surface::from_bgra(&bgra, 30 * 4, 30, 20, false).unwrap()); wt::Window { geometry: rect(x, y, 30, 20), inset_top: 8, inset_right: 2, inset_bottom: 2, inset_left: 2, deco: vec![fill(0, 0, 34, 30, if focused { color(60, 90, 200, 230) } else { color(90, 90, 90, 200) }, 3)], fullscreen: false, surface: id, } } fn scene_frame(windows: Vec) -> wt::Frame { let mut f = frame(120, 90); f.wallpaper = Some((0..12).map(|i| fill(i * 10, 0, 10, 90, color((i * 20) as u8, 100, 200 - (i * 10) as u8, 255), 0)).collect()); f.windows = windows; f.panel = vec![fill(0, 80, 120, 10, color(20, 20, 30, 220), 0), fill(4, 82, 6, 6, color(250, 250, 250, 255), 3)]; f } #[test] fn redrawing_only_the_damage_gives_the_same_pixels_as_a_full_redraw() { let mut fonts = Fonts::default(); // Frame 1 (full), then steps that only change windows: a client redraw, a move, a focus change. let mut inc = Raster::default(); let w1 = scene_window(&mut inc, 10, 15, 10, false); let w2 = scene_window(&mut inc, 30, 25, 200, true); inc.submit(&scene_frame(vec![w1.clone(), w2.clone()]), &mut fonts); assert_eq!(inc.last_drawn, 120 * 90); let mut new_w1 = scene_window(&mut inc, 10, 15, 99, false); // the client drew a new buffer let steps = vec![ vec![new_w1.clone(), w2.clone()], { new_w1.geometry = rect(60, 40, 30, 20); // moved, now overlapping the panel vec![new_w1.clone(), w2.clone()] }, { let mut a = new_w1.clone(); a.deco = vec![fill(0, 0, 34, 30, color(60, 90, 200, 230), 3)]; let mut b = w2.clone(); b.deco = vec![fill(0, 0, 34, 30, color(90, 90, 90, 200), 3)]; vec![b, a] // focus moved and the stacking order swapped }, ]; for (i, wins) in steps.into_iter().enumerate() { let f = scene_frame(wins); let mut f_inc = f.clone(); f_inc.wallpaper = None; // the compositor sends an unchanged backdrop as None inc.submit(&f_inc, &mut fonts); assert!(inc.last_drawn < 120 * 90, "step {i}: only part of the screen is redrawn"); // The same frame drawn from scratch, with the same surfaces. let mut full = Raster::default(); for (id, s) in &inc.surfaces { full.surfaces.insert(*id, Surface { w: s.w, h: s.h, rgba: s.rgba.clone(), opaque: s.opaque }); } full.submit(&f, &mut fonts); assert!(full.fb == inc.fb, "step {i}: partial redraw differs from a full one"); } // An unchanged frame draws nothing. let f = inc.prev.clone().unwrap(); inc.submit(&f, &mut fonts); assert_eq!(inc.last_drawn, 0); } #[test] fn translucent_surfaces_blend_over_what_is_behind() { let mut r = Raster::default(); // One ARGB pixel: B=0 G=0 R=255 A=128, over a grey background. let id = r.add_surface(Surface::from_bgra(&[0, 0, 255, 128], 4, 1, 1, false).unwrap()); let mut f = frame(8, 8); f.background = vec![fill(0, 0, 8, 8, color(100, 100, 100, 255), 0)]; f.windows = vec![wt::Window { geometry: rect(2, 2, 1, 1), inset_top: 0, inset_right: 0, inset_bottom: 0, inset_left: 0, deco: vec![], fullscreen: true, surface: id }]; r.submit(&f, &mut Fonts::default()); // (255*128 + 100*127 + 127) / 255 = 178, (0 + 100*127 + 127) / 255 = 50 assert_eq!(px(&r, 2, 2), [178, 50, 50, 255]); } #[test] fn argb_export_swaps_red_and_blue() { let mut r = Raster::default(); let mut f = frame(2, 1); f.background = vec![fill(0, 0, 2, 1, color(1, 2, 3, 255), 0)]; r.submit(&f, &mut Fonts::default()); assert_eq!(&r.to_argb8888()[..4], &[3, 2, 1, 255]); } #[test] fn thumbnails_scale_a_surface_and_reuse_their_handle() { let mut r = Raster::default(); // A 4x2 surface: left half red, right half blue (BGRA in, RGBA out). let mut src = Vec::new(); for _ in 0..2 { for x in 0..4 { src.extend_from_slice(if x < 2 { &[0, 0, 255, 255] } else { &[255, 0, 0, 255] }); } } let s = r.add_surface(Surface::from_bgra(&src, 16, 4, 2, true).unwrap()); assert_eq!(r.thumbnail(999, 2, 1, 0), 0); assert_eq!(r.thumbnail(s, 0, 1, 0), 0); let t = r.thumbnail(s, 2, 1, 0); assert_ne!(t, 0); r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 2, 1), image: t })], ..frame(4, 4) }, &mut Fonts::default()); assert_eq!(px(&r, 0, 0), [255, 0, 0, 255]); assert_eq!(px(&r, 1, 0), [0, 0, 255, 255]); // Refreshing overwrites the same handle, and the old pixels are not served from the cache. let blue = [255u8, 0, 0, 255].repeat(8); let s2 = r.add_surface(Surface::from_bgra(&blue, 16, 4, 2, true).unwrap()); assert_eq!(r.thumbnail(s2, 2, 1, t), t); r.submit(&wt::Frame { panel: vec![wt::Op::DrawImage(wt::Picture { area: rect(0, 0, 2, 1), image: t })], ..frame(4, 4) }, &mut Fonts::default()); assert_eq!(px(&r, 0, 0), [0, 0, 255, 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##""##).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); } }