diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7896e16..9ab2fcf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -70,6 +70,7 @@ jobs: run: | mkdir "$PACKAGE" cp "target/$TARGET/release/drwr" LICENSE.md README.md "$PACKAGE" + cp assets/drwr.desktop assets/app_icon/drwr.png "$PACKAGE" tar -czf "$PACKAGE.tar.gz" "$PACKAGE" - name: Package for macOS @@ -78,10 +79,11 @@ jobs: contents=drwr.app/Contents mkdir -p "$contents/MacOS" "$contents/Resources" cp "target/$TARGET/release/drwr" "$contents/MacOS" - cp LICENSE.md "$contents/Resources" + cp LICENSE.md assets/app_icon/drwr.icns "$contents/Resources" version=$(cargo metadata --no-deps --format-version 1 | jq -er '.packages[] | select(.name == "drwr") | .version') /usr/libexec/PlistBuddy \ -c "Add :CFBundleExecutable string drwr" \ + -c "Add :CFBundleIconFile string drwr" \ -c "Add :CFBundleIdentifier string io.github.pvik.drwr" \ -c "Add :CFBundleName string drwr" \ -c "Add :CFBundlePackageType string APPL" \ @@ -93,6 +95,7 @@ jobs: codesign --force --sign - drwr.app ditto -c -k --keepParent drwr.app "$PACKAGE.zip" + # build.rs gives drwr.exe its icon. - name: Package for Windows if: runner.os == 'Windows' run: | diff --git a/Cargo.lock b/Cargo.lock index 9e3706d..26d680f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -801,7 +801,7 @@ checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" [[package]] name = "drwr" -version = "0.1.1" +version = "0.2.0" dependencies = [ "base64", "directories", @@ -814,6 +814,7 @@ dependencies = [ "harfrust", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "png 0.17.16", "resvg", "rfd", "serde", diff --git a/Cargo.toml b/Cargo.toml index 5ba229a..b5b687a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ default-members = [".", "crates/graphml"] [package] name = "drwr" -version = "0.1.1" +version = "0.2.0" edition = "2024" homepage = "https://pvik.github.io/drwr/" @@ -31,6 +31,11 @@ serde = { version = "1.0.229", features = ["derive"] } skrifa = { version = "0.44.0", default-features = false, features = ["std", "autohint_shaping"] } toml = "1.2.1" +[dev-dependencies] +# Compresses the app icon files three times better than tiny-skia does. +# tiny-skia uses it, so it builds nothing new. +png = "0.17.16" + [target.'cfg(target_os = "macos")'.dependencies] # Has quitting ask about unsaved changes. eframe uses them, so they build # nothing new. diff --git a/README.md b/README.md index 03f92fb..678214b 100644 --- a/README.md +++ b/README.md @@ -7,3 +7,11 @@ A simple, fast and lightweight GraphML based diagraming tool - Good keyboard support - Export to PNG and SVG - Can read in yEd GraphML files + +#### Installing on Mac + +Unzip it and move drwr.app to Applications. drwr isn't notarized by Apple yet, so macOS blocks its first launch: allow it under System Settings › Privacy & Security › Open Anyway, or run this in Terminal: +``` +xattr -dr com.apple.quarantine /Applications/drwr.app +``` + diff --git a/assets/app_icon/drwr.icns b/assets/app_icon/drwr.icns new file mode 100644 index 0000000..ab1f190 Binary files /dev/null and b/assets/app_icon/drwr.icns differ diff --git a/assets/app_icon/drwr.ico b/assets/app_icon/drwr.ico new file mode 100644 index 0000000..7221fc3 Binary files /dev/null and b/assets/app_icon/drwr.ico differ diff --git a/assets/app_icon/drwr.png b/assets/app_icon/drwr.png new file mode 100644 index 0000000..070e9dc Binary files /dev/null and b/assets/app_icon/drwr.png differ diff --git a/assets/app_icon/drwr.svg b/assets/app_icon/drwr.svg new file mode 100644 index 0000000..91253ff --- /dev/null +++ b/assets/app_icon/drwr.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/assets/drwr.desktop b/assets/drwr.desktop new file mode 100644 index 0000000..79b819e --- /dev/null +++ b/assets/drwr.desktop @@ -0,0 +1,11 @@ +[Desktop Entry] +Type=Application +Name=drwr +GenericName=Diagram Editor +Comment=Draw diagrams and edit yEd GraphML files +Keywords=diagram;graph;graphml;yed;flowchart; +Exec=drwr +Icon=drwr +Terminal=false +Categories=Graphics;2DGraphics;VectorGraphics; +StartupWMClass=drwr diff --git a/build.rs b/build.rs index 25406a4..8233ded 100644 --- a/build.rs +++ b/build.rs @@ -1,7 +1,12 @@ //! Embeds the short commit hash (or `unknown`) for `drwr -version` and the -//! About dialog. +//! About dialog, and the app icon in Windows builds. +use std::path::PathBuf; use std::process::Command; +use std::{env, fs}; + +/// The icon Explorer and the taskbar show for drwr.exe. +const WINDOWS_ICON: &str = "assets/app_icon/drwr.ico"; fn main() { let commit = git(&["rev-parse", "--short", "HEAD"]).unwrap_or_else(|| "unknown".to_owned()); @@ -13,6 +18,59 @@ fn main() { if let Some(branch_ref) = git(&["symbolic-ref", "--quiet", "HEAD"]) { rerun_if_git_path_changes(&branch_ref); } + + // -gnu builds go without the icon, as GNU ld needs resources converted + // by windres first. + let target = |key| env::var(key).unwrap_or_default(); + if target("CARGO_CFG_TARGET_OS") == "windows" && target("CARGO_CFG_TARGET_ENV") == "msvc" { + println!("cargo::rerun-if-changed={WINDOWS_ICON}"); + let ico = fs::read(WINDOWS_ICON).expect("couldn't read the Windows icon"); + let res = PathBuf::from(env::var_os("OUT_DIR").unwrap()).join("drwr.res"); + fs::write(&res, icon_resources(&ico)).expect("couldn't write drwr.res"); + println!("cargo::rustc-link-arg-bins={}", res.display()); + } +} + +/// The resource file rc.exe compiles `1 ICON "drwr.ico"` to, for the icon +/// file `ico`: each image as a resource, then a directory of them. MSVC's +/// linker takes it as it is, so building needs no resource compiler. +fn icon_resources(ico: &[u8]) -> Vec { + const RT_ICON: u16 = 3; + const RT_GROUP_ICON: u16 = 14; + const EN_US: u16 = 0x0409; + assert_eq!(ico[..4], [0, 0, 1, 0], "{WINDOWS_ICON} isn't an icon"); + // Every resource file starts with an empty resource. + let mut res = resource(0, 0, 0, 0, &[]); + let mut group = ico[..6].to_vec(); + for id in 1..=u16::from_le_bytes([ico[4], ico[5]]) { + let entry = &ico[6 + 16 * usize::from(id - 1)..][..16]; + let len = u32::from_le_bytes(entry[8..12].try_into().unwrap()) as usize; + let offset = u32::from_le_bytes(entry[12..].try_into().unwrap()) as usize; + res.extend(resource(RT_ICON, id, 0x1010, EN_US, &ico[offset..][..len])); + // The image's entry, with its resource id in place of its offset. + group.extend(&entry[..12]); + group.extend(id.to_le_bytes()); + } + res.extend(resource(RT_GROUP_ICON, 1, 0x1030, EN_US, &group)); + res +} + +/// A resource with a numbered type and name. `flags` are the 16-bit Windows +/// memory flags rc.exe still writes. +fn resource(kind: u16, id: u16, flags: u16, language: u16, data: &[u8]) -> Vec { + let mut res = Vec::new(); + // The data's length, then the header's. + res.extend((data.len() as u32).to_le_bytes()); + res.extend(32u32.to_le_bytes()); + // 0xffff marks the type and name as numbers. The zeros are the data + // version, the version and the characteristics. + for word in [0xffff, kind, 0xffff, id, 0, 0, flags, language, 0, 0, 0, 0] { + res.extend(word.to_le_bytes()); + } + res.extend(data); + // The next resource starts at a multiple of 4 bytes. + res.resize(res.len().next_multiple_of(4), 0); + res } /// Uses `--git-path` because `.git` is a file in worktrees and submodules. diff --git a/src/app_icon/mod.rs b/src/app_icon/mod.rs new file mode 100644 index 0000000..6d3b47c --- /dev/null +++ b/src/app_icon/mod.rs @@ -0,0 +1,21 @@ +//! drwr's icon, drawn in `assets/app_icon/drwr.svg`. The window and the +//! release packages use the icon files beside it, which the tests draw from +//! the SVG. + +use egui::IconData; + +/// The icon, 256 pixels across. Decoding it is over ten times faster than +/// drawing the SVG. +const PNG: &[u8] = include_bytes!("../../assets/app_icon/drwr.png"); + +/// The window's icon. On macOS it's empty, so the Dock shows the app bundle's +/// icon instead of eframe's default one. +pub fn window_icon() -> IconData { + if cfg!(target_os = "macos") { + return IconData::default(); + } + eframe::icon_data::from_png_bytes(PNG).expect("drwr.png is a PNG") +} + +#[cfg(test)] +mod tests; diff --git a/src/app_icon/tests.rs b/src/app_icon/tests.rs new file mode 100644 index 0000000..6ccae37 --- /dev/null +++ b/src/app_icon/tests.rs @@ -0,0 +1,282 @@ +use std::collections::HashMap; +use std::path::PathBuf; + +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD; +use resvg::tiny_skia::{self, ColorU8, Pixmap}; +use resvg::usvg; + +use super::*; + +/// The icon, a tile filling its square canvas. +const SVG: &str = include_str!("../../assets/app_icon/drwr.svg"); + +/// How many pixels across drwr.png is. +const PNG_SIZE: u32 = 256; + +/// The Windows icon's sizes: small and large icons at 100% to 200% scaling, +/// and Explorer's biggest. +const ICO_SIZES: [u32; 8] = [16, 20, 24, 32, 40, 48, 64, 256]; + +/// The macOS icon's images, as `(type, pixels across)`. The 16 and 32 pixel +/// ones are RLE-compressed RGB plus an 8-bit mask, which every macOS reads; +/// the others are PNGs, two of each size for normal and Retina screens. +const ICNS_IMAGES: [(&[u8; 4], u32); 12] = [ + (b"is32", 16), + (b"s8mk", 16), + (b"il32", 32), + (b"l8mk", 32), + (b"ic11", 32), + (b"ic12", 64), + (b"ic07", 128), + (b"ic13", 256), + (b"ic08", 256), + (b"ic14", 512), + (b"ic09", 512), + (b"ic10", 1024), +]; + +fn dir() -> PathBuf { + PathBuf::from(concat!(env!("CARGO_MANIFEST_DIR"), "/assets/app_icon")) +} + +/// The icon files, as `(name, contents)`. +fn files() -> [(&'static str, Vec); 3] { + [ + ("drwr.png", png(&render(SVG, PNG_SIZE))), + ("drwr.ico", ico()), + ("drwr.icns", icns()), + ] +} + +/// Redraws the icon files from drwr.svg. +#[test] +#[ignore = "writes assets/app_icon/: run it after editing drwr.svg"] +fn write_files() { + for (name, contents) in files() { + std::fs::write(dir().join(name), contents).unwrap(); + } +} + +#[test] +fn files_match_the_svg() { + let read = |name: &str| std::fs::read(dir().join(name)).unwrap(); + + assert_drawn("drwr.png", &read("drwr.png"), &render(SVG, PNG_SIZE)); + + let ico = read("drwr.ico"); + let images = ico_images(&ico); + let sizes: Vec = images.iter().map(|&(size, _)| size).collect(); + assert_eq!(sizes, ICO_SIZES); + let &(size, largest) = images.last().unwrap(); + assert_drawn("drwr.ico", largest, &render(SVG, size)); + + let icns = read("drwr.icns"); + let images = icns_images(&icns); + let types: Vec<[u8; 4]> = images.iter().map(|&(kind, _)| kind).collect(); + assert_eq!(types, ICNS_IMAGES.map(|(kind, _)| *kind)); + let &(_, ic08) = images.iter().find(|(kind, _)| kind == b"ic08").unwrap(); + assert_drawn("drwr.icns", ic08, &render(&mac_svg(), 256)); +} + +#[test] +fn window_icon_is_the_tile() { + let icon = window_icon(); + if cfg!(target_os = "macos") { + assert!(icon.is_empty()); + return; + } + assert_eq!([icon.width, icon.height], [PNG_SIZE; 2]); + let pixel = |x: usize, y: usize| &icon.rgba[4 * (y * PNG_SIZE as usize + x)..][..4]; + // Past the tile's rounded corner, then inside the box. + assert_eq!(pixel(1, 1)[3], 0); + assert_eq!(pixel(95, 86), [0xad, 0xd8, 0xe6, 0xff]); +} + +/// Asserts that the PNG `png`, from the file `name`, is `expected` give or +/// take rounding, which may differ by processor. +fn assert_drawn(name: &str, png: &[u8], expected: &Pixmap) { + let actual = Pixmap::decode_png(png).unwrap(); + let size = |pixmap: &Pixmap| [pixmap.width(), pixmap.height()]; + assert_eq!(size(&actual), size(expected), "{name}"); + let differs = |(a, b): (&u8, &u8)| a.abs_diff(*b) > 8; + assert!( + !actual.data().iter().zip(expected.data()).any(differs), + "{name} isn't drawn from drwr.svg; redraw it with `cargo test app_icon -- --ignored`" + ); +} + +/// The images in the .ico file `ico`, as `(pixels across, data)`. +fn ico_images(ico: &[u8]) -> Vec<(u32, &[u8])> { + assert_eq!(ico[..4], [0, 0, 1, 0]); + let count = u16::from_le_bytes([ico[4], ico[5]]); + (0..usize::from(count)) + .map(|i| { + let entry = &ico[6 + 16 * i..][..16]; + let size = if entry[0] == 0 { 256 } else { entry[0].into() }; + let len = u32::from_le_bytes(entry[8..12].try_into().unwrap()) as usize; + let offset = u32::from_le_bytes(entry[12..].try_into().unwrap()) as usize; + (size, &ico[offset..offset + len]) + }) + .collect() +} + +/// The images in the .icns file `icns`, as `(type, data)`. +fn icns_images(icns: &[u8]) -> Vec<([u8; 4], &[u8])> { + let len = |bytes: &[u8]| u32::from_be_bytes(bytes[4..8].try_into().unwrap()) as usize; + assert_eq!(icns[..4], *b"icns"); + assert_eq!(len(icns), icns.len()); + let mut images = Vec::new(); + let mut rest = &icns[8..]; + while !rest.is_empty() { + let (image, after) = rest.split_at(len(rest)); + images.push((image[..4].try_into().unwrap(), &image[8..])); + rest = after; + } + images +} + +/// The square SVG image `svg`, drawn `size` pixels wide and high. +fn render(svg: &str, size: u32) -> Pixmap { + let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).unwrap(); + let mut pixmap = Pixmap::new(size, size).unwrap(); + let scale = size as f32 / tree.size().width(); + resvg::render( + &tree, + tiny_skia::Transform::from_scale(scale, scale), + &mut pixmap.as_mut(), + ); + pixmap +} + +/// The pixels of `pixmap` as RGBA without premultiplied alpha. +fn rgba(pixmap: &Pixmap) -> Vec { + let pixels = pixmap.pixels().iter().map(|pixel| pixel.demultiply()); + pixels + .flat_map(|color| [color.red(), color.green(), color.blue(), color.alpha()]) + .collect() +} + +fn png(pixmap: &Pixmap) -> Vec { + let mut data = Vec::new(); + let mut encoder = png::Encoder::new(&mut data, pixmap.width(), pixmap.height()); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder.set_compression(png::Compression::Best); + encoder.set_adaptive_filter(png::AdaptiveFilterType::Adaptive); + let mut writer = encoder.write_header().unwrap(); + writer.write_image_data(&rgba(pixmap)).unwrap(); + writer.finish().unwrap(); + data +} + +/// A Windows icon. Images below 256 pixels are bitmaps, which every reader +/// takes. +fn ico() -> Vec { + let images: Vec> = ICO_SIZES + .iter() + .map(|&size| { + let encode = if size < 256 { bmp } else { png }; + encode(&render(SVG, size)) + }) + .collect(); + // Type 1 is an icon. + let mut ico = vec![0, 0, 1, 0]; + ico.extend((images.len() as u16).to_le_bytes()); + let mut offset = 6 + 16 * images.len(); + for (&size, image) in ICO_SIZES.iter().zip(&images) { + // Width and height, where 256 wraps around to 0, no palette, then + // reserved; 1 color plane of 32 bits per pixel. + ico.extend([size as u8, size as u8, 0, 0, 1, 0, 32, 0]); + ico.extend((image.len() as u32).to_le_bytes()); + ico.extend((offset as u32).to_le_bytes()); + offset += image.len(); + } + ico.extend(images.concat()); + ico +} + +/// `pixmap` as an icon's bitmap: a header, the rows bottom-up in BGRA, then +/// a 1-bit mask of the transparent pixels, which the format needs even with +/// alpha. +fn bmp(pixmap: &Pixmap) -> Vec { + let (width, height) = (pixmap.width(), pixmap.height()); + let mask_row_len = width.div_ceil(32) * 4; + // BITMAPINFOHEADER, whose height counts the mask's rows too. + let mut bmp = Vec::new(); + for field in [40, width, 2 * height] { + bmp.extend(field.to_le_bytes()); + } + // 1 color plane of 32 bits per pixel, uncompressed. + bmp.extend([1, 0, 32, 0, 0, 0, 0, 0]); + bmp.extend((height * (4 * width + mask_row_len)).to_le_bytes()); + // No resolution or palette. + bmp.extend([0; 16]); + let rows = || pixmap.pixels().chunks(width as usize).rev(); + for row in rows() { + for pixel in row { + let color = pixel.demultiply(); + bmp.extend([color.blue(), color.green(), color.red(), color.alpha()]); + } + } + for row in rows() { + let mut mask = vec![0; mask_row_len as usize]; + for (x, pixel) in row.iter().enumerate() { + if pixel.alpha() == 0 { + mask[x / 8] |= 0x80 >> (x % 8); + } + } + bmp.extend(mask); + } + bmp +} + +/// A macOS icon, which Finder and the Dock show. +fn icns() -> Vec { + let svg = mac_svg(); + let mut pixmaps = HashMap::new(); + // The file's length goes after its type. + let mut icns = b"icns\0\0\0\0".to_vec(); + for (kind, size) in ICNS_IMAGES { + let pixmap = pixmaps.entry(size).or_insert_with(|| render(&svg, size)); + let image = match kind { + b"is32" | b"il32" => rle_rgb(pixmap), + b"s8mk" | b"l8mk" => pixmap.pixels().iter().map(|pixel| pixel.alpha()).collect(), + _ => png(pixmap), + }; + icns.extend(kind); + icns.extend((8 + image.len() as u32).to_be_bytes()); + icns.extend(image); + } + let len = icns.len() as u32; + icns[4..8].copy_from_slice(&len.to_be_bytes()); + icns +} + +/// The red, green and blue planes of `pixmap` one after another, each +/// RLE-compressed for is32 and il32 images. All runs here are literal: a +/// byte n, then n + 1 bytes. +fn rle_rgb(pixmap: &Pixmap) -> Vec { + let colors: Vec = pixmap.pixels().iter().map(|p| p.demultiply()).collect(); + let mut rle = Vec::new(); + for channel in [ColorU8::red, ColorU8::green, ColorU8::blue] { + let plane: Vec = colors.iter().copied().map(channel).collect(); + for run in plane.chunks(128) { + rle.push(run.len() as u8 - 1); + rle.extend(run); + } + } + rle +} + +/// The icon on Apple's grid for macOS 11 and later: the tile 824 of 1024 +/// pixels across, in the middle, casting a shadow. +fn mac_svg() -> String { + let icon = STANDARD.encode(SVG); + format!( + r#" + + +"# + ) +} diff --git a/src/main.rs b/src/main.rs index 47c5074..1802daf 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,6 +6,7 @@ mod about_dialog; mod action; +mod app_icon; mod atomic_file; mod canvas; mod cli; @@ -106,9 +107,13 @@ fn main() -> eframe::Result { } fn run_gui(app: DrwrApp) -> eframe::Result { + let options = eframe::NativeOptions { + viewport: egui::ViewportBuilder::default().with_icon(app_icon::window_icon()), + ..Default::default() + }; eframe::run_native( NAME, - eframe::NativeOptions::default(), + options, Box::new(|cc| { #[cfg(target_os = "macos")] macos::ask_before_quitting();