Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Merge storytold/main into AF.3 native Affinity import

callmeBalloch57ae2fb1a3f9
diff --cc README.md
index ed7523915,787433909..09e5a58e2
--- a/README.md
+++ b/README.md
@@@ -199,7 -199,7 +199,7 @@@ Every screenshot here is the real app a
</td>
<td width="33%" valign="top">
<h4>🗂️ Formats</h4>
- PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, HEIC photos from iPhone and Mac (read; in official builds, an optional <code>--features heif</code> build feature), and the native <code>.pcraft</code> format. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
- PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, HEIC photos from iPhone and Mac (read; in official builds, an optional <code>--features heif</code> build feature), and the native <code>.pcraft</code> format.
++ PSD and PSB, layered TIFF (Photoshop's layer data in the TIFF, read and written in either byte order), SVG (opens as shape layers, places as a vector Smart Object), plus flat PNG, JPEG, TIFF, WebP (lossy and lossless), GIF, BMP, TGA, ICO, QOI, PNM, OpenEXR, Radiance HDR and AVIF, with symmetric read and write at 8, 16 and 32 bits, HEIC photos from iPhone and Mac (read; in official builds, an optional <code>--features heif</code> build feature), and the native <code>.pcraft</code> format. Affinity documents (<code>.af</code>, <code>.afdesign</code>, <code>.afphoto</code>, <code>.afpub</code>) open natively, read only, with artboards, layers, vectors, text, images and masks; effects, adjustments and other unsupported parts are listed in a warning, and Affinity export is unavailable.
</td>
<td width="33%" valign="top">
<h4>🪄 The everyday essentials</h4>
diff --cc apps/photocraft-web/src/web.rs
index 368f6edda,3c794a38a..81fe29d55
--- a/apps/photocraft-web/src/web.rs
+++ b/apps/photocraft-web/src/web.rs
@@@ -11,11 -12,11 +12,12 @@@ use wasm_bindgen::JsCast as _
type Inbox = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
- /// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and Photoshop
- /// brushes (.abr) and gradients (.grd), which go to the preset libraries.
-/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
-/// brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
++/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
++/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
"pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "af", "afdesign", "afphoto", "afpub",
- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase",
++ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
++ "afdesign", "afphoto", "afpub",
];
const CANVAS_ID: &str = "photocraft_canvas";
diff --cc apps/photocraft/src/services.rs
index 6189f44f0,48bc1ad5b..bc3e81cd0
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@@ -11,11 -13,11 +13,12 @@@ use std::pin::Pin
use std::rc::Rc;
use std::sync::Arc;
- /// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and Photoshop
- /// brushes (.abr) and gradients (.grd), which go to the preset libraries.
-/// Everything File › Open reads: PhotoCraft and Photoshop documents, flat images, and Photoshop
-/// brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
++/// Everything File › Open reads: PhotoCraft, Photoshop and Affinity documents, flat images, and
++/// Photoshop brushes (.abr), gradients (.grd) and swatches (.aco, .ase), which go to the preset libraries.
const OPEN_EXTS: &[&str] = &[
"pcraft", "psd", "psb", "psdt", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "ico", "qoi", "exr", "hdr", "pbm", "pgm", "ppm", "pam",
- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "af", "afdesign", "afphoto", "afpub",
- "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase",
++ "pfm", "heic", "heif", "hif", "dng", "cr2", "cr3", "nef", "nrw", "arw", "pef", "orf", "rw2", "raf", "abr", "grd", "svg", "svgz", "aco", "ase", "af",
++ "afdesign", "afphoto", "afpub",
];
/// File › Save As formats: (filter name, extensions). The filter matching the suggested name's
diff --cc book/src/SUMMARY.md
index e99430f22,a141aded9..c85cfdf1f
--- a/book/src/SUMMARY.md
+++ b/book/src/SUMMARY.md
@@@ -21,7 -21,7 +21,8 @@@
- [Overview](formats/overview.md)
- [PSD and PSB](formats/psd-psb.md)
- [Raster formats](formats/raster-formats.md)
+ - [SVG](formats/svg.md)
+- [Affinity documents](formats/affinity.md)
- [The `.pcraft` format](formats/pcraft.md)
# Automation
diff --cc book/src/formats/overview.md
index b2aabb2f7,bb8108c08..0f066983c
--- a/book/src/formats/overview.md
+++ b/book/src/formats/overview.md
@@@ -11,4 -10,4 +11,4 @@@ External bytes enter PhotoCraft throug
Formats are a primary security boundary. File extension is not a trust signal, metadata can be attacker-controlled, and small compressed inputs can declare very large decoded outputs. Callers should use the bounded default APIs and preserve errors rather than retrying with unlimited limits.
- See [PSD and PSB](psd-psb.md), [Raster formats](raster-formats.md), [Affinity documents](affinity.md), and [The `.pcraft` format](pcraft.md). Cross-format hardening guidance is in [Parser hardening](../security/parser-hardening.md).
-See [PSD and PSB](psd-psb.md), [Raster formats](raster-formats.md), [SVG](svg.md), and [The `.pcraft` format](pcraft.md). Cross-format hardening guidance is in [Parser hardening](../security/parser-hardening.md).
++See [PSD and PSB](psd-psb.md), [Raster formats](raster-formats.md), [SVG](svg.md), [Affinity documents](affinity.md), and [The `.pcraft` format](pcraft.md). Cross-format hardening guidance is in [Parser hardening](../security/parser-hardening.md).
diff --cc crates/engine/src/file_cmds.rs
index 6779b6bd2,23539fa2e..9c7ac2c47
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@@ -117,9 -117,16 +117,16 @@@ pub(crate) fn list_images(dir: &str) -
/// Extensions the batch commands pick up from a folder.
const OPENABLE: &[&str] = &[
"psd", "psb", "pcraft", "png", "jpg", "jpeg", "tif", "tiff", "webp", "gif", "bmp", "tga", "exr", "hdr", "qoi", "ico", "pnm", "ppm", "pgm", "heic", "heif",
- "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "af", "afdesign", "afphoto", "afpub",
- "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz",
++ "hif", "dng", "cr2", "nef", "nrw", "arw", "pef", "svg", "svgz", "af", "afdesign", "afphoto", "afpub",
];
+ /// Whether saving `doc` as a TIFF writes Photoshop layer data (anything beyond a lone
+ /// Background layer). The UI asks before such a save when the "ask before saving layered TIFF"
+ /// preference is on; see `photocraft_io::tiff_layers`.
+ pub fn tiff_would_write_layers(doc: &Document) -> bool {
+ photocraft_io::tiff_layers::would_write_layers(doc)
+ }
+
pub(crate) fn file_name(path: &str) -> String {
path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
}
diff --cc crates/io/Cargo.toml
index f0f9aab02,eb917910c..763297d10
--- a/crates/io/Cargo.toml
+++ b/crates/io/Cargo.toml
@@@ -34,11 -33,15 +34,18 @@@ photocraft-format = { path = "../format
thiserror = { workspace = true }
serde_json = { workspace = true }
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
+ # SVG import (svg.rs): usvg parses, resvg rasterises what the shape model can't hold. Both are
+ # already in the tree through the UI's icon loader; text shaping needs the fonts feature set.
+ [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+ resvg = { version = "0.45", default-features = false, features = ["text", "system-fonts", "raster-images"] }
+
+ [target.'cfg(target_arch = "wasm32")'.dependencies]
+ resvg = { version = "0.45", default-features = false, features = ["text", "raster-images"] }
[dev-dependencies]
+crc32fast = "1.5"
+photocraft-affinity = { workspace = true, features = ["synth"] }
+flate2 = { workspace = true }
photocraft-psd = { workspace = true, features = ["testgen"] }
photocraft-raw = { workspace = true, features = ["testgen"] }
proptest = { workspace = true }
diff --cc crates/io/src/affinity.rs
index 0ee9f2a94,000000000..4e0ea614c
mode 100644,000000..100644
--- a/crates/io/src/affinity.rs
+++ b/crates/io/src/affinity.rs
@@@ -1,619 -1,0 +1,620 @@@
+//! Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): the native layers, curves,
+//! shapes, artboards, text, images and masks `photocraft-affinity` reads, mapped to PhotoCraft
+//! layers (groups, shape layers, type layers, embedded smart objects, pixel layers, layer and
+//! vector masks). What could not be mapped is listed in the warnings. A file whose native data
+//! can't be read opens as its embedded preview, with a warning saying why.
+
+use std::sync::Arc;
+
+use photocraft_affinity::model::{self as af, Align, Blend, Kind, Pixels};
+use photocraft_affinity::paint::{self as ap, Cap, GradientKind, Join};
+use photocraft_color::{BlendMode, Color, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::text::{CharStyle, ParagraphRun, ParagraphStyle, TextAlign, TextRun, TextShape};
+use photocraft_doc::vector::{Knot, LineCap, LineJoin, Path, ShapeLayer, ShapeStroke, StrokeAlign, Subpath, VectorMask};
+use photocraft_doc::{
+ Artboard, ArtboardBackground, Document, Fill, GradientStyle, Group, Layer, LayerContent, LayerMask, Locks, SmartObject, SmartSource, TextLayer,
+};
+use photocraft_geom::{Affine, Point, Rect, Size};
+use photocraft_raster::Surface;
+
+use crate::{ImportResult, IoError};
+
+pub use photocraft_affinity::is_affinity;
+
+/// Extensions recognized as Affinity documents.
+pub const EXTENSIONS: &[&str] = &["af", "afphoto", "afdesign", "afpub"];
+
+/// Pixels an image or mask is resampled into, after cropping to the canvas.
+const MAX_PIXELS: u64 = 64 << 20;
+/// Canvas side in pixels.
+const MAX_SIDE: f64 = 300_000.0;
+
+pub fn has_extension(name: &str) -> bool {
+ name.rsplit(['/', '\\']).next().and_then(|n| n.rsplit_once('.')).is_some_and(|(_, ext)| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
+}
+
+pub(crate) fn import(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
+ match photocraft_affinity::read(bytes, photocraft_affinity::Limits::default()) {
+ Ok(d) => {
+ let mut b = Builder::new(name, &d)?;
+ b.document(&d)?;
+ let mut warnings: Vec<String> = d.warnings.iter().map(|w| format!("Affinity: not imported or approximated: {w}.")).collect();
+ warnings.extend(b.warnings.iter().map(|w| format!("Affinity: {w}.")));
++ // Type layers draw from their model, within the import's raster bound: the sizes and
++ // frames come from an untrusted file.
++ let mut document = b.doc;
++ crate::text_import::prepare(&mut document);
+ // Save never writes back over the Affinity file.
- Ok(ImportResult { document: b.doc, warnings, source_read_only: true, preview_only: false })
++ Ok(ImportResult { document, warnings, source_read_only: true, preview_only: false })
+ }
+ Err(native) => preview(name, bytes, &native),
+ }
+}
+
+/// The embedded preview, for files whose native document can't be read.
+fn preview(name: &str, bytes: &[u8], native: &photocraft_affinity::Error) -> Result<ImportResult, IoError> {
+ let p = photocraft_affinity::preview(bytes).map_err(|e| IoError::Unsupported(format!("{native}; its embedded preview can't be read either ({e})")))?;
+ let opts = photocraft_codecs::DecodeOptions {
+ limits: photocraft_codecs::Limits { max_width: 4096, max_height: 4096, max_pixels: 4096 * 4096, max_alloc: 128 << 20 },
+ ..Default::default()
+ };
+ let img = photocraft_codecs::decode_with(p.png, &opts)?;
+ let mut r = crate::flat::image_to_document(name, &img)?;
+ if let Some(layer) = r.document.layers.first_mut() {
+ layer.name = "Affinity preview".into();
+ layer.locks = Default::default();
+ }
+ r.source_read_only = true;
+ r.preview_only = true;
+ r.warnings.insert(
+ 0,
+ format!(
+ "The native Affinity document could not be read ({native}). Opened only its embedded {}×{} PNG preview, which may be smaller than the document: no layers, vectors, text or pages. Save a new copy; the Affinity source cannot be saved back. Export PSD or PNG from Affinity for full-resolution artwork.",
+ p.width, p.height
+ ),
+ );
+ Ok(r)
+}
+
+struct Builder {
+ doc: Document,
+ warnings: Vec<String>,
+ /// Document pixels (in the canvas) per Affinity document pixel: always 1; spreads are offset.
+ format: PixelFormat,
+ canvas: Rect,
+}
+
+fn affine(a: af::Affine) -> Affine {
+ Affine { m: a.0 }
+}
+
+fn point(p: af::Point) -> Point {
+ Point::new(p.x, p.y)
+}
+
+impl Builder {
+ fn new(name: &str, d: &af::Document) -> Result<Self, IoError> {
+ // Spreads (Publisher pages) side by side, 64 px apart.
+ let mut w: f64 = 0.0;
+ let mut h: f64 = 0.0;
+ for (i, s) in d.spreads.iter().enumerate() {
+ w += (s.bounds.x1 - s.bounds.x0).max(1.0) + if i > 0 { 64.0 } else { 0.0 };
+ h = h.max((s.bounds.y1 - s.bounds.y0).max(1.0));
+ }
+ if !(w.is_finite() && h.is_finite()) || w > MAX_SIDE || h > MAX_SIDE {
+ return Err(IoError::Unsupported("the Affinity document is larger than 300 000 pixels on a side".into()));
+ }
+ let size = Size::new(w.ceil().max(1.0) as u32, h.ceil().max(1.0) as u32);
+ let mut doc = Document::new(name, size, ColorMode::Rgb, SampleType::U8);
+ doc.resolution_dpi = d.dpi as f32;
+ let canvas = Rect::new(0, 0, size.width as i32, size.height as i32);
+ Ok(Self { doc, warnings: Vec::new(), format: PixelFormat::RGBA8, canvas })
+ }
+
+ fn warn(&mut self, w: &str) {
+ if !self.warnings.iter().any(|x| x == w) {
+ self.warnings.push(w.to_string());
+ }
+ }
+
+ fn document(&mut self, d: &af::Document) -> Result<(), IoError> {
+ let pages = d.spreads.len() > 1 || d.spreads.iter().any(|s| s.pages.len() > 1);
+ let mut x = 0.0;
+ let mut layers = Vec::new();
+ for (i, spread) in d.spreads.iter().enumerate() {
+ let to_doc = Affine::translate(x - spread.bounds.x0, -spread.bounds.y0);
+ let mut children: Vec<Layer> = spread.nodes.iter().filter_map(|n| self.layer(n, to_doc, true)).collect();
+ if pages {
+ // Each page becomes an artboard holding the art drawn on it.
+ let rects: Vec<af::Rect> = if spread.pages.is_empty() { vec![spread.bounds] } else { spread.pages.clone() };
+ let page = rects.first().copied().unwrap_or(spread.bounds);
+ let r = self.bbox(to_doc, page);
+ let mut g = Layer::new(
+ format!("Page {}", i + 1),
+ LayerContent::Group(Group { children: std::mem::take(&mut children), expanded: true, artboard: None }),
+ );
+ if let LayerContent::Group(gr) = &mut g.content {
+ gr.artboard = Some(Artboard { rect: r, background: ArtboardBackground::White, preset: String::new() });
+ }
+ if rects.len() > 1 {
+ self.warn("facing pages import as one artboard per spread");
+ }
+ layers.push(g);
+ } else {
+ layers.append(&mut children);
+ }
+ x += (spread.bounds.x1 - spread.bounds.x0).max(1.0) + 64.0;
+ }
+ if d.spreads.first().is_some_and(|s| !s.transparent) && !self.doc_has_artboards(&layers) {
+ // An opaque page: a white background below the art.
+ let mut bg = Surface::with_default(self.format, &[1.0, 1.0, 1.0, 1.0]);
+ bg.prune();
+ let mut l = Layer::new("Background", LayerContent::Raster(bg));
+ l.locks.transparency = true;
+ layers.insert(0, l);
+ }
+ self.doc.layers = layers;
+ Ok(())
+ }
+
+ fn doc_has_artboards(&self, layers: &[Layer]) -> bool {
+ layers.iter().any(|l| matches!(&l.content, LayerContent::Group(g) if g.artboard.is_some()))
+ }
+
+ /// Integer bounding box of `r` mapped by `m`, clipped to the canvas.
+ fn bbox(&self, m: Affine, r: af::Rect) -> Rect {
+ let pts = [(r.x0, r.y0), (r.x1, r.y0), (r.x1, r.y1), (r.x0, r.y1)].map(|(x, y)| m.apply(Point::new(x, y)));
+ let fold = |f: fn(f64, f64) -> f64, init: f64, g: fn(&Point) -> f64| pts.iter().map(g).fold(init, f);
+ let x0 = fold(f64::min, f64::INFINITY, |p| p.x).floor();
+ let y0 = fold(f64::min, f64::INFINITY, |p| p.y).floor();
+ let x1 = fold(f64::max, f64::NEG_INFINITY, |p| p.x).ceil();
+ let y1 = fold(f64::max, f64::NEG_INFINITY, |p| p.y).ceil();
+ let c = |v: f64, lo: i32, hi: i32| (v.clamp(f64::from(lo), f64::from(hi))) as i32;
+ Rect::new(
+ c(x0, self.canvas.x0, self.canvas.x1),
+ c(y0, self.canvas.y0, self.canvas.y1),
+ c(x1, self.canvas.x0, self.canvas.x1),
+ c(y1, self.canvas.y0, self.canvas.y1),
+ )
+ }
+
+ fn blend(&mut self, b: Blend) -> BlendMode {
+ match b {
+ Blend::Normal => BlendMode::Normal,
+ Blend::PassThrough => BlendMode::PassThrough,
+ Blend::Darken => BlendMode::Darken,
+ Blend::DarkerColor => BlendMode::DarkerColor,
+ Blend::Multiply => BlendMode::Multiply,
+ Blend::ColorBurn => BlendMode::ColorBurn,
+ Blend::Lighten => BlendMode::Lighten,
+ Blend::LighterColor => BlendMode::LighterColor,
+ Blend::Screen => BlendMode::Screen,
+ Blend::ColorDodge => BlendMode::ColorDodge,
+ Blend::Add => BlendMode::LinearDodge,
+ Blend::Overlay => BlendMode::Overlay,
+ Blend::SoftLight => BlendMode::SoftLight,
+ Blend::HardLight => BlendMode::HardLight,
+ Blend::VividLight => BlendMode::VividLight,
+ Blend::PinLight => BlendMode::PinLight,
+ Blend::LinearLight => BlendMode::LinearLight,
+ Blend::HardMix => BlendMode::HardMix,
+ Blend::Difference => BlendMode::Difference,
+ Blend::Exclusion => BlendMode::Exclusion,
+ Blend::Subtract => BlendMode::Subtract,
+ Blend::Hue => BlendMode::Hue,
+ Blend::Saturation => BlendMode::Saturation,
+ Blend::Luminosity => BlendMode::Luminosity,
+ Blend::Color => BlendMode::Color,
+ Blend::Average | Blend::Negation | Blend::Reflect | Blend::Glow | Blend::Erase => {
+ self.warn("the Average, Negation, Reflect, Glow and Erase blend modes import as Normal");
+ BlendMode::Normal
+ }
+ }
+ }
+
+ fn base(&mut self, n: &af::Node, content: LayerContent) -> Layer {
+ let mut l = Layer::new(if n.name.is_empty() { default_name(&n.kind) } else { n.name.clone() }, content);
+ l.visible = n.visible;
+ l.opacity = n.opacity as f32;
+ l.blend = self.blend(n.blend);
+ if n.locked {
+ l.locks = Locks { all: true, ..Locks::default() };
+ }
+ l
+ }
+
+ fn group(&mut self, n: &af::Node, children: Vec<Layer>) -> Layer {
+ // Pass-through and Normal (isolated) groups map one to one.
+ self.base(n, LayerContent::Group(Group { children, expanded: false, artboard: None }))
+ }
+
+ /// One Affinity node and its subtree; `to_doc` maps Affinity document pixels to the canvas.
+ fn layer(&mut self, n: &af::Node, to_doc: Affine, top: bool) -> Option<Layer> {
+ let children: Vec<Layer> = n.children.iter().filter_map(|c| self.layer(c, to_doc, false)).collect();
+ let mut l = match &n.kind {
+ Kind::Layer | Kind::Group => self.group(n, children),
+ Kind::Unsupported if children.is_empty() => return None,
+ Kind::Unsupported => self.group(n, children),
+ Kind::Shape { path, fills, strokes, even_odd } => {
+ let path = self.path(path, to_doc, *even_odd);
+ let shape = self.shape(path.clone(), fills, strokes, to_doc);
+ if children.is_empty() {
+ self.base(n, LayerContent::Shape(shape))
+ } else {
+ // A shape clips its children: a group masked by the outline, the shape at its bottom.
+ let mut own = Layer::new(if n.name.is_empty() { "Shape".to_string() } else { n.name.clone() }, LayerContent::Shape(shape));
+ own.opacity = 1.0;
+ let mut kids = vec![own];
+ kids.extend(children);
+ let mut g = self.group(n, kids);
+ g.vector_mask = Some(VectorMask { path, enabled: true, linked: true, density: 1.0, feather: 0.0 });
+ if !strokes.is_empty() {
+ self.warn("strokes of shapes that clip other layers are clipped to the shape");
+ }
+ g
+ }
+ }
+ Kind::Artboard { rect, background } => {
+ let r = self.bbox(to_doc, *rect);
+ let bg = match background.first() {
+ Some(ap::Paint::Solid(c)) => {
+ let c = color(*c);
+ if c.alpha <= 0.0 { ArtboardBackground::Transparent } else { ArtboardBackground::Custom(c) }
+ }
+ Some(_) => {
+ self.warn("artboard backgrounds other than a solid colour import as transparent");
+ ArtboardBackground::Transparent
+ }
+ None => ArtboardBackground::Transparent,
+ };
+ let mut g = self.group(n, children);
+ if top {
+ if let LayerContent::Group(gr) = &mut g.content {
+ gr.artboard = Some(Artboard { rect: r, background: bg, preset: String::new() });
+ }
+ } else {
+ // PhotoCraft artboards are top-level groups: a nested one clips by a vector mask.
+ let p = Path::new(vec![Subpath::polygon(&[
+ (f64::from(r.x0), f64::from(r.y0)),
+ (f64::from(r.x1), f64::from(r.y0)),
+ (f64::from(r.x1), f64::from(r.y1)),
+ (f64::from(r.x0), f64::from(r.y1)),
+ ])]);
+ g.vector_mask = Some(VectorMask { path: p, enabled: true, linked: true, density: 1.0, feather: 0.0 });
+ self.warn("artboards inside groups import as masked groups");
+ }
+ g
+ }
+ Kind::Text(t) => {
+ let layer = self.text(t, to_doc);
+ let l = self.base(n, LayerContent::Text(layer));
+ if children.is_empty() {
+ l
+ } else {
+ let mut kids = vec![l];
+ kids.extend(children);
+ self.group(n, kids)
+ }
+ }
+ Kind::Image(img) => match self.image(img, to_doc) {
+ Some(content) => self.base(n, content),
+ None if children.is_empty() => return None,
+ None => self.group(n, children),
+ },
+ };
+ if let Some(mask) = &n.mask {
+ l.vector_mask = Some(VectorMask { path: self.path(mask, to_doc, false), enabled: true, linked: true, density: 1.0, feather: 0.0 });
+ }
+ if let Some(mask) = &n.pixel_mask
+ && let Some(surface) = self.mask(mask, to_doc)
+ {
+ l.mask = Some(LayerMask { surface, enabled: true, linked: true, density: 1.0, feather: 0.0 });
+ }
+ Some(l)
+ }
+
+ fn path(&self, p: &af::Path, to_doc: Affine, even_odd: bool) -> Path {
+ let m = to_doc;
+ let subpaths = p
+ .subpaths
+ .iter()
+ .map(|s| {
+ // Knots: each anchor with the control points of the segments arriving and leaving.
+ let mut knots: Vec<Knot> = Vec::with_capacity(s.segments.len() + 1);
+ let start = m.apply(point(s.start));
+ knots.push(Knot::corner(start.x, start.y));
+ for [c1, c2, e] in &s.segments {
+ if let Some(prev) = knots.last_mut() {
+ prev.out_ctrl = m.apply(point(*c1));
+ }
+ let e = m.apply(point(*e));
+ let mut k = Knot::corner(e.x, e.y);
+ k.in_ctrl = m.apply(point(*c2));
+ knots.push(k);
+ }
+ // A closed subpath that ends where it starts: the last knot is the first.
+ if s.closed
+ && knots.len() > 1
+ && let (Some(f), Some(l)) = (knots.first().copied(), knots.last().copied())
+ && (f.anchor.x - l.anchor.x).abs() < 1e-9
+ && (f.anchor.y - l.anchor.y).abs() < 1e-9
+ {
+ knots.pop();
+ if let Some(first) = knots.first_mut() {
+ first.in_ctrl = l.in_ctrl;
+ }
+ }
+ Subpath { closed: s.closed, knots, op: Default::default() }
+ })
+ .collect();
+ let mut path = Path::new(subpaths);
+ if even_odd {
+ // One component filled even-odd, so inner subpaths cut holes as in Affinity.
+ path.fill_rule = photocraft_doc::vector::FillRule::EvenOdd;
+ for s in path.subpaths.iter_mut().skip(1) {
+ s.op = photocraft_doc::vector::PathOp::Join;
+ }
+ }
+ path
+ }
+
+ fn fill(&mut self, p: &ap::Paint, frame: Rect, to_doc: Affine) -> Option<Fill> {
+ match p {
+ ap::Paint::None => None,
+ ap::Paint::Solid(c) => Some(Fill::Solid(color(*c))),
+ ap::Paint::Gradient(g) => {
+ let style = match g.kind {
+ GradientKind::Linear => GradientStyle::Linear,
+ GradientKind::Radial => GradientStyle::Radial,
+ GradientKind::Conical => GradientStyle::Angle,
+ };
+ let m = to_doc.mul(&affine(g.transform));
+ let (o, e, v) = (m.apply(Point::new(0.0, 0.0)), m.apply(Point::new(1.0, 0.0)), m.apply(Point::new(0.0, 1.0)));
+ let (u, w) = ((e.x - o.x).hypot(e.y - o.y), (v.x - o.x).hypot(v.y - o.y));
+ if style == GradientStyle::Radial && u > 0.0 && (w / u - 1.0).abs() > 0.01 {
+ self.warn("elliptical gradients import as circular ones");
+ }
+ let (angle, scale, offset) =
+ photocraft_compose::gradient_fill::from_handles(style, [o.x as f32, o.y as f32], [e.x as f32, e.y as f32], frame, 0.0);
+ let stops = g.stops.iter().map(|s| (s.offset as f32, Color { alpha: 1.0, ..color(s.color) })).collect();
+ let opacity_stops = g.stops.iter().map(|s| (s.offset as f32, s.color.alpha() as f32)).collect();
+ let midpoints = g.stops.iter().take(g.stops.len().saturating_sub(1)).map(|s| s.half_point() as f32).collect();
+ Some(Fill::Gradient { stops, angle, scale, style, reverse: false, opacity_stops, midpoints, offset, dither: false, align: true })
+ }
+ }
+ }
+
+ fn shape(&mut self, path: Path, fills: &[ap::Paint], strokes: &[ap::Stroke], to_doc: Affine) -> ShapeLayer {
+ let frame = path
+ .control_bounds()
+ .map(|(x0, y0, x1, y1)| Rect::new(x0.floor() as i32, y0.floor() as i32, x1.ceil() as i32, y1.ceil() as i32))
+ .unwrap_or(self.canvas);
+ if fills.len() > 1 || strokes.len() > 1 {
+ self.warn("only one fill and one stroke per shape import");
+ }
+ let fill = fills.first().and_then(|f| self.fill(f, frame, to_doc));
+ let stroke = strokes.first().and_then(|s| {
+ let paint = self.fill(&s.paint, frame, to_doc)?;
+ if s.behind {
+ self.warn("strokes drawn behind their fill import in front of it");
+ }
+ Some(ShapeStroke {
+ width: s.width as f32,
+ paint,
+ opacity: 1.0,
+ align: match s.align {
+ ap::Align::Center => StrokeAlign::Center,
+ ap::Align::Inside => StrokeAlign::Inside,
+ ap::Align::Outside => StrokeAlign::Outside,
+ },
+ cap: match s.cap {
+ Cap::Butt => LineCap::Butt,
+ Cap::Round => LineCap::Round,
+ Cap::Square => LineCap::Square,
+ },
+ join: match s.join {
+ Join::Miter => LineJoin::Miter,
+ Join::Round => LineJoin::Round,
+ Join::Bevel => LineJoin::Bevel,
+ },
+ miter_limit: s.miter_limit as f32,
+ // In multiples of the width, as Photoshop stores them.
+ dashes: s.dash.as_ref().map(|(d, _)| d.iter().map(|v| (v / s.width.max(1e-9)) as f32).collect()).unwrap_or_default(),
+ dash_offset: s.dash.as_ref().map_or(0.0, |(_, o)| (o / s.width.max(1e-9)) as f32),
+ })
+ });
+ let mut sh = ShapeLayer { path, fill, stroke, live: None, cache: None, psd_raw: None };
+ sh.cache = Some(photocraft_vector::render_shape(&sh, self.format, self.canvas));
+ sh
+ }
+
+ fn text(&mut self, t: &af::Text, to_doc: Affine) -> TextLayer {
+ let origin = match t.frame {
+ Some(f) => Point::new(f.x0, f.y0),
+ None => point(t.anchor),
+ };
+ let m = to_doc.mul(&affine(t.transform)).mul(&Affine::translate(origin.x, origin.y));
+ let k = m.determinant().abs().sqrt().max(1e-9);
+ let transform = m.mul(&Affine::scale(1.0 / k));
+ let dpi = self.doc.resolution_dpi.max(1.0) as f64;
+ let mut text = String::new();
+ let mut runs = Vec::new();
+ for r in &t.runs {
+ // Affinity separates paragraphs with U+2029 and lines with U+2028.
+ let s = r.text.replace(['\u{2029}', '\u{2028}'], "\r");
+ let style = CharStyle {
+ font_family: r.family.clone(),
+ postscript_name: (!r.postscript.is_empty()).then(|| r.postscript.clone()),
+ weight: r.weight.clamp(100, 900) as u16,
+ italic: r.italic,
+ size_pt: (r.size * k * 72.0 / dpi) as f32,
+ color: match &r.fill {
+ ap::Paint::Solid(c) => color(*c),
+ _ => Color::BLACK,
+ },
+ tracking: (r.tracking * 1000.0) as f32,
+ leading_pt: r.leading.map(|l| (l * k * 72.0 / dpi) as f32),
+ ..CharStyle::default()
+ };
+ text.push_str(&s);
+ runs.push(TextRun { len: s.len(), style });
+ }
+ let align = match t.align {
+ Align::Left => TextAlign::Left,
+ Align::Center => TextAlign::Center,
+ Align::Right => TextAlign::Right,
+ Align::Justify => TextAlign::JustifyLeft,
+ };
+ let mut layer = TextLayer {
+ text: text.clone(),
+ font_family: runs.first().map(|r| r.style.font_family.clone()).unwrap_or_default(),
+ size_pt: runs.first().map_or(12.0, |r| r.style.size_pt),
+ color: runs.first().map_or(Color::BLACK, |r| r.style.color),
+ transform,
+ runs,
+ paragraphs: vec![ParagraphRun { len: text.len(), style: ParagraphStyle { align, ..ParagraphStyle::default() } }],
+ ..TextLayer::default()
+ };
+ if let Some(f) = t.frame {
+ layer.shape = TextShape::Box { x: 0.0, y: 0.0, width: ((f.x1 - f.x0) * k) as f32, height: ((f.y1 - f.y0) * k) as f32 };
+ }
- let engine = photocraft_text::shared();
- let mut e = engine.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
- e.render_layer(&mut layer, self.doc.resolution_dpi, self.format);
+ layer
+ }
+
+ /// Straight RGBA8 pixels of an image (decoding an embedded file), with its size.
+ fn pixels(&mut self, img: &af::Image) -> Option<(u32, u32, Vec<u8>)> {
+ match &img.pixels {
+ Pixels::Rgba8(v) => Some((img.width, img.height, v.clone())),
+ Pixels::Encoded(bytes) => {
+ let opts = photocraft_codecs::DecodeOptions {
+ limits: photocraft_codecs::Limits { max_width: 65_535, max_height: 65_535, max_pixels: MAX_PIXELS, max_alloc: 512 << 20 },
+ ..Default::default()
+ };
+ match photocraft_codecs::decode_with(bytes, &opts) {
+ Ok(d) => {
+ let (w, h) = d.dimensions();
+ Some((w, h, d.to_rgba8()))
+ }
+ Err(_) => {
+ self.warn("an embedded image that could not be decoded was left out");
+ None
+ }
+ }
+ }
+ }
+ }
+
+ fn image(&mut self, img: &af::Image, to_doc: Affine) -> Option<LayerContent> {
+ let (w, h, rgba) = self.pixels(img)?;
+ // The pixel grid maps onto the Affinity image's own size, whatever the stored file's.
+ let m = to_doc
+ .mul(&affine(img.transform))
+ .mul(&Affine { m: [f64::from(img.width) / f64::from(w.max(1)), 0.0, 0.0, f64::from(img.height) / f64::from(h.max(1)), 0.0, 0.0] });
+ let surface = self.resample(w, h, &rgba, m, 4)?;
+ Some(match &img.pixels {
+ // A placed image keeps its file, as a smart object placed by the same transform.
+ Pixels::Encoded(bytes) => LayerContent::Smart(SmartObject::new(
+ SmartSource::Embedded { file_name: "Affinity image".into(), bytes: Arc::new(bytes.clone()) },
+ m,
+ Some(surface),
+ )),
+ Pixels::Rgba8(_) => LayerContent::Raster(surface),
+ })
+ }
+
+ fn mask(&mut self, img: &af::Image, to_doc: Affine) -> Option<Surface> {
+ let (w, h, rgba) = self.pixels(img)?;
+ let grey: Vec<u8> = rgba.chunks_exact(4).map(|p| p[0]).collect();
+ let m = to_doc.mul(&affine(img.transform));
+ self.resample(w, h, &grey, m, 1)
+ }
+
+ /// Bilinear resampling of `src` (`w`×`h`, `channels` 4 = straight RGBA8 or 1 = grey) mapped
+ /// by `m` (source pixels to canvas pixels) into a surface; exact copy when `m` is an integer
+ /// translation. Pixels outside the source are transparent (grey: 0, hidden).
+ fn resample(&mut self, w: u32, h: u32, src: &[u8], m: Affine, channels: usize) -> Option<Surface> {
+ let format = if channels == 1 { PixelFormat::GRAY8 } else { self.format };
+ let mut out = if channels == 1 { Surface::with_default(format, &[0.0]) } else { Surface::new(format) };
+ let r = self.bbox(m, af::Rect { x0: 0.0, y0: 0.0, x1: f64::from(w), y1: f64::from(h) });
+ if r.width() == 0 || r.height() == 0 {
+ return Some(out);
+ }
+ if u64::from(r.width()) * u64::from(r.height()) > MAX_PIXELS {
+ self.warn("images larger than 64 megapixels on the canvas were left out");
+ return None;
+ }
+ let [a, b, c, d, e, f] = m.m;
+ let exact = a == 1.0 && d == 1.0 && b == 0.0 && c == 0.0 && e.fract() == 0.0 && f.fract() == 0.0;
+ let inv = m.inverse()?;
+ let (rw, rh) = (r.width() as usize, r.height() as usize);
+ let mut buf = vec![0u8; rw * rh * channels];
+ let at = |x: i64, y: i64, ch: usize| -> f64 {
+ if x < 0 || y < 0 || x >= i64::from(w) || y >= i64::from(h) {
+ return 0.0;
+ }
+ f64::from(src.get((y as usize * w as usize + x as usize) * channels + ch).copied().unwrap_or(0))
+ };
+ for (row, out_row) in buf.chunks_exact_mut(rw * channels).enumerate() {
+ for (col, px) in out_row.chunks_exact_mut(channels).enumerate() {
+ let p = inv.apply(Point::new(f64::from(r.x0) + col as f64 + 0.5, f64::from(r.y0) + row as f64 + 0.5));
+ if exact {
+ let (x, y) = (p.x.floor() as i64, p.y.floor() as i64);
+ for (ch, v) in px.iter_mut().enumerate() {
+ *v = at(x, y, ch) as u8;
+ }
+ continue;
+ }
+ let (fx, fy) = (p.x - 0.5, p.y - 0.5);
+ let (x0, y0) = (fx.floor() as i64, fy.floor() as i64);
+ let (tx, ty) = (fx - x0 as f64, fy - y0 as f64);
+ let weights =
+ [((x0, y0), (1.0 - tx) * (1.0 - ty)), ((x0 + 1, y0), tx * (1.0 - ty)), ((x0, y0 + 1), (1.0 - tx) * ty), ((x0 + 1, y0 + 1), tx * ty)];
+ if channels == 1 {
+ px[0] = weights.iter().map(|((x, y), wgt)| at(*x, *y, 0) * wgt).sum::<f64>().round().clamp(0.0, 255.0) as u8;
+ } else {
+ // Interpolate premultiplied colour so transparent pixels don't bleed.
+ let alpha: f64 = weights.iter().map(|((x, y), wgt)| at(*x, *y, 3) * wgt).sum();
+ for (ch, v) in px.iter_mut().enumerate().take(3) {
+ let pm: f64 = weights.iter().map(|((x, y), wgt)| at(*x, *y, ch) * at(*x, *y, 3) / 255.0 * wgt).sum();
+ *v = if alpha > 0.0 { (pm * 255.0 / alpha).round().clamp(0.0, 255.0) as u8 } else { 0 };
+ }
+ px[3] = alpha.round().clamp(0.0, 255.0) as u8;
+ }
+ }
+ }
+ out.write_interleaved(r, &buf);
+ out.prune();
+ Some(out)
+ }
+}
+
+fn default_name(k: &Kind) -> String {
+ match k {
+ Kind::Layer => "Layer",
+ Kind::Group => "Group",
+ Kind::Artboard { .. } => "Artboard",
+ Kind::Shape { .. } => "Shape",
+ Kind::Text(_) => "Text",
+ Kind::Image(_) => "Image",
+ Kind::Unsupported => "Group",
+ }
+ .into()
+}
+
+fn color(c: ap::Color) -> Color {
+ let f = |v: f64| v.clamp(0.0, 1.0) as f32;
+ match c {
+ ap::Color::Rgb { r, g, b, a } => Color::rgba(f(r), f(g), f(b), f(a)),
+ ap::Color::Cmyk { c, m, y, k, a } => {
+ let cmyk = Color { mode: ColorMode::Cmyk, c: [f(c), f(m), f(y), f(k)], alpha: f(a) };
+ let [r, g, b] = cmyk.to_rgb();
+ Color::rgba(r, g, b, f(a))
+ }
+ ap::Color::Gray { v, a } => Color::rgba(f(v), f(v), f(v), f(a)),
+ ap::Color::Lab { l, a, b, alpha } => {
+ let lab = Color { mode: ColorMode::Lab, c: [f(l / 100.0), f((a + 128.0) / 255.0), f((b + 128.0) / 255.0), 0.0], alpha: f(alpha) };
+ let [r, g, bl] = lab.to_rgb();
+ Color::rgba(r, g, bl, f(alpha))
+ }
+ }
+}
diff --cc crates/io/src/lib.rs
index 399865f21,bff525fef..a0be5d207
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@@ -91,13 -92,16 +96,21 @@@ pub struct ImportResult
pub document: Document,
/// Human-readable notes about anything approximated or dropped.
pub warnings: Vec<String>,
+ /// Save must not write back to the source (an Affinity document: PhotoCraft can't write it).
+ pub source_read_only: bool,
+ /// Only a stand-in picture of the file (an Affinity document whose native data couldn't be
+ /// read): Open shows it with its warning; Place and other auxiliary imports refuse it.
+ pub preview_only: bool,
}
+ /// The import note for a file whose horizontal and vertical resolutions (`x`, `y`, in pixels per
+ /// inch) differ: a document has one resolution, so it keeps the horizontal one and saves it on
+ /// both axes (#1018). Differences under 0.01 ppi are below what the warning can show.
+ pub(crate) fn unequal_resolution_warning(x: f64, y: f64) -> Option<String> {
+ ((x - y).abs() >= 0.01)
+ .then(|| format!("the vertical resolution ({y:.2} ppi) differs from the horizontal ({x:.2} ppi); the document keeps {x:.2} ppi for both"))
+ }
+
/// Result of [`export`].
#[derive(Debug, Clone)]
pub struct ExportResult {
@@@ -180,10 -184,8 +193,11 @@@ fn import_stages(name: &str, bytes: &[u
ctl.progress(0.05);
let (mut document, warnings) = psd_import::psd_to_document_with(&file, ctl).ok_or(IoError::Cancelled)?;
document.name = name.to_string();
+ text_import::prepare(&mut document);
- return Ok(ImportResult { document, warnings });
+ return Ok(ImportResult { document, warnings, source_read_only: false, preview_only: false });
+ }
+ if affinity::is_affinity(bytes) || affinity::has_extension(name) {
+ return affinity::import(name, bytes);
}
if raw::is_raw(bytes) {
return raw::import_raw(name, bytes);
diff --cc crates/io/src/svg.rs
index 000000000,6b7abe76f..58fc996be
mode 000000,100644..100644
--- a/crates/io/src/svg.rs
+++ b/crates/io/src/svg.rs
@@@ -1,0 -1,562 +1,562 @@@
+ //! SVG import: a drawing opens as a document of shape layers, and places as a vector smart
+ //! object that is re-rasterised at its placement scale ([`rasterize`]).
+ //!
+ //! Parsing is `usvg`'s (the crate the UI's icons already go through): it resolves CSS, `use`,
+ //! units, nested transforms and turns text into outlines, handing over a tree of groups, paths,
+ //! images and text. Each path becomes a [`ShapeLayer`] (cubic Bézier knots, fill, stroke) and
+ //! each group a layer group with its opacity and blend mode. What the shape model cannot hold,
+ //! clip paths, masks, filters, pattern paints and embedded images, is rasterised by `resvg` into
+ //! a pixel layer so the picture still looks right, with a warning; gradient paints keep their
+ //! stops and direction in the layer's own gradient fill, with a warning that the exact geometry
+ //! is not kept.
+
+ use std::sync::{Arc, OnceLock};
+
+ use photocraft_color::blend::BlendMode;
+ use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
+ use photocraft_doc::effects::GradientStyle;
+ use photocraft_doc::vector::{FillRule, Knot, LineCap, LineJoin, Path, PathOp, ShapeLayer, ShapeStroke, StrokeAlign, Subpath};
+ use photocraft_doc::{Document, Fill, Group, Layer, LayerContent, MAX_GROUP_DEPTH};
+ use photocraft_geom::{Point, Rect, Size};
+ use photocraft_raster::Surface;
+ use resvg::tiny_skia;
+ use resvg::usvg;
+
+ use crate::{ImportResult, IoError};
+
+ /// Largest canvas side an SVG opens at; a larger drawing is scaled down to fit.
+ pub const MAX_SIDE: u32 = 16_384;
+ /// A rasterised fallback layer or a smart-object render never exceeds this many pixels.
+ const MAX_RASTER_PIXELS: u64 = 24_000_000;
+ /// Past this many drawable elements the whole drawing opens as one pixel layer.
+ const MAX_NODES: usize = 2_000;
+ /// Nesting past which a subtree is rasterised instead of walked (bounded recursion).
+ const MAX_RECURSION: usize = 200;
+
+ /// Does this look like an SVG document (plain XML; `.svgz` is recognised by its extension)?
+ pub fn is_svg(bytes: &[u8]) -> bool {
+ let head = bytes.get(..bytes.len().min(4096)).unwrap_or(bytes);
+ let text = String::from_utf8_lossy(head);
+ let t = text.trim_start_matches('\u{feff}').trim_start();
+ if t.starts_with("<svg") {
+ return true;
+ }
+ (t.starts_with("<?xml") || t.starts_with("<!DOCTYPE") || t.starts_with("<!--")) && t.contains("<svg")
+ }
+
+ /// The fonts text runs are shaped with: the bundled craft fonts plus, on the desktop, the
+ /// system's. Loaded once per process.
+ fn fonts() -> Arc<usvg::fontdb::Database> {
+ static DB: OnceLock<Arc<usvg::fontdb::Database>> = OnceLock::new();
+ DB.get_or_init(|| {
+ let mut db = usvg::fontdb::Database::new();
+ for f in photocraft_text::CRAFT_FONTS {
+ db.load_font_data(f.bytes.to_vec());
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ db.load_system_fonts();
+ Arc::new(db)
+ })
+ .clone()
+ }
+
+ /// Parse options for an untrusted drawing. `<image href>` resolves only `data:` URLs: a file path
+ /// or relative href is never read, so opening an SVG cannot pull local files (`/etc/...`,
+ /// `~/.ssh/...`) into the document. Embedded SVG images get no `<image>` resolution at all
+ /// (`usvg` already blanks it for sub-SVGs). The font database (and its one-off scan of the system
+ /// fonts) is only loaded when the drawing may contain text.
+ fn options(bytes: &[u8]) -> usvg::Options<'static> {
+ // `.svgz` is gzip: it can't be scanned before usvg inflates it, so assume it has text.
+ let has_text = bytes.starts_with(&[0x1f, 0x8b]) || bytes.windows(4).any(|w| w == b"text");
+ usvg::Options {
+ resources_dir: None,
+ image_href_resolver: usvg::ImageHrefResolver { resolve_data: usvg::ImageHrefResolver::default_data_resolver(), resolve_string: Box::new(|_, _| None) },
+ fontdb: if has_text { fonts() } else { Arc::new(usvg::fontdb::Database::new()) },
+ ..usvg::Options::default()
+ }
+ }
+
+ fn parse(bytes: &[u8]) -> Result<usvg::Tree, IoError> {
+ let opt = options(bytes);
+ usvg::Tree::from_data(bytes, &opt).map_err(|e| IoError::Svg(e.to_string()))
+ }
+
+ /// The document canvas for a drawing: its size in px, scaled down to [`MAX_SIDE`] when needed.
+ struct Canvas {
+ size: Size,
+ /// Drawing units → canvas pixels (1 unless the drawing had to shrink).
+ scale: f32,
+ }
+
+ fn canvas(tree: &usvg::Tree, warnings: &mut Vec<String>) -> Canvas {
+ let (w, h) = (tree.size().width().max(1.0), tree.size().height().max(1.0));
+ let limit = MAX_SIDE as f32;
+ let scale = (limit / w).min(limit / h).min(1.0);
+ if scale < 1.0 {
+ warnings.push(format!("SVG: the {w:.0} × {h:.0} px drawing was scaled down to fit {MAX_SIDE} px"));
+ }
+ let side = |v: f32| ((v * scale).round() as u32).clamp(1, MAX_SIDE);
+ Canvas { size: Size::new(side(w), side(h)), scale }
+ }
+
+ /// Opens an SVG as a document of shape layers (see the module docs for what is rasterised).
+ pub fn import_svg(name: &str, bytes: &[u8]) -> Result<ImportResult, IoError> {
+ let tree = parse(bytes)?;
+ let mut warnings = Vec::new();
+ let cv = canvas(&tree, &mut warnings);
+ let mut doc = Document::new(name, cv.size, ColorMode::Rgb, SampleType::U8);
+ let fmt = doc.pixel_format();
+ let global = tiny_skia::Transform::from_scale(cv.scale, cv.scale);
+ let mut conv = Conv { fmt, canvas: doc.bounds(), global, warnings, noted: Vec::new(), counts: [0; 4] };
+ if count_nodes(tree.root()) > MAX_NODES {
+ conv.warnings.push(format!("SVG: more than {MAX_NODES} elements; opened as one pixel layer instead of shapes"));
+ let (w, h) = (cv.size.width, cv.size.height);
+ if let Some(mut pixmap) = pixmap(w, h) {
+ resvg::render(&tree, global, &mut pixmap.as_mut());
+ doc.layers.push(Layer::new("Background", LayerContent::Raster(surface(&pixmap, doc.bounds(), fmt))));
+ }
+ } else {
+ doc.layers = conv.convert_children(tree.root().children(), 0, 0, tree.root().abs_transform());
+ }
+ if doc.layers.is_empty() {
+ conv.warnings.push("SVG: nothing to draw (an empty drawing)".to_string());
+ }
- Ok(ImportResult { document: doc, warnings: conv.warnings })
++ Ok(ImportResult { document: doc, warnings: conv.warnings, source_read_only: false, preview_only: false })
+ }
+
+ /// The whole drawing rendered at `scale` (1 = its own size), as a straight-alpha RGBA buffer at
+ /// the origin. Smart objects use it to stay sharp at any placement.
+ pub fn rasterize(bytes: &[u8], scale: f32) -> Result<photocraft_compose::Buffer, IoError> {
+ let tree = parse(bytes)?;
+ let cv = canvas(&tree, &mut Vec::new());
+ let k = cv.scale * scale.clamp(1.0 / 64.0, 64.0);
+ let side = |v: f32| ((v * k).ceil() as u32).max(1);
+ let (w, h) = (side(tree.size().width()), side(tree.size().height()));
+ let mut pixmap = pixmap(w, h).ok_or_else(|| IoError::Svg(format!("{w} × {h} px is too large to rasterise")))?;
+ resvg::render(&tree, tiny_skia::Transform::from_scale(k, k), &mut pixmap.as_mut());
+ let rect = Rect::new(0, 0, w as i32, h as i32);
+ let px = pixmap.pixels().iter().map(|p| rgba(p.demultiply())).collect();
+ Ok(photocraft_compose::Buffer { rect, px })
+ }
+
+ /// A transparent pixmap, or `None` past [`MAX_RASTER_PIXELS`].
+ fn pixmap(w: u32, h: u32) -> Option<tiny_skia::Pixmap> {
+ if u64::from(w) * u64::from(h) > MAX_RASTER_PIXELS {
+ return None;
+ }
+ tiny_skia::Pixmap::new(w, h)
+ }
+
+ fn rgba(c: tiny_skia::ColorU8) -> [f32; 4] {
+ [f32::from(c.red()) / 255.0, f32::from(c.green()) / 255.0, f32::from(c.blue()) / 255.0, f32::from(c.alpha()) / 255.0]
+ }
+
+ /// A pixmap as a surface covering `rect` in `fmt`.
+ fn surface(pixmap: &tiny_skia::Pixmap, rect: Rect, fmt: PixelFormat) -> Surface {
+ let n = fmt.channels();
+ let mut data = vec![0.0f32; pixmap.pixels().len() * n];
+ for (p, out) in pixmap.pixels().iter().zip(data.chunks_exact_mut(n)) {
+ photocraft_raster::from_rgba_into(&fmt, rgba(p.demultiply()), out);
+ }
+ let mut s = Surface::new(fmt);
+ if !rect.is_empty() {
+ s.write_region(rect, &data);
+ }
+ s.prune();
+ s
+ }
+
+ /// Drawable elements in the tree (iterative: the nesting can be anything).
+ fn count_nodes(root: &usvg::Group) -> usize {
+ let mut n = 0;
+ let mut stack: Vec<&usvg::Group> = vec![root];
+ while let Some(g) = stack.pop() {
+ for node in g.children() {
+ n += 1;
+ if let usvg::Node::Group(child) = node {
+ stack.push(child);
+ }
+ if n > MAX_NODES {
+ return n;
+ }
+ }
+ }
+ n
+ }
+
+ /// Converts a parsed tree into layers.
+ struct Conv {
+ fmt: PixelFormat,
+ canvas: Rect,
+ /// Drawing units → canvas pixels.
+ global: tiny_skia::Transform,
+ warnings: Vec<String>,
+ /// Features already warned about (one warning each).
+ noted: Vec<&'static str>,
+ /// Unnamed shapes, groups, images and texts so far, for "Shape 3"-style names.
+ counts: [usize; 4],
+ }
+
+ impl Conv {
+ fn note(&mut self, what: &'static str, msg: String) {
+ if !self.noted.contains(&what) {
+ self.noted.push(what);
+ self.warnings.push(msg);
+ }
+ }
+
+ /// The element's `id`, or a numbered name by kind (0 shape, 1 group, 2 image, 3 text).
+ fn name(&mut self, id: &str, kind: usize) -> String {
+ if !id.is_empty() {
+ return id.to_string();
+ }
+ let label = ["Shape", "Group", "Image", "Text"].get(kind).copied().unwrap_or("Layer");
+ let n = self.counts.get_mut(kind).map(|c| {
+ *c += 1;
+ *c
+ });
+ format!("{label} {}", n.unwrap_or(0))
+ }
+
+ /// `nodes` in paint order (first = bottom), as layers in the same order. `parent` is the
+ /// absolute transform of the group holding them (what resvg needs to render one of them
+ /// alone, since a node's own data is in its parent's space).
+ fn convert_children(&mut self, nodes: &[usvg::Node], depth: usize, rec: usize, parent: tiny_skia::Transform) -> Vec<Layer> {
+ let mut out = Vec::new();
+ for node in nodes {
+ self.convert_node(node, &mut out, depth, rec, parent);
+ }
+ out
+ }
+
+ fn convert_node(&mut self, node: &usvg::Node, out: &mut Vec<Layer>, depth: usize, rec: usize, parent: tiny_skia::Transform) {
+ match node {
+ usvg::Node::Group(g) => {
+ let dropped: [(bool, &'static str); 3] =
+ [(!g.filters().is_empty(), "filter"), (g.clip_path().is_some(), "clip-path"), (g.mask().is_some(), "mask")];
+ let too_deep = depth >= MAX_GROUP_DEPTH || rec >= MAX_RECURSION;
+ if dropped.iter().any(|d| d.0) || too_deep {
+ for (yes, what) in dropped {
+ if yes {
+ self.note(what, format!("SVG: a group with a {what} was rasterised, so it is not editable as shapes"));
+ }
+ }
+ if too_deep {
+ self.note("depth", "SVG: groups nested too deeply were rasterised".to_string());
+ }
+ let name = self.name(g.id(), 1);
+ out.extend(self.raster_layer(node, name, parent));
+ return;
+ }
+ // A group that only carries a transform (baked into its paths by usvg) or that
+ // usvg inserted for its own bookkeeping adds nothing to the layer tree.
+ let plain = g.id().is_empty() && g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal;
+ let children = self.convert_children(g.children(), if plain { depth } else { depth + 1 }, rec + 1, g.abs_transform());
+ if children.is_empty() {
+ return;
+ }
+ if plain {
+ out.extend(children);
+ return;
+ }
+ let only_id = g.opacity().get() >= 1.0 && g.blend_mode() == usvg::BlendMode::Normal;
+ if only_id && children.len() == 1 {
+ if let Some(mut child) = children.into_iter().next() {
+ child.name = g.id().to_string();
+ out.push(child);
+ }
+ return;
+ }
+ let mut l = Layer::new(self.name(g.id(), 1), LayerContent::Group(Group { children, expanded: false, artboard: None }));
+ l.opacity = g.opacity().get();
+ l.blend = blend(g.blend_mode());
+ out.push(l);
+ }
+ usvg::Node::Path(p) => out.extend(self.shape_layer(node, p, parent)),
+ usvg::Node::Image(i) => {
+ self.note("image", "SVG: embedded images are pixel layers".to_string());
+ let name = self.name(i.id(), 2);
+ out.extend(self.raster_layer(node, name, parent));
+ }
+ usvg::Node::Text(t) => {
+ let children = self.convert_children(t.flattened().children(), depth + 1, rec + 1, t.flattened().abs_transform());
+ if children.is_empty() {
+ self.note("text", "SVG: text needs a font the drawing can use; none matched, so it was dropped".to_string());
+ return;
+ }
+ let name = if t.id().is_empty() {
+ let content: String = t.chunks().iter().map(|c| c.text()).collect::<Vec<_>>().join("");
+ let content = content.trim();
+ if content.is_empty() { self.name("", 3) } else { content.chars().take(31).collect() }
+ } else {
+ t.id().to_string()
+ };
+ out.push(Layer::new(name, LayerContent::Group(Group { children, expanded: false, artboard: None })));
+ }
+ }
+ }
+
+ /// A path as a shape layer, or a pixel layer when its paint is a pattern.
+ fn shape_layer(&mut self, node: &usvg::Node, p: &usvg::Path, parent: tiny_skia::Transform) -> Option<Layer> {
+ if !p.is_visible() {
+ return None;
+ }
+ let is_pattern = |paint: &usvg::Paint| matches!(paint, usvg::Paint::Pattern(_));
+ if p.fill().is_some_and(|f| is_pattern(f.paint())) || p.stroke().is_some_and(|s| is_pattern(s.paint())) {
+ self.note("pattern", "SVG: pattern paints were rasterised, so those shapes are not editable".to_string());
+ let name = self.name(p.id(), 0);
+ return self.raster_layer(node, name, parent);
+ }
+ let ts = p.abs_transform().post_concat(self.global);
+ let data = (*p.data()).clone().transform(ts)?;
+ let subpaths = knots(&data);
+ if subpaths.is_empty() {
+ return None;
+ }
+ let fill = p.fill().map(|f| self.paint(f.paint(), f.opacity().get(), ts));
+ let stroke = p.stroke().map(|s| {
+ // Stroke widths are in drawing units; under a non-uniform scale they take the
+ // geometric mean, the one width the shape model has.
+ let (kx, ky) = ((ts.sx * ts.sx + ts.ky * ts.ky).sqrt(), (ts.kx * ts.kx + ts.sy * ts.sy).sqrt());
+ if (kx - ky).abs() > 0.01 * kx.max(ky) {
+ self.note("stroke-scale", "SVG: strokes under a non-uniform scale keep one averaged width".to_string());
+ }
+ let k = (ts.sx * ts.sy - ts.kx * ts.ky).abs().sqrt().max(1e-6);
+ let width = (s.width().get() * k).max(0.01);
+ ShapeStroke {
+ width,
+ paint: self.paint(s.paint(), 1.0, ts),
+ opacity: s.opacity().get(),
+ align: StrokeAlign::Center,
+ cap: match s.linecap() {
+ usvg::LineCap::Butt => LineCap::Butt,
+ usvg::LineCap::Round => LineCap::Round,
+ usvg::LineCap::Square => LineCap::Square,
+ },
+ join: match s.linejoin() {
+ usvg::LineJoin::Round => LineJoin::Round,
+ usvg::LineJoin::Bevel => LineJoin::Bevel,
+ usvg::LineJoin::Miter | usvg::LineJoin::MiterClip => LineJoin::Miter,
+ },
+ miter_limit: s.miterlimit().get(),
+ dashes: s.dasharray().map(|d| d.iter().map(|v| v * k / width).collect()).unwrap_or_default(),
+ dash_offset: s.dashoffset() * k / width,
+ }
+ });
+ let fill_rule = match p.fill().map(|f| f.rule()) {
+ Some(usvg::FillRule::EvenOdd) => FillRule::EvenOdd,
+ _ => FillRule::NonZero,
+ };
+ let mut sh = ShapeLayer { path: Path { subpaths, fill_rule, inverted: false }, fill, stroke, ..Default::default() };
+ sh.cache = Some(photocraft_vector::render_shape(&sh, self.fmt, self.canvas));
+ Some(Layer::new(self.name(p.id(), 0), LayerContent::Shape(sh)))
+ }
+
+ /// A paint as a layer fill. `ts` maps the paint's space onto the canvas.
+ fn paint(&mut self, paint: &usvg::Paint, opacity: f32, ts: tiny_skia::Transform) -> Fill {
+ let stops = |g: &usvg::BaseGradient| -> Vec<(f32, Color)> {
+ g.stops().iter().map(|s| (s.offset().get(), color(s.color(), s.opacity().get() * opacity))).collect()
+ };
+ let gradient = |stops: Vec<(f32, Color)>, angle: f32, style: GradientStyle| Fill::Gradient {
+ stops,
+ angle,
+ scale: 1.0,
+ style,
+ reverse: false,
+ opacity_stops: Vec::new(),
+ midpoints: Vec::new(),
+ offset: (0.0, 0.0),
+ dither: false,
+ align: true,
+ };
+ match paint {
+ usvg::Paint::Color(c) => Fill::Solid(color(*c, opacity)),
+ usvg::Paint::LinearGradient(g) => {
+ self.note("gradient", "SVG: gradient paints keep their stops and direction, not their exact geometry".to_string());
+ let gt = g.transform().post_concat(ts);
+ let mut a = tiny_skia::Point::from_xy(g.x1(), g.y1());
+ let mut b = tiny_skia::Point::from_xy(g.x2(), g.y2());
+ gt.map_point(&mut a);
+ gt.map_point(&mut b);
+ // Photoshop's angle: 0° left → right, counter-clockwise positive (y points down).
+ let angle = (-(b.y - a.y)).atan2(b.x - a.x).to_degrees();
+ gradient(stops(g), if angle.is_finite() { angle } else { 0.0 }, GradientStyle::Linear)
+ }
+ usvg::Paint::RadialGradient(g) => {
+ self.note("gradient", "SVG: gradient paints keep their stops and direction, not their exact geometry".to_string());
+ gradient(stops(g), 0.0, GradientStyle::Radial)
+ }
+ // Pattern paints are rasterised before we get here.
+ usvg::Paint::Pattern(_) => Fill::Solid(Color::rgba(0.5, 0.5, 0.5, opacity)),
+ }
+ }
+
+ /// The node rendered by resvg into a pixel layer over its bounding box, clipped to the canvas.
+ /// `parent` is the absolute transform of the node's parent group.
+ fn raster_layer(&mut self, node: &usvg::Node, name: String, parent: tiny_skia::Transform) -> Option<Layer> {
+ let bb = node.abs_layer_bounding_box()?;
+ let k = self.global.sx;
+ let x0 = ((bb.x() * k).floor() as i32).max(self.canvas.x0);
+ let y0 = ((bb.y() * k).floor() as i32).max(self.canvas.y0);
+ let x1 = ((bb.right() * k).ceil() as i32).min(self.canvas.x1);
+ let y1 = ((bb.bottom() * k).ceil() as i32).min(self.canvas.y1);
+ if x1 <= x0 || y1 <= y0 {
+ return None;
+ }
+ let Some(mut pixmap) = pixmap((x1 - x0) as u32, (y1 - y0) as u32) else {
+ self.note("raster-size", "SVG: an element too large to rasterise was dropped".to_string());
+ return None;
+ };
+ // resvg renders the node in its parent's space after shifting its absolute bounding box
+ // to the origin: undo that shift, apply the parent's transform, then scale to the canvas
+ // and shift so the pixmap starts at (x0, y0).
+ let canvas = tiny_skia::Transform::from_row(k, 0.0, 0.0, k, -(x0 as f32), -(y0 as f32));
+ let ts = canvas.pre_concat(parent).pre_translate(bb.x(), bb.y());
+ resvg::render_node(node, ts, &mut pixmap.as_mut())?;
+ Some(Layer::new(name, LayerContent::Raster(surface(&pixmap, Rect::new(x0, y0, x1, y1), self.fmt))))
+ }
+ }
+
+ fn color(c: usvg::Color, alpha: f32) -> Color {
+ Color::rgba(f32::from(c.red) / 255.0, f32::from(c.green) / 255.0, f32::from(c.blue) / 255.0, alpha.clamp(0.0, 1.0))
+ }
+
+ fn blend(b: usvg::BlendMode) -> BlendMode {
+ use usvg::BlendMode as B;
+ match b {
+ B::Normal => BlendMode::Normal,
+ B::Multiply => BlendMode::Multiply,
+ B::Screen => BlendMode::Screen,
+ B::Overlay => BlendMode::Overlay,
+ B::Darken => BlendMode::Darken,
+ B::Lighten => BlendMode::Lighten,
+ B::ColorDodge => BlendMode::ColorDodge,
+ B::ColorBurn => BlendMode::ColorBurn,
+ B::HardLight => BlendMode::HardLight,
+ B::SoftLight => BlendMode::SoftLight,
+ B::Difference => BlendMode::Difference,
+ B::Exclusion => BlendMode::Exclusion,
+ B::Hue => BlendMode::Hue,
+ B::Saturation => BlendMode::Saturation,
+ B::Color => BlendMode::Color,
+ B::Luminosity => BlendMode::Luminosity,
+ }
+ }
+
+ fn pt(p: tiny_skia::Point) -> Point {
+ Point::new(f64::from(p.x), f64::from(p.y))
+ }
+
+ /// A flattened-transform path as subpaths of knots: lines keep retracted handles, quadratics
+ /// are raised to cubics, and a closing segment that returns to the start merges into it. Every
+ /// subpath after the first joins its component, so the fill rule counts winding across the whole
+ /// path as SVG does (a second subpath drawn inside the first is a hole under even-odd).
+ fn knots(path: &tiny_skia::Path) -> Vec<Subpath> {
+ use tiny_skia::PathSegment as S;
+ let mut out: Vec<Subpath> = Vec::new();
+ let mut cur: Option<Subpath> = None;
+ fn flush(cur: &mut Option<Subpath>, out: &mut Vec<Subpath>, closed: bool) {
+ let Some(mut sp) = cur.take() else { return };
+ sp.closed = closed;
+ if closed && sp.knots.len() > 1 {
+ let (first, last) = (sp.knots.first().map(|k| k.anchor), sp.knots.last().map(|k| (k.anchor, k.in_ctrl)));
+ if let (Some(a), Some((b, in_ctrl))) = (first, last)
+ && (a.x - b.x).abs() < 1e-6
+ && (a.y - b.y).abs() < 1e-6
+ {
+ sp.knots.pop();
+ if let Some(k) = sp.knots.first_mut() {
+ k.in_ctrl = in_ctrl;
+ }
+ }
+ }
+ if !sp.knots.is_empty() {
+ if !out.is_empty() {
+ sp.op = PathOp::Join;
+ }
+ out.push(sp);
+ }
+ }
+ fn curve(sp: &mut Subpath, c1: Point, c2: Point, p: Point) {
+ if let Some(last) = sp.knots.last_mut() {
+ last.out_ctrl = c1;
+ }
+ sp.knots.push(Knot { anchor: p, in_ctrl: c2, out_ctrl: p, smooth: false });
+ }
+ for seg in path.segments() {
+ match seg {
+ S::MoveTo(p) => {
+ flush(&mut cur, &mut out, false);
+ cur = Some(Subpath { knots: vec![Knot::corner(f64::from(p.x), f64::from(p.y))], ..Default::default() });
+ }
+ S::LineTo(p) => {
+ if let Some(sp) = cur.as_mut() {
+ sp.knots.push(Knot::corner(f64::from(p.x), f64::from(p.y)));
+ }
+ }
+ S::QuadTo(c, p) => {
+ if let Some(sp) = cur.as_mut() {
+ let (c, p) = (pt(c), pt(p));
+ let p0 = sp.knots.last().map_or(p, |k| k.anchor);
+ let c1 = Point::new(p0.x + 2.0 / 3.0 * (c.x - p0.x), p0.y + 2.0 / 3.0 * (c.y - p0.y));
+ let c2 = Point::new(p.x + 2.0 / 3.0 * (c.x - p.x), p.y + 2.0 / 3.0 * (c.y - p.y));
+ curve(sp, c1, c2, p);
+ }
+ }
+ S::CubicTo(c1, c2, p) => {
+ if let Some(sp) = cur.as_mut() {
+ curve(sp, pt(c1), pt(c2), pt(p));
+ }
+ }
+ S::Close => flush(&mut cur, &mut out, true),
+ }
+ }
+ flush(&mut cur, &mut out, false);
+ out
+ }
+
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ #[test]
+ fn sniffing_accepts_svg_and_rejects_other_xml() {
+ assert!(is_svg(b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>"));
+ assert!(is_svg("\u{feff}<?xml version=\"1.0\"?>\n<!-- hi -->\n<svg/>".as_bytes()));
+ assert!(is_svg(b"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"x\"><svg/>"));
+ assert!(!is_svg(b"<?xml version=\"1.0\"?><x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>"));
+ assert!(!is_svg(b"\x89PNG\r\n"));
+ assert!(!is_svg(b""));
+ }
+
+ #[test]
+ fn quadratics_become_cubics_and_closing_merges_the_start_knot() {
+ let mut pb = tiny_skia::PathBuilder::new();
+ pb.move_to(0.0, 0.0);
+ pb.quad_to(5.0, 10.0, 10.0, 0.0);
+ pb.line_to(0.0, 0.0);
+ pb.close();
+ pb.move_to(20.0, 20.0);
+ pb.line_to(30.0, 20.0);
+ let path = pb.finish().unwrap();
+ let sp = knots(&path);
+ assert_eq!(sp.len(), 2);
+ assert!(sp[0].closed && !sp[1].closed);
+ // The explicit line back to the start was merged into the first knot.
+ assert_eq!(sp[0].knots.len(), 2);
+ let (a, b) = (&sp[0].knots[0], &sp[0].knots[1]);
+ assert!((a.out_ctrl.x - 10.0 / 3.0).abs() < 1e-9 && (a.out_ctrl.y - 20.0 / 3.0).abs() < 1e-9);
+ assert!((b.in_ctrl.x - 20.0 / 3.0).abs() < 1e-9 && (b.in_ctrl.y - 20.0 / 3.0).abs() < 1e-9);
+ assert_eq!(b.anchor, Point::new(10.0, 0.0));
+ assert_eq!(sp[1].knots.len(), 2);
+ }
+
+ #[test]
+ fn huge_drawings_scale_to_the_side_limit() {
+ let tree = parse(b"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100000 50000\"/>").unwrap();
+ let mut w = Vec::new();
+ let cv = canvas(&tree, &mut w);
+ assert_eq!((cv.size.width, cv.size.height), (MAX_SIDE, MAX_SIDE / 2));
+ assert_eq!(w.len(), 1);
+ }
+ }
diff --cc crates/ui-egui/src/file_open/tests.rs
index cbe22155d,5251c3aa9..7856f0545
--- a/crates/ui-egui/src/file_open/tests.rs
+++ b/crates/ui-egui/src/file_open/tests.rs
@@@ -61,27 -80,6 +80,27 @@@ fn open_file_sets_name_path_and_recent(
assert!(app.ui.notices.is_empty());
}
+#[test]
+fn affinity_preview_does_not_acquire_the_source_path_even_when_renamed() {
+ for automation in [false, true] {
+ for path in ["/pics/source.af", "/pics/renamed.psd"] {
- let (mut app, written) = app_with(None, None);
++ let (mut app, written) = app_with(Vec::new());
+ // The fake importer supplies the preview; its source signature controls path policy.
+ if automation {
+ app.open_automation_bytes(&display_name(path), b"\x00\xffKA").unwrap();
+ app.opened_from(path);
+ } else {
+ app.open_file(path, b"\x00\xffKA").unwrap();
+ }
+ assert!(app.session.active().unwrap().source_read_only);
+ assert!(app.session.active().unwrap().path.is_none());
+ assert_eq!(app.ui.recent_files.first().map(String::as_str), Some(path));
+ assert_eq!(menus::invoke(&mut app, &egui::Context::default(), "file.save", json!({})).unwrap_err(), "cancelled");
+ assert!(written.borrow().is_empty());
+ }
+ }
+}
+
#[test]
fn file_open_dialog_sets_path_so_save_writes_in_place() {
// The dialog returns a full path: the document is named after the file, not the path.
diff --cc docs/development.md
index 729d8337a,5b3f6f239..519d1c9d5
--- a/docs/development.md
+++ b/docs/development.md
@@@ -330,7 -354,7 +354,8 @@@ against committed **sha256 manifests**
| `corpus/psd/` | 170 small psd-tools and ag-psd files, the mix most PSD tests use | psd-tools and ag-psd upstreams (MIT) | `xtask/psd-corpus.sha256` |
| `corpus/psd-tools/` | the complete psd-tools test set (309 files) | psd-tools upstream (MIT) | `xtask/psd-tools-corpus.sha256` |
| `corpus/heif/` | 9 small HEIC/HEIF files (checkerboards, RGB strips, a grid-tiled photo with EXIF/XMP, each with Apple's decode as `.ref.png`; a 10-bit RGBA file with its source PNG), for the `heif` feature | heic-rs (MIT OR Apache-2.0) and pillow-heif (BSD-3-Clause) upstreams | `xtask/heif-corpus.sha256` |
+ | `corpus/exr/` | the 5 deep OpenEXR test images (scanline deep data with half colour and u32 ID channels; 2.3 MB), checked against the ID manifests of their upstream sidecars | OpenEXR upstream at v3.5.2 (BSD-3-Clause) | `xtask/exr-corpus.sha256` |
+| `corpus/affinity/` | 21 public Affinity documents (four Affinity 3 `.af` files, `.afdesign` vector art, layer/shape/raster test files, a template with artboards), each holding Affinity's own render as its thumbnail | vector-art (CC0), AFDesignLoad, Jac21/Branding and AssetStoreTemplate (MIT) upstreams | `xtask/affinity-corpus.sha256` |
| `corpus/pngsuite/` | PngSuite | schaik.com release archive (public domain) | (fixed archive) |
```sh
diff --cc docs/scorecard.md
index fa4fcec70,74ab0cbbf..66931fdde
--- a/docs/scorecard.md
+++ b/docs/scorecard.md
@@@ -7,12 -7,12 +7,12 @@@ Generated by `cargo xtask scorecard` fr
| Area | Done | Partial | Missing | Key numbers |
|---|---:|---:|---:|---|
| [Performance](#performance) | 3 | 22 | 13 | 47 scenarios: 3 within budget, 22 over budget or failing, 15 tracked only, 6 not run, 7 not measurable yet (baseline 2026-10-05) |
- | [File compatibility](#file-compatibility) | 3 | 9 | 15 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 229/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
- | [Tools](#tools) | 6 | 15 | 9 | |
- | [Workspace and UI](#workspace-and-ui) | 0 | 5 | 18 | settings that do nothing: 57 of 135 (target 0) |
+ | [File compatibility](#file-compatibility) | 4 | 12 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 307/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
+ | [Tools](#tools) | 10 | 14 | 8 | |
+ | [Workspace and UI](#workspace-and-ui) | 0 | 6 | 17 | settings that do nothing: 56 of 140 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
| [Automation](#automation) | 3 | 2 | 6 | 627 of 627 menu items live (100.0%) |
-| [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 27 of 27 crates; panic_hunt present |
+| [Reliability](#reliability) | 4 | 1 | 2 | never-crash lints on 28 of 28 crates; panic_hunt present |
| [Distribution](#distribution) | 4 | 4 | 3 | |
| [Open bugs](#open-bugs) | 12 | 4 | 16 | |
diff --cc xtask/src/corpus.rs
index 080fdb879,c47778731..6bae7a395
--- a/xtask/src/corpus.rs
+++ b/xtask/src/corpus.rs
@@@ -17,7 -17,7 +17,7 @@@ const HEIF_CRATES: &[&str] = &["photocr
/// Paths whose changes make `test-corpus --changed` run (the file-format and rendering crates).
const CRITICAL: &[&str] = &["crates/psd/", "crates/io/", "crates/codecs/", "crates/heif/", "crates/compose/", "crates/gpu/", "crates/text/", "crates/format/"];
- /// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --affinity | --photoshop [--local]] [--update-manifest]`
-/// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --exr | --photoshop [--local]] [--update-manifest]`
++/// `cargo xtask corpus [--all | --pngsuite | --download | --psd | --psd-tools | --heif | --exr | --affinity | --photoshop [--local]] [--update-manifest]`
pub fn cmd(args: &[&str]) -> Result<(), String> {
let update = args.contains(&"--update-manifest");
let mut did = false;
@@@ -40,10 -40,10 +40,14 @@@
corpus_pins::HEIF.fetch(update)?;
did = true;
}
+ if args.contains(&"--exr") {
+ corpus_pins::EXR.fetch(update)?;
+ did = true;
+ }
+ if args.contains(&"--affinity") {
+ corpus_pins::AFFINITY.fetch(update)?;
+ did = true;
+ }
if args.contains(&"--photoshop") {
if args.contains(&"--local") {
corpus_pins::PHOTOSHOP.fetch_local(&local_clone()?, update)?;
@@@ -109,10 -109,10 +113,12 @@@ fn list()
manifest xtask/psd-tools-corpus.sha256. Fetch: --psd-tools
corpus/heif/ [{}] a few HEIC/HEIF files from heic-rs@{} (MIT OR Apache-2.0) and
pillow-heif@{} (BSD-3-Clause), manifest xtask/heif-corpus.sha256. Fetch: --heif
- corpus/affinity/ [{}] 20 public Affinity 1–3 documents (CC0, MIT): vector-art, AFDesignLoad,
+ corpus/exr/ [{}] the deep OpenEXR test images (BSD-3-Clause), openexr@{}
+ manifest xtask/exr-corpus.sha256. Fetch: --exr
++ corpus/affinity/ [{}] 21 public Affinity 1–3 documents (CC0, MIT): vector-art, AFDesignLoad,
+ Jac21/Branding, AssetStoreTemplate; manifest xtask/affinity-corpus.sha256. Fetch: --affinity
corpus/pngsuite/ [{}] PngSuite (public domain), {PNGSUITE_URL}. Fetch: --pngsuite
- corpus/tiff/, corpus/exr/, corpus/raw/ optional, copied in by hand
+ corpus/tiff/, corpus/raw/ optional, copied in by hand
Pins: xtask/src/corpus_pins.rs. Moving one: change it, then --<name> --update-manifest.",
corpus.display(),
@@@ -124,7 -124,8 +130,9 @@@
status(corpus_pins::HEIF.is_current()),
&HEIC_RS_COMMIT[..12],
&PILLOW_HEIF_COMMIT[..12],
+ status(corpus_pins::EXR.is_current()),
+ &OPENEXR_COMMIT[..12],
+ status(corpus_pins::AFFINITY.is_current()),
status(png_ok),
);
}
diff --cc xtask/src/corpus_pins.rs
index dc0377593,5a09881dc..8e12c6919
--- a/xtask/src/corpus_pins.rs
+++ b/xtask/src/corpus_pins.rs
@@@ -23,15 -23,9 +23,18 @@@ pub const AG_PSD_COMMIT: &str = "387049
pub const HEIC_RS_COMMIT: &str = "4f0d4df474c773dfc3b14fa80e7219be6898866e";
/// https://github.com/bigcat88/pillow_heif (BSD-3-Clause): `tests/images` (master, 2026-09-25).
pub const PILLOW_HEIF_COMMIT: &str = "b16be1196dfa465a342d68894696e685ca3655cb";
+ /// https://github.com/AcademySoftwareFoundation/openexr (BSD-3-Clause): `src/test/bin/test_images`
+ /// at the v3.5.2 tag (2026-10-03).
+ pub const OPENEXR_COMMIT: &str = "69b2604fc76e370615438bdc8d2cd95b9349c12e";
+/// https://github.com/samuel-etver/vector-art (CC0-1.0): `simple/`, four Affinity 3 `.af` files and
+/// Designer `.afdesign` files (main, 2026-04-22).
+pub const VECTOR_ART_COMMIT: &str = "255f8add3c8f0740196e22bd59502b811b532f0b";
+/// https://github.com/NickBeeuwsaert/AFDesignLoad (MIT): `testDesigns/`, purpose-made Designer files.
+pub const AFDESIGNLOAD_COMMIT: &str = "a18dd50a7079fb861a28835eeefa0d015f03f4a1";
+/// https://github.com/Jac21/Branding (MIT): Designer logos with artboards and placed images.
+pub const JAC21_BRANDING_COMMIT: &str = "57ae3f45bf4637f6927c0b07de25b922c55f944f";
+/// https://github.com/eviltwo/AssetStoreTemplate (MIT): an Affinity template with artboards.
+pub const ASSET_STORE_TEMPLATE_COMMIT: &str = "f671981ee89d15526285b3cc87b4393d3defe644";
/// PngSuite (public domain), a fixed release archive.
pub const PNGSUITE_URL: &str = "http://www.schaik.com/pngsuite/PngSuite-2017jul19.tgz";
@@@ -143,58 -137,31 +146,84 @@@ pub const HEIF: PinnedCorpus = PinnedCo
},
};
+ /// `corpus/exr`: the deep OpenEXR test images (scanline and tiled deep data, several channel
+ /// types) the deep decoder was verified against. The manifest selects the files.
+ pub const EXR: PinnedCorpus = PinnedCorpus {
+ name: "exr",
+ dest: "exr",
+ upstreams: &[Upstream {
+ prefix: "",
+ repo: "AcademySoftwareFoundation/openexr",
+ commit: OPENEXR_COMMIT,
+ subdir: "src/test/bin/test_images",
+ extras: &[("LICENSE.md", "LICENSE.md")],
+ }],
+ manifest: "xtask/exr-corpus.sha256",
+ exts: &["exr"],
+ subset: true,
+ sources_md: |c| {
+ format!(
+ "# Deep OpenEXR test corpus
+
+ The `*.deep.exr` files of https://github.com/AcademySoftwareFoundation/openexr/tree/{OPENEXR_COMMIT}/src/test/bin/test_images, unmodified. BSD-3-Clause, Copyright Contributors to the OpenEXR Project (see `LICENSE.md`). Selected by and sha256-verified against `{}` by `cargo xtask corpus --exr`. Gitignored; never commit these files.
+ ",
+ c.manifest
+ )
+ },
+ };
+
+/// `corpus/affinity`: public Affinity documents saved by Affinity 1.x to 3.x, chosen for having no
+/// personal paths in their metadata. Each embeds Affinity's own render of itself (its thumbnail),
+/// the oracle `photocraft-io`'s corpus test compares the imported document against. The manifest
+/// selects the files.
+pub const AFFINITY: PinnedCorpus = PinnedCorpus {
+ name: "affinity",
+ dest: "affinity",
+ upstreams: &[
+ Upstream {
+ prefix: "vector-art/",
+ repo: "samuel-etver/vector-art",
+ commit: VECTOR_ART_COMMIT,
+ subdir: "simple",
+ extras: &[("LICENSE", "vector-art/LICENSE")],
+ },
+ Upstream {
+ prefix: "afdesignload/",
+ repo: "NickBeeuwsaert/AFDesignLoad",
+ commit: AFDESIGNLOAD_COMMIT,
+ subdir: "testDesigns",
+ extras: &[("LICENSE", "afdesignload/LICENSE")],
+ },
+ Upstream {
+ prefix: "jac21/",
+ repo: "Jac21/Branding",
+ commit: JAC21_BRANDING_COMMIT,
+ subdir: "Logos/JC/DesignerFiles/Affinity",
+ extras: &[("LICENSE.md", "jac21/LICENSE.md")],
+ },
+ Upstream {
+ prefix: "asset-store-template/",
+ repo: "eviltwo/AssetStoreTemplate",
+ commit: ASSET_STORE_TEMPLATE_COMMIT,
+ subdir: "AssetStoreTemplate",
+ extras: &[("LICENSE", "asset-store-template/LICENSE")],
+ },
+ ],
+ manifest: "xtask/affinity-corpus.sha256",
+ exts: &["af", "afdesign", "aftemplate"],
+ subset: true,
+ sources_md: |c| {
+ format!(
+ "# Affinity test corpus\n\nPublic Affinity documents, unmodified, with their licences next to them: \
+ https://github.com/samuel-etver/vector-art/tree/{VECTOR_ART_COMMIT}/simple (`vector-art/`, CC0-1.0), \
+ https://github.com/NickBeeuwsaert/AFDesignLoad/tree/{AFDESIGNLOAD_COMMIT}/testDesigns (`afdesignload/`, MIT, Copyright (c) 2015 Nick Beeuwsaert), \
+ https://github.com/Jac21/Branding/tree/{JAC21_BRANDING_COMMIT}/Logos/JC/DesignerFiles/Affinity (`jac21/`, MIT, Copyright (c) 2018 Jeremy Cantu) and \
+ https://github.com/eviltwo/AssetStoreTemplate/tree/{ASSET_STORE_TEMPLATE_COMMIT}/AssetStoreTemplate (`asset-store-template/`, MIT). \
+ Selected by and sha256-verified against `{}` by `cargo xtask corpus --affinity`. Gitignored; never commit these files.\n",
+ c.manifest
+ )
+ },
+};
+
/// Every pinned corpus, in fetch order.
- pub const ALL: &[&PinnedCorpus] = &[&PSD_MIXED, &PSD_TOOLS, &PHOTOSHOP, &HEIF, &AFFINITY];
-pub const ALL: &[&PinnedCorpus] = &[&PSD_MIXED, &PSD_TOOLS, &PHOTOSHOP, &HEIF, &EXR];
++pub const ALL: &[&PinnedCorpus] = &[&PSD_MIXED, &PSD_TOOLS, &PHOTOSHOP, &HEIF, &EXR, &AFFINITY];