B1: alpha installers (NSIS, DMG), identifier com.tyrveil.lutra with data migration

- App identifier com.tyrveil.lutra (D26) in tauri.conf.json and
  rendezvous::APP_IDENTIFIER; a test keeps them equal.
- First normal start copies settings.json, recovery/ and tools/ once from
  the dev.lutra.desktop directories (staging dir + rename, logged, info
  notification); old directories stay untouched.
- Bundling on: per-user NSIS setup (English, German, Start menu, optional
  desktop shortcut, uninstaller) and DMG; `cargo xtask bundle` builds the
  platform's installer, joining the DMG backgrounds into a HiDPI TIFF on
  macOS. build.rs also writes icons/512x512.png for the .icns.
- Installer images from the banner, designed by Amy, generated by
  `cargo xtask installer-images` (assets/installer/, ASSETS.md rows);
  approved by Daniel.
- docs/install.md (SmartScreen, Gatekeeper, uninstall, data locations),
  README install section, architecture, development and macOS notes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-31 21:48:15 +01:00
parent 071b2a5644
commit bd225d9e3a
22 changed files with 1367 additions and 17 deletions

View file

@ -1,6 +1,6 @@
[package]
name = "xtask"
description = "Project automation: ci, layers, assets, cleanroom, dev, fixtures, demo-project, mac-report"
description = "Project automation: ci, layers, assets, cleanroom, dev, bundle, fixtures, demo-project, mac-report"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
@ -13,6 +13,7 @@ layer = "tool"
[dependencies]
lutra-proc.workspace = true
png = "0.18.1"
serde_json = "1.0.154"
toml = "1.1.8"

127
xtask/src/bundle.rs Normal file
View file

@ -0,0 +1,127 @@
//! `cargo xtask bundle`: the platform's installer.
//!
//! Builds the desktop app in release mode with the bundled UI through the
//! Tauri CLI and packs it: an NSIS setup (`.exe`, per-user install) on
//! Windows, a DMG on macOS. The settings live in
//! `apps/lutra-desktop/tauri.conf.json`; the installer images in
//! `assets/installer/`. On macOS the 1x and 2x DMG backgrounds are joined
//! into one HiDPI TIFF with `tiffutil` first, so Finder picks the sharp one
//! on a Retina display; without `tiffutil` the 1x PNG from the config is
//! used. Other platforms have no installer yet.
use std::path::{Path, PathBuf};
use crate::util::{TaskResult, repo_root, run};
/// The Tauri bundle target and the output folder under `bundle/` for this
/// platform, or `None` without an installer.
fn target() -> Option<(&'static str, &'static str)> {
if cfg!(windows) {
Some(("nsis", "nsis"))
} else if cfg!(target_os = "macos") {
Some(("dmg", "dmg"))
} else {
None
}
}
/// Builds the platform's installer and prints where it is.
///
/// # Errors
/// Fails on a platform without an installer, if the frontend dependencies
/// cannot be installed, or if the Tauri CLI is missing or fails.
pub fn bundle() -> TaskResult {
let Some((bundles, folder)) = target() else {
return Err("no installer for this platform yet (Windows: NSIS, macOS: DMG)".into());
};
let root = repo_root()?;
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
if !root.join("ui").join("node_modules").is_dir() {
run(&root.join("ui"), "pnpm", &["install", "--frozen-lockfile"])?;
}
let mut args = vec![
"tauri".to_string(),
"build".into(),
"--bundles".into(),
bundles.into(),
"--features".into(),
"bundled-ui".into(),
];
let target_dir = target_dir(&root);
if cfg!(target_os = "macos")
&& let Some(tiff) = hidpi_background(&root, &target_dir)
{
args.push("--config".into());
args.push(dmg_background_override(&tiff));
}
let args: Vec<&str> = args.iter().map(String::as_str).collect();
run(&root.join("apps").join("lutra-desktop"), &cargo, &args).map_err(|e| {
format!("{e}\n(install the Tauri CLI with `cargo install tauri-cli --locked`)")
})?;
let out = target_dir.join("release").join("bundle").join(folder);
let listing = std::fs::read_dir(&out)
.map_err(|e| format!("no installer folder {}: {e}", out.display()))?;
for entry in listing.flatten() {
let path = entry.path();
let size = entry.metadata().map(|m| m.len()).unwrap_or(0);
println!(
"bundle: {} ({:.1} MB)",
path.display(),
size as f64 / 1_000_000.0
);
}
Ok(())
}
/// The Cargo target directory: `CARGO_TARGET_DIR` (relative to the
/// repository root) or `<root>/target`.
fn target_dir(root: &Path) -> PathBuf {
match std::env::var_os("CARGO_TARGET_DIR").filter(|v| !v.is_empty()) {
Some(dir) => root.join(dir),
None => root.join("target"),
}
}
/// Joins `dmg-background.png` and `dmg-background@2x.png` into
/// `<target>/dmg-background.tiff` with `tiffutil -cathidpicheck`. `None`
/// (and a note) if that fails; the bundle then uses the 1x PNG.
fn hidpi_background(root: &Path, target_dir: &Path) -> Option<PathBuf> {
let dir = root.join("assets").join("installer");
let out = target_dir.join("dmg-background.tiff");
std::fs::create_dir_all(target_dir).ok()?;
let status = std::process::Command::new("tiffutil")
.arg("-cathidpicheck")
.arg(dir.join("dmg-background.png"))
.arg(dir.join("dmg-background@2x.png"))
.arg("-out")
.arg(&out)
.status();
match status {
Ok(s) if s.success() => Some(out),
_ => {
println!("bundle: tiffutil failed; the DMG uses the 1x background");
None
}
}
}
/// The `--config` JSON for the Tauri CLI that sets the DMG background to
/// `tiff`.
fn dmg_background_override(tiff: &Path) -> String {
serde_json::json!({
"bundle": { "macOS": { "dmg": { "background": tiff } } }
})
.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_override_names_the_tiff() {
let json: serde_json::Value =
serde_json::from_str(&dmg_background_override(Path::new("/t/bg.tiff"))).unwrap();
assert_eq!(json["bundle"]["macOS"]["dmg"]["background"], "/t/bg.tiff");
}
}

212
xtask/src/images.rs Normal file
View file

@ -0,0 +1,212 @@
//! `cargo xtask installer-images`: the installer images, generated from
//! the README banner `docs/images/banner.png` into `assets/installer/`.
//!
//! Amy's design (B1): crops of the banner on its magenta, no new art.
//! - `nsis-sidebar.bmp` (164 × 314): the otter on its tower.
//! - `nsis-header.bmp` (150 × 57): the "Lutra" wordmark, centred.
//! - `dmg-background.png` (720 × 400) and `dmg-background@2x.png`
//! (1440 × 800): wordmark top left, the otter column on the right, the
//! skyline along the bottom, a lighter magenta shelf behind the app and
//! Applications icons (centred at (100, 184) and (326, 184)) so Finder's
//! black or white labels stay readable, and a cream arrow between them.
//!
//! Every crop is resampled straight from the banner to its final size;
//! the 2x background is drawn with every target coordinate doubled. The
//! output is deterministic, so running the task again gives the same
//! files.
use std::path::Path;
use crate::raster::{Raster, Rect, color};
use crate::util::{TaskResult, repo_root};
/// The banner's flat background.
const MAGENTA: &str = "#bb3b78";
/// The wordmark and otter colour, used for the arrow.
const CREAM: &str = "#f2ebd9";
/// The label shelf: black and white text both reach WCAG AA on it.
const SHELF: &str = "#c54883";
/// Width of the feathered edges of the DMG wordmark, in 1x pixels.
const FEATHER: u32 = 16;
/// Shorthand for a [`Rect`].
const fn rect(x: u32, y: u32, w: u32, h: u32) -> Rect {
Rect { x, y, w, h }
}
/// Writes all installer images from the banner.
///
/// # Errors
/// If the banner cannot be read or decoded, a crop lies outside it, or a
/// file cannot be written.
pub fn generate() -> TaskResult {
let root = repo_root()?;
let banner_path = root.join("docs").join("images").join("banner.png");
let bytes = std::fs::read(&banner_path)
.map_err(|e| format!("cannot read {}: {e}", banner_path.display()))?;
let banner = Raster::decode_png(&bytes)?;
let out = root.join("assets").join("installer");
std::fs::create_dir_all(&out).map_err(|e| e.to_string())?;
write(&out, "nsis-sidebar.bmp", &sidebar(&banner)?.encode_bmp())?;
write(&out, "nsis-header.bmp", &header(&banner)?.encode_bmp())?;
write(&out, "dmg-background.png", &dmg(&banner, 1)?.encode_png()?)?;
write(
&out,
"dmg-background@2x.png",
&dmg(&banner, 2)?.encode_png()?,
)?;
Ok(())
}
/// Writes `bytes` to `dir/name` and prints it.
///
/// # Errors
/// If the file cannot be written.
fn write(dir: &Path, name: &str, bytes: &[u8]) -> TaskResult {
let path = dir.join(name);
std::fs::write(&path, bytes).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
println!(
"installer-images: {} ({} bytes)",
path.display(),
bytes.len()
);
Ok(())
}
/// The NSIS sidebar: the otter, head in the upper third, on magenta.
///
/// # Errors
/// If the crop lies outside the banner.
pub fn sidebar(banner: &Raster) -> TaskResult<Raster> {
let mut img = Raster::new(164, 314, color(MAGENTA)?);
let otter = banner.crop(rect(980, 60, 345, 660))?.resize(164, 314);
img.draw(&otter, 0, 0, 1.0);
Ok(img)
}
/// The NSIS header: the wordmark, 9 px of magenta above and below.
///
/// # Errors
/// If the crop lies outside the banner.
pub fn header(banner: &Raster) -> TaskResult<Raster> {
let mut img = Raster::new(150, 57, color(MAGENTA)?);
let mark = banner.crop(rect(14, 28, 820, 214))?.resize(150, 39);
img.draw(&mark, 0, 9, 1.0);
Ok(img)
}
/// The DMG background at `scale` (1 or 2) times 720 × 400; layers in
/// Amy's order: magenta, feathered wordmark, skyline, otter column, label
/// shelf, arrow.
///
/// # Errors
/// If a crop lies outside the banner.
pub fn dmg(banner: &Raster, scale: u32) -> TaskResult<Raster> {
let s = |v: u32| v * scale;
let mut img = Raster::new(s(720), s(400), color(MAGENTA)?);
let mut mark = banner.crop(rect(0, 0, 860, 330))?.resize(s(310), s(119));
feather(&mut mark, s(FEATHER));
img.draw(&mark, 0, 0, 1.0);
let skyline = banner.crop(rect(0, 520, 766, 200))?.resize(s(426), s(111));
img.draw(&skyline, 0, i64::from(s(289)), 1.0);
let otter = banner.crop(rect(870, 0, 527, 720))?.resize(s(294), s(400));
img.draw(&otter, i64::from(s(426)), 0, 1.0);
img.fill_rect(rect(s(10), s(116), s(406), s(172)), color(SHELF)?);
let cream = color(CREAM)?;
img.fill_rect(rect(s(178), s(180), s(54), s(8)), cream);
let p = |x: u32, y: u32| (f64::from(s(x)), f64::from(s(y)));
img.fill_triangle([p(232, 172), p(248, 184), p(232, 196)], cream);
Ok(img)
}
/// Fades the right and bottom `width` pixels of `img` to transparent with
/// a linear ramp (the factors multiply in the corner), so the crop melts
/// into the background.
fn feather(img: &mut Raster, width: u32) {
let (w, h) = (img.width, img.height);
let ramp = |pos: u32, size: u32| {
if pos + width >= size {
f64::from(size - pos) / f64::from(width + 1)
} else {
1.0
}
};
for y in 0..h {
for x in 0..w {
let factor = ramp(x, w) * ramp(y, h);
if factor < 1.0 {
let [r, g, b, a] = img.pixel(x, y);
img.put(x, y, [r, g, b, (f64::from(a) * factor).round() as u8]);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A flat stand-in banner of the real size.
fn banner() -> Raster {
Raster::new(1456, 720, color(MAGENTA).unwrap())
}
#[test]
fn images_have_the_installer_sizes_and_are_opaque() {
let b = banner();
for (img, w, h) in [
(sidebar(&b).unwrap(), 164, 314),
(header(&b).unwrap(), 150, 57),
(dmg(&b, 1).unwrap(), 720, 400),
(dmg(&b, 2).unwrap(), 1440, 800),
] {
assert_eq!((img.width, img.height), (w, h));
assert!(img.rgba.as_chunks::<4>().0.iter().all(|p| p[3] == 255));
}
}
#[test]
fn the_dmg_has_the_shelf_and_the_arrow() {
let b = banner();
let one = dmg(&b, 1).unwrap();
assert_eq!(one.pixel(100, 260), color(SHELF).unwrap());
assert_eq!(one.pixel(200, 184), color(CREAM).unwrap());
assert_eq!(one.pixel(236, 184), color(CREAM).unwrap());
let two = dmg(&b, 2).unwrap();
assert_eq!(two.pixel(400, 368), color(CREAM).unwrap());
}
#[test]
fn feathering_fades_only_the_right_and_bottom_edges() {
let mut img = Raster::new(40, 40, [0, 0, 0, 255]);
feather(&mut img, 16);
assert_eq!(img.pixel(0, 0)[3], 255);
assert_eq!(img.pixel(23, 23)[3], 255);
assert_eq!(img.pixel(39, 0)[3], 15);
assert!(img.pixel(39, 39)[3] < 2);
}
#[test]
fn the_real_banner_gives_the_committed_images() {
let root = repo_root().unwrap();
let bytes = std::fs::read(root.join("docs/images/banner.png")).unwrap();
let banner = Raster::decode_png(&bytes).unwrap();
let dir = root.join("assets/installer");
let committed = |name: &str| std::fs::read(dir.join(name)).unwrap();
assert_eq!(
sidebar(&banner).unwrap().encode_bmp(),
committed("nsis-sidebar.bmp")
);
assert_eq!(
header(&banner).unwrap().encode_bmp(),
committed("nsis-header.bmp")
);
assert_eq!(
dmg(&banner, 1).unwrap().encode_png().unwrap(),
committed("dmg-background.png")
);
}
}

View file

@ -4,12 +4,15 @@
//! message when the check fails.
mod assets;
mod bundle;
mod cleanroom;
mod demo;
mod images;
mod layers;
mod licences;
mod lints;
mod macreport;
mod raster;
mod tasks;
mod util;
@ -27,6 +30,8 @@ commands:
ui-licences check the licences of the frontend's production dependencies
lints-selftest prove that shipped unwrap() fails clippy and test unwrap() passes
dev [-- ARGS] run the desktop app in development mode, ARGS go to the app
bundle build this platform's installer (Windows: NSIS setup, macOS: DMG)
installer-images regenerate assets/installer/ from docs/images/banner.png
fixtures create Symfony and Laravel reference projects in target/fixtures/
demo-project DIR create the offline demo for docs/alpha-checklist.md in DIR
",
@ -58,6 +63,8 @@ fn main() -> ExitCode {
.collect();
tasks::dev(&app_args)
}
"bundle" => bundle::bundle(),
"installer-images" => images::generate(),
"fixtures" => tasks::fixtures(),
"demo-project" => demo::run(rest),
"mac-report" => macreport::parse(rest).and_then(|o| macreport::mac_report(&o)),

498
xtask/src/raster.rs Normal file
View file

@ -0,0 +1,498 @@
//! A small RGBA raster for the generated installer images: PNG decoding,
//! cropping, resampling, solid fills, simple shapes,
//! alpha compositing, and PNG and 24-bit BMP encoding.
//!
//! Pixels are 8-bit RGBA, not premultiplied, row by row from the top.
//! Resampling works on premultiplied alpha with a tent filter whose width
//! grows with the shrink factor, so it averages areas when shrinking and
//! interpolates linearly when enlarging.
use std::io::Cursor;
use crate::util::TaskResult;
/// Largest accepted edge length of a decoded image.
const MAX_EDGE: u32 = 8192;
/// An RGBA colour, 8 bits per channel, not premultiplied.
pub type Rgba = [u8; 4];
/// A rectangle in pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
/// Left edge.
pub x: u32,
/// Top edge.
pub y: u32,
/// Width.
pub w: u32,
/// Height.
pub h: u32,
}
/// An RGBA image.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Raster {
/// Width in pixels.
pub width: u32,
/// Height in pixels.
pub height: u32,
/// Pixels, four bytes each, row by row from the top.
pub rgba: Vec<u8>,
}
/// Parses `#rrggbb` (opaque) or `#rrggbbaa`.
///
/// # Errors
/// If `hex` is not in one of those forms.
pub fn color(hex: &str) -> TaskResult<Rgba> {
let digits = hex
.strip_prefix('#')
.ok_or_else(|| format!("colour `{hex}` lacks `#`"))?;
let byte = |at: usize| {
digits
.get(at..at + 2)
.and_then(|s| u8::from_str_radix(s, 16).ok())
.ok_or_else(|| format!("bad colour `{hex}`"))
};
match digits.len() {
6 => Ok([byte(0)?, byte(2)?, byte(4)?, 255]),
8 => Ok([byte(0)?, byte(2)?, byte(4)?, byte(6)?]),
_ => Err(format!("bad colour `{hex}`")),
}
}
impl Raster {
/// A `width`×`height` image filled with `fill`.
pub fn new(width: u32, height: u32, fill: Rgba) -> Self {
let count = width as usize * height as usize;
Self {
width,
height,
rgba: fill.repeat(count),
}
}
/// Decodes a PNG of any 8-bit colour type into RGBA.
///
/// # Errors
/// If the bytes are not a PNG, use 16 bits per channel, or exceed
/// [`MAX_EDGE`].
pub fn decode_png(bytes: &[u8]) -> TaskResult<Self> {
let mut decoder = png::Decoder::new(Cursor::new(bytes));
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info().map_err(|e| e.to_string())?;
let (width, height) = (reader.info().width, reader.info().height);
if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE {
return Err(format!("image size {width}x{height} not supported"));
}
let size = reader
.output_buffer_size()
.ok_or("image too large to decode")?;
let mut buf = vec![0; size];
let frame = reader.next_frame(&mut buf).map_err(|e| e.to_string())?;
if frame.bit_depth != png::BitDepth::Eight {
return Err("only 8-bit PNGs are supported".into());
}
let data = buf.get(..frame.buffer_size()).ok_or("short PNG frame")?;
let rgba: Vec<u8> = match frame.color_type {
png::ColorType::Rgba => data.to_vec(),
png::ColorType::Rgb => data
.as_chunks::<3>()
.0
.iter()
.flat_map(|&[r, g, b]| [r, g, b, 255])
.collect(),
png::ColorType::GrayscaleAlpha => data
.as_chunks::<2>()
.0
.iter()
.flat_map(|&[v, a]| [v, v, v, a])
.collect(),
png::ColorType::Grayscale => data.iter().flat_map(|&v| [v, v, v, 255]).collect(),
png::ColorType::Indexed => return Err("PNG palette was not expanded".into()),
};
Ok(Self {
width,
height,
rgba,
})
}
/// The pixel at (`x`, `y`), transparent outside the image.
pub fn pixel(&self, x: u32, y: u32) -> Rgba {
if x >= self.width || y >= self.height {
return [0; 4];
}
let at = (y as usize * self.width as usize + x as usize) * 4;
match self.rgba.get(at..at + 4) {
Some(&[r, g, b, a]) => [r, g, b, a],
_ => [0; 4],
}
}
/// Sets the pixel at (`x`, `y`); ignored outside the image.
pub fn put(&mut self, x: u32, y: u32, value: Rgba) {
if x >= self.width || y >= self.height {
return;
}
let at = (y as usize * self.width as usize + x as usize) * 4;
if let Some(cell) = self.rgba.get_mut(at..at + 4) {
cell.copy_from_slice(&value);
}
}
/// Blends `value` over the pixel at (`x`, `y`) with extra coverage
/// `cover` (0–1); ignored outside the image.
fn blend(&mut self, x: u32, y: u32, value: Rgba, cover: f64) {
let under = self.pixel(x, y);
self.put(x, y, over(value, under, cover));
}
/// The part of the image inside `rect`.
///
/// # Errors
/// If `rect` is empty or reaches outside the image.
pub fn crop(&self, rect: Rect) -> TaskResult<Self> {
if rect.w == 0
|| rect.h == 0
|| rect.x + rect.w > self.width
|| rect.y + rect.h > self.height
{
return Err(format!(
"crop {rect:?} outside the {}x{} image",
self.width, self.height
));
}
let mut out = Self::new(rect.w, rect.h, [0; 4]);
for y in 0..rect.h {
for x in 0..rect.w {
out.put(x, y, self.pixel(rect.x + x, rect.y + y));
}
}
Ok(out)
}
/// The image resampled to `width`×`height`.
pub fn resize(&self, width: u32, height: u32) -> Self {
if width == self.width && height == self.height {
return self.clone();
}
let premul: Vec<[f64; 4]> = self
.rgba
.as_chunks::<4>()
.0
.iter()
.map(|&[r, g, b, a]| {
let a = f64::from(a) / 255.0;
[f64::from(r) * a, f64::from(g) * a, f64::from(b) * a, a]
})
.collect();
let (sw, sh) = (self.width as usize, self.height as usize);
let dw = width as usize;
let xtaps = taps(self.width, width);
let ytaps = taps(self.height, height);
let mut rows = vec![[0.0f64; 4]; dw * sh];
for y in 0..sh {
for (x, row_taps) in xtaps.iter().enumerate() {
let mut acc = [0.0f64; 4];
for &(i, w) in row_taps {
if let Some(p) = premul.get(y * sw + i) {
add(&mut acc, p, w);
}
}
if let Some(cell) = rows.get_mut(y * dw + x) {
*cell = acc;
}
}
}
let mut out = Self::new(width, height, [0; 4]);
for (y, col_taps) in ytaps.iter().enumerate() {
for x in 0..dw {
let mut acc = [0.0f64; 4];
for &(j, w) in col_taps {
if let Some(p) = rows.get(j * dw + x) {
add(&mut acc, p, w);
}
}
out.put(x as u32, y as u32, unpremultiply(acc));
}
}
out
}
/// Blends `value` over every pixel of `rect` (clipped to the image).
pub fn fill_rect(&mut self, rect: Rect, value: Rgba) {
for y in rect.y..(rect.y + rect.h).min(self.height) {
for x in rect.x..(rect.x + rect.w).min(self.width) {
self.blend(x, y, value, 1.0);
}
}
}
/// Blends `value` over the triangle `points` (in pixel coordinates,
/// pixel centres at +0.5), anti-aliased with 4×4 samples per pixel.
pub fn fill_triangle(&mut self, points: [(f64, f64); 3], value: Rgba) {
let xs = points.map(|p| p.0);
let ys = points.map(|p| p.1);
let lo = |v: [f64; 3]| {
v.iter()
.copied()
.fold(f64::INFINITY, f64::min)
.floor()
.max(0.0)
};
let hi = |v: [f64; 3]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil();
let (x0, y0) = (lo(xs) as u32, lo(ys) as u32);
let x1 = (hi(xs) as u32).min(self.width);
let y1 = (hi(ys) as u32).min(self.height);
for y in y0..y1 {
for x in x0..x1 {
let mut inside = 0u32;
for sy in 0..4 {
for sx in 0..4 {
let px = f64::from(x) + (f64::from(sx) + 0.5) / 4.0;
let py = f64::from(y) + (f64::from(sy) + 0.5) / 4.0;
if in_triangle((px, py), points) {
inside += 1;
}
}
}
if inside > 0 {
self.blend(x, y, value, f64::from(inside) / 16.0);
}
}
}
}
/// Blends `layer` over this image with its top-left corner at
/// (`x`, `y`), scaling its alpha by `opacity` (0–1).
pub fn draw(&mut self, layer: &Self, x: i64, y: i64, opacity: f64) {
for ly in 0..layer.height {
for lx in 0..layer.width {
let (tx, ty) = (x + i64::from(lx), y + i64::from(ly));
let (Ok(tx), Ok(ty)) = (u32::try_from(tx), u32::try_from(ty)) else {
continue;
};
self.blend(tx, ty, layer.pixel(lx, ly), opacity);
}
}
}
/// Encodes the image as an RGBA PNG.
///
/// # Errors
/// If the encoder fails.
pub fn encode_png(&self) -> TaskResult<Vec<u8>> {
let mut out = Vec::new();
{
let mut encoder = png::Encoder::new(&mut out, self.width, self.height);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().map_err(|e| e.to_string())?;
writer
.write_image_data(&self.rgba)
.map_err(|e| e.to_string())?;
}
Ok(out)
}
/// Encodes the image as an uncompressed 24-bit BMP (bottom-up rows
/// padded to four bytes), the format NSIS shows. Alpha is dropped, so
/// the image should be opaque.
pub fn encode_bmp(&self) -> Vec<u8> {
let row = (self.width as usize * 3).div_ceil(4) * 4;
let data = row * self.height as usize;
let size = 54 + data;
let mut out = Vec::with_capacity(size);
out.extend_from_slice(b"BM");
out.extend_from_slice(&(size as u32).to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(&54u32.to_le_bytes());
out.extend_from_slice(&40u32.to_le_bytes());
out.extend_from_slice(&(self.width as i32).to_le_bytes());
out.extend_from_slice(&(self.height as i32).to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&24u16.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(&(data as u32).to_le_bytes());
out.extend_from_slice(&2835i32.to_le_bytes());
out.extend_from_slice(&2835i32.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
out.extend_from_slice(&0u32.to_le_bytes());
for y in (0..self.height).rev() {
let start = out.len();
for x in 0..self.width {
let [r, g, b, _] = self.pixel(x, y);
out.extend_from_slice(&[b, g, r]);
}
out.resize(start + row, 0);
}
out
}
}
/// `value` blended over `under` with extra coverage `cover` (Porter-Duff
/// "over" on straight alpha).
fn over(value: Rgba, under: Rgba, cover: f64) -> Rgba {
let sa = f64::from(value[3]) / 255.0 * cover.clamp(0.0, 1.0);
let da = f64::from(under[3]) / 255.0;
let oa = sa + da * (1.0 - sa);
if oa <= 0.0 {
return [0; 4];
}
let channel = |s: u8, d: u8| {
((f64::from(s) * sa + f64::from(d) * da * (1.0 - sa)) / oa)
.round()
.clamp(0.0, 255.0) as u8
};
[
channel(value[0], under[0]),
channel(value[1], under[1]),
channel(value[2], under[2]),
(oa * 255.0).round() as u8,
]
}
/// Adds `p` weighted by `w` to `acc`.
fn add(acc: &mut [f64; 4], p: &[f64; 4], w: f64) {
for (a, v) in acc.iter_mut().zip(p) {
*a += v * w;
}
}
/// Straight 8-bit RGBA from a premultiplied accumulator.
fn unpremultiply(acc: [f64; 4]) -> Rgba {
let a = acc[3].clamp(0.0, 1.0);
if a <= 0.0 {
return [0; 4];
}
let channel = |v: f64| (v / a).round().clamp(0.0, 255.0) as u8;
[
channel(acc[0]),
channel(acc[1]),
channel(acc[2]),
(a * 255.0).round() as u8,
]
}
/// Whether `p` lies inside the triangle `t` (either winding).
fn in_triangle(p: (f64, f64), t: [(f64, f64); 3]) -> bool {
let side = |a: (f64, f64), b: (f64, f64)| (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
let d = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])];
d.iter().all(|&v| v >= 0.0) || d.iter().all(|&v| v <= 0.0)
}
/// Source taps (index, weight) for each output position when resampling
/// `src` samples to `dst` with a tent filter; weights sum to 1.
fn taps(src: u32, dst: u32) -> Vec<Vec<(usize, f64)>> {
let scale = f64::from(src) / f64::from(dst);
let support = scale.max(1.0);
(0..dst)
.map(|o| {
let centre = (f64::from(o) + 0.5) * scale - 0.5;
let first = (centre - support).floor().max(0.0) as u32;
let last = ((centre + support).ceil() as u32).min(src.saturating_sub(1));
let mut list: Vec<(usize, f64)> = (first..=last)
.filter_map(|i| {
let w = 1.0 - (f64::from(i) - centre).abs() / support;
(w > 0.0).then_some((i as usize, w))
})
.collect();
if list.is_empty() {
let nearest = centre.round().clamp(0.0, f64::from(src.saturating_sub(1)));
list.push((nearest as usize, 1.0));
}
let total: f64 = list.iter().map(|t| t.1).sum();
for t in &mut list {
t.1 /= total;
}
list
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_colours() {
assert_eq!(color("#c03a7c").unwrap(), [0xc0, 0x3a, 0x7c, 255]);
assert_eq!(color("#00000080").unwrap(), [0, 0, 0, 0x80]);
assert!(color("c03a7c").is_err());
assert!(color("#c03").is_err());
}
#[test]
fn resizing_keeps_a_flat_colour() {
let flat = Raster::new(30, 20, [10, 200, 30, 255]);
for (w, h) in [(7, 5), (60, 40), (30, 20)] {
let out = flat.resize(w, h);
assert_eq!((out.width, out.height), (w, h));
assert!(
out.rgba
.as_chunks::<4>()
.0
.iter()
.all(|p| *p == [10, 200, 30, 255])
);
}
}
#[test]
fn crops_and_rejects_outside_rects() {
let mut img = Raster::new(4, 4, [0, 0, 0, 255]);
img.put(2, 1, [255, 0, 0, 255]);
let part = img
.crop(Rect {
x: 2,
y: 1,
w: 2,
h: 2,
})
.unwrap();
assert_eq!(part.pixel(0, 0), [255, 0, 0, 255]);
assert!(
img.crop(Rect {
x: 3,
y: 0,
w: 2,
h: 1
})
.is_err()
);
}
#[test]
fn blends_and_draws_shapes() {
let mut img = Raster::new(10, 10, [0, 0, 0, 255]);
img.fill_rect(
Rect {
x: 0,
y: 0,
w: 5,
h: 10,
},
[255, 255, 255, 128],
);
assert_eq!(img.pixel(1, 1), [128, 128, 128, 255]);
assert_eq!(img.pixel(7, 1), [0, 0, 0, 255]);
img.fill_triangle([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], [255, 0, 0, 255]);
assert_eq!(img.pixel(1, 1), [255, 0, 0, 255]);
assert_eq!(img.pixel(9, 9), [0, 0, 0, 255]);
}
#[test]
fn encodes_a_padded_bmp_and_a_png_that_decodes() {
let mut img = Raster::new(3, 2, [1, 2, 3, 255]);
img.put(0, 1, [9, 8, 7, 255]);
let bmp = img.encode_bmp();
assert_eq!(&bmp[..2], b"BM");
assert_eq!(bmp.len(), 54 + 12 * 2);
assert_eq!(&bmp[54..57], &[7, 8, 9]);
assert_eq!(&bmp[63..66], &[0, 0, 0]);
let back = Raster::decode_png(&img.encode_png().unwrap()).unwrap();
assert_eq!(back, img);
}
}