IO-2/SHP-5/PRV-2: PSD import, SVG import + vector/text conversions, persistent disk cache

- effectcraft-psd (L1): PSD/PSB reader from Adobe's published file format spec (layers, groups,
  masks, blend modes, text engine data, lfx2 effects, fill/adjustment layers, vector masks;
  1/8/16/32-bit, RGB/CMYK/Gray/Lab/Indexed, raw/RLE/ZIP) and a minimal writer for fixtures.
- File > Import: importAs footage|composition|compositionLayerSizes, layer (Choose Layer);
  groups -> precomps (pass-through collapses), text -> editable text, styles -> Layer Styles,
  adjustments -> adjustment layers with effects; UI asks the Import Kind for Photoshop files.
- effectcraft-svg (L2): SVG parser (shapes, paths, transforms, use, CSS, gradients) and
  rasteriser; .svg imports as footage, continuously rasterised when the switch is on.
- layer.create: shapesFromVector, shapesFromText, masksFromText, editableText (stub removed).
- Disk cache (render::disk_cache): LZ4 content-keyed frames and layer buffers, LRU size limit
  from prefs, atomic writes, restart persistence; edit.purge clears it, cache.diskStats query;
  viewer frames read/write it and the timeline shows disk-only frames in blue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon Thomas
2026-10-02 22:10:48 -04:00
co-authored by Claude Opus 5.5
parent e911cc5c93
commit 94e1c86d89
64 changed files with 7388 additions and 34 deletions
+430
View File
@@ -0,0 +1,430 @@
//! The descriptor ("action descriptor") structure: typed key/value trees used by text layers,
//! layer effects, fill layers and newer adjustment layers (spec: "Descriptor structure").
use crate::read::Reader;
use crate::{Error, Result};
/// A descriptor: a class and a list of keyed items (in file order).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Descriptor {
pub class_name: String,
pub class_id: String,
pub items: Vec<(String, DValue)>,
}
/// One descriptor value.
#[derive(Clone, Debug, PartialEq)]
pub enum DValue {
Descriptor(Descriptor),
List(Vec<DValue>),
Double(f64),
/// Unit (`#Pxl`, `#Prc`, `#Ang`, `#Pnt`…) and value.
UnitFloat(String, f64),
UnitFloats(String, Vec<f64>),
Text(String),
/// Enumerated value: type and value ids.
Enum(String, String),
Integer(i32),
LargeInteger(i64),
Bool(bool),
Class(String, String),
Raw(Vec<u8>),
Reference(Vec<RefItem>),
}
/// An item of a reference (`obj `).
#[derive(Clone, Debug, PartialEq)]
pub enum RefItem {
Property(String, String),
Class(String),
Enum(String, String, String),
Offset(String, i32),
Identifier(i32),
Index(i32),
Name(String, String),
}
impl Descriptor {
pub fn get(&self, key: &str) -> Option<&DValue> {
self.items.iter().find(|(k, _)| k == key).map(|(_, v)| v)
}
pub fn obj(&self, key: &str) -> Option<&Descriptor> {
match self.get(key)? {
DValue::Descriptor(d) => Some(d),
_ => None,
}
}
/// A number: doubles, unit floats, integers.
pub fn num(&self, key: &str) -> Option<f64> {
match self.get(key)? {
DValue::Double(v) | DValue::UnitFloat(_, v) => Some(*v),
DValue::Integer(v) => Some(*v as f64),
DValue::LargeInteger(v) => Some(*v as f64),
_ => None,
}
}
pub fn bool(&self, key: &str) -> Option<bool> {
match self.get(key)? {
DValue::Bool(b) => Some(*b),
_ => None,
}
}
pub fn text(&self, key: &str) -> Option<&str> {
match self.get(key)? {
DValue::Text(s) => Some(s),
_ => None,
}
}
/// The value id of an enumerated item.
pub fn enum_value(&self, key: &str) -> Option<&str> {
match self.get(key)? {
DValue::Enum(_, v) => Some(v),
_ => None,
}
}
pub fn raw(&self, key: &str) -> Option<&[u8]> {
match self.get(key)? {
DValue::Raw(v) => Some(v),
_ => None,
}
}
/// An RGB colour object (`RGBC` with `Rd `/`Grn `/`Bl ` in 0..255) as 0..1 values; also
/// reads grayscale (`Gry `) colours.
pub fn color(&self, key: &str) -> Option<[f64; 3]> {
let c = self.obj(key)?;
if let (Some(r), Some(g), Some(b)) = (c.num("Rd "), c.num("Grn "), c.num("Bl ")) {
return Some([r / 255.0, g / 255.0, b / 255.0]);
}
if let (Some(r), Some(g), Some(b)) = (c.num("redFloat"), c.num("greenFloat"), c.num("blueFloat")) {
return Some([r, g, b]);
}
c.num("Gry ").map(|g| {
let v = 1.0 - g / 100.0;
[v, v, v]
})
}
}
/// A key or class id: length-prefixed string, or a 4-character code when the length is 0.
pub(crate) fn read_id(r: &mut Reader) -> Result<String> {
let n = r.u32()? as usize;
let n = if n == 0 { 4 } else { n };
let b = r.bytes(n)?;
Ok(String::from_utf8_lossy(b).into_owned())
}
pub(crate) fn read_unicode(r: &mut Reader) -> Result<String> {
let n = r.u32()? as usize;
let mut v = Vec::with_capacity(n);
for _ in 0..n {
v.push(r.u16()?);
}
while v.last() == Some(&0) {
v.pop();
}
Ok(String::from_utf16_lossy(&v))
}
/// Read a descriptor (after its version field).
pub fn read_descriptor(r: &mut Reader) -> Result<Descriptor> {
let class_name = read_unicode(r)?;
let class_id = read_id(r)?;
let n = r.u32()? as usize;
if n > 100_000 {
return Err(Error::Invalid("descriptor item count".into()));
}
let mut items = Vec::with_capacity(n.min(64));
for _ in 0..n {
let key = read_id(r)?;
let ty = r.tag()?;
let v = read_value(r, &ty, 0)?;
items.push((key, v));
}
Ok(Descriptor { class_name, class_id, items })
}
fn read_value(r: &mut Reader, ty: &[u8; 4], depth: usize) -> Result<DValue> {
if depth > 64 {
return Err(Error::Invalid("descriptor nesting".into()));
}
Ok(match ty {
b"Objc" | b"GlbO" => DValue::Descriptor(read_descriptor(r)?),
b"VlLs" => {
let n = r.u32()? as usize;
if n > 1_000_000 {
return Err(Error::Invalid("descriptor list length".into()));
}
let mut v = Vec::with_capacity(n.min(256));
for _ in 0..n {
let t = r.tag()?;
v.push(read_value(r, &t, depth + 1)?);
}
DValue::List(v)
}
b"doub" => DValue::Double(r.f64()?),
b"UntF" => {
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
DValue::UnitFloat(unit, r.f64()?)
}
b"UnFl" => {
let unit = String::from_utf8_lossy(&r.tag()?).into_owned();
let n = r.u32()? as usize;
let mut v = Vec::with_capacity(n.min(1024));
for _ in 0..n {
v.push(r.f64()?);
}
DValue::UnitFloats(unit, v)
}
b"TEXT" => DValue::Text(read_unicode(r)?),
b"enum" => {
let t = read_id(r)?;
DValue::Enum(t, read_id(r)?)
}
b"long" => DValue::Integer(r.u32()? as i32),
b"comp" => DValue::LargeInteger(r.u64()? as i64),
b"bool" => DValue::Bool(r.u8()? != 0),
b"type" | b"GlbC" => {
let name = read_unicode(r)?;
DValue::Class(name, read_id(r)?)
}
b"alis" | b"tdta" | b"Pth " => {
let n = r.u32()? as usize;
DValue::Raw(r.bytes(n)?.to_vec())
}
b"obj " => {
let n = r.u32()? as usize;
let mut items = Vec::with_capacity(n.min(16));
for _ in 0..n {
let t = r.tag()?;
items.push(match &t {
b"prop" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
RefItem::Property(class, read_id(r)?)
}
b"Clss" => {
let _name = read_unicode(r)?;
RefItem::Class(read_id(r)?)
}
b"Enmr" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
let ty = read_id(r)?;
RefItem::Enum(class, ty, read_id(r)?)
}
b"rele" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
RefItem::Offset(class, r.u32()? as i32)
}
b"Idnt" => RefItem::Identifier(r.u32()? as i32),
b"indx" => RefItem::Index(r.u32()? as i32),
b"name" => {
let _name = read_unicode(r)?;
let class = read_id(r)?;
RefItem::Name(class, read_unicode(r)?)
}
other => return Err(Error::Invalid(format!("reference item `{}`", String::from_utf8_lossy(other)))),
});
}
DValue::Reference(items)
}
other => return Err(Error::Invalid(format!("descriptor type `{}`", String::from_utf8_lossy(other)))),
})
}
// ---------------------------------------------------------------- writing
fn put_u32(out: &mut Vec<u8>, v: u32) {
out.extend_from_slice(&v.to_be_bytes());
}
fn put_id(out: &mut Vec<u8>, id: &str) {
if id.len() == 4 {
put_u32(out, 0);
} else {
put_u32(out, id.len() as u32);
}
out.extend_from_slice(id.as_bytes());
}
pub(crate) fn put_unicode(out: &mut Vec<u8>, s: &str) {
let v: Vec<u16> = s.encode_utf16().chain(std::iter::once(0)).collect();
put_u32(out, v.len() as u32);
for c in v {
out.extend_from_slice(&c.to_be_bytes());
}
}
/// Serialise a descriptor (without the version field).
pub fn write_descriptor(out: &mut Vec<u8>, d: &Descriptor) {
put_unicode(out, &d.class_name);
put_id(out, &d.class_id);
put_u32(out, d.items.len() as u32);
for (k, v) in &d.items {
put_id(out, k);
write_value(out, v);
}
}
fn write_value(out: &mut Vec<u8>, v: &DValue) {
match v {
DValue::Descriptor(d) => {
out.extend_from_slice(b"Objc");
write_descriptor(out, d);
}
DValue::List(l) => {
out.extend_from_slice(b"VlLs");
put_u32(out, l.len() as u32);
for x in l {
write_value(out, x);
}
}
DValue::Double(x) => {
out.extend_from_slice(b"doub");
out.extend_from_slice(&x.to_be_bytes());
}
DValue::UnitFloat(u, x) => {
out.extend_from_slice(b"UntF");
out.extend_from_slice(&tag4(u));
out.extend_from_slice(&x.to_be_bytes());
}
DValue::UnitFloats(u, xs) => {
out.extend_from_slice(b"UnFl");
out.extend_from_slice(&tag4(u));
put_u32(out, xs.len() as u32);
for x in xs {
out.extend_from_slice(&x.to_be_bytes());
}
}
DValue::Text(s) => {
out.extend_from_slice(b"TEXT");
put_unicode(out, s);
}
DValue::Enum(t, e) => {
out.extend_from_slice(b"enum");
put_id(out, t);
put_id(out, e);
}
DValue::Integer(i) => {
out.extend_from_slice(b"long");
out.extend_from_slice(&i.to_be_bytes());
}
DValue::LargeInteger(i) => {
out.extend_from_slice(b"comp");
out.extend_from_slice(&i.to_be_bytes());
}
DValue::Bool(b) => {
out.extend_from_slice(b"bool");
out.push(*b as u8);
}
DValue::Class(n, c) => {
out.extend_from_slice(b"type");
put_unicode(out, n);
put_id(out, c);
}
DValue::Raw(b) => {
out.extend_from_slice(b"tdta");
put_u32(out, b.len() as u32);
out.extend_from_slice(b);
}
DValue::Reference(items) => {
out.extend_from_slice(b"obj ");
put_u32(out, items.len() as u32);
for it in items {
match it {
RefItem::Property(c, k) => {
out.extend_from_slice(b"prop");
put_unicode(out, "");
put_id(out, c);
put_id(out, k);
}
RefItem::Class(c) => {
out.extend_from_slice(b"Clss");
put_unicode(out, "");
put_id(out, c);
}
RefItem::Enum(c, t, e) => {
out.extend_from_slice(b"Enmr");
put_unicode(out, "");
put_id(out, c);
put_id(out, t);
put_id(out, e);
}
RefItem::Offset(c, o) => {
out.extend_from_slice(b"rele");
put_unicode(out, "");
put_id(out, c);
out.extend_from_slice(&o.to_be_bytes());
}
RefItem::Identifier(i) => {
out.extend_from_slice(b"Idnt");
out.extend_from_slice(&i.to_be_bytes());
}
RefItem::Index(i) => {
out.extend_from_slice(b"indx");
out.extend_from_slice(&i.to_be_bytes());
}
RefItem::Name(c, n) => {
out.extend_from_slice(b"name");
put_unicode(out, "");
put_id(out, c);
put_unicode(out, n);
}
}
}
}
}
}
fn tag4(s: &str) -> [u8; 4] {
let mut t = *b" ";
for (i, b) in s.bytes().take(4).enumerate() {
t[i] = b;
}
t
}
/// Builder helpers for descriptors (tests and the writer).
impl Descriptor {
pub fn new(class_id: &str) -> Descriptor {
Descriptor { class_name: String::new(), class_id: class_id.into(), items: vec![] }
}
pub fn with(mut self, key: &str, v: DValue) -> Descriptor {
self.items.push((key.into(), v));
self
}
/// An `RGBC` colour object from 0..1 values.
pub fn rgb(c: [f64; 3]) -> Descriptor {
Descriptor::new("RGBC").with("Rd ", DValue::Double(c[0] * 255.0)).with("Grn ", DValue::Double(c[1] * 255.0)).with("Bl ", DValue::Double(c[2] * 255.0))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trip() {
let d = Descriptor::new("null")
.with("Txt ", DValue::Text("Héllo".into()))
.with("Clr ", DValue::Descriptor(Descriptor::rgb([1.0, 0.5, 0.0])))
.with("Opct", DValue::UnitFloat("#Prc".into(), 75.0))
.with("Md ", DValue::Enum("BlnM".into(), "Mltp".into()))
.with("enab", DValue::Bool(true))
.with("longKeyName", DValue::List(vec![DValue::Integer(3), DValue::Double(1.5)]))
.with("EngineData", DValue::Raw(b"<< >>".to_vec()))
.with("ref", DValue::Reference(vec![RefItem::Enum("Lyr ".into(), "Ordn".into(), "Trgt".into()), RefItem::Index(2)]));
let mut out = vec![];
write_descriptor(&mut out, &d);
let back = read_descriptor(&mut Reader::new(&out)).unwrap();
assert_eq!(back.class_id, "null");
assert_eq!(back.text("Txt "), Some("Héllo"));
assert_eq!(back.color("Clr "), Some([1.0, 0.5, 0.0]));
assert_eq!(back.num("Opct"), Some(75.0));
assert_eq!(back.enum_value("Md "), Some("Mltp"));
assert_eq!(back.bool("enab"), Some(true));
assert_eq!(back.raw("EngineData"), Some(&b"<< >>"[..]));
assert_eq!(back, d);
}
}
+288
View File
@@ -0,0 +1,288 @@
//! The text engine data of type layers (`EngineData` in the `TySh` descriptor): a PostScript-like
//! tree of dictionaries (`<< /Key value >>`), arrays (`[ ]`), numbers, names, booleans and
//! strings (`(þÿ` + UTF-16BE with backslash escapes `)`). Read best-effort.
#[derive(Clone, Debug, PartialEq)]
pub enum EValue {
Dict(Vec<(String, EValue)>),
Array(Vec<EValue>),
Num(f64),
Bool(bool),
Name(String),
Str(String),
}
impl EValue {
pub fn get(&self, key: &str) -> Option<&EValue> {
match self {
EValue::Dict(v) => v.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
}
}
pub fn idx(&self, i: usize) -> Option<&EValue> {
match self {
EValue::Array(v) => v.get(i),
_ => None,
}
}
/// Follow a `/`-separated path; numeric segments index arrays.
pub fn path(&self, p: &str) -> Option<&EValue> {
let mut cur = self;
for seg in p.split('/').filter(|s| !s.is_empty()) {
cur = match seg.parse::<usize>() {
Ok(i) => cur.idx(i)?,
Err(_) => cur.get(seg)?,
};
}
Some(cur)
}
pub fn num(&self) -> Option<f64> {
match self {
EValue::Num(n) => Some(*n),
_ => None,
}
}
pub fn str(&self) -> Option<&str> {
match self {
EValue::Str(s) | EValue::Name(s) => Some(s),
_ => None,
}
}
}
struct P<'a> {
b: &'a [u8],
i: usize,
}
impl P<'_> {
fn ws(&mut self) {
while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == 0) {
self.i += 1;
}
}
fn peek(&self, s: &[u8]) -> bool {
self.b[self.i..].starts_with(s)
}
fn value(&mut self, depth: usize) -> Option<EValue> {
if depth > 128 {
return None;
}
self.ws();
if self.i >= self.b.len() {
return None;
}
if self.peek(b"<<") {
self.i += 2;
let mut v = vec![];
loop {
self.ws();
if self.i >= self.b.len() {
return Some(EValue::Dict(v));
}
if self.peek(b">>") {
self.i += 2;
return Some(EValue::Dict(v));
}
if self.b[self.i] != b'/' {
// Unexpected token: skip it.
self.i += 1;
continue;
}
let key = self.name();
let val = self.value(depth + 1)?;
v.push((key, val));
}
}
match self.b[self.i] {
b'[' => {
self.i += 1;
let mut v = vec![];
loop {
self.ws();
if self.i >= self.b.len() {
return Some(EValue::Array(v));
}
if self.b[self.i] == b']' {
self.i += 1;
return Some(EValue::Array(v));
}
let start = self.i;
match self.value(depth + 1) {
Some(x) => v.push(x),
None => return Some(EValue::Array(v)),
}
if self.i == start {
self.i += 1;
}
}
}
b'/' => Some(EValue::Name(self.name())),
b'(' => Some(EValue::Str(self.string())),
_ => {
let start = self.i;
while self.i < self.b.len() && !self.b[self.i].is_ascii_whitespace() && !b"[]<>/(".contains(&self.b[self.i]) {
self.i += 1;
}
let tok = std::str::from_utf8(&self.b[start..self.i]).unwrap_or("");
if self.i == start {
self.i += 1;
return Some(EValue::Name(String::new()));
}
Some(match tok {
"true" => EValue::Bool(true),
"false" => EValue::Bool(false),
t => t.parse::<f64>().map(EValue::Num).unwrap_or_else(|_| EValue::Name(t.to_string())),
})
}
}
}
fn name(&mut self) -> String {
self.i += 1; // '/'
let start = self.i;
while self.i < self.b.len() && !self.b[self.i].is_ascii_whitespace() && !b"[]<>/(".contains(&self.b[self.i]) {
self.i += 1;
}
String::from_utf8_lossy(&self.b[start..self.i]).into_owned()
}
fn string(&mut self) -> String {
self.i += 1; // '('
let mut raw = vec![];
while self.i < self.b.len() {
let c = self.b[self.i];
self.i += 1;
match c {
b'\\' if self.i < self.b.len() => {
let e = self.b[self.i];
self.i += 1;
raw.push(match e {
b'n' => b'\n',
b'r' => b'\r',
b't' => b'\t',
other => other,
});
}
b')' => break,
_ => raw.push(c),
}
}
if raw.starts_with(&[0xFE, 0xFF]) {
let u: Vec<u16> = raw[2..].chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect();
String::from_utf16_lossy(&u).trim_end_matches('\0').to_string()
} else {
String::from_utf8_lossy(&raw).into_owned()
}
}
}
/// Parse engine data (returns an empty dictionary on garbage).
pub fn parse(b: &[u8]) -> EValue {
let mut p = P { b, i: 0 };
p.value(0).unwrap_or(EValue::Dict(vec![]))
}
/// Encode a string the way engine data stores it (UTF-16BE with a BOM, escaped).
pub fn encode_string(s: &str) -> Vec<u8> {
let mut out = vec![b'(', 0xFE, 0xFF];
for u in s.encode_utf16() {
for b in u.to_be_bytes() {
if matches!(b, b'(' | b')' | b'\\') {
out.push(b'\\');
}
out.push(b);
}
}
out.push(b')');
out
}
/// The first style run's character attributes.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextStyle {
pub font: Option<String>,
pub size: Option<f64>,
/// RGB 0..1.
pub color: Option<[f64; 3]>,
/// 0 left, 1 right, 2 centre, 3+ justified variants.
pub justification: Option<u8>,
pub tracking: Option<f64>,
pub leading: Option<f64>,
pub faux_bold: bool,
pub faux_italic: bool,
/// Paragraph (box) text rather than point text.
pub box_text: bool,
}
pub fn text_style(ed: &EValue) -> TextStyle {
let engine = ed.get("EngineDict").unwrap_or(ed);
let resources = ed.get("ResourceDict").or_else(|| ed.get("DocumentResources"));
let run = engine.path("StyleRun/RunArray/0/StyleSheet/StyleSheetData");
let normal = resources.and_then(|r| r.path("StyleSheetSet/0/StyleSheetData"));
let attr = |k: &str| run.and_then(|r| r.get(k)).or_else(|| normal.and_then(|n| n.get(k)));
let font =
attr("Font").and_then(EValue::num).and_then(|i| resources?.path(&format!("FontSet/{}/Name", i as usize))).and_then(EValue::str).map(str::to_string);
let color = attr("FillColor").and_then(|c| c.get("Values")).and_then(|v| match v {
EValue::Array(a) if a.len() >= 4 => Some([a[1].num()?, a[2].num()?, a[3].num()?]),
_ => None,
});
let para = engine.path("ParagraphRun/RunArray/0/ParagraphSheet/Properties");
let para_normal = resources.and_then(|r| r.path("ParagraphSheetSet/0/Properties"));
let justification =
para.and_then(|p| p.get("Justification")).or_else(|| para_normal.and_then(|p| p.get("Justification"))).and_then(EValue::num).map(|n| n as u8);
let auto_leading = attr("AutoLeading").is_none_or(|v| *v != EValue::Bool(false));
let box_text = engine.path("Rendered/Shapes/Children/0/ShapeType").and_then(EValue::num) == Some(1.0);
TextStyle {
font,
size: attr("FontSize").and_then(EValue::num),
color,
justification,
tracking: attr("Tracking").and_then(EValue::num),
leading: if auto_leading { None } else { attr("Leading").and_then(EValue::num) },
faux_bold: attr("FauxBold") == Some(&EValue::Bool(true)),
faux_italic: attr("FauxItalic") == Some(&EValue::Bool(true)),
box_text,
}
}
/// Minimal engine data for a type layer with one style run (fixtures, and what a writer needs).
pub fn minimal(text: &str, font: &str, size: f64, color: [f64; 3], justification: u8) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(b"\n\n<<\n\t/EngineDict\n\t<<\n\t\t/Editor << /Text ");
out.extend_from_slice(&encode_string(&format!("{text}\r")));
out.extend_from_slice(b" >>\n\t\t/ParagraphRun << /RunArray [ << /ParagraphSheet << /Properties << /Justification ");
out.extend_from_slice(justification.to_string().as_bytes());
out.extend_from_slice(b" >> >> >> ] >>\n\t\t/StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /Font 0 /FontSize ");
out.extend_from_slice(format!("{size:.1}").as_bytes());
out.extend_from_slice(
format!(" /FillColor << /Type 1 /Values [ 1.0 {:.5} {:.5} {:.5} ] >> /AutoLeading true >> >> >> ] >>\n\t>>\n", color[0], color[1], color[2]).as_bytes(),
);
out.extend_from_slice(b"\t/ResourceDict << /FontSet [ << /Name ");
out.extend_from_slice(&encode_string(font));
out.extend_from_slice(b" /Type 0 >> ] >>\n>>");
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_minimal() {
let b = minimal("Hi (there)", "Arial-BoldMT", 36.0, [1.0, 0.5, 0.0], 2);
let v = parse(&b);
assert_eq!(v.path("EngineDict/Editor/Text").and_then(EValue::str), Some("Hi (there)\r"));
let st = text_style(&v);
assert_eq!(st.font.as_deref(), Some("Arial-BoldMT"));
assert_eq!(st.size, Some(36.0));
assert_eq!(st.color, Some([1.0, 0.5, 0.0]));
assert_eq!(st.justification, Some(2));
assert!(!st.box_text);
}
#[test]
fn garbage_is_harmless() {
let _ = parse(b"<< /A [ 1 2 << /B (unterminated");
let _ = parse(b"]]]>>>> /x");
let _ = parse(&[0xFF; 64]);
}
}
+965
View File
@@ -0,0 +1,965 @@
//! Photoshop document (PSD / PSB) reader, implemented from Adobe's public *Photoshop File Formats
//! Specification* (see README.md), and a minimal writer ([`write`]) for fixtures.
//!
//! [`Psd::parse`] reads the structure (header, layer records and their additional information,
//! the layer tree) without decoding pixels; [`Psd::composite`] decodes the merged image and
//! [`Psd::layer_pixels`] one layer (with its layer mask applied to alpha) on demand. Pixels come
//! out as straight (unpremultiplied) RGBA `f32` in 0..1, display-encoded (32-bit documents,
//! which are linear, are encoded to sRGB).
pub mod descriptor;
pub mod engine_data;
mod read;
pub mod write;
use std::sync::Arc;
pub use descriptor::{DValue, Descriptor};
use read::Reader;
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
NotPsd,
Truncated,
Unsupported(String),
Invalid(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NotPsd => write!(f, "not a Photoshop document"),
Error::Truncated => write!(f, "truncated Photoshop document"),
Error::Unsupported(s) => write!(f, "unsupported Photoshop feature: {s}"),
Error::Invalid(s) => write!(f, "invalid Photoshop document: {s}"),
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;
/// Whether `bytes` start like a Photoshop document.
pub fn is_psd(bytes: &[u8]) -> bool {
bytes.len() >= 6 && &bytes[..4] == b"8BPS" && matches!(u16::from_be_bytes([bytes[4], bytes[5]]), 1 | 2)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorMode {
Bitmap,
Grayscale,
Indexed,
Rgb,
Cmyk,
Multichannel,
Duotone,
Lab,
}
impl ColorMode {
pub fn from_u16(v: u16) -> Option<ColorMode> {
Some(match v {
0 => ColorMode::Bitmap,
1 => ColorMode::Grayscale,
2 => ColorMode::Indexed,
3 => ColorMode::Rgb,
4 => ColorMode::Cmyk,
7 => ColorMode::Multichannel,
8 => ColorMode::Duotone,
9 => ColorMode::Lab,
_ => return None,
})
}
pub fn to_u16(self) -> u16 {
match self {
ColorMode::Bitmap => 0,
ColorMode::Grayscale => 1,
ColorMode::Indexed => 2,
ColorMode::Rgb => 3,
ColorMode::Cmyk => 4,
ColorMode::Multichannel => 7,
ColorMode::Duotone => 8,
ColorMode::Lab => 9,
}
}
/// Number of colour channels (before alpha).
pub fn color_channels(self) -> usize {
match self {
ColorMode::Rgb | ColorMode::Lab => 3,
ColorMode::Cmyk => 4,
_ => 1,
}
}
}
/// A rectangle in document pixels (`right`/`bottom` exclusive).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rect {
pub top: i32,
pub left: i32,
pub bottom: i32,
pub right: i32,
}
impl Rect {
pub fn new(left: i32, top: i32, width: i32, height: i32) -> Rect {
Rect { top, left, bottom: top + height, right: left + width }
}
pub fn width(&self) -> u32 {
(self.right - self.left).max(0) as u32
}
pub fn height(&self) -> u32 {
(self.bottom - self.top).max(0) as u32
}
pub fn is_empty(&self) -> bool {
self.width() == 0 || self.height() == 0
}
}
/// One channel of a layer: id (0.. colour, -1 transparency, -2 layer mask, -3 real user mask) and
/// where its data (compression + image data) sits in the file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChannelInfo {
pub id: i16,
pub offset: usize,
pub len: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LayerMask {
pub rect: Rect,
/// Value outside the mask rectangle (0 or 255).
pub default_color: u8,
pub disabled: bool,
pub inverted: bool,
}
/// Layer kind from the section divider setting (`lsct`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Section {
#[default]
Layer,
OpenFolder,
ClosedFolder,
/// The hidden "</Layer group>" record that closes a group (below its children).
Divider,
}
/// A type layer (`TySh`).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextInfo {
/// Text with `\n` line breaks.
pub text: String,
/// Affine transform (xx, xy, yx, yy, tx, ty): the text origin sits at (tx, ty).
pub transform: [f64; 6],
pub style: engine_data::TextStyle,
/// Text bounds (left, top, right, bottom) relative to the origin, when stored.
pub bounds: Option<[f64; 4]>,
}
/// Adjustment layers (best effort).
#[derive(Clone, Debug, PartialEq)]
pub enum Adjustment {
Invert,
BrightnessContrast {
brightness: f64,
contrast: f64,
legacy: bool,
},
HueSaturation {
hue: f64,
saturation: f64,
lightness: f64,
colorize: bool,
},
Levels {
in_black: f64,
in_white: f64,
gamma: f64,
out_black: f64,
out_white: f64,
},
Exposure {
exposure: f64,
offset: f64,
gamma: f64,
},
/// Another adjustment (its tagged-block key, e.g. `curv`, `blnc`).
Other(String),
}
/// A vector mask path: sub-paths of (in tangent, vertex, out tangent) points in document pixels.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct VectorMask {
pub inverted: bool,
pub disabled: bool,
pub subpaths: Vec<SubPath>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct SubPath {
pub closed: bool,
/// Per knot: [control point preceding, anchor, control point leaving] as (x, y).
pub knots: Vec<[[f64; 2]; 3]>,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Layer {
/// Index in [`Psd::layers`] (file order: bottom of the stack first).
pub index: usize,
pub name: String,
pub id: Option<u32>,
pub rect: Rect,
/// Blend mode key (`norm`, `mul `, `pass`…).
pub blend: [u8; 4],
pub opacity: u8,
/// Fill opacity (`iOpa`), 255 when absent.
pub fill_opacity: u8,
/// Clipped to the layer below.
pub clipping: bool,
pub hidden: bool,
pub protect_transparency: bool,
pub section: Section,
pub channels: Vec<ChannelInfo>,
pub mask: Option<LayerMask>,
pub text: Option<TextInfo>,
pub adjustment: Option<Adjustment>,
/// Solid colour fill layer (`SoCo`), RGB 0..1.
pub fill: Option<[f64; 3]>,
/// Layer effects (`lfx2` descriptor).
pub effects: Option<Descriptor>,
pub vector_mask: Option<VectorMask>,
/// Keys of every additional-information block the layer carries.
pub keys: Vec<[u8; 4]>,
}
impl Layer {
pub fn is_group(&self) -> bool {
matches!(self.section, Section::OpenFolder | Section::ClosedFolder)
}
pub fn blend_key(&self) -> &str {
std::str::from_utf8(&self.blend).unwrap_or("norm")
}
pub fn has_pixels(&self) -> bool {
!self.rect.is_empty() && self.channels.iter().any(|c| c.id >= 0)
}
}
/// The layer tree, top of the stack first.
#[derive(Clone, Debug, PartialEq)]
pub enum Node {
Layer(usize),
Group { layer: usize, children: Vec<Node> },
}
/// Decoded pixels: straight RGBA, row-major.
#[derive(Clone, Debug, PartialEq)]
pub struct Pixels {
pub width: u32,
pub height: u32,
pub data: Vec<[f32; 4]>,
}
/// A parsed Photoshop document.
#[derive(Clone, Debug)]
pub struct Psd {
/// PSB (large document format).
pub psb: bool,
pub width: u32,
pub height: u32,
pub channels: u16,
pub depth: u16,
pub mode: ColorMode,
/// Bottom of the stack first (file order).
pub layers: Vec<Layer>,
/// The merged image's first extra channel is transparency.
pub merged_alpha: bool,
/// Indexed colour palette (256 R, then G, then B).
pub palette: Vec<u8>,
data: Arc<[u8]>,
merged_offset: usize,
}
impl Psd {
pub fn parse(data: impl Into<Arc<[u8]>>) -> Result<Psd> {
let data: Arc<[u8]> = data.into();
let mut r = Reader::new(&data);
if r.bytes(4).ok() != Some(b"8BPS") {
return Err(Error::NotPsd);
}
let version = r.u16()?;
let psb = match version {
1 => false,
2 => true,
_ => return Err(Error::NotPsd),
};
r.skip(6)?;
let channels = r.u16()?;
let height = r.u32()?;
let width = r.u32()?;
let depth = r.u16()?;
let mode_v = r.u16()?;
let mode = ColorMode::from_u16(mode_v).ok_or_else(|| Error::Unsupported(format!("colour mode {mode_v}")))?;
if !matches!(depth, 1 | 8 | 16 | 32) {
return Err(Error::Unsupported(format!("{depth}-bit")));
}
if width == 0 || height == 0 || width > 300_000 || height > 300_000 {
return Err(Error::Invalid(format!("size {width}x{height}")));
}
// Colour mode data.
let n = r.u32()? as usize;
let palette = r.bytes(n)?.to_vec();
// Image resources.
let n = r.u32()? as usize;
r.skip(n)?;
// Layer and mask information.
let mut psd = Psd { psb, width, height, channels, depth, mode, layers: vec![], merged_alpha: false, palette, data: data.clone(), merged_offset: 0 };
let lm_len = r.length(psb)?;
let lm_end = r.pos.checked_add(lm_len).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?;
if lm_len > 0 {
let li_len = r.length(psb)?;
let li_end = r.pos.checked_add(li_len).filter(|&e| e <= lm_end).ok_or(Error::Truncated)?;
if li_len > 0 {
psd.layer_info(&data, r.pos, li_end)?;
}
r.pos = li_end;
if r.pos + 4 <= lm_end {
let g = r.u32()? as usize;
r.pos = (r.pos + g).min(lm_end);
}
// Global additional layer information (16/32-bit layer info lives here).
while let Some((key, start, end)) = next_block(&data, &mut r.pos, lm_end, psb) {
if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") && psd.layers.is_empty() && end > start {
// The block holds the layer info, normally without its length field; accept
// both layouts.
if psd.layer_info(&data, start, end).is_err() || psd.layers.is_empty() {
psd.layers.clear();
let skip = if psb { 8 } else { 4 };
if start + skip < end && psd.layer_info(&data, start + skip, end).is_err() {
psd.layers.clear();
}
}
}
r.pos = end;
}
}
psd.merged_offset = lm_end;
Ok(psd)
}
fn layer_info(&mut self, data: &[u8], start: usize, end: usize) -> Result<()> {
let mut r = Reader::at(&data[..end], start);
let count = r.i16()?;
self.merged_alpha = count < 0;
let n = count.unsigned_abs() as usize;
let mut layers = Vec::with_capacity(n);
for i in 0..n {
layers.push(self.layer_record(&mut r, i)?);
}
// Channel image data follows in record order.
for l in &mut layers {
for c in &mut l.channels {
c.offset = r.pos;
r.skip(c.len)?;
}
}
self.layers = layers;
Ok(())
}
fn layer_record(&self, r: &mut Reader, index: usize) -> Result<Layer> {
let psb = self.psb;
let (top, left, bottom, right) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?);
let nch = r.u16()? as usize;
if nch > 64 {
return Err(Error::Invalid("channel count".into()));
}
let mut channels = Vec::with_capacity(nch);
for _ in 0..nch {
let id = r.i16()?;
let len = r.length(psb)?;
channels.push(ChannelInfo { id, offset: 0, len });
}
if r.bytes(4)? != b"8BIM" {
return Err(Error::Invalid("layer record signature".into()));
}
let blend = r.tag()?;
let opacity = r.u8()?;
let clipping = r.u8()? != 0;
let flags = r.u8()?;
r.skip(1)?;
let extra = r.u32()? as usize;
let extra_end = r.pos.checked_add(extra).filter(|&e| e <= r.data.len()).ok_or(Error::Truncated)?;
let mut l = Layer {
index,
rect: Rect { top, left, bottom, right },
blend,
opacity,
fill_opacity: 255,
clipping,
hidden: flags & 2 != 0,
protect_transparency: flags & 1 != 0,
channels,
..Default::default()
};
// Layer mask data.
let mlen = r.u32()? as usize;
let mstart = r.pos;
if mlen >= 18 {
let rect = Rect { top: r.i32()?, left: r.i32()?, bottom: r.i32()?, right: r.i32()? };
let default_color = r.u8()?;
let mflags = r.u8()?;
l.mask = Some(LayerMask { rect, default_color, disabled: mflags & 2 != 0, inverted: mflags & 4 != 0 });
}
r.pos = mstart + mlen;
// Blending ranges.
let blen = r.u32()? as usize;
r.skip(blen)?;
l.name = r.pascal(4)?;
let mut pos = r.pos;
let data = r.data;
while let Some((key, start, end)) = next_block(data, &mut pos, extra_end, psb) {
l.keys.push(key);
let block = &data[start..end];
// A malformed block only loses that block's information.
let _ = self.layer_block(&mut l, &key, block);
pos = end;
}
r.pos = extra_end;
Ok(l)
}
fn layer_block(&self, l: &mut Layer, key: &[u8; 4], b: &[u8]) -> Result<()> {
let mut r = Reader::new(b);
match key {
b"luni" => {
let name = descriptor::read_unicode(&mut r)?;
if !name.is_empty() {
l.name = name;
}
}
b"lyid" => l.id = Some(r.u32()?),
b"iOpa" => l.fill_opacity = r.u8()?,
b"lsct" | b"lsdk" => {
l.section = match r.u32()? {
1 => Section::OpenFolder,
2 => Section::ClosedFolder,
3 => Section::Divider,
_ => Section::Layer,
};
if b.len() >= 12 && &b[4..8] == b"8BIM" {
l.blend.copy_from_slice(&b[8..12]);
}
}
b"TySh" => {
let _ver = r.u16()?;
let mut t = [0.0; 6];
for v in &mut t {
*v = r.f64()?;
}
let _text_ver = r.u16()?;
let _desc_ver = r.u32()?;
let d = descriptor::read_descriptor(&mut r)?;
let text = d.text("Txt ").unwrap_or_default().replace("\r\n", "\n").replace('\r', "\n");
let text = text.strip_suffix('\n').map(str::to_string).unwrap_or(text);
let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse(e))).unwrap_or_default();
let bounds =
d.obj("bounds").or_else(|| d.obj("boundingBox")).and_then(|o| Some([o.num("Left")?, o.num("Top ")?, o.num("Rght")?, o.num("Btom")?]));
l.text = Some(TextInfo { text, transform: t, style, bounds });
}
b"lfx2" => {
let _ver = r.u32()?;
let _dver = r.u32()?;
l.effects = Some(descriptor::read_descriptor(&mut r)?);
}
b"SoCo" => {
let _ver = r.u32()?;
let d = descriptor::read_descriptor(&mut r)?;
l.fill = d.color("Clr ");
}
b"nvrt" => l.adjustment = Some(Adjustment::Invert),
b"brit" => {
let brightness = r.i16()? as f64;
let contrast = r.i16()? as f64;
if l.adjustment.is_none() {
l.adjustment = Some(Adjustment::BrightnessContrast { brightness, contrast, legacy: true });
}
}
b"CgEd" => {
let _ver = r.u32()?;
let d = descriptor::read_descriptor(&mut r)?;
l.adjustment = Some(Adjustment::BrightnessContrast {
brightness: d.num("Brgh").unwrap_or(0.0),
contrast: d.num("Cntr").unwrap_or(0.0),
legacy: d.bool("useLegacy").unwrap_or(false),
});
}
b"hue2" | b"hue " => {
let _ver = r.u16()?;
let colorize = r.u8()? != 0;
r.skip(1)?;
let ch = (r.i16()? as f64, r.i16()? as f64, r.i16()? as f64);
let m = (r.i16()? as f64, r.i16()? as f64, r.i16()? as f64);
let (hue, saturation, lightness) = if colorize { ch } else { m };
l.adjustment = Some(Adjustment::HueSaturation { hue, saturation, lightness, colorize });
}
b"levl" => {
let _ver = r.u16()?;
let (ib, iw, ob, ow, g) = (r.i16()?, r.i16()?, r.i16()?, r.i16()?, r.i16()?);
l.adjustment =
Some(Adjustment::Levels { in_black: ib as f64, in_white: iw as f64, gamma: g as f64 / 100.0, out_black: ob as f64, out_white: ow as f64 });
}
b"expA" => {
let _ver = r.u16()?;
let exposure = r.f32()? as f64;
let offset = r.f32()? as f64;
let gamma = r.f32()? as f64;
l.adjustment = Some(Adjustment::Exposure { exposure, offset, gamma });
}
b"curv" | b"blnc" | b"post" | b"thrs" | b"selc" | b"mixr" | b"phfl" | b"vibA" | b"blwh" | b"grdm" | b"clrL" => {
if l.adjustment.is_none() {
l.adjustment = Some(Adjustment::Other(String::from_utf8_lossy(key).into_owned()));
}
}
b"vmsk" | b"vsms" => {
let _ver = r.u32()?;
let flags = r.u32()?;
l.vector_mask = Some(self.vector_paths(&mut r, flags)?);
}
_ => {}
}
Ok(())
}
fn vector_paths(&self, r: &mut Reader, flags: u32) -> Result<VectorMask> {
let (w, h) = (self.width as f64, self.height as f64);
let mut vm = VectorMask { inverted: flags & 1 != 0, disabled: flags & 4 != 0, subpaths: vec![] };
let fixed = |r: &mut Reader| -> Result<f64> { Ok(r.i32()? as f64 / (1 << 24) as f64) };
while r.remaining() >= 26 {
let sel = r.u16()?;
match sel {
0 | 3 => {
let _n = r.u16()?;
r.skip(22)?;
vm.subpaths.push(SubPath { closed: sel == 0, knots: vec![] });
}
1 | 2 | 4 | 5 => {
let mut pts = [[0.0; 2]; 3];
for p in &mut pts {
let y = fixed(r)?;
let x = fixed(r)?;
*p = [x * w, y * h];
}
if let Some(sp) = vm.subpaths.last_mut() {
sp.knots.push(pts);
}
}
_ => r.skip(24)?,
}
}
vm.subpaths.retain(|s| !s.knots.is_empty());
Ok(vm)
}
/// The layer tree, top of the stack first.
pub fn tree(&self) -> Vec<Node> {
let mut stack: Vec<Vec<Node>> = vec![vec![]];
for l in &self.layers {
match l.section {
Section::Divider => stack.push(vec![]),
Section::OpenFolder | Section::ClosedFolder => {
let children = if stack.len() > 1 { stack.pop().unwrap_or_default() } else { vec![] };
if let Some(top) = stack.last_mut() {
top.push(Node::Group { layer: l.index, children });
}
}
Section::Layer => {
if let Some(top) = stack.last_mut() {
top.push(Node::Layer(l.index));
}
}
}
}
while stack.len() > 1 {
let c = stack.pop().unwrap_or_default();
if let Some(top) = stack.last_mut() {
top.extend(c);
}
}
fn rev(v: &mut Vec<Node>) {
v.reverse();
for n in v {
if let Node::Group { children, .. } = n {
rev(children);
}
}
}
let mut out = stack.pop().unwrap_or_default();
rev(&mut out);
out
}
fn bytes_per_sample(&self) -> usize {
match self.depth {
16 => 2,
32 => 4,
_ => 1,
}
}
/// Decode one channel of `w`×`h` samples at `offset` (compression field first). Values 0..1.
fn decode_channel(&self, offset: usize, len: usize, w: usize, h: usize) -> Result<Vec<f32>> {
let end = offset.checked_add(len).filter(|&e| e <= self.data.len()).ok_or(Error::Truncated)?;
let mut r = Reader::at(&self.data[..end], offset);
let comp = r.u16()?;
let rowb = self.row_bytes(w);
let raw = match comp {
0 => r.bytes(rowb * h)?.to_vec(),
1 => {
let mut counts = Vec::with_capacity(h);
for _ in 0..h {
counts.push(if self.psb { r.u32()? as usize } else { r.u16()? as usize });
}
let mut out = Vec::with_capacity(rowb * h);
for c in counts {
unpack_bits(r.bytes(c)?, rowb, &mut out)?;
}
out
}
2 | 3 => {
let rest = r.bytes(r.remaining())?;
let mut v = miniz_oxide::inflate::decompress_to_vec_zlib(rest).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?;
v.resize(rowb * h, 0);
if comp == 3 {
self.unpredict(&mut v, w, h);
}
v
}
c => return Err(Error::Unsupported(format!("compression {c}"))),
};
Ok(self.samples(&raw, w, h))
}
fn row_bytes(&self, w: usize) -> usize {
if self.depth == 1 { w.div_ceil(8) } else { w * self.bytes_per_sample() }
}
fn unpredict(&self, v: &mut [u8], w: usize, h: usize) {
match self.depth {
16 => {
for row in v.chunks_exact_mut(w * 2).take(h) {
let mut prev = 0u16;
for c in row.chunks_exact_mut(2) {
let x = u16::from_be_bytes([c[0], c[1]]).wrapping_add(prev);
c.copy_from_slice(&x.to_be_bytes());
prev = x;
}
}
}
32 => {
for row in v.chunks_exact_mut(w * 4).take(h) {
for i in 1..row.len() {
row[i] = row[i].wrapping_add(row[i - 1]);
}
// Bytes are stored plane by plane (all first bytes, then all second bytes…).
let planar = row.to_vec();
for x in 0..w {
for b in 0..4 {
row[x * 4 + b] = planar[b * w + x];
}
}
}
}
_ => {
for row in v.chunks_exact_mut(w).take(h) {
for i in 1..row.len() {
row[i] = row[i].wrapping_add(row[i - 1]);
}
}
}
}
}
fn samples(&self, raw: &[u8], w: usize, h: usize) -> Vec<f32> {
match self.depth {
1 => {
let rowb = w.div_ceil(8);
let mut out = Vec::with_capacity(w * h);
for y in 0..h {
for x in 0..w {
let b = raw.get(y * rowb + x / 8).copied().unwrap_or(0);
// 1 = black.
out.push(if b & (0x80 >> (x % 8)) != 0 { 0.0 } else { 1.0 });
}
}
out
}
16 => raw.chunks_exact(2).take(w * h).map(|c| u16::from_be_bytes([c[0], c[1]]) as f32 / 65535.0).collect(),
32 => raw.chunks_exact(4).take(w * h).map(|c| f32::from_be_bytes([c[0], c[1], c[2], c[3]])).collect(),
_ => raw.iter().take(w * h).map(|&b| b as f32 / 255.0).collect(),
}
}
/// Convert colour channels (in the document's mode) to RGB.
fn to_rgb(&self, ch: &[Option<Vec<f32>>], i: usize) -> [f32; 3] {
let g = |k: usize| ch.get(k).and_then(|c| c.as_ref()).map_or(0.0, |c| c[i]);
let rgb = match self.mode {
ColorMode::Rgb => [g(0), g(1), g(2)],
ColorMode::Cmyk => {
// Stored inverted (1 = no ink).
let k = g(3);
[g(0) * k, g(1) * k, g(2) * k]
}
ColorMode::Indexed if self.palette.len() >= 768 => {
let idx = (g(0) * 255.0).round() as usize & 255;
[self.palette[idx] as f32 / 255.0, self.palette[256 + idx] as f32 / 255.0, self.palette[512 + idx] as f32 / 255.0]
}
ColorMode::Lab => lab_to_rgb(g(0) * 100.0, g(1) * 255.0 - 128.0, g(2) * 255.0 - 128.0),
_ => [g(0); 3],
};
if self.depth == 32 && self.mode != ColorMode::Lab { rgb.map(srgb_encode) } else { rgb }
}
/// The merged (flattened) image.
pub fn composite(&self) -> Result<Pixels> {
let (w, h) = (self.width as usize, self.height as usize);
let mut r = Reader::at(&self.data, self.merged_offset);
let comp = r.u16()?;
let nch = self.channels as usize;
let cc = self.mode.color_channels();
let want = (cc + usize::from(self.merged_alpha)).min(nch);
let rowb = self.row_bytes(w);
let mut planes: Vec<Option<Vec<f32>>> = vec![None; nch];
match comp {
0 => {
for p in planes.iter_mut().take(want) {
*p = Some(self.samples(r.bytes(rowb * h)?, w, h));
}
}
1 => {
let mut counts = Vec::with_capacity(nch * h);
for _ in 0..nch * h {
counts.push(if self.psb { r.u32()? as usize } else { r.u16()? as usize });
}
for (c, p) in planes.iter_mut().enumerate().take(want) {
let mut out = Vec::with_capacity(rowb * h);
for row in 0..h {
unpack_bits(r.bytes(counts[c * h + row])?, rowb, &mut out)?;
}
*p = Some(self.samples(&out, w, h));
}
}
2 | 3 => {
let rest = r.bytes(r.remaining())?;
let v = miniz_oxide::inflate::decompress_to_vec_zlib(rest).map_err(|e| Error::Invalid(format!("zip: {e:?}")))?;
for (c, p) in planes.iter_mut().enumerate().take(want) {
let mut plane = v.get(c * rowb * h..(c + 1) * rowb * h).ok_or(Error::Truncated)?.to_vec();
if comp == 3 {
self.unpredict(&mut plane, w, h);
}
*p = Some(self.samples(&plane, w, h));
}
}
c => return Err(Error::Unsupported(format!("compression {c}"))),
}
let alpha = if self.merged_alpha && nch > cc { planes[cc].take() } else { None };
let mut data = Vec::with_capacity(w * h);
for i in 0..w * h {
let [r, g, b] = self.to_rgb(&planes, i);
let a = alpha.as_ref().map_or(1.0, |a| a[i]);
data.push([r, g, b, a]);
}
Ok(Pixels { width: w as u32, height: h as u32, data })
}
/// One layer's pixels with its layer mask (and vector-less fill colour) applied to alpha.
/// `canvas`: document-sized with the layer in place; otherwise the layer's own bounds.
pub fn layer_pixels(&self, index: usize, canvas: bool) -> Result<Pixels> {
let l = self.layers.get(index).ok_or_else(|| Error::Invalid(format!("no layer {index}")))?;
let doc = Rect { top: 0, left: 0, bottom: self.height as i32, right: self.width as i32 };
// Fill layers often have no pixel data: they cover the canvas (or the mask).
let fill_rect =
if l.fill.is_some() && !l.has_pixels() { l.mask.filter(|m| !m.rect.is_empty() && m.default_color == 0).map_or(doc, |m| m.rect) } else { l.rect };
let out_rect = if canvas {
doc
} else if fill_rect.is_empty() {
Rect { top: 0, left: 0, bottom: 1, right: 1 }
} else {
fill_rect
};
let (ow, oh) = (out_rect.width() as usize, out_rect.height() as usize);
let mut out = vec![[0.0f32; 4]; ow * oh];
let src = fill_rect;
let (sw, sh) = (src.width() as usize, src.height() as usize);
if sw > 0 && sh > 0 {
let mut planes: Vec<Option<Vec<f32>>> = vec![None; self.mode.color_channels()];
let mut alpha = None;
if l.has_pixels() {
for c in &l.channels {
match c.id {
-1 => alpha = Some(self.decode_channel(c.offset, c.len, sw, sh)?),
id if id >= 0 && (id as usize) < planes.len() => planes[id as usize] = Some(self.decode_channel(c.offset, c.len, sw, sh)?),
_ => {}
}
}
}
let fill = l.fill.map(|c| c.map(|v| v as f32));
for y in 0..sh {
let dy = src.top + y as i32 - out_rect.top;
if dy < 0 || dy >= oh as i32 {
continue;
}
for x in 0..sw {
let dx = src.left + x as i32 - out_rect.left;
if dx < 0 || dx >= ow as i32 {
continue;
}
let i = y * sw + x;
let (rgb, a) = match fill {
Some(f) if !l.has_pixels() => (f, 1.0),
_ => (self.to_rgb(&planes, i), alpha.as_ref().map_or(1.0, |a| a[i])),
};
out[dy as usize * ow + dx as usize] = [rgb[0], rgb[1], rgb[2], a];
}
}
}
// Layer mask: multiplies alpha (also outside the mask rect, by its default colour).
if let Some(m) = l.mask.filter(|m| !m.disabled) {
let mc = l.channels.iter().find(|c| c.id == -2);
let (mw, mh) = (m.rect.width() as usize, m.rect.height() as usize);
let mask = match mc {
Some(c) if mw > 0 && mh > 0 => Some(self.decode_channel(c.offset, c.len, mw, mh)?),
_ => None,
};
let def = m.default_color as f32 / 255.0;
for y in 0..oh {
let py = out_rect.top + y as i32;
for x in 0..ow {
let px = out_rect.left + x as i32;
let inside = py >= m.rect.top && py < m.rect.bottom && px >= m.rect.left && px < m.rect.right;
let mut v = match (&mask, inside) {
(Some(mk), true) => mk[(py - m.rect.top) as usize * mw + (px - m.rect.left) as usize],
_ => def,
};
if m.inverted {
v = 1.0 - v;
}
out[y * ow + x][3] *= v;
}
}
}
Ok(Pixels { width: ow as u32, height: oh as u32, data: out })
}
}
/// The next additional-information block at `*pos` (signature `8BIM`/`8B64`, key, length):
/// returns (key, data start, data end). Skips up to 3 padding bytes before a signature.
fn next_block(data: &[u8], pos: &mut usize, end: usize, psb: bool) -> Option<([u8; 4], usize, usize)> {
let mut p = *pos;
for _ in 0..4 {
if p + 12 > end {
return None;
}
if &data[p..p + 4] == b"8BIM" || &data[p..p + 4] == b"8B64" {
break;
}
p += 1;
}
if p + 12 > end || !(&data[p..p + 4] == b"8BIM" || &data[p..p + 4] == b"8B64") {
return None;
}
let mut key = [0u8; 4];
key.copy_from_slice(&data[p + 4..p + 8]);
let wide =
psb && matches!(&key, b"LMsk" | b"Lr16" | b"Lr32" | b"Layr" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD");
let mut r = Reader::at(&data[..end], p + 8);
let len = r.length(wide).ok()?;
let start = r.pos;
let stop = start.checked_add(len)?;
if stop > end {
return None;
}
*pos = stop;
Some((key, start, stop))
}
/// PackBits decoding of one row (appends exactly `row` bytes, zero-padded).
fn unpack_bits(src: &[u8], row: usize, out: &mut Vec<u8>) -> Result<()> {
let start = out.len();
let mut i = 0;
while i < src.len() && out.len() - start < row {
let n = src[i] as i8;
i += 1;
if n >= 0 {
let k = n as usize + 1;
let s = src.get(i..i + k).ok_or(Error::Truncated)?;
out.extend_from_slice(s);
i += k;
} else if n != -128 {
let k = (1 - n as isize) as usize;
let v = *src.get(i).ok_or(Error::Truncated)?;
out.extend(std::iter::repeat_n(v, k));
i += 1;
}
}
out.resize(start + row, 0);
Ok(())
}
/// PackBits encoding of one row.
pub(crate) fn pack_bits(src: &[u8]) -> Vec<u8> {
let mut out = vec![];
let mut i = 0;
while i < src.len() {
// run of identical bytes
let mut run = 1;
while i + run < src.len() && src[i + run] == src[i] && run < 128 {
run += 1;
}
if run >= 2 {
out.push((1 - run as isize) as i8 as u8);
out.push(src[i]);
i += run;
continue;
}
// literal run
let start = i;
let mut n = 0;
while i < src.len() && n < 128 {
if i + 1 < src.len() && src[i + 1] == src[i] {
break;
}
i += 1;
n += 1;
}
if n == 0 {
i += 1;
n = 1;
}
out.push((n - 1) as u8);
out.extend_from_slice(&src[start..start + n]);
}
out
}
fn srgb_encode(v: f32) -> f32 {
if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 }
}
/// CIE L*a*b* (D50) to sRGB (D65 via the Bradford-adapted matrix), clamped.
fn lab_to_rgb(l: f32, a: f32, b: f32) -> [f32; 3] {
let fy = (l + 16.0) / 116.0;
let fx = fy + a / 500.0;
let fz = fy - b / 200.0;
let f = |t: f32| if t > 6.0 / 29.0 { t * t * t } else { 3.0 * (6.0f32 / 29.0).powi(2) * (t - 4.0 / 29.0) };
let (x, y, z) = (0.964_22 * f(fx), f(fy), 0.825_21 * f(fz));
// XYZ (D50) → linear sRGB.
let r = 3.133_856 * x - 1.616_867 * y - 0.490_615 * z;
let g = -0.978_768 * x + 1.916_142 * y + 0.033_454 * z;
let bb = 0.071_945 * x - 0.228_991 * y + 1.405_243 * z;
[r, g, bb].map(|v| srgb_encode(v.clamp(0.0, 1.0)))
}
#[cfg(test)]
mod tests;
+86
View File
@@ -0,0 +1,86 @@
//! Big-endian byte reader.
use crate::{Error, Result};
#[derive(Clone)]
pub struct Reader<'a> {
pub data: &'a [u8],
pub pos: usize,
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Reader { data, pos: 0 }
}
pub fn at(data: &'a [u8], pos: usize) -> Self {
Reader { data, pos }
}
pub fn remaining(&self) -> usize {
self.data.len().saturating_sub(self.pos)
}
pub fn bytes(&mut self, n: usize) -> Result<&'a [u8]> {
if self.remaining() < n {
return Err(Error::Truncated);
}
let s = &self.data[self.pos..self.pos + n];
self.pos += n;
Ok(s)
}
pub fn skip(&mut self, n: usize) -> Result<()> {
self.bytes(n).map(|_| ())
}
pub fn u8(&mut self) -> Result<u8> {
Ok(self.bytes(1)?[0])
}
pub fn u16(&mut self) -> Result<u16> {
let b = self.bytes(2)?;
Ok(u16::from_be_bytes([b[0], b[1]]))
}
pub fn i16(&mut self) -> Result<i16> {
Ok(self.u16()? as i16)
}
pub fn u32(&mut self) -> Result<u32> {
let b = self.bytes(4)?;
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
pub fn i32(&mut self) -> Result<i32> {
Ok(self.u32()? as i32)
}
pub fn u64(&mut self) -> Result<u64> {
let b = self.bytes(8)?;
let mut a = [0u8; 8];
a.copy_from_slice(b);
Ok(u64::from_be_bytes(a))
}
pub fn f32(&mut self) -> Result<f32> {
Ok(f32::from_bits(self.u32()?))
}
pub fn f64(&mut self) -> Result<f64> {
Ok(f64::from_bits(self.u64()?))
}
pub fn tag(&mut self) -> Result<[u8; 4]> {
let b = self.bytes(4)?;
Ok([b[0], b[1], b[2], b[3]])
}
/// A length field: 4 bytes in PSD, 8 bytes in PSB (`wide`).
pub fn length(&mut self, wide: bool) -> Result<usize> {
let v = if wide { self.u64()? } else { self.u32()? as u64 };
usize::try_from(v).map_err(|_| Error::Invalid("length".into()))
}
/// A Pascal string padded so that length byte + text is a multiple of `pad`.
pub fn pascal(&mut self, pad: usize) -> Result<String> {
let n = self.u8()? as usize;
let s = self.bytes(n)?;
let total = 1 + n;
let padded = total.div_ceil(pad) * pad;
self.skip(padded - total)?;
// Pascal strings are in the system (Mac Roman) encoding; ASCII covers the common case.
Ok(s.iter().map(|&b| if b < 0x80 { b as char } else { mac_roman(b) }).collect())
}
}
/// Mac OS Roman upper half (0x80..=0xFF), as published by the Unicode Consortium mapping table.
fn mac_roman(b: u8) -> char {
const T: &str = "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ\u{F8FF}ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ";
T.chars().nth((b - 0x80) as usize).unwrap_or('?')
}
+189
View File
@@ -0,0 +1,189 @@
use super::write::*;
use super::*;
fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> {
(0..w * h).map(|i| [(i % w) as f32 / (w - 1).max(1) as f32, (i / w) as f32 / (h - 1).max(1) as f32, 0.25, 1.0]).collect()
}
fn close(a: &[[f32; 4]], b: &[[f32; 4]], tol: f32) -> bool {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (0..4).all(|c| (x[c] - y[c]).abs() <= tol))
}
fn doc_with_layers(depth: u16, mode: ColorMode, rle: bool) -> WDoc {
let mut d = WDoc::new(40, 30);
d.depth = depth;
d.mode = mode;
d.rle = rle;
let mut bg = WLayer::pixels("Background", Rect::new(0, 0, 40, 30), gradient(40, 30));
bg.opacity = 255;
let mut red = WLayer::solid("Red box", Rect::new(5, 6, 10, 8), [1.0, 0.0, 0.0, 1.0]).with_blend(b"mul ").with_opacity(128);
red.hidden = true;
let mut masked = WLayer::solid("Masked", Rect::new(20, 10, 12, 12), [0.0, 0.5, 1.0, 1.0]).with_blend(b"scrn");
// Mask: left half opaque, right half transparent; default (outside) black.
let mrect = Rect::new(20, 10, 12, 12);
masked.mask = Some(WMask { rect: mrect, data: (0..144).map(|i| if i % 12 < 6 { 1.0 } else { 0.0 }).collect(), default_color: 0, disabled: false });
d.layers = vec![bg, red, masked];
d
}
#[test]
fn layers_round_trip_8bit_rle() {
let bytes = write(&doc_with_layers(8, ColorMode::Rgb, true));
assert!(is_psd(&bytes));
let p = Psd::parse(bytes).unwrap();
assert_eq!((p.width, p.height, p.depth, p.mode), (40, 30, 8, ColorMode::Rgb));
assert_eq!(p.layers.len(), 3);
let names: Vec<&str> = p.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(names, ["Background", "Red box", "Masked"]);
assert_eq!(p.layers[1].blend_key(), "mul ");
assert_eq!(p.layers[1].opacity, 128);
assert!(p.layers[1].hidden && !p.layers[0].hidden);
assert_eq!(p.layers[2].blend_key(), "scrn");
assert_eq!(p.layers[1].rect, Rect::new(5, 6, 10, 8));
// Pixels (8-bit quantisation).
let bg = p.layer_pixels(0, false).unwrap();
assert!(close(&bg.data, &gradient(40, 30), 1.0 / 255.0));
// Retain layer size vs canvas.
let red = p.layer_pixels(1, false).unwrap();
assert_eq!((red.width, red.height), (10, 8));
let red_c = p.layer_pixels(1, true).unwrap();
assert_eq!((red_c.width, red_c.height), (40, 30));
assert_eq!(red_c.data[6 * 40 + 5], [1.0, 0.0, 0.0, 1.0]);
assert_eq!(red_c.data[0][3], 0.0);
// Layer mask becomes alpha.
let m = p.layer_pixels(2, false).unwrap();
assert_eq!(m.data[0][3], 1.0);
assert_eq!(m.data[11][3], 0.0);
// Merged composite.
let c = p.composite().unwrap();
assert_eq!((c.width, c.height), (40, 30));
assert!(p.merged_alpha);
}
#[test]
fn layers_round_trip_16bit_raw_and_cmyk_gray() {
for (depth, mode, rle) in
[(16, ColorMode::Rgb, false), (16, ColorMode::Rgb, true), (8, ColorMode::Cmyk, true), (16, ColorMode::Cmyk, false), (8, ColorMode::Grayscale, false)]
{
let bytes = write(&doc_with_layers(depth, mode, rle));
let p = Psd::parse(bytes).unwrap_or_else(|e| panic!("{depth} {mode:?} {rle}: {e}"));
assert_eq!(p.layers.len(), 3, "{depth} {mode:?}");
assert_eq!(p.depth, depth);
let bg = p.layer_pixels(0, true).unwrap();
let tol = if depth == 16 { 1.0 / 30000.0 } else { 1.5 / 255.0 };
let want: Vec<[f32; 4]> =
if mode == ColorMode::Grayscale { gradient(40, 30).iter().map(|p| [p[0], p[0], p[0], 1.0]).collect() } else { gradient(40, 30) };
assert!(close(&bg.data, &want, tol), "{depth} {mode:?} {rle}: {:?} vs {:?}", bg.data[41], want[41]);
let c = p.composite().unwrap();
assert_eq!(c.data.len(), 1200);
}
}
#[test]
fn groups_build_a_tree() {
let mut d = WDoc::new(16, 16);
d.layers = vec![
WLayer::solid("Bottom", Rect::new(0, 0, 16, 16), [1.0; 4]),
WLayer::group_end(),
WLayer::solid("Inner A", Rect::new(0, 0, 4, 4), [1.0, 0.0, 0.0, 1.0]),
WLayer::group_end(),
WLayer::solid("Deep", Rect::new(2, 2, 4, 4), [0.0, 1.0, 0.0, 1.0]),
WLayer::group("Nested", false, *b"norm"),
WLayer::group("Group 1", true, *b"pass"),
WLayer::solid("Top", Rect::new(8, 8, 4, 4), [0.0, 0.0, 1.0, 1.0]),
];
let p = Psd::parse(write(&d)).unwrap();
assert_eq!(p.layers[6].section, Section::OpenFolder);
assert_eq!(p.layers[6].blend_key(), "pass");
assert_eq!(p.layers[5].section, Section::ClosedFolder);
let t = p.tree();
assert_eq!(
t,
vec![
Node::Layer(7),
Node::Group { layer: 6, children: vec![Node::Group { layer: 5, children: vec![Node::Layer(4)] }, Node::Layer(2)] },
Node::Layer(0)
]
);
}
#[test]
fn text_effects_fill_and_adjustments() {
let mut d = WDoc::new(64, 32);
let fx = Descriptor::new("null").with("masterFXSwitch", DValue::Bool(true)).with(
"DrSh",
DValue::Descriptor(
Descriptor::new("DrSh")
.with("enab", DValue::Bool(true))
.with("Md ", DValue::Enum("BlnM".into(), "Mltp".into()))
.with("Clr ", DValue::Descriptor(Descriptor::rgb([0.0, 0.0, 1.0])))
.with("Opct", DValue::UnitFloat("#Prc".into(), 60.0))
.with("Dstn", DValue::UnitFloat("#Pxl".into(), 7.0)),
),
);
d.layers = vec![
WLayer::empty("Fill", vec![solid_color_block([0.0, 1.0, 0.0])]),
WLayer::empty("Title", vec![text_block("Hello\nWorld", [10.0, 20.0], "Inter-Bold", 18.0, [1.0, 0.0, 0.0], 2)]).with_block(effects_block(&fx)),
WLayer::empty("Hue", vec![hue_sat_block(30, -20, 10)]),
WLayer::empty("Lev", vec![levels_block(10, 240, 5, 250, 1.2)]),
WLayer::empty("Inv", vec![invert_block()]),
WLayer::empty("BC", vec![brightness_block(20, -10)]),
WLayer::empty("Exp", vec![exposure_block(1.5, 0.0, 1.0)]),
WLayer::solid("Vec", Rect::new(0, 0, 64, 32), [1.0; 4]).with_block(vector_mask_block(
&[vec![[[8.0, 4.0]; 3], [[40.0, 4.0]; 3], [[40.0, 20.0]; 3]]],
64,
32,
false,
)),
];
let p = Psd::parse(write(&d)).unwrap();
assert_eq!(p.layers[0].fill, Some([0.0, 1.0, 0.0]));
let fill = p.layer_pixels(0, false).unwrap();
assert_eq!((fill.width, fill.height), (64, 32));
assert_eq!(fill.data[5], [0.0, 1.0, 0.0, 1.0]);
let t = p.layers[1].text.as_ref().unwrap();
assert_eq!(t.text, "Hello\nWorld");
assert_eq!(t.transform[4..], [10.0, 20.0]);
assert_eq!(t.style.font.as_deref(), Some("Inter-Bold"));
assert_eq!(t.style.size, Some(18.0));
assert_eq!(t.style.color, Some([1.0, 0.0, 0.0]));
assert_eq!(t.style.justification, Some(2));
let e = p.layers[1].effects.as_ref().unwrap();
let ds = e.obj("DrSh").unwrap();
assert_eq!(ds.enum_value("Md "), Some("Mltp"));
assert_eq!(ds.num("Dstn"), Some(7.0));
assert_eq!(p.layers[2].adjustment, Some(Adjustment::HueSaturation { hue: 30.0, saturation: -20.0, lightness: 10.0, colorize: false }));
assert_eq!(p.layers[3].adjustment, Some(Adjustment::Levels { in_black: 10.0, in_white: 240.0, gamma: 1.2, out_black: 5.0, out_white: 250.0 }));
assert_eq!(p.layers[4].adjustment, Some(Adjustment::Invert));
assert_eq!(p.layers[5].adjustment, Some(Adjustment::BrightnessContrast { brightness: 20.0, contrast: -10.0, legacy: true }));
assert_eq!(p.layers[6].adjustment, Some(Adjustment::Exposure { exposure: 1.5, offset: 0.0, gamma: 1.0 }));
let vm = p.layers[7].vector_mask.as_ref().unwrap();
assert_eq!(vm.subpaths.len(), 1);
assert!(vm.subpaths[0].closed);
let k = &vm.subpaths[0].knots;
assert_eq!(k.len(), 3);
assert!((k[1][1][0] - 40.0).abs() < 1e-4 && (k[2][1][1] - 20.0).abs() < 1e-4);
}
#[test]
fn packbits_round_trip() {
for src in [vec![], vec![1u8], vec![5; 300], (0..=255).collect::<Vec<u8>>(), vec![1, 1, 2, 3, 3, 3, 4, 5, 5]] {
let enc = pack_bits(&src);
let mut out = vec![];
unpack_bits(&enc, src.len(), &mut out).unwrap();
assert_eq!(out, src);
}
}
#[test]
fn truncated_and_garbage_input_errors() {
let bytes = write(&doc_with_layers(8, ColorMode::Rgb, true));
for n in [0, 3, 10, 26, 40, 100, bytes.len() / 2] {
let r = Psd::parse(bytes[..n].to_vec());
if let Ok(p) = r {
let _ = p.composite();
}
}
assert!(Psd::parse(b"8BPS\0\x09garbage".to_vec()).is_err());
assert!(Psd::parse(b"PNG".to_vec()).is_err());
}
+491
View File
@@ -0,0 +1,491 @@
//! A minimal Photoshop document writer, per the same specification as the reader: RGB, CMYK or
//! Grayscale, 8 or 16 bits, raw or RLE channels, pixel layers with layer masks, groups and any
//! additional-information blocks (helpers below build text, effects, fill and adjustment
//! blocks). Used to generate test fixtures; not a full exporter.
use crate::descriptor::{self, DValue, Descriptor};
use crate::{ColorMode, Rect, Section, engine_data, pack_bits};
/// A layer mask for [`WLayer`].
#[derive(Clone, Debug)]
pub struct WMask {
pub rect: Rect,
/// `rect.width() * rect.height()` values in 0..1.
pub data: Vec<f32>,
pub default_color: u8,
pub disabled: bool,
}
/// A layer to write.
#[derive(Clone, Debug)]
pub struct WLayer {
pub name: String,
pub rect: Rect,
/// Straight RGBA, `rect.width() * rect.height()` pixels.
pub pixels: Vec<[f32; 4]>,
pub blend: [u8; 4],
pub opacity: u8,
pub hidden: bool,
pub clipping: bool,
pub mask: Option<WMask>,
pub section: Section,
/// Extra additional-information blocks (key, data).
pub blocks: Vec<([u8; 4], Vec<u8>)>,
}
impl WLayer {
/// A pixel layer.
pub fn pixels(name: &str, rect: Rect, pixels: Vec<[f32; 4]>) -> WLayer {
WLayer {
name: name.into(),
rect,
pixels,
blend: *b"norm",
opacity: 255,
hidden: false,
clipping: false,
mask: None,
section: Section::Layer,
blocks: vec![],
}
}
/// A layer filled with one colour.
pub fn solid(name: &str, rect: Rect, rgba: [f32; 4]) -> WLayer {
let n = (rect.width() * rect.height()) as usize;
WLayer::pixels(name, rect, vec![rgba; n])
}
/// The top record of a group (its children come *before* it in file order, after a
/// [`WLayer::group_end`]).
pub fn group(name: &str, open: bool, blend: [u8; 4]) -> WLayer {
let mut l = WLayer::pixels(name, Rect::default(), vec![]);
l.section = if open { Section::OpenFolder } else { Section::ClosedFolder };
l.blend = blend;
l
}
/// The hidden record that closes a group (written below its children).
pub fn group_end() -> WLayer {
let mut l = WLayer::pixels("</Layer group>", Rect::default(), vec![]);
l.section = Section::Divider;
l
}
/// A layer without pixels carrying `blocks` (adjustment and fill layers, type layers).
pub fn empty(name: &str, blocks: Vec<([u8; 4], Vec<u8>)>) -> WLayer {
let mut l = WLayer::pixels(name, Rect::default(), vec![]);
l.blocks = blocks;
l
}
pub fn with_blend(mut self, key: &[u8; 4]) -> WLayer {
self.blend = *key;
self
}
pub fn with_opacity(mut self, o: u8) -> WLayer {
self.opacity = o;
self
}
pub fn with_block(mut self, b: ([u8; 4], Vec<u8>)) -> WLayer {
self.blocks.push(b);
self
}
}
/// A document to write.
#[derive(Clone, Debug)]
pub struct WDoc {
pub width: u32,
pub height: u32,
/// 8 or 16.
pub depth: u16,
/// Rgb, Cmyk or Grayscale.
pub mode: ColorMode,
pub rle: bool,
/// Bottom of the stack first (file order).
pub layers: Vec<WLayer>,
/// Merged image (straight RGBA, document-sized); `None` composites visible pixel layers
/// with Normal blending.
pub composite: Option<Vec<[f32; 4]>>,
}
impl WDoc {
pub fn new(width: u32, height: u32) -> WDoc {
WDoc { width, height, depth: 8, mode: ColorMode::Rgb, rle: true, layers: vec![], composite: None }
}
}
fn u16b(out: &mut Vec<u8>, v: u16) {
out.extend_from_slice(&v.to_be_bytes());
}
fn u32b(out: &mut Vec<u8>, v: u32) {
out.extend_from_slice(&v.to_be_bytes());
}
/// Colour channels for a straight RGB pixel in the document mode.
fn mode_channels(mode: ColorMode, p: [f32; 4]) -> Vec<f32> {
match mode {
ColorMode::Cmyk => {
// Stored values are inverted ink amounts: k = max, c = r / max (reader: r = c * k).
let m = p[0].max(p[1]).max(p[2]);
if m <= 0.0 { vec![0.0, 0.0, 0.0, 0.0] } else { vec![p[0] / m, p[1] / m, p[2] / m, m] }
}
ColorMode::Grayscale => vec![p[0]],
_ => vec![p[0], p[1], p[2]],
}
}
fn encode_samples(v: &[f32], depth: u16) -> Vec<u8> {
let mut out = Vec::with_capacity(v.len() * if depth == 16 { 2 } else { 1 });
for &x in v {
let x = x.clamp(0.0, 1.0);
if depth == 16 {
u16b(&mut out, (x * 65535.0).round() as u16);
} else {
out.push((x * 255.0).round() as u8);
}
}
out
}
/// One channel's data (compression field + data) for a `w`×`h` plane.
fn channel_data(v: &[f32], w: usize, h: usize, depth: u16, rle: bool) -> Vec<u8> {
let raw = encode_samples(v, depth);
let mut out = vec![];
let rowb = raw.len() / h.max(1);
if !rle || w == 0 || h == 0 {
u16b(&mut out, 0);
out.extend_from_slice(&raw);
return out;
}
u16b(&mut out, 1);
let rows: Vec<Vec<u8>> = raw.chunks(rowb.max(1)).map(pack_bits).collect();
for r in &rows {
u16b(&mut out, r.len() as u16);
}
for r in rows {
out.extend_from_slice(&r);
}
out
}
fn pascal4(out: &mut Vec<u8>, s: &str) {
let b: Vec<u8> = s.bytes().map(|c| if c < 0x80 { c } else { b'?' }).take(255).collect();
out.push(b.len() as u8);
out.extend_from_slice(&b);
let total = 1 + b.len();
out.resize(out.len() + total.div_ceil(4) * 4 - total, 0);
}
fn block(out: &mut Vec<u8>, key: &[u8; 4], data: &[u8]) {
out.extend_from_slice(b"8BIM");
out.extend_from_slice(key);
let padded = data.len().div_ceil(2) * 2;
u32b(out, padded as u32);
out.extend_from_slice(data);
out.resize(out.len() + padded - data.len(), 0);
}
fn layer_info(doc: &WDoc) -> Vec<u8> {
let mut out = vec![];
out.extend_from_slice(&(-(doc.layers.len() as i16)).to_be_bytes());
let mut chan_data: Vec<Vec<(i16, Vec<u8>)>> = vec![];
for l in &doc.layers {
let (w, h) = (l.rect.width() as usize, l.rect.height() as usize);
let mut chans: Vec<(i16, Vec<u8>)> = vec![];
let n = w * h;
let alpha: Vec<f32> = l.pixels.iter().take(n).map(|p| p[3]).collect();
chans.push((-1, channel_data(&alpha, w, h, doc.depth, doc.rle)));
let cc = doc.mode.color_channels();
let planes: Vec<Vec<f32>> = l.pixels.iter().take(n).map(|p| mode_channels(doc.mode, *p)).collect();
for c in 0..cc {
let plane: Vec<f32> = planes.iter().map(|v| v[c]).collect();
chans.push((c as i16, channel_data(&plane, w, h, doc.depth, doc.rle)));
}
if let Some(m) = &l.mask {
chans.push((-2, channel_data(&m.data, m.rect.width() as usize, m.rect.height() as usize, doc.depth, doc.rle)));
}
// record
for v in [l.rect.top, l.rect.left, l.rect.bottom, l.rect.right] {
out.extend_from_slice(&v.to_be_bytes());
}
u16b(&mut out, chans.len() as u16);
for (id, d) in &chans {
out.extend_from_slice(&id.to_be_bytes());
u32b(&mut out, d.len() as u32);
}
out.extend_from_slice(b"8BIM");
out.extend_from_slice(&l.blend);
out.push(l.opacity);
out.push(l.clipping as u8);
let mut flags = 8u8;
if l.hidden {
flags |= 2;
}
out.push(flags);
out.push(0);
let mut extra = vec![];
match &l.mask {
Some(m) => {
u32b(&mut extra, 20);
for v in [m.rect.top, m.rect.left, m.rect.bottom, m.rect.right] {
extra.extend_from_slice(&v.to_be_bytes());
}
extra.push(m.default_color);
extra.push(if m.disabled { 2 } else { 0 });
extra.extend_from_slice(&[0, 0]);
}
None => u32b(&mut extra, 0),
}
u32b(&mut extra, 0); // blending ranges
pascal4(&mut extra, &l.name);
let luni = unicode_plain(&l.name);
block(&mut extra, b"luni", &luni);
match l.section {
Section::Layer => {}
s => {
let mut d = vec![];
u32b(
&mut d,
match s {
Section::OpenFolder => 1,
Section::ClosedFolder => 2,
_ => 3,
},
);
d.extend_from_slice(b"8BIM");
d.extend_from_slice(&l.blend);
block(&mut extra, b"lsct", &d);
}
}
for (k, d) in &l.blocks {
block(&mut extra, k, d);
}
u32b(&mut out, extra.len() as u32);
out.extend_from_slice(&extra);
chan_data.push(chans);
}
for chans in chan_data {
for (_, d) in chans {
out.extend_from_slice(&d);
}
}
if out.len() % 2 == 1 {
out.push(0);
}
out
}
fn unicode_plain(s: &str) -> Vec<u8> {
let v: Vec<u16> = s.encode_utf16().collect();
let mut out = vec![];
u32b(&mut out, v.len() as u32);
for c in v {
u16b(&mut out, c);
}
out
}
/// Normal "over" of the visible pixel layers (groups ignored), straight alpha.
fn flatten(doc: &WDoc) -> Vec<[f32; 4]> {
let (w, h) = (doc.width as i32, doc.height as i32);
let mut acc = vec![[0.0f32; 4]; (w * h) as usize];
for l in doc.layers.iter().filter(|l| !l.hidden && l.section == Section::Layer) {
let lw = l.rect.width() as i32;
for (i, p) in l.pixels.iter().enumerate() {
let (x, y) = (l.rect.left + i as i32 % lw.max(1), l.rect.top + i as i32 / lw.max(1));
if x < 0 || y < 0 || x >= w || y >= h {
continue;
}
let a = p[3] * l.opacity as f32 / 255.0;
let d = &mut acc[(y * w + x) as usize];
let oa = a + d[3] * (1.0 - a);
for c in 0..3 {
d[c] = if oa > 0.0 { (p[c] * a + d[c] * d[3] * (1.0 - a)) / oa } else { 0.0 };
}
d[3] = oa;
}
}
acc
}
/// Serialise a document.
pub fn write(doc: &WDoc) -> Vec<u8> {
let cc = doc.mode.color_channels();
let mut out = vec![];
out.extend_from_slice(b"8BPS");
u16b(&mut out, 1);
out.extend_from_slice(&[0; 6]);
u16b(&mut out, (cc + 1) as u16);
u32b(&mut out, doc.height);
u32b(&mut out, doc.width);
u16b(&mut out, doc.depth);
u16b(&mut out, doc.mode.to_u16());
u32b(&mut out, 0); // colour mode data
u32b(&mut out, 0); // image resources
// Layer and mask information.
let mut lm = vec![];
if !doc.layers.is_empty() {
let li = layer_info(doc);
if doc.depth == 16 {
u32b(&mut lm, 0);
u32b(&mut lm, 0); // global layer mask info
let mut padded = li;
while !padded.len().is_multiple_of(4) {
padded.push(0);
}
lm.extend_from_slice(b"8BIM");
lm.extend_from_slice(b"Lr16");
u32b(&mut lm, padded.len() as u32);
lm.extend_from_slice(&padded);
} else {
u32b(&mut lm, li.len() as u32);
lm.extend_from_slice(&li);
u32b(&mut lm, 0);
}
}
u32b(&mut out, lm.len() as u32);
out.extend_from_slice(&lm);
// Merged image.
let comp = doc.composite.clone().unwrap_or_else(|| flatten(doc));
let (w, h) = (doc.width as usize, doc.height as usize);
let planes: Vec<Vec<f32>> = comp.iter().map(|p| mode_channels(doc.mode, *p)).collect();
let mut chans: Vec<Vec<f32>> = (0..cc).map(|c| planes.iter().map(|v| v[c]).collect()).collect();
chans.push(comp.iter().map(|p| p[3]).collect());
if doc.rle {
u16b(&mut out, 1);
let rows: Vec<Vec<Vec<u8>>> =
chans.iter().map(|c| encode_samples(c, doc.depth).chunks((w * if doc.depth == 16 { 2 } else { 1 }).max(1)).map(pack_bits).collect()).collect();
for c in &rows {
for r in c {
u16b(&mut out, r.len() as u16);
}
}
for c in rows {
for r in c {
out.extend_from_slice(&r);
}
}
} else {
u16b(&mut out, 0);
for c in &chans {
out.extend_from_slice(&encode_samples(c, doc.depth));
}
}
let _ = h;
out
}
// ---------------------------------------------------------------- block helpers
/// `TySh`: a type layer with one style run; the text origin sits at `origin`.
pub fn text_block(text: &str, origin: [f64; 2], font: &str, size: f64, color: [f64; 3], justification: u8) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u16b(&mut d, 1);
for v in [1.0, 0.0, 0.0, 1.0, origin[0], origin[1]] {
d.extend_from_slice(&f64::to_be_bytes(v));
}
u16b(&mut d, 50);
u32b(&mut d, 16);
let desc = Descriptor::new("TxLr")
.with("Txt ", DValue::Text(text.replace('\n', "\r")))
.with("textGridding", DValue::Enum("textGridding".into(), "None".into()))
.with("Ornt", DValue::Enum("Ornt".into(), "Hrzn".into()))
.with("EngineData", DValue::Raw(engine_data::minimal(text, font, size, color, justification)));
descriptor::write_descriptor(&mut d, &desc);
// Warp: version, descriptor version, an empty warp descriptor.
u16b(&mut d, 1);
u32b(&mut d, 16);
descriptor::write_descriptor(&mut d, &Descriptor::new("warp").with("warpStyle", DValue::Enum("warpStyle".into(), "warpNone".into())));
for _ in 0..4 {
u32b(&mut d, 0);
}
(*b"TySh", d)
}
/// `lfx2`: layer effects from an effects descriptor (`null` class with `DrSh`, `FrFX`…).
pub fn effects_block(desc: &Descriptor) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u32b(&mut d, 0);
u32b(&mut d, 16);
descriptor::write_descriptor(&mut d, desc);
(*b"lfx2", d)
}
/// `SoCo`: solid colour fill.
pub fn solid_color_block(rgb: [f64; 3]) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u32b(&mut d, 16);
descriptor::write_descriptor(&mut d, &Descriptor::new("null").with("Clr ", DValue::Descriptor(Descriptor::rgb(rgb))));
(*b"SoCo", d)
}
/// `hue2`: Hue/Saturation (master).
pub fn hue_sat_block(hue: i16, sat: i16, light: i16) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u16b(&mut d, 2);
d.extend_from_slice(&[0, 0]);
for v in [0i16, 0, 0, hue, sat, light] {
d.extend_from_slice(&v.to_be_bytes());
}
// Six colour ranges (unused).
d.resize(d.len() + 6 * 24, 0);
(*b"hue2", d)
}
/// `levl`: Levels (composite record).
pub fn levels_block(in_black: i16, in_white: i16, out_black: i16, out_white: i16, gamma: f64) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u16b(&mut d, 2);
for v in [in_black, in_white, out_black, out_white, (gamma * 100.0).round() as i16] {
d.extend_from_slice(&v.to_be_bytes());
}
for _ in 0..28 {
for v in [0i16, 255, 0, 255, 100] {
d.extend_from_slice(&v.to_be_bytes());
}
}
(*b"levl", d)
}
pub fn invert_block() -> ([u8; 4], Vec<u8>) {
(*b"nvrt", vec![])
}
pub fn brightness_block(brightness: i16, contrast: i16) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
for v in [brightness, contrast, 127] {
d.extend_from_slice(&v.to_be_bytes());
}
d.push(0);
(*b"brit", d)
}
pub fn exposure_block(exposure: f32, offset: f32, gamma: f32) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u16b(&mut d, 1);
for v in [exposure, offset, gamma] {
d.extend_from_slice(&v.to_be_bytes());
}
(*b"expA", d)
}
/// `vmsk`: a vector mask from closed polygons/curves given as (in, anchor, out) knots in pixels.
pub fn vector_mask_block(subpaths: &[Vec<[[f64; 2]; 3]>], width: u32, height: u32, inverted: bool) -> ([u8; 4], Vec<u8>) {
let mut d = vec![];
u32b(&mut d, 3);
u32b(&mut d, inverted as u32);
// Path fill rule record.
u16b(&mut d, 6);
d.resize(d.len() + 24, 0);
let fx = |v: f64| ((v * (1 << 24) as f64).round() as i32).to_be_bytes();
for sp in subpaths {
u16b(&mut d, 0);
u16b(&mut d, sp.len() as u16);
d.resize(d.len() + 22, 0);
for k in sp {
u16b(&mut d, 1);
for p in k {
d.extend_from_slice(&fx(p[1] / height as f64));
d.extend_from_slice(&fx(p[0] / width as f64));
}
}
}
(*b"vmsk", d)
}