Lutra/apps/lutra-desktop/build.rs
danny bd225d9e3a 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>
2026-10-31 21:48:15 +01:00

320 lines
12 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! Build script of the desktop app.
//!
//! Produces the app icons Tauri needs into the gitignored `icons/` directory,
//! then runs the Tauri build step, which needs those files. The source is the
//! owner's master icon `assets/app-icon/icon.png` (listed in ASSETS.md),
//! downscaled to the window icon `icon.png`, to `512x512.png` (the macOS
//! bundler builds the `.icns` from the PNGs) and to a multi-size `icon.ico`.
//! If the master is missing or unreadable, the build prints a warning and
//! falls back to a placeholder generated in code (an otter-brown rounded
//! square holding a pale stone), so the build never fails over the icon.
use std::error::Error;
use std::fs;
use std::io::Cursor;
use std::path::{Path, PathBuf};
/// Edge length of the placeholder and of the window icon `icon.png`.
const SIZE: u32 = 256;
/// Edge length of the large PNG for the macOS app icon.
const LARGE: u32 = 512;
/// Edge lengths of the images in `icon.ico`.
const ICO_SIZES: [u32; 6] = [16, 32, 48, 64, 128, 256];
/// Largest accepted edge length of the master icon, which caps the decoding
/// work a broken or oversized file can cause.
const MAX_MASTER: u32 = 4096;
/// Path of the master icon relative to the crate directory.
const MASTER: &str = "../../assets/app-icon/icon.png";
/// A square RGBA image with 8 bits per channel, not premultiplied.
struct Image {
/// Edge length in pixels.
size: u32,
/// Pixels row by row, four bytes each.
rgba: Vec<u8>,
}
/// Writes the icons and runs `tauri_build`.
///
/// # Errors
/// Fails if the icons cannot be encoded or written. An unusable master icon
/// is not an error; the placeholder replaces it.
fn main() -> Result<(), Box<dyn Error>> {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?);
let master_path = manifest.join(MASTER);
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed={}", master_path.display());
let master = match load_master(&master_path) {
Ok(image) => image,
Err(e) => {
println!(
"cargo:warning=app icon {}: {e}; using the generated placeholder",
master_path.display()
);
Image {
size: SIZE,
rgba: draw_icon(),
}
}
};
let dir = manifest.join("icons");
fs::create_dir_all(&dir)?;
write_if_changed(&dir.join("icon.png"), &encode_png(&resize(&master, SIZE))?)?;
write_if_changed(
&dir.join("512x512.png"),
&encode_png(&resize(&master, LARGE))?,
)?;
let mut entries = Vec::with_capacity(ICO_SIZES.len());
for size in ICO_SIZES {
entries.push((size, encode_png(&resize(&master, size))?));
}
write_if_changed(&dir.join("icon.ico"), &ico(&entries))?;
tauri_build::build();
Ok(())
}
/// Writes a file only if its content differs, so that the Tauri build step
/// does not see a changed icon on every build.
///
/// # Errors
/// Fails if the file cannot be written.
fn write_if_changed(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
if fs::read(path).ok().as_deref() == Some(bytes) {
return Ok(());
}
fs::write(path, bytes)
}
/// Reads the master icon and converts it to 8-bit RGBA.
///
/// # Errors
/// Fails if the file cannot be read or decoded, is not square, or its edge
/// length is 0 or above [`MAX_MASTER`].
fn load_master(path: &Path) -> Result<Image, Box<dyn Error>> {
let bytes = fs::read(path)?;
let mut decoder = png::Decoder::new(Cursor::new(bytes));
decoder.set_transformations(png::Transformations::normalize_to_color8());
let mut reader = decoder.read_info()?;
let (width, height) = (reader.info().width, reader.info().height);
if width != height {
return Err(format!("not square ({width}x{height})").into());
}
if width == 0 || width > MAX_MASTER {
return Err(format!("edge length {width} outside 1..={MAX_MASTER}").into());
}
let mut buf = vec![0; reader.output_buffer_size().ok_or("image too large")?];
let frame = reader.next_frame(&mut buf)?;
if frame.bit_depth != png::BitDepth::Eight {
return Err("unsupported bit depth".into());
}
let data = buf.get(..frame.buffer_size()).ok_or("short 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("palette not expanded".into()),
};
let expected = (width as usize) * (width as usize) * 4;
if rgba.len() != expected {
return Err(format!("pixel data has {} bytes, expected {expected}", rgba.len()).into());
}
Ok(Image { size: width, rgba })
}
/// Resamples an image to `size`×`size` with an area-averaging box filter on
/// premultiplied alpha, which keeps edges clean when shrinking a lot (720 px
/// to 16 px). Returns a copy when the size already matches.
fn resize(src: &Image, size: u32) -> Image {
if src.size == size {
return Image {
size,
rgba: src.rgba.clone(),
};
}
let taps = box_taps(src.size, size);
let (src_n, dst_n) = (src.size as usize, size as usize);
let mut rows = vec![[0.0f64; 4]; dst_n * src_n];
for y in 0..src_n {
for (x, row_taps) in taps.iter().enumerate() {
let mut acc = [0.0f64; 4];
for &(i, w) in row_taps {
let at = (y * src_n + i) * 4;
if let Some(&[r, g, b, a]) = src.rgba.get(at..at + 4) {
let a = f64::from(a) / 255.0;
acc[0] += f64::from(r) * a * w;
acc[1] += f64::from(g) * a * w;
acc[2] += f64::from(b) * a * w;
acc[3] += a * w;
}
}
if let Some(cell) = rows.get_mut(y * dst_n + x) {
*cell = acc;
}
}
}
let mut rgba = Vec::with_capacity(dst_n * dst_n * 4);
for col_taps in &taps {
for x in 0..dst_n {
let mut acc = [0.0f64; 4];
for &(j, w) in col_taps {
if let Some(cell) = rows.get(j * dst_n + x) {
for (sum, value) in acc.iter_mut().zip(cell) {
*sum += value * w;
}
}
}
let [r, g, b, a] = acc;
let channel = |c: f64| {
if a > 0.0 {
(c / a).round().clamp(0.0, 255.0) as u8
} else {
0
}
};
rgba.extend_from_slice(&[
channel(r),
channel(g),
channel(b),
(a * 255.0).round().clamp(0.0, 255.0) as u8,
]);
}
}
Image { size, rgba }
}
/// Box-filter taps for scaling `src` samples to `dst`: for each output
/// sample, the source indices it covers and their weights, which sum to 1.
fn box_taps(src: u32, dst: u32) -> Vec<Vec<(usize, f64)>> {
let scale = f64::from(src) / f64::from(dst);
(0..dst)
.map(|o| {
let start = f64::from(o) * scale;
let end = start + scale;
let first = start.floor() as u32;
let last = (end.ceil() as u32).min(src);
(first..last)
.filter_map(|i| {
let lo = start.max(f64::from(i));
let hi = end.min(f64::from(i) + 1.0);
(hi > lo).then(|| (i as usize, (hi - lo) / scale))
})
.collect()
})
.collect()
}
/// Draws the placeholder icon as RGBA pixels, row by row, with 4×4
/// supersampling for smooth edges.
fn draw_icon() -> Vec<u8> {
let body = [0x6b, 0x4a, 0x32];
let stone = [0xd9, 0xd2, 0xc5];
let size = f64::from(SIZE);
let mut pixels = Vec::with_capacity((SIZE * SIZE * 4) as usize);
for y in 0..SIZE {
for x in 0..SIZE {
let (mut body_cover, mut stone_cover) = (0.0, 0.0);
for sy in 0..4 {
for sx in 0..4 {
let px = (f64::from(x) + (f64::from(sx) + 0.5) / 4.0) / size;
let py = (f64::from(y) + (f64::from(sy) + 0.5) / 4.0) / size;
if in_rounded_square(px, py) {
body_cover += 1.0 / 16.0;
if in_stone(px, py) {
stone_cover += 1.0 / 16.0;
}
}
}
}
let mix = |b: u8, s: u8| {
let b = f64::from(b);
let s = f64::from(s);
let t = if body_cover > 0.0 {
stone_cover / body_cover
} else {
0.0
};
(b + (s - b) * t).round().clamp(0.0, 255.0) as u8
};
pixels.extend_from_slice(&[
mix(body[0], stone[0]),
mix(body[1], stone[1]),
mix(body[2], stone[2]),
(body_cover * 255.0).round().clamp(0.0, 255.0) as u8,
]);
}
}
pixels
}
/// Whether a point in unit coordinates lies in the rounded square with a
/// small margin.
fn in_rounded_square(x: f64, y: f64) -> bool {
let (lo, hi, r) = (0.06, 0.94, 0.2);
if !(lo..=hi).contains(&x) || !(lo..=hi).contains(&y) {
return false;
}
let cx = x.clamp(lo + r, hi - r);
let cy = y.clamp(lo + r, hi - r);
(x - cx).powi(2) + (y - cy).powi(2) <= r * r
}
/// Whether a point in unit coordinates lies in the stone, an ellipse in the
/// lower middle.
fn in_stone(x: f64, y: f64) -> bool {
((x - 0.5) / 0.26).powi(2) + ((y - 0.6) / 0.18).powi(2) <= 1.0
}
/// Encodes an image as RGBA PNG.
///
/// # Errors
/// Fails if the encoder rejects the data.
fn encode_png(image: &Image) -> Result<Vec<u8>, png::EncodingError> {
let mut out = Vec::new();
{
let mut encoder = png::Encoder::new(&mut out, image.size, image.size);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header()?;
writer.write_image_data(&image.rgba)?;
}
Ok(out)
}
/// Builds an ICO container from PNG-encoded entries of the given edge
/// lengths, which every Windows version since Vista reads. An edge length of
/// 256 is stored as 0, as the format requires.
fn ico(entries: &[(u32, Vec<u8>)]) -> Vec<u8> {
let count = u16::try_from(entries.len()).unwrap_or(u16::MAX);
let mut offset = 6 + 16 * entries.len();
let mut ico = Vec::with_capacity(offset + entries.iter().map(|(_, p)| p.len()).sum::<usize>());
ico.extend_from_slice(&[0, 0, 1, 0]);
ico.extend_from_slice(&count.to_le_bytes());
for (size, png) in entries {
let edge = u8::try_from(*size).unwrap_or(0);
let len = u32::try_from(png.len()).unwrap_or(u32::MAX);
let at = u32::try_from(offset).unwrap_or(u32::MAX);
ico.extend_from_slice(&[edge, edge, 0, 0, 1, 0, 32, 0]);
ico.extend_from_slice(&len.to_le_bytes());
ico.extend_from_slice(&at.to_le_bytes());
offset += png.len();
}
for (_, png) in entries {
ico.extend_from_slice(png);
}
ico
}