mirror of
https://github.com/storytold/craft-launcher.git
synced 2026-12-02 20:22:35 -05:00
fix: pack small macOS application icons as legacy RGB (#1699)
This commit is contained in:
1 parent
11372822d7
commit
8f7847a54e
6 files changed
+101
-19
No files matched your search
Generated
+1
@@ -7899,6 +7899,7 @@ checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9"
|
||||
name = "xtask"
|
||||
version = "0.20.4"
|
||||
dependencies = [
|
||||
"image",
|
||||
"jiff",
|
||||
"semver",
|
||||
"tempfile",
|
||||
|
||||
@@ -14,7 +14,8 @@ versions.
|
||||
|
||||
- `artcraft-launcher.svg`: a copy of `docs/brand/artcraft-mark.svg`; also the hicolor scalable icon.
|
||||
- `artcraft-launcher-1024.png`: 1024 px render, with extra transparent margin for Apple's icon grid.
|
||||
- `artcraft-launcher.icns`: macOS bundle icon (`CFBundleIconFile`).
|
||||
- `artcraft-launcher.icns`: macOS bundle icon (`CFBundleIconFile`), with legacy RGB and masks
|
||||
for 16 and 32 px non-Retina slots. The artwork and the other slots' PNGs are unchanged.
|
||||
- `artcraft-launcher.ico`: Windows icon, 16–256 px, embedded in the `.exe` by
|
||||
`apps/artcraft-launcher/build.rs` and used by the MSI.
|
||||
- `hicolor/<size>/apps/ai.storyteller.artcraft-launcher.png` (16–512) and
|
||||
@@ -25,5 +26,5 @@ versions.
|
||||
## Regenerate
|
||||
|
||||
Run `packaging/icons.sh` on any OS. It needs `resvg`; the `.ico` and `.icns` are packed by
|
||||
`cargo xtask ico`. Never edit these files by hand: change the source only if the ArtCraft Team
|
||||
`cargo xtask ico` and `cargo xtask icns`. Never edit these files by hand: change the source only if the ArtCraft Team
|
||||
supplies a new mark in `docs/brand/`.
|
||||
Binary file not shown.
@@ -9,6 +9,7 @@ publish = false
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
jiff = { workspace = true }
|
||||
semver = { workspace = true }
|
||||
|
||||
|
||||
+95
-16
@@ -1,17 +1,19 @@
|
||||
//! `cargo xtask icns <out.icns> <in.png>…`: pack PNG images into a macOS `.icns`, on any OS
|
||||
//! (`iconutil` only exists on macOS).
|
||||
//!
|
||||
//! Every entry is a PNG, which macOS reads for all of these types since 10.7. Each PNG fills
|
||||
//! every slot of its pixel size: a 32 px image is both the 32 pt icon and the 16 pt @2x one.
|
||||
//! macOS icon services misread PNG in the 16 and 32 px non-Retina slots. Use the legacy RGB
|
||||
//! and separate alpha-mask slots there, like macOS's image tools. Retina and larger slots
|
||||
//! keep the original PNG bytes: a 32 px image still supplies the 16 pt @2x slot.
|
||||
|
||||
use std::io::Cursor;
|
||||
use std::path::Path;
|
||||
|
||||
use image::{ImageFormat, ImageReader, Limits};
|
||||
|
||||
use crate::ico::png_size;
|
||||
|
||||
/// The PNG entry types, by pixel size.
|
||||
const SLOTS: [(u32, &[u8; 4]); 11] = [
|
||||
(16, b"icp4"),
|
||||
(32, b"icp5"),
|
||||
const SLOTS: [(u32, &[u8; 4]); 9] = [
|
||||
(32, b"ic11"), // 16 @2x
|
||||
(64, b"icp6"),
|
||||
(64, b"ic12"), // 32 @2x
|
||||
@@ -23,7 +25,35 @@ const SLOTS: [(u32, &[u8; 4]); 11] = [
|
||||
(1024, b"ic10"), // 512 @2x
|
||||
];
|
||||
|
||||
/// An `.icns` file holding `pngs`, which must be square and one of the sizes in [`SLOTS`].
|
||||
/// The legacy 1× RGB and alpha mask. The uncompressed form uses four bytes per
|
||||
/// pixel; macOS ignores the first and reads transparency from the separate mask.
|
||||
/// This also avoids a macOS decoder quirk that drops the last blue sample in RLE.
|
||||
fn legacy_pixels(png: &[u8], size: u32) -> Result<(Vec<u8>, Vec<u8>), String> {
|
||||
let mut reader = ImageReader::with_format(Cursor::new(png), ImageFormat::Png);
|
||||
let mut limits = Limits::default();
|
||||
limits.max_image_width = Some(size);
|
||||
limits.max_image_height = Some(size);
|
||||
limits.max_alloc = Some(1024 * 1024);
|
||||
reader.limits(limits);
|
||||
let rgba = reader.decode().map_err(|e| format!("could not read {size} px icon: {e}"))?.into_rgba8();
|
||||
let mut rgb = Vec::with_capacity(rgba.as_raw().len());
|
||||
let mut mask = Vec::with_capacity(rgba.as_raw().len() / 4);
|
||||
for &image::Rgba([r, g, b, a]) in rgba.pixels() {
|
||||
rgb.extend_from_slice(&[0, r, g, b]);
|
||||
mask.push(a);
|
||||
}
|
||||
Ok((rgb, mask))
|
||||
}
|
||||
|
||||
fn append_entry(body: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) -> Result<(), String> {
|
||||
let len = u32::try_from(data.len() + 8).map_err(|_| "entry too large for an .icns".to_string())?;
|
||||
body.extend_from_slice(kind);
|
||||
body.extend_from_slice(&len.to_be_bytes());
|
||||
body.extend_from_slice(data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An `.icns` file holding square PNGs of 16, 32, 64, 128, 256, 512 or 1024 px.
|
||||
pub fn pack(pngs: &[Vec<u8>]) -> Result<Vec<u8>, String> {
|
||||
if pngs.is_empty() {
|
||||
return Err("need at least one PNG".into());
|
||||
@@ -34,15 +64,22 @@ pub fn pack(pngs: &[Vec<u8>]) -> Result<Vec<u8>, String> {
|
||||
if w != h {
|
||||
return Err(format!("icon images must be square, got {w}x{h}"));
|
||||
}
|
||||
let legacy = match w {
|
||||
16 => Some((b"is32", b"s8mk")),
|
||||
32 => Some((b"il32", b"l8mk")),
|
||||
_ => None,
|
||||
};
|
||||
let types: Vec<&[u8; 4]> = SLOTS.iter().filter(|(size, _)| *size == w).map(|(_, kind)| *kind).collect();
|
||||
if types.is_empty() {
|
||||
if legacy.is_none() && types.is_empty() {
|
||||
return Err(format!("no .icns slot for a {w} px image (use 16, 32, 64, 128, 256, 512 or 1024)"));
|
||||
}
|
||||
let len = u32::try_from(png.len() + 8).map_err(|_| "PNG too large for an .icns".to_string())?;
|
||||
if let Some((rgb_kind, mask_kind)) = legacy {
|
||||
let (rgb, mask) = legacy_pixels(png, w)?;
|
||||
append_entry(&mut body, rgb_kind, &rgb)?;
|
||||
append_entry(&mut body, mask_kind, &mask)?;
|
||||
}
|
||||
for kind in types {
|
||||
body.extend_from_slice(kind);
|
||||
body.extend_from_slice(&len.to_be_bytes());
|
||||
body.extend_from_slice(png);
|
||||
append_entry(&mut body, kind, png)?;
|
||||
}
|
||||
}
|
||||
let total = u32::try_from(body.len() + 8).map_err(|_| ".icns too large".to_string())?;
|
||||
@@ -67,6 +104,20 @@ pub fn run(args: &[&str]) -> Result<(), String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample_png(size: u32) -> (image::RgbaImage, Vec<u8>) {
|
||||
use image::ImageEncoder;
|
||||
// Synthetic image: unequal RGB channels and transparent/opaque pixels expose swapping
|
||||
// the planes, a missing mask, or copying the PNG into a legacy slot.
|
||||
let pixels = image::RgbaImage::from_fn(size, size, |x, y| match (x + y) % 4 {
|
||||
0 => image::Rgba([0, 0, 0, 0]),
|
||||
1 => image::Rgba([0, 0, 255, 128]),
|
||||
_ => image::Rgba([x as u8, (2 * y) as u8, 200, 255]),
|
||||
});
|
||||
let mut png = Vec::new();
|
||||
image::codecs::png::PngEncoder::new(&mut png).write_image(pixels.as_raw(), size, size, image::ExtendedColorType::Rgba8).unwrap();
|
||||
(pixels, png)
|
||||
}
|
||||
|
||||
fn fake_png(size: u32) -> Vec<u8> {
|
||||
let mut v = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
|
||||
v.extend_from_slice(&size.to_be_bytes());
|
||||
@@ -89,15 +140,38 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn fills_every_slot_of_each_size() {
|
||||
let (a, b) = (fake_png(32), fake_png(1024));
|
||||
let (a, b) = (sample_png(32).1, fake_png(1024));
|
||||
let icns = pack(&[a.clone(), b.clone()]).unwrap();
|
||||
assert_eq!(&icns[..4], b"icns");
|
||||
assert_eq!(u32::from_be_bytes(icns[4..8].try_into().unwrap()) as usize, icns.len());
|
||||
let e = entries(&icns);
|
||||
let kinds: Vec<&str> = e.iter().map(|(k, _)| k.as_str()).collect();
|
||||
assert_eq!(kinds, ["icp5", "ic11", "ic10"]);
|
||||
assert_eq!(e[0].1, a);
|
||||
assert_eq!(e[2].1, b);
|
||||
assert_eq!(kinds, ["il32", "l8mk", "ic11", "ic10"]);
|
||||
assert_eq!(e[2].1, a, "the high-resolution PNG is unchanged");
|
||||
assert_eq!(e[3].1, b);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn macos_decodes_each_small_icon_with_its_original_colors_and_transparency() {
|
||||
let (small, small_png) = sample_png(16);
|
||||
let (medium, medium_png) = sample_png(32);
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let icns = folder.path().join("icon.icns");
|
||||
let extracted = folder.path().join("icon.iconset");
|
||||
std::fs::write(&icns, pack(&[small_png, medium_png]).unwrap()).unwrap();
|
||||
let output = std::process::Command::new("/usr/bin/iconutil").args(["-c", "iconset"]).arg(&icns).arg("-o").arg(&extracted).output().unwrap();
|
||||
assert!(output.status.success(), "iconutil: {}", String::from_utf8_lossy(&output.stderr));
|
||||
for (file, expected) in [("icon_16x16.png", small), ("icon_32x32.png", medium)] {
|
||||
let actual = image::open(extracted.join(file)).unwrap().into_rgba8();
|
||||
assert_eq!(actual.dimensions(), expected.dimensions(), "{file}");
|
||||
let mismatch = actual.enumerate_pixels().find(|&(x, y, pixel)| pixel != expected.get_pixel(x, y));
|
||||
assert!(
|
||||
mismatch.is_none(),
|
||||
"{file} did not round-trip through macOS iconutil; first differing pixel: {:?}",
|
||||
mismatch.map(|(x, y, pixel)| (x, y, pixel, expected.get_pixel(x, y)))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -112,6 +186,11 @@ mod tests {
|
||||
let path = crate::root().join("assets/app-icon/artcraft-launcher.icns");
|
||||
let Ok(icns) = std::fs::read(&path) else { return };
|
||||
assert_eq!(&icns[..4], b"icns");
|
||||
assert!(entries(&icns).iter().any(|(k, _)| k == "ic10"), "expected a 1024 px image in {}", path.display());
|
||||
let entries = entries(&icns);
|
||||
for (kind, size) in [("s8mk", 16), ("l8mk", 32)] {
|
||||
assert!(entries.iter().any(|(k, data)| k == kind && data.len() == size * size), "expected a {size} px alpha mask in {}", path.display());
|
||||
}
|
||||
assert!(!entries.iter().any(|(k, _)| matches!(k.as_str(), "icp4" | "icp5")));
|
||||
assert!(entries.iter().any(|(k, _)| k == "ic10"), "expected a 1024 px image in {}", path.display());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
//! Workspace tooling: `cargo xtask <command>`.
|
||||
//!
|
||||
//! Pure Rust (std only). External tools (`cargo`) are invoked through `std::process::Command`.
|
||||
//! Pure Rust. External tools (`cargo`) are invoked through `std::process::Command`.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod icns;
|
||||
|
||||
Reference in new issue
Block a user