mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 17:27:19 +00:00
Merge storytold next into next-workspace-ci
This commit is contained in:
@@ -20,6 +20,9 @@ jobs:
|
||||
uses: storytold/craft-common-actions/.github/workflows/sonarcloud.yml@main
|
||||
with:
|
||||
pdf-test-fonts: true
|
||||
# The instrumented build runs without a dependency cache: its 1.2 GB entry does not fit the
|
||||
# repository's 10 GB cache budget beside the Workspace gate's. It runs on main only.
|
||||
build-cache: false
|
||||
# The codec and format code behind features that are off by default. Without these the
|
||||
# coverage build never compiles it, and new code there reads as untested.
|
||||
cargo-features: >-
|
||||
|
||||
Generated
+9
@@ -1902,6 +1902,7 @@ dependencies = [
|
||||
"craft-smime",
|
||||
"craft-sniff",
|
||||
"craft-sourcemap",
|
||||
"craft-sqlite",
|
||||
"craft-ssip",
|
||||
"craft-stencilcraft-document",
|
||||
"craft-stencilcraft-format",
|
||||
@@ -2319,11 +2320,13 @@ dependencies = [
|
||||
name = "craft-develop"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"craft-color-transform",
|
||||
"craft-develop-model",
|
||||
"craft-render-parity",
|
||||
"proptest",
|
||||
"rayon",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2644,6 +2647,7 @@ dependencies = [
|
||||
"craft-dxf",
|
||||
"craft-eps",
|
||||
"craft-file-formats",
|
||||
"craft-image-codecs",
|
||||
"craft-pdf 0.1.0",
|
||||
"craft-raster-codecs",
|
||||
"craft-svg",
|
||||
@@ -3954,6 +3958,10 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-sqlite"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "craft-ssip"
|
||||
version = "0.1.0"
|
||||
@@ -4457,6 +4465,7 @@ dependencies = [
|
||||
name = "craft-usd"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"half",
|
||||
"lz4_flex",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
@@ -21,6 +21,7 @@ craft-xfdf = { path = "crates/xfdf" }
|
||||
craft-jsonc = { path = "crates/jsonc" }
|
||||
craft-palette = { path = "crates/palette" }
|
||||
craft-score = { path = "crates/score" }
|
||||
craft-sqlite = { path = "crates/sqlite" }
|
||||
craft-shx = { path = "crates/shx" }
|
||||
craft-http-url = { path = "crates/http-url" }
|
||||
craft-usd = { path = "crates/usd" }
|
||||
|
||||
@@ -34,7 +34,12 @@ struct EnvelopeOut<'a, P, T> {
|
||||
|
||||
/// Serializes the envelope in its stable wire order and uses AniCraft's compact/pretty threshold.
|
||||
pub fn write<P: Serialize, T: Serialize>(generator: &str, paths: &[P], document: &T) -> Result<String, serde_json::Error> {
|
||||
let envelope = EnvelopeOut { format: FORMAT_NAME, version: FORMAT_VERSION, generator, paths, document };
|
||||
write_version(FORMAT_VERSION, generator, paths, document)
|
||||
}
|
||||
|
||||
/// Serializes the envelope with an explicit format version and AniCraft's compact/pretty threshold.
|
||||
pub fn write_version<P: Serialize, T: Serialize>(version: u32, generator: &str, paths: &[P], document: &T) -> Result<String, serde_json::Error> {
|
||||
let envelope = EnvelopeOut { format: FORMAT_NAME, version, generator, paths, document };
|
||||
let compact = serde_json::to_string(&envelope)?;
|
||||
if compact.len() < PRETTY_LIMIT { serde_json::to_string_pretty(&envelope) } else { Ok(compact) }
|
||||
}
|
||||
|
||||
@@ -240,4 +240,24 @@ mod tests {
|
||||
assert_eq!(xy_to_temp_tint(p), (6500.0, 0.0), "{p:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Pins the current behavior for warm, strongly green illuminants (e.g. 2000–3500 K with high
|
||||
/// positive tint) where the source white's Bradford blue cone response is `<= 0.0`. The
|
||||
/// checked Bradford path currently returns `Mat3::IDENTITY` there (so `wb_matrix` is
|
||||
/// `REC2020.from_xyz() * REC2020.to_xyz()`, i.e. identity within `f64` rounding) rather than
|
||||
/// inverting blue; final `#587` process-version policy for this region remains open.
|
||||
#[test]
|
||||
fn warm_green_wb_with_non_positive_cone_response_returns_identity() {
|
||||
for (t, tint) in [(2000.0, 30.0), (2500.0, 60.0), (3000.0, 100.0), (3500.0, 125.0)] {
|
||||
let src = temp_tint_to_xy(t, tint);
|
||||
assert_eq!(crate::bradford(src, REC2020.white), Mat3::IDENTITY, "{t} K tint {tint}");
|
||||
let m = wb_matrix(&REC2020, src);
|
||||
for (i, row) in m.0.iter().enumerate() {
|
||||
for (j, &val) in row.iter().enumerate() {
|
||||
let want = if i == j { 1.0 } else { 0.0 };
|
||||
assert!((val - want).abs() < 1e-12, "{t} K tint {tint} [{i}][{j}] = {val}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,6 +225,32 @@ impl Lut1 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Resample this table to `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]).
|
||||
pub fn resample(&self, n: usize) -> Lut1 {
|
||||
let n = n.clamp(2, MAX_LUT);
|
||||
if self.v.len() == n {
|
||||
return self.clone();
|
||||
}
|
||||
Lut1::from_fn(n, |x| self.eval(x))
|
||||
}
|
||||
|
||||
/// `self ∘ inner` sampled at `n` evenly spaced entries over `0..1` (2 to [`MAX_LUT`]).
|
||||
///
|
||||
/// Preserves fixed-size GPU LUT contracts (such as 1,024-entry shader tables) where
|
||||
/// [`Lut1::compose`] would expand to the common refinement grid. When `inner` is empty it
|
||||
/// resamples `self` to `n` entries; when `inner` already has `n` entries it evaluates `self`
|
||||
/// directly at each of `inner`'s samples.
|
||||
pub fn compose_len(&self, inner: &Lut1, n: usize) -> Lut1 {
|
||||
let n = n.clamp(2, MAX_LUT);
|
||||
if inner.v.is_empty() {
|
||||
return self.resample(n);
|
||||
}
|
||||
if inner.v.len() == n {
|
||||
return Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() };
|
||||
}
|
||||
Lut1::from_fn(n, |x| self.eval(inner.eval(x)))
|
||||
}
|
||||
|
||||
pub fn is_identity(&self) -> bool {
|
||||
let n = self.v.len();
|
||||
n >= 2 && self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6)
|
||||
@@ -319,6 +345,21 @@ mod tests {
|
||||
assert_eq!(a.compose(&Lut1 { v: vec![] }), a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compose_len_preserves_fixed_gpu_lut_size() {
|
||||
const N: usize = 1024;
|
||||
let a = Lut1::from_fn(N, |x| x * x);
|
||||
let b = Lut1::from_fn(N, f32::sqrt);
|
||||
let c = a.compose_len(&b, N);
|
||||
assert_eq!(c.v.len(), N);
|
||||
assert!((c.eval(0.3) - 0.3).abs() < 2e-3);
|
||||
assert_eq!(a.compose_len(&Lut1 { v: vec![] }, N), a);
|
||||
let small = Lut1::from_fn(17, f32::sqrt);
|
||||
let d = a.compose_len(&small, N);
|
||||
assert_eq!(d.v.len(), N);
|
||||
assert!((d.eval(0.3) - a.eval(small.eval(0.3))).abs() < 2e-3);
|
||||
}
|
||||
|
||||
/// A short `inner` does not drop the outer table's points between its own.
|
||||
#[test]
|
||||
fn composing_with_a_short_table_keeps_the_outer_curve() {
|
||||
|
||||
@@ -18,4 +18,6 @@ pub mod oklab;
|
||||
mod space;
|
||||
pub mod tonemap;
|
||||
|
||||
pub use space::{BRADFORD, D50, D65, DISPLAY_P3, Mat3, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz};
|
||||
pub use space::{
|
||||
ADOBE_RGB, BRADFORD, D50, D65, DISPLAY_P3, Mat3, PROPHOTO, REC601_525, REC601_625, REC2020, RgbSpace, SRGB, Xy, bradford, bradford_xyz,
|
||||
};
|
||||
|
||||
@@ -118,6 +118,11 @@ pub const REC601_525: RgbSpace = RgbSpace { r: Xy::new(0.630, 0.340), g: Xy::new
|
||||
pub const REC2020: RgbSpace = RgbSpace { r: Xy::new(0.708, 0.292), g: Xy::new(0.170, 0.797), b: Xy::new(0.131, 0.046), white: D65 };
|
||||
/// The DCI-P3 primaries with a D65 white (SMPTE EG 432-1).
|
||||
pub const DISPLAY_P3: RgbSpace = RgbSpace { r: Xy::new(0.680, 0.320), g: Xy::new(0.265, 0.690), b: Xy::new(0.150, 0.060), white: D65 };
|
||||
/// ProPhoto RGB (ROMM RGB, ISO 22028-2) primaries with a D50 white.
|
||||
pub const PROPHOTO: RgbSpace =
|
||||
RgbSpace { r: Xy::new(0.734699, 0.265301), g: Xy::new(0.159597, 0.840403), b: Xy::new(0.036598, 0.000105), white: D50 };
|
||||
/// The 1998 Adobe RGB primaries with a D65 white.
|
||||
pub const ADOBE_RGB: RgbSpace = RgbSpace { r: Xy::new(0.64, 0.33), g: Xy::new(0.21, 0.71), b: Xy::new(0.15, 0.06), white: D65 };
|
||||
|
||||
impl From<Primaries> for RgbSpace {
|
||||
fn from(p: Primaries) -> RgbSpace {
|
||||
@@ -292,4 +297,16 @@ mod tests {
|
||||
let m: [[f64; 3]; 3] = read.to_xyz().into();
|
||||
assert_eq!(Mat3::from(m), read.to_xyz());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prophoto_and_adobe_rgb_map_white_and_roundtrip() {
|
||||
for sp in [PROPHOTO, ADOBE_RGB] {
|
||||
let w = sp.to_space(&REC2020).apply([1.0, 1.0, 1.0]);
|
||||
assert!(w.iter().all(|c| (c - 1.0).abs() < 1e-3), "{sp:?} -> {w:?}");
|
||||
}
|
||||
let a = SRGB.to_space(&PROPHOTO);
|
||||
let b = PROPHOTO.to_space(&SRGB);
|
||||
let v = b.apply(a.apply([0.2, 0.5, 0.9]));
|
||||
assert!((v[0] - 0.2).abs() < 1e-9 && (v[1] - 0.5).abs() < 1e-9 && (v[2] - 0.9).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,6 +220,7 @@ craft-gpu-providers = { workspace = true, optional = true }
|
||||
craft-gpu-wgpu = { workspace = true, optional = true }
|
||||
craft-ipp = { workspace = true, optional = true }
|
||||
craft-ppt-binary = { workspace = true, optional = true }
|
||||
craft-sqlite = { workspace = true, optional = true }
|
||||
|
||||
[features]
|
||||
ui = [
|
||||
@@ -509,6 +510,7 @@ heif-testdata = ["heif", "craft-heif/testdata"]
|
||||
|
||||
html = ["dep:craft-html"]
|
||||
html-flow = ["html", "craft-html/flow"]
|
||||
html-standalone = ["html", "craft-html/standalone"]
|
||||
|
||||
http-url = ["dep:craft-http-url"]
|
||||
|
||||
@@ -596,6 +598,8 @@ media-source = ["dep:craft-media-source"]
|
||||
menu = ["dep:craft-menu"]
|
||||
|
||||
mesh = ["dep:craft-mesh"]
|
||||
mesh-abc = ["mesh", "craft-mesh/abc"]
|
||||
mesh-dae = ["mesh", "craft-mesh/dae"]
|
||||
mesh-fbx = ["mesh", "craft-mesh/fbx"]
|
||||
mesh-gltf = ["mesh", "craft-mesh/gltf"]
|
||||
mesh-obj = ["mesh", "craft-mesh/obj"]
|
||||
@@ -643,6 +647,7 @@ pdf-content = ["pdf", "craft-pdf/content"]
|
||||
pdf-cos = ["pdf", "craft-pdf/cos"]
|
||||
pdf-crypt = ["pdf", "craft-pdf/crypt"]
|
||||
pdf-filters = ["pdf", "craft-pdf/filters"]
|
||||
pdf-fonts = ["pdf", "craft-pdf/fonts"]
|
||||
pdf-interpret = ["pdf", "craft-pdf/interpret"]
|
||||
pdf-paths = ["pdf", "craft-pdf/paths"]
|
||||
pdf-raster = ["pdf", "craft-pdf/raster"]
|
||||
@@ -763,6 +768,8 @@ sniff = ["dep:craft-sniff"]
|
||||
|
||||
sourcemap = ["dep:craft-sourcemap"]
|
||||
|
||||
sqlite = ["dep:craft-sqlite"]
|
||||
|
||||
ssip = ["dep:craft-ssip"]
|
||||
|
||||
stencilcraft-document = ["dep:craft-stencilcraft-document"]
|
||||
|
||||
@@ -333,6 +333,8 @@ pub use craft_smime as smime;
|
||||
pub use craft_sniff as sniff;
|
||||
#[cfg(feature = "sourcemap")]
|
||||
pub use craft_sourcemap as sourcemap;
|
||||
#[cfg(feature = "sqlite")]
|
||||
pub use craft_sqlite as sqlite;
|
||||
#[cfg(feature = "ssip")]
|
||||
pub use craft_ssip as ssip;
|
||||
#[cfg(feature = "stencilcraft-document")]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,107 @@
|
||||
//! ETC1 and EAC 4×4 block decoders.
|
||||
//!
|
||||
//! EAC's 11-bit channel blocks are reduced to display bytes after reconstruction and clamping.
|
||||
//! The signed layouts map -1..1 to 0..255 so negative values remain visible; zero is 128.
|
||||
//! Layout and modifier tables: <https://registry.khronos.org/DataFormat/specs/1.4/dataformat.1.4.html>.
|
||||
|
||||
// Positive halves of the Khronos EAC modifier tables. Negative entries are -positive - 1.
|
||||
const MODIFIERS: [[i16; 4]; 16] = [
|
||||
[2, 5, 8, 14],
|
||||
[2, 6, 9, 12],
|
||||
[1, 4, 7, 12],
|
||||
[1, 3, 5, 12],
|
||||
[2, 5, 7, 11],
|
||||
[2, 6, 8, 10],
|
||||
[3, 6, 7, 10],
|
||||
[2, 4, 7, 10],
|
||||
[1, 5, 7, 9],
|
||||
[1, 4, 7, 9],
|
||||
[1, 3, 7, 9],
|
||||
[1, 4, 6, 9],
|
||||
[2, 3, 6, 9],
|
||||
[0, 1, 2, 9],
|
||||
[3, 5, 7, 8],
|
||||
[2, 4, 6, 8],
|
||||
];
|
||||
|
||||
fn split_halves(block: &[u8; 16]) -> ([u8; 8], [u8; 8]) {
|
||||
let mut first = [0u8; 8];
|
||||
let mut second = [0u8; 8];
|
||||
for (i, x) in block.iter().enumerate() {
|
||||
if i < 8 {
|
||||
first[i] = *x;
|
||||
} else {
|
||||
second[i - 8] = *x;
|
||||
}
|
||||
}
|
||||
(first, second)
|
||||
}
|
||||
|
||||
/// ETC1 uses big-endian blocks and column-major selector bits, independently of the split.
|
||||
/// Differential bases outside RGB555 are undefined by the format and are refused.
|
||||
pub(crate) fn etc1(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> {
|
||||
const ETC1_MODIFIERS: [[i16; 2]; 8] = [[2, 8], [5, 17], [9, 29], [13, 42], [18, 60], [24, 80], [33, 106], [47, 183]];
|
||||
let bits = u64::from_be_bytes(*block);
|
||||
let differential = bits & (1 << 33) != 0;
|
||||
let horizontal = bits & (1 << 32) != 0;
|
||||
let mut bases = [[0i16; 3]; 2];
|
||||
for (channel, shift) in [56, 48, 40].into_iter().enumerate() {
|
||||
let value = ((bits >> shift) & 255) as i16;
|
||||
let (first, second) = if differential {
|
||||
let first = value >> 3;
|
||||
let delta = ((value & 7) ^ 4) - 4;
|
||||
let second = first + delta;
|
||||
if !(0..=31).contains(&second) {
|
||||
return None;
|
||||
}
|
||||
((first << 3) | (first >> 2), (second << 3) | (second >> 2))
|
||||
} else {
|
||||
((value >> 4) * 17, (value & 15) * 17)
|
||||
};
|
||||
bases[0][channel] = first;
|
||||
bases[1][channel] = second;
|
||||
}
|
||||
let first_table = ETC1_MODIFIERS.get(((bits >> 37) & 7) as usize)?;
|
||||
let second_table = ETC1_MODIFIERS.get(((bits >> 34) & 7) as usize)?;
|
||||
Some(std::array::from_fn(|pixel| {
|
||||
let (x, y) = (pixel % 4, pixel / 4);
|
||||
let second = if horizontal { y >= 2 } else { x >= 2 };
|
||||
let (base, table) = if second { (bases[1], second_table) } else { (bases[0], first_table) };
|
||||
let selector = x * 4 + y;
|
||||
let magnitude = if bits & (1 << selector) == 0 { table[0] } else { table[1] };
|
||||
let delta = if bits & (1 << (selector + 16)) == 0 { magnitude } else { -magnitude };
|
||||
let rgb = base.map(|channel| (channel + delta).clamp(0, 255) as u8);
|
||||
[rgb[0], rgb[1], rgb[2], 255]
|
||||
}))
|
||||
}
|
||||
|
||||
fn channel(block: &[u8; 8], signed: bool) -> [u8; 16] {
|
||||
let bits = u64::from_be_bytes(*block);
|
||||
let base = if signed { i16::from((block[0] as i8).max(-127)) * 8 } else { i16::from(block[0]) * 8 + 4 };
|
||||
let scale = (i16::from(block[1] >> 4) * 8).max(1);
|
||||
let table = MODIFIERS.get(usize::from(block[1] & 15)).copied().unwrap_or_default();
|
||||
std::array::from_fn(|pixel| {
|
||||
let (x, y) = (pixel % 4, pixel / 4);
|
||||
let selector = ((bits >> (45 - 3 * (x * 4 + y))) & 7) as usize;
|
||||
let magnitude = table.get(selector & 3).copied().unwrap_or_default();
|
||||
let modifier = if selector < 4 { -magnitude - 1 } else { magnitude };
|
||||
let value = base + modifier * scale;
|
||||
if signed {
|
||||
let value = u32::try_from(value.clamp(-1023, 1023) + 1023).unwrap_or_default();
|
||||
((value * 255 + 1023) / 2046) as u8
|
||||
} else {
|
||||
let value = u32::try_from(value.clamp(0, 2047)).unwrap_or_default();
|
||||
((value * 255 + 1023) / 2047) as u8
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn scalar(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] {
|
||||
channel(block, signed).map(|value| [value, value, value, 255])
|
||||
}
|
||||
|
||||
pub(crate) fn dual(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
|
||||
let (red, green) = split_halves(block);
|
||||
let (red, green) = (channel(&red, signed), channel(&green, signed));
|
||||
std::array::from_fn(|pixel| [red[pixel], green[pixel], 0, 255])
|
||||
}
|
||||
@@ -39,6 +39,10 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
mod bc;
|
||||
pub mod bptc;
|
||||
mod eac;
|
||||
mod packed;
|
||||
pub mod pixels;
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::fmt;
|
||||
@@ -84,6 +88,8 @@ pub enum DdsError {
|
||||
Alloc(usize),
|
||||
/// The decoded output exceeds the caller-selected per-buffer byte limit.
|
||||
LimitExceeded { required: usize, limit: u64 },
|
||||
/// Input pixel data ended before the declared dimensions or block count.
|
||||
Truncated(String),
|
||||
}
|
||||
|
||||
impl fmt::Display for DdsError {
|
||||
@@ -94,6 +100,7 @@ impl fmt::Display for DdsError {
|
||||
DdsError::Encode(reason) => write!(f, "DDS encode failed: {reason}"),
|
||||
DdsError::Alloc(len) => write!(f, "cannot allocate {len} bytes for the texture"),
|
||||
DdsError::LimitExceeded { required, limit } => write!(f, "decoded texture requires {required} bytes, exceeding limit {limit}"),
|
||||
DdsError::Truncated(reason) => write!(f, "truncated pixel data: {reason}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Four-byte packed RGB layouts. Words are little-endian, with red in the low bits.
|
||||
//! Unsigned floats: <https://registry.khronos.org/DataFormat/specs/1.4/dataformat.1.4.html>, sections 10.2 and 10.3.
|
||||
|
||||
use crate::bptc;
|
||||
|
||||
pub(crate) fn rgba1010102(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
let word = u32::from_le_bytes(*bytes);
|
||||
let channel = |shift: u32| (((word >> shift) & 1023) * 255 + 511) / 1023;
|
||||
[channel(0) as u8, channel(10) as u8, channel(20) as u8, (word >> 30) as u8 * 85]
|
||||
}
|
||||
|
||||
// These unsigned formats share binary16's five-bit exponent and bias. Padding the
|
||||
// six- or five-bit fraction with zeroes produces the same value in a positive half.
|
||||
fn unsigned_float(bits: u16, padding: u32) -> f32 {
|
||||
bptc::half(bits << padding)
|
||||
}
|
||||
|
||||
pub(crate) fn rgb111110(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
let word = u32::from_le_bytes(*bytes);
|
||||
let channel = |shift: u32, mask: u32, padding: u32| bptc::srgb8(unsigned_float(((word >> shift) & mask) as u16, padding));
|
||||
[channel(0, 0x7ff, 4), channel(11, 0x7ff, 4), channel(22, 0x3ff, 5), 255]
|
||||
}
|
||||
|
||||
pub(crate) fn rgb9e5(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
let packed = u32::from_le_bytes(*bytes);
|
||||
let scale = 2.0f32.powi((packed >> 27) as i32 - 24);
|
||||
let channel = |shift: u32| bptc::srgb8(((packed >> shift) & 0x1ff) as f32 * scale);
|
||||
[channel(0), channel(9), channel(18), 255]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::unsigned_float;
|
||||
|
||||
#[test]
|
||||
fn unsigned_float_boundaries_are_preserved_before_display_quantization() {
|
||||
for (fraction_bits, padding, smallest, largest_subnormal, maximum) in
|
||||
[(6, 4, 0x3580_0000, 0x387c_0000, 65024.0), (5, 5, 0x3600_0000, 0x3878_0000, 64512.0)]
|
||||
{
|
||||
let fractions = 1u16 << fraction_bits;
|
||||
assert_eq!(unsigned_float(0, padding).to_bits(), 0);
|
||||
assert_eq!(unsigned_float(1, padding).to_bits(), smallest);
|
||||
assert_eq!(unsigned_float(fractions - 1, padding).to_bits(), largest_subnormal);
|
||||
assert_eq!(unsigned_float(fractions, padding).to_bits(), 0x3880_0000);
|
||||
assert_eq!(unsigned_float(31 * fractions - 1, padding), maximum);
|
||||
assert_eq!(unsigned_float(31 * fractions, padding), f32::INFINITY);
|
||||
assert!(unsigned_float(31 * fractions + 1, padding).is_nan());
|
||||
assert!(unsigned_float(32 * fractions - 1, padding).is_nan());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//! Turning GPU textures' stored pixels into RGBA: uncompressed layouts, packed 32-bit layouts,
|
||||
//! and 4×4 block formats (BC1–BC7, ETC1, and EAC). Rows come out in the order they're stored.
|
||||
|
||||
use crate::{DdsError, alloc_zeroed, bc, bptc, eac, packed, with_alpha};
|
||||
|
||||
/// Default RGBA output budget: 256 MiB, matching an 8192×8192 RGBA8 texture.
|
||||
pub const DEFAULT_MAX_RGBA_BYTES: u64 = 256 << 20;
|
||||
|
||||
/// How a texture's pixels are laid out.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PixelLayout {
|
||||
/// Alpha only (shown as white with that alpha).
|
||||
Alpha8,
|
||||
/// One grey channel.
|
||||
R8,
|
||||
/// One unsigned 16-bit channel, shown as grey.
|
||||
R16,
|
||||
/// Two unsigned 8-bit channels; blue is zero and alpha is opaque.
|
||||
Rg8,
|
||||
/// Two unsigned 16-bit channels; blue is zero and alpha is opaque.
|
||||
Rg16,
|
||||
/// Three unsigned 16-bit channels; alpha is opaque.
|
||||
Rgb16,
|
||||
/// Four unsigned 16-bit channels, including alpha.
|
||||
Rgba16,
|
||||
RHalf,
|
||||
RgHalf,
|
||||
RgbaHalf,
|
||||
RFloat,
|
||||
RgFloat,
|
||||
RgbaFloat,
|
||||
/// Nine-bit RGB mantissas with a shared five-bit exponent, displayed as opaque sRGB.
|
||||
Rgb9e5,
|
||||
/// Packed unsigned 10-bit RGB with two-bit alpha, low bits first.
|
||||
Rgba1010102,
|
||||
/// Packed unsigned 11/11/10-bit floating-point RGB, displayed as opaque sRGB.
|
||||
Rgb111110Float,
|
||||
Rgb24,
|
||||
Rgba32,
|
||||
Argb32,
|
||||
Bgra32,
|
||||
Rgb565,
|
||||
Rgba4444,
|
||||
Argb4444,
|
||||
/// BC1 / DXT1.
|
||||
Dxt1,
|
||||
/// BC2 / DXT3: four-colour blocks with one explicit four-bit alpha value per texel.
|
||||
Dxt3,
|
||||
/// BC3 / DXT5.
|
||||
Dxt5,
|
||||
/// One channel in blocks (shown as grey).
|
||||
Bc4,
|
||||
/// Two channels in blocks, usually a normal map (blue is rebuilt from red and green).
|
||||
Bc5,
|
||||
/// High dynamic range RGB in blocks (unsigned half floats), tone-mapped to 8-bit sRGB.
|
||||
Bc6h,
|
||||
/// BC6H with signed half floats.
|
||||
Bc6hSigned,
|
||||
Bc7,
|
||||
/// ETC1 RGB, with individual or differential base colours.
|
||||
Etc1,
|
||||
/// One EAC channel, shown as grey.
|
||||
EacR,
|
||||
/// One signed EAC channel; -1..1 maps to 0..255.
|
||||
EacRSigned,
|
||||
/// Two EAC channels; blue is zero and alpha is opaque.
|
||||
EacRg,
|
||||
/// Two signed EAC channels; -1..1 maps to 0..255.
|
||||
EacRgSigned,
|
||||
}
|
||||
|
||||
/// Bytes of a `width`×`height` picture in `layout`.
|
||||
pub fn size(layout: PixelLayout, width: u32, height: u32) -> Option<usize> {
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let blocks = w.div_ceil(4).checked_mul(h.div_ceil(4))?;
|
||||
match layout {
|
||||
PixelLayout::Alpha8 | PixelLayout::R8 => w.checked_mul(h),
|
||||
PixelLayout::Rgb565 | PixelLayout::Rgba4444 | PixelLayout::Argb4444 | PixelLayout::RHalf | PixelLayout::R16 | PixelLayout::Rg8 => {
|
||||
w.checked_mul(h)?.checked_mul(2)
|
||||
}
|
||||
PixelLayout::Rgb24 => w.checked_mul(h)?.checked_mul(3),
|
||||
PixelLayout::Rg16 => w.checked_mul(h)?.checked_mul(4),
|
||||
PixelLayout::Rgb16 => w.checked_mul(h)?.checked_mul(6),
|
||||
PixelLayout::Rgba16 => w.checked_mul(h)?.checked_mul(8),
|
||||
PixelLayout::Rgba32
|
||||
| PixelLayout::Argb32
|
||||
| PixelLayout::Bgra32
|
||||
| PixelLayout::RgHalf
|
||||
| PixelLayout::RFloat
|
||||
| PixelLayout::Rgb9e5
|
||||
| PixelLayout::Rgba1010102
|
||||
| PixelLayout::Rgb111110Float => w.checked_mul(h)?.checked_mul(4),
|
||||
PixelLayout::RgbaHalf | PixelLayout::RgFloat => w.checked_mul(h)?.checked_mul(8),
|
||||
PixelLayout::RgbaFloat => w.checked_mul(h)?.checked_mul(16),
|
||||
PixelLayout::Dxt1 | PixelLayout::Bc4 | PixelLayout::Etc1 | PixelLayout::EacR | PixelLayout::EacRSigned => blocks.checked_mul(8),
|
||||
PixelLayout::Dxt3
|
||||
| PixelLayout::Dxt5
|
||||
| PixelLayout::Bc5
|
||||
| PixelLayout::Bc6h
|
||||
| PixelLayout::Bc6hSigned
|
||||
| PixelLayout::Bc7
|
||||
| PixelLayout::EacRg
|
||||
| PixelLayout::EacRgSigned => blocks.checked_mul(16),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert an IEEE 754 binary16 half-float's bits to `f32`.
|
||||
pub fn half_to_f32(h: u16) -> f32 {
|
||||
bptc::half(h)
|
||||
}
|
||||
|
||||
/// Convert a linear-light value to 8-bit sRGB; 0..1 is kept, brighter and negative values clip.
|
||||
pub fn linear_to_srgb8(v: f32) -> u8 {
|
||||
bptc::srgb8(v)
|
||||
}
|
||||
|
||||
/// Decode one BC1 (DXT1) 8-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc1_block(block: &[u8; 8]) -> [[u8; 4]; 16] {
|
||||
bc::decode_colour(block, true)
|
||||
}
|
||||
|
||||
/// Decode one BC2 (DXT3) 16-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc2_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_bc2_alpha(block.get(..8).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Decode one BC3 (DXT5) 16-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc3_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
with_alpha(bc::decode_colour(block.get(8..).unwrap_or_default(), false), bc::decode_values(block.get(..8).unwrap_or_default()))
|
||||
}
|
||||
|
||||
/// Decode one BC4 8-byte block into 16 greyscale RGBA8 texels (`[r, r, r, 255]`, row by row).
|
||||
pub fn decode_bc4_block(block: &[u8; 8]) -> [[u8; 4]; 16] {
|
||||
bc::decode_values(block).map(|r| [r, r, r, 255])
|
||||
}
|
||||
|
||||
/// Decode one BC5 16-byte normal-map block into 16 RGBA8 texels with reconstructed Z (row by row).
|
||||
pub fn decode_bc5_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
let (r, g) = (bc::decode_values(block.get(..8).unwrap_or_default()), bc::decode_values(block.get(8..).unwrap_or_default()));
|
||||
std::array::from_fn(|k| {
|
||||
let (x, y) = (f32::from(r[k]) / 127.5 - 1.0, f32::from(g[k]) / 127.5 - 1.0);
|
||||
let z = (1.0 - x * x - y * y).max(0.0).sqrt();
|
||||
[r[k], g[k], ((z + 1.0) * 127.5) as u8, 255]
|
||||
})
|
||||
}
|
||||
|
||||
/// Decode one BC6H 16-byte block into 16 sRGB8 RGBA texels (opaque).
|
||||
pub fn decode_bc6h_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
|
||||
bptc::bc6h(block, signed)
|
||||
}
|
||||
|
||||
/// Decode one BC7 16-byte block into 16 RGBA8 texels (row by row).
|
||||
pub fn decode_bc7_block(block: &[u8; 16]) -> [[u8; 4]; 16] {
|
||||
bptc::bc7(block)
|
||||
}
|
||||
|
||||
/// Decode one ETC1 8-byte block into 16 RGBA8 texels; returns `None` if differential colours overflow 5 bits.
|
||||
pub fn decode_etc1_block(block: &[u8; 8]) -> Option<[[u8; 4]; 16]> {
|
||||
eac::etc1(block)
|
||||
}
|
||||
|
||||
/// Decode one single-channel EAC 8-byte block into 16 greyscale RGBA8 texels.
|
||||
pub fn decode_eac_r_block(block: &[u8; 8], signed: bool) -> [[u8; 4]; 16] {
|
||||
eac::scalar(block, signed)
|
||||
}
|
||||
|
||||
/// Decode one dual-channel EAC 16-byte block into 16 RGBA8 texels (blue 0, alpha 255).
|
||||
pub fn decode_eac_rg_block(block: &[u8; 16], signed: bool) -> [[u8; 4]; 16] {
|
||||
eac::dual(block, signed)
|
||||
}
|
||||
|
||||
/// Decode one little-endian `RGB9E5` 4-byte pixel into opaque sRGB8 RGBA.
|
||||
pub fn decode_rgb9e5(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
packed::rgb9e5(bytes)
|
||||
}
|
||||
|
||||
/// Decode one little-endian `RGBA1010102` 4-byte pixel into RGBA8.
|
||||
pub fn decode_rgba1010102(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
packed::rgba1010102(bytes)
|
||||
}
|
||||
|
||||
/// Decode one little-endian `R11G11B10_FLOAT` 4-byte pixel into opaque sRGB8 RGBA.
|
||||
pub fn decode_rgb111110_float(bytes: &[u8; 4]) -> [u8; 4] {
|
||||
packed::rgb111110(bytes)
|
||||
}
|
||||
|
||||
fn unorm8(value: u16) -> u8 {
|
||||
((u32::from(value) * 255 + 32767) / 65535) as u8
|
||||
}
|
||||
|
||||
fn unorm16_pixels(samples: impl Iterator<Item = u16>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
|
||||
let mut samples = samples.map(unorm8);
|
||||
std::iter::from_fn(move || {
|
||||
let (r, g) = (samples.next()?, samples.next()?);
|
||||
let b = if channels > 2 { samples.next()? } else { 0 };
|
||||
let a = if channels > 3 { samples.next()? } else { 255 };
|
||||
Some([r, g, b, a])
|
||||
})
|
||||
}
|
||||
|
||||
fn float_pixels(mut samples: impl Iterator<Item = f32>, channels: usize) -> impl Iterator<Item = [u8; 4]> {
|
||||
std::iter::from_fn(move || {
|
||||
let r = bptc::srgb8(samples.next()?);
|
||||
if channels == 1 {
|
||||
return Some([r, r, r, 255]);
|
||||
}
|
||||
let g = bptc::srgb8(samples.next()?);
|
||||
if channels == 2 {
|
||||
return Some([r, g, 0, 255]);
|
||||
}
|
||||
let b = bptc::srgb8(samples.next()?);
|
||||
let a = (samples.next()?.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
Some([r, g, b, a])
|
||||
})
|
||||
}
|
||||
|
||||
fn expand5(v: u16) -> u8 {
|
||||
let v = (v & 31) as u8;
|
||||
(v << 3) | (v >> 2)
|
||||
}
|
||||
|
||||
fn expand6(v: u16) -> u8 {
|
||||
let v = (v & 63) as u8;
|
||||
(v << 2) | (v >> 4)
|
||||
}
|
||||
|
||||
fn rgb565(v: u16) -> [u8; 4] {
|
||||
[expand5(v >> 11), expand6(v >> 5), expand5(v), 255]
|
||||
}
|
||||
|
||||
fn nibbles(v: u16, order: [u32; 4]) -> [u8; 4] {
|
||||
order.map(|shift| ((v >> shift) & 15) as u8 * 17)
|
||||
}
|
||||
|
||||
fn place_blocks(out: &mut [u8], w: usize, h: usize, texels: impl Iterator<Item = [[u8; 4]; 16]>) {
|
||||
let across = w.div_ceil(4);
|
||||
for (i, block) in texels.enumerate() {
|
||||
let (bx, by) = (i % across, i / across);
|
||||
for (k, p) in block.iter().enumerate() {
|
||||
let (x, y) = (bx * 4 + k % 4, by * 4 + k / 4);
|
||||
if x < w && y < h {
|
||||
let at = (y * w + x) * 4;
|
||||
if let Some(dst) = out.get_mut(at..at + 4) {
|
||||
dst.copy_from_slice(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a `width`×`height` picture (`data` starts with it) into RGBA8, rows in stored order.
|
||||
///
|
||||
/// Caps the output at [`DEFAULT_MAX_RGBA_BYTES`]; use [`decode_with_limit`] for a different budget.
|
||||
pub fn decode(layout: PixelLayout, width: u32, height: u32, data: &[u8]) -> Result<Vec<u8>, DdsError> {
|
||||
decode_with_limit(layout, width, height, data, DEFAULT_MAX_RGBA_BYTES)
|
||||
}
|
||||
|
||||
/// Decode into RGBA8, allowing at most `max_bytes` of output.
|
||||
///
|
||||
/// The budget applies to RGBA bytes, not the encoded input, and is checked before reading pixels
|
||||
/// or reserving the output.
|
||||
pub fn decode_with_limit(layout: PixelLayout, width: u32, height: u32, data: &[u8], max_bytes: u64) -> Result<Vec<u8>, DdsError> {
|
||||
let need = size(layout, width, height).ok_or(DdsError::Alloc(usize::MAX))?;
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let out_len =
|
||||
w.checked_mul(h).and_then(|pixels| pixels.checked_mul(4)).filter(|bytes| *bytes <= isize::MAX as usize).ok_or(DdsError::Alloc(usize::MAX))?;
|
||||
if out_len as u64 > max_bytes {
|
||||
return Err(DdsError::LimitExceeded { required: out_len, limit: max_bytes });
|
||||
}
|
||||
let data = data.get(..need).ok_or_else(|| DdsError::Truncated(format!("{} bytes of pixels, {need} needed", data.len())))?;
|
||||
if w == 0 || h == 0 {
|
||||
return Err(DdsError::Malformed("an empty picture".into()));
|
||||
}
|
||||
let mut out: Vec<u8> = alloc_zeroed(out_len)?;
|
||||
let mut put = |px: &mut dyn Iterator<Item = [u8; 4]>| {
|
||||
for (dst, p) in out.as_chunks_mut::<4>().0.iter_mut().zip(px) {
|
||||
*dst = p;
|
||||
}
|
||||
};
|
||||
let u16s = data.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b));
|
||||
let floats = data.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b));
|
||||
match layout {
|
||||
PixelLayout::RHalf => put(&mut float_pixels(u16s.map(bptc::half), 1)),
|
||||
PixelLayout::RgHalf => put(&mut float_pixels(u16s.map(bptc::half), 2)),
|
||||
PixelLayout::RgbaHalf => put(&mut float_pixels(u16s.map(bptc::half), 4)),
|
||||
PixelLayout::RFloat => put(&mut float_pixels(floats, 1)),
|
||||
PixelLayout::RgFloat => put(&mut float_pixels(floats, 2)),
|
||||
PixelLayout::RgbaFloat => put(&mut float_pixels(floats, 4)),
|
||||
PixelLayout::Rgba1010102 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgba1010102)),
|
||||
PixelLayout::Rgb111110Float => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb111110)),
|
||||
PixelLayout::Rgb9e5 => put(&mut data.as_chunks::<4>().0.iter().map(packed::rgb9e5)),
|
||||
PixelLayout::Alpha8 => put(&mut data.iter().map(|a| [255, 255, 255, *a])),
|
||||
PixelLayout::R8 => put(&mut data.iter().map(|r| [*r, *r, *r, 255])),
|
||||
PixelLayout::R16 => put(&mut u16s.map(|value| {
|
||||
let grey = unorm8(value);
|
||||
[grey, grey, grey, 255]
|
||||
})),
|
||||
PixelLayout::Rg8 => put(&mut data.as_chunks::<2>().0.iter().map(|[r, g]| [*r, *g, 0, 255])),
|
||||
PixelLayout::Rg16 => put(&mut unorm16_pixels(u16s, 2)),
|
||||
PixelLayout::Rgb16 => put(&mut unorm16_pixels(u16s, 3)),
|
||||
PixelLayout::Rgba16 => put(&mut unorm16_pixels(u16s, 4)),
|
||||
PixelLayout::Rgb24 => put(&mut data.as_chunks::<3>().0.iter().map(|[r, g, b]| [*r, *g, *b, 255])),
|
||||
PixelLayout::Rgba32 => put(&mut data.as_chunks::<4>().0.iter().copied()),
|
||||
PixelLayout::Argb32 => put(&mut data.as_chunks::<4>().0.iter().map(|[a, r, g, b]| [*r, *g, *b, *a])),
|
||||
PixelLayout::Bgra32 => put(&mut data.as_chunks::<4>().0.iter().map(|[b, g, r, a]| [*r, *g, *b, *a])),
|
||||
PixelLayout::Rgb565 => put(&mut u16s.map(rgb565)),
|
||||
PixelLayout::Rgba4444 => put(&mut u16s.map(|v| nibbles(v, [12, 8, 4, 0]))),
|
||||
PixelLayout::Argb4444 => put(&mut u16s.map(|v| nibbles(v, [8, 4, 0, 12]))),
|
||||
PixelLayout::Dxt1 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc1_block)),
|
||||
PixelLayout::Dxt3 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc2_block)),
|
||||
PixelLayout::Dxt5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc3_block)),
|
||||
PixelLayout::Bc4 => place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(decode_bc4_block)),
|
||||
PixelLayout::Bc5 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(decode_bc5_block)),
|
||||
PixelLayout::Bc6h => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, false))),
|
||||
PixelLayout::Bc6hSigned => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|b| bptc::bc6h(b, true))),
|
||||
PixelLayout::Bc7 => place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(bptc::bc7)),
|
||||
PixelLayout::EacR | PixelLayout::EacRSigned => {
|
||||
place_blocks(&mut out, w, h, data.as_chunks::<8>().0.iter().map(|block| eac::scalar(block, layout == PixelLayout::EacRSigned)))
|
||||
}
|
||||
PixelLayout::EacRg | PixelLayout::EacRgSigned => {
|
||||
place_blocks(&mut out, w, h, data.as_chunks::<16>().0.iter().map(|block| eac::dual(block, layout == PixelLayout::EacRgSigned)))
|
||||
}
|
||||
PixelLayout::Etc1 => {
|
||||
let mut valid = true;
|
||||
let texels = data.as_chunks::<8>().0.iter().map_while(|block| {
|
||||
let pixels = eac::etc1(block);
|
||||
valid &= pixels.is_some();
|
||||
pixels
|
||||
});
|
||||
place_blocks(&mut out, w, h, texels);
|
||||
if !valid {
|
||||
return Err(DdsError::Malformed("ETC1 differential colour is outside its five-bit range".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Flip a `width`-wide RGBA8 picture upside down.
|
||||
pub fn flip_rows(rgba: &[u8], width: u32) -> Vec<u8> {
|
||||
let row = (width as usize).saturating_mul(4).max(1);
|
||||
rgba.chunks(row).rev().flatten().copied().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{PixelLayout, decode, decode_with_limit, flip_rows, size};
|
||||
use crate::DdsError;
|
||||
|
||||
#[test]
|
||||
fn uncompressed_and_swizzled_layouts() {
|
||||
assert_eq!(decode(PixelLayout::Rgba32, 1, 2, &[1, 2, 3, 4, 5, 6, 7, 8]).unwrap(), [1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
assert_eq!(decode(PixelLayout::Argb32, 1, 1, &[9, 1, 2, 3]).unwrap(), [1, 2, 3, 9]);
|
||||
assert_eq!(decode(PixelLayout::Bgra32, 1, 1, &[3, 2, 1, 9]).unwrap(), [1, 2, 3, 9]);
|
||||
assert_eq!(decode(PixelLayout::Rgb24, 1, 1, &[1, 2, 3]).unwrap(), [1, 2, 3, 255]);
|
||||
assert_eq!(decode(PixelLayout::Alpha8, 1, 1, &[7]).unwrap(), [255, 255, 255, 7]);
|
||||
assert_eq!(decode(PixelLayout::R8, 1, 1, &[7]).unwrap(), [7, 7, 7, 255]);
|
||||
assert_eq!(decode(PixelLayout::Rgb565, 1, 1, &0xf800u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
|
||||
assert_eq!(decode(PixelLayout::Rgba4444, 1, 1, &0xf00fu16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
|
||||
assert_eq!(decode(PixelLayout::Argb4444, 1, 1, &0xff00u16.to_le_bytes()).unwrap(), [255, 0, 0, 255]);
|
||||
assert_eq!(flip_rows(&[1, 1, 1, 1, 2, 2, 2, 2], 1), [2, 2, 2, 2, 1, 1, 1, 1]);
|
||||
assert!(matches!(decode(PixelLayout::Rgba32, 2, 2, &[0; 15]), Err(DdsError::Truncated(_))));
|
||||
assert!(matches!(decode(PixelLayout::Rgba32, 0, 1, &[]), Err(DdsError::Malformed(_))));
|
||||
assert!(matches!(decode_with_limit(PixelLayout::R8, 2, 2, &[0; 4], 15), Err(DdsError::LimitExceeded { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_and_packed_layouts_crop_partial_blocks() {
|
||||
assert_eq!(size(PixelLayout::Dxt1, 5, 5), Some(32));
|
||||
assert_eq!(decode(PixelLayout::Dxt1, 5, 5, &[0; 32]).unwrap().len(), 100);
|
||||
// DXT1: colour 0 red, colour 1 blue; the first texel uses index 1, the rest index 0.
|
||||
let px = decode(PixelLayout::Dxt1, 4, 4, &[0x00, 0xf8, 0x1f, 0x00, 0b01, 0, 0, 0]).unwrap();
|
||||
assert_eq!((&px[..4], &px[4..8]), (&[0, 0, 255, 255][..], &[255, 0, 0, 255][..]));
|
||||
// DXT5: alpha 255 -> 0; first texel index 1 (0), rest index 0 (255).
|
||||
let mut b = vec![255, 0, 1, 0, 0, 0, 0, 0];
|
||||
b.extend_from_slice(&[0x00, 0xf8, 0x1f, 0x00, 0, 0, 0, 0]);
|
||||
let px = decode(PixelLayout::Dxt5, 4, 4, &b).unwrap();
|
||||
assert_eq!((px[3], px[7]), (0, 255));
|
||||
// BC4 & BC5.
|
||||
assert_eq!(&decode(PixelLayout::Bc4, 4, 4, &[200, 10, 0, 0, 0, 0, 0, 0]).unwrap()[..4], &[200, 200, 200, 255]);
|
||||
let mut n = vec![128, 128, 0, 0, 0, 0, 0, 0];
|
||||
n.extend_from_slice(&[128, 128, 0, 0, 0, 0, 0, 0]);
|
||||
assert_eq!(&decode(PixelLayout::Bc5, 4, 4, &n).unwrap()[..4], &[128, 128, 254, 255]);
|
||||
// Packed RGB9E5 & RGBA1010102.
|
||||
let rgb9e5 = (256u32 | (128 << 9) | (64 << 18) | (15 << 27)).to_le_bytes();
|
||||
assert_eq!(decode(PixelLayout::Rgb9e5, 1, 1, &rgb9e5).unwrap(), [188, 137, 99, 255]);
|
||||
let rgba10 = (1023u32 | (512 << 10) | (2 << 30)).to_le_bytes();
|
||||
assert_eq!(decode(PixelLayout::Rgba1010102, 1, 1, &rgba10).unwrap(), [255, 128, 0, 170]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Independent known-answer test vectors (raw bitstreams and hand-verified spec outputs)
|
||||
//! for BC6H (unsigned/signed), BC7, ETC1, and EAC R/RG (unsigned/signed).
|
||||
|
||||
use craft_dds::DdsError;
|
||||
use craft_dds::pixels::{self, PixelLayout};
|
||||
|
||||
#[test]
|
||||
fn bc7_mode6_known_bitstream() {
|
||||
// Raw 128-bit BC7 Mode 6 block (7-bit RGBA endpoints + per-endpoint P-bits, 4-bit indices):
|
||||
// e0 = (241, 121, 21, 255), e1 = (40, 200, 254, 128); texels 0..3 use indices 0, 15, 8, 4.
|
||||
let block: [u8; 16] = [0x40, 0x3c, 0x85, 0x47, 0x56, 0xfc, 0xff, 0xc0, 0xf0, 0x48, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44];
|
||||
let texels = pixels::decode_bc7_block(&block);
|
||||
assert_eq!(texels[0], [241, 121, 21, 255]);
|
||||
assert_eq!(texels[1], [40, 200, 254, 128]);
|
||||
assert_eq!(texels[2], [134, 163, 145, 188]);
|
||||
assert_eq!(texels[3], [188, 142, 83, 221]);
|
||||
|
||||
// Reserved mode (low byte 0x00) decodes to all zeroes.
|
||||
assert_eq!(pixels::decode_bc7_block(&[0; 16]), [[0, 0, 0, 0]; 16]);
|
||||
|
||||
// Cropped 3x2 image keeps the top-left 3x2 texels in row-major order.
|
||||
let rgba = pixels::decode(PixelLayout::Bc7, 3, 2, &block).unwrap();
|
||||
assert_eq!(rgba.len(), 3 * 2 * 4);
|
||||
assert_eq!(&rgba[..4], &[241, 121, 21, 255]);
|
||||
assert_eq!(&rgba[4..8], &[40, 200, 254, 128]);
|
||||
assert_eq!(&rgba[8..12], &[134, 163, 145, 188]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bc6h_unsigned_and_signed_known_bitstreams() {
|
||||
// Mode 11 (untransformed 10-bit endpoints, 1 subset, 4-bit indices):
|
||||
// e0 = (480, 400, 200), e1 = (200, 480, 400); texels 0..2 use indices 0, 15, 8.
|
||||
let block: [u8; 16] = [0x03, 0x3c, 0xc8, 0x90, 0x41, 0x06, 0x3c, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
|
||||
|
||||
let unsigned = pixels::decode_bc6h_block(&block, false);
|
||||
assert_eq!(unsigned[0], [228, 105, 7, 255]);
|
||||
assert_eq!(unsigned[1], [7, 228, 105, 255]);
|
||||
assert_eq!(unsigned[2], [51, 160, 39, 255]);
|
||||
|
||||
let signed_pos = pixels::decode_bc6h_block(&block, true);
|
||||
assert_eq!(signed_pos[0], [255, 255, 105, 255]);
|
||||
assert_eq!(signed_pos[1], [105, 255, 255, 255]);
|
||||
assert_eq!(signed_pos[2], [255, 255, 255, 255]);
|
||||
|
||||
// Signed Mode 11 with negative 10-bit endpoints: R0 = -200 (0x338), G1 = -200 (0x338).
|
||||
// Negative linear values clip to 0 in sRGB8 output.
|
||||
let neg_block: [u8; 16] = [0x03, 0x67, 0x64, 0x20, 0x43, 0x06, 0x67, 0xc8, 0xf0, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
|
||||
let signed_neg = pixels::decode_bc6h_block(&neg_block, true);
|
||||
assert_eq!(signed_neg[0], [0, 105, 255, 255]);
|
||||
assert_eq!(signed_neg[1], [105, 0, 255, 255]);
|
||||
assert_eq!(signed_neg[2], [0, 0, 255, 255]);
|
||||
|
||||
let rgba = pixels::decode(PixelLayout::Bc6h, 2, 1, &block).unwrap();
|
||||
assert_eq!(rgba, [228, 105, 7, 255, 7, 228, 105, 255]);
|
||||
let rgba_signed = pixels::decode(PixelLayout::Bc6hSigned, 2, 1, &neg_block).unwrap();
|
||||
assert_eq!(rgba_signed, [0, 105, 255, 255, 105, 0, 255, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn etc1_known_bitstreams_and_invalid_differential() {
|
||||
// Individual mode (diff=0, flip=0): left half (x<2) RGB4=(15,0,8) + 2, right half (x>=2) RGB4=(0,15,4) + 5.
|
||||
let individual: [u8; 8] = [0xf0, 0x0f, 0x84, 0x04, 0x00, 0x00, 0x00, 0x00];
|
||||
let texels = pixels::decode_etc1_block(&individual).unwrap();
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
let expected = if x < 2 { [255, 2, 138, 255] } else { [5, 255, 73, 255] };
|
||||
assert_eq!(texels[y * 4 + x], expected);
|
||||
}
|
||||
}
|
||||
|
||||
// Differential mode (diff=1, flip=1 horizontal): base0=(20,10,4), delta=(+2,-2,+1), tables=(2,3).
|
||||
let differential: [u8; 8] = [0xa2, 0x56, 0x21, 0x4f, 0x00, 0x00, 0x00, 0x00];
|
||||
let texels = pixels::decode_etc1_block(&differential).unwrap();
|
||||
for y in 0..4 {
|
||||
for x in 0..4 {
|
||||
let expected = if y < 2 { [174, 91, 42, 255] } else { [194, 79, 54, 255] };
|
||||
assert_eq!(texels[y * 4 + x], expected);
|
||||
}
|
||||
}
|
||||
|
||||
// Differential base + delta outside 0..=31 must be rejected.
|
||||
let invalid: [u8; 8] = [0x04, 0x40, 0x40, 0x02, 0x00, 0x00, 0x00, 0x00];
|
||||
assert!(pixels::decode_etc1_block(&invalid).is_none());
|
||||
assert!(matches!(pixels::decode(PixelLayout::Etc1, 4, 4, &invalid), Err(DdsError::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac_r_and_rg_unsigned_and_signed_known_bitstreams() {
|
||||
// Unsigned EAC_R: base=100, mult=2, table=0, all selectors=7 (+14) -> 1028/2047 -> 128.
|
||||
let eac_r_u: [u8; 8] = [0x64, 0x20, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
|
||||
assert_eq!(pixels::decode_eac_r_block(&eac_r_u, false), [[128, 128, 128, 255]; 16]);
|
||||
|
||||
// Signed EAC_R: base=-64 (0xc0), mult=2, table=0, all selectors=0 (-3) -> (-560+1023)/2046 -> 58.
|
||||
let eac_r_s: [u8; 8] = [0xc0, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
|
||||
assert_eq!(pixels::decode_eac_r_block(&eac_r_s, true), [[58, 58, 58, 255]; 16]);
|
||||
|
||||
// Column-major selector order: texel (x=1, y=0) has selector 7 (+14 -> 142), others selector 0 (-3 -> 125).
|
||||
let eac_col: [u8; 8] = [0x80, 0x10, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00];
|
||||
let col_texels = pixels::decode_eac_r_block(&eac_col, false);
|
||||
assert_eq!(col_texels[1], [142, 142, 142, 255]);
|
||||
assert_eq!(col_texels[0], [125, 125, 125, 255]);
|
||||
assert_eq!(col_texels[4], [125, 125, 125, 255]);
|
||||
|
||||
// Dual-channel EAC_RG (unsigned and signed): R then G.
|
||||
let mut eac_rg_u = [0u8; 16];
|
||||
eac_rg_u[..8].copy_from_slice(&eac_r_u);
|
||||
eac_rg_u[8..].copy_from_slice(&[0xff, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
assert_eq!(pixels::decode(PixelLayout::EacRg, 2, 2, &eac_rg_u).unwrap(), [128, 255, 0, 255].repeat(4));
|
||||
|
||||
let mut eac_rg_s = [0u8; 16];
|
||||
eac_rg_s[..8].copy_from_slice(&eac_r_s);
|
||||
eac_rg_s[8..].copy_from_slice(&[0x7f, 0xf0, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);
|
||||
assert_eq!(pixels::decode(PixelLayout::EacRgSigned, 2, 2, &eac_rg_s).unwrap(), [58, 255, 0, 255].repeat(4));
|
||||
}
|
||||
@@ -137,6 +137,9 @@ const NO_GLOBAL_STATE_PREFIXES: &[&str] = &[
|
||||
const NO_GLOBAL_STATE: &[(&str, &str)] = &[
|
||||
// The trait's home crate: it implements `MemoProps` by hand for std and framework value types.
|
||||
("crates/ui-contract/src/contract/memo.rs", "MemoProps"),
|
||||
// Settled fact: `ModalRules` holds a closure the derive cannot take; it keys on its plain fields and the revision
|
||||
// the app moves with every rule change, which stands for the closure.
|
||||
("crates/menu/src/modal.rs", "MemoProps"),
|
||||
// Settled fact: constant font bytes, decompressed once from compile-time input and immutable after init.
|
||||
("crates/ui-contract/src/fonts/defaults.rs", "HACK"),
|
||||
("crates/ui-contract/src/fonts/defaults.rs", "EGUI_ICONS"),
|
||||
|
||||
@@ -11,6 +11,7 @@ repository.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-color-transform = { workspace = true }
|
||||
craft-develop-model = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
@@ -20,3 +21,4 @@ rayon = { workspace = true }
|
||||
[dev-dependencies]
|
||||
craft-render-parity = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
@@ -12,9 +12,11 @@ craft-develop = { git = "https://github.com/storytold/craft-libs", rev = "<commi
|
||||
|
||||
| Module | From LightCraft (`a75497d6`) | Contents |
|
||||
|---|---|---|
|
||||
| `color::spline` | `crates/color/src/spline.rs` | `MonotoneCurve` (a tone curve through points that does not overshoot) and `Lut1`. |
|
||||
| `color::spline` | `crates/color/src/spline.rs` | Re-exports `craft_color_transform::curve` (`MonotoneCurve`, `Lut1`). |
|
||||
| `curve` | `crates/pipeline` | The parametric tone curve and its regions. |
|
||||
| `finish` | `crates/pipeline` | Pure-Rust finishing helpers: sharpening masks/limits, vignette parameters, value grain, gamut mapping, and curve saturation refinement. |
|
||||
| `lut` | `crates/pipeline` | 3D lookup tables and the `.cube` reader. |
|
||||
| `tone` | `crates/pipeline` | Global tone mapping (`ToneMap` and `CameraTone`) from scene luminance to display-linear luminance, SDR and HDR. |
|
||||
| `inpaint` | `crates/inpaint` | Content-aware hole filling for spot removal: `complete` (multi-scale patch completion with PatchMatch) and `membrane_fill` (a smooth harmonic fill, its seed and fallback). Interleaved `f32` buffers of any channel count, a fixed-seed RNG, the same result on any number of threads. |
|
||||
|
||||
## Parity with LightCraft
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
//! Colour helpers for the develop pipeline.
|
||||
|
||||
pub mod spline;
|
||||
pub use craft_color_transform::curve as spline;
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
//! Curves for tone mapping: monotone cubic Hermite splines (Fritsch–Carlson) and lookup tables.
|
||||
//!
|
||||
//! Monotone interpolation never overshoots between control points, so a point curve can't invert
|
||||
//! tones by accident (a common complaint with natural cubic splines).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A curve through control points in `0..1 × 0..1` (x strictly increasing after normalization).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct MonotoneCurve {
|
||||
xs: Vec<f64>,
|
||||
ys: Vec<f64>,
|
||||
ms: Vec<f64>,
|
||||
}
|
||||
|
||||
impl MonotoneCurve {
|
||||
/// Build from points; sorts by x, merges duplicates. Fewer than two points → identity.
|
||||
pub fn new(points: &[(f64, f64)]) -> MonotoneCurve {
|
||||
let mut p: Vec<(f64, f64)> = points.iter().copied().filter(|(x, y)| x.is_finite() && y.is_finite()).collect();
|
||||
p.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9);
|
||||
if p.len() < 2 {
|
||||
p = vec![(0.0, 0.0), (1.0, 1.0)];
|
||||
}
|
||||
let n = p.len();
|
||||
let xs: Vec<f64> = p.iter().map(|q| q.0).collect();
|
||||
let ys: Vec<f64> = p.iter().map(|q| q.1).collect();
|
||||
let d: Vec<f64> = (0..n - 1).map(|i| (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i])).collect();
|
||||
let mut ms = vec![0.0; n];
|
||||
ms[0] = d[0];
|
||||
ms[n - 1] = d[n - 2];
|
||||
for i in 1..n - 1 {
|
||||
ms[i] = if d[i - 1] * d[i] <= 0.0 { 0.0 } else { (d[i - 1] + d[i]) / 2.0 };
|
||||
}
|
||||
// Fritsch–Carlson limiter where the data is monotone within a segment.
|
||||
for i in 0..n - 1 {
|
||||
if d[i] == 0.0 {
|
||||
ms[i] = 0.0;
|
||||
ms[i + 1] = 0.0;
|
||||
continue;
|
||||
}
|
||||
let a = ms[i] / d[i];
|
||||
let b = ms[i + 1] / d[i];
|
||||
let s = a * a + b * b;
|
||||
if s > 9.0 {
|
||||
let t = 3.0 / s.sqrt();
|
||||
ms[i] = t * a * d[i];
|
||||
ms[i + 1] = t * b * d[i];
|
||||
}
|
||||
}
|
||||
MonotoneCurve { xs, ys, ms }
|
||||
}
|
||||
|
||||
pub fn identity() -> MonotoneCurve {
|
||||
MonotoneCurve::new(&[(0.0, 0.0), (1.0, 1.0)])
|
||||
}
|
||||
|
||||
pub fn eval(&self, x: f64) -> f64 {
|
||||
// NaN passes both bound checks below and would send the search past either end
|
||||
if x.is_nan() {
|
||||
return x;
|
||||
}
|
||||
let n = self.xs.len();
|
||||
if x <= self.xs[0] {
|
||||
return self.ys[0] + self.ms[0] * (x - self.xs[0]).min(0.0) * 0.0;
|
||||
}
|
||||
if x >= self.xs[n - 1] {
|
||||
return self.ys[n - 1];
|
||||
}
|
||||
let i = match self.xs.binary_search_by(|v| v.total_cmp(&x)) {
|
||||
Ok(i) => return self.ys[i],
|
||||
Err(i) => i - 1,
|
||||
};
|
||||
let h = self.xs[i + 1] - self.xs[i];
|
||||
let t = (x - self.xs[i]) / h;
|
||||
let (t2, t3) = (t * t, t * t * t);
|
||||
(2.0 * t3 - 3.0 * t2 + 1.0) * self.ys[i]
|
||||
+ (t3 - 2.0 * t2 + t) * h * self.ms[i]
|
||||
+ (-2.0 * t3 + 3.0 * t2) * self.ys[i + 1]
|
||||
+ (t3 - t2) * h * self.ms[i + 1]
|
||||
}
|
||||
|
||||
/// Sample into a LUT of `n` entries (at least 2) over `0..1`.
|
||||
pub fn to_lut(&self, n: usize) -> Lut1 {
|
||||
let n = n.max(2);
|
||||
Lut1 { v: (0..n).map(|i| self.eval(i as f64 / (n - 1) as f64) as f32).collect() }
|
||||
}
|
||||
|
||||
pub fn points(&self) -> Vec<(f64, f64)> {
|
||||
self.xs.iter().copied().zip(self.ys.iter().copied()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A 1-D lookup table over `0..1` with linear interpolation; inputs outside clamp.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Lut1 {
|
||||
pub v: Vec<f32>,
|
||||
}
|
||||
|
||||
impl Lut1 {
|
||||
/// At least 2 entries, like [`Lut1::from_fn`].
|
||||
pub fn identity(n: usize) -> Lut1 {
|
||||
Lut1::from_fn(n, |x| x)
|
||||
}
|
||||
/// `f` sampled at `n` evenly spaced points over `0..1` (at least 2).
|
||||
pub fn from_fn(n: usize, f: impl Fn(f32) -> f32) -> Lut1 {
|
||||
let n = n.max(2);
|
||||
Lut1 { v: (0..n).map(|i| f(i as f32 / (n - 1) as f32)).collect() }
|
||||
}
|
||||
/// `v` is public, so a table shorter than 2 entries is read as constant (1) or the identity (0).
|
||||
#[inline]
|
||||
pub fn eval(&self, x: f32) -> f32 {
|
||||
let x = x.clamp(0.0, 1.0);
|
||||
let n = self.v.len();
|
||||
if n < 2 {
|
||||
return self.v.first().copied().unwrap_or(x);
|
||||
}
|
||||
let f = x * (n - 1) as f32;
|
||||
let i = (f as usize).min(n - 2);
|
||||
let t = f - i as f32;
|
||||
self.v[i] + (self.v[i + 1] - self.v[i]) * t
|
||||
}
|
||||
/// `self ∘ inner` (apply `inner` first).
|
||||
pub fn compose(&self, inner: &Lut1) -> Lut1 {
|
||||
Lut1 { v: inner.v.iter().map(|&x| self.eval(x)).collect() }
|
||||
}
|
||||
pub fn is_identity(&self) -> bool {
|
||||
let n = self.v.len();
|
||||
self.v.iter().enumerate().all(|(i, &y)| (y - i as f32 / (n - 1) as f32).abs() < 1e-6)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn identity_curve() {
|
||||
let c = MonotoneCurve::identity();
|
||||
for i in 0..=10 {
|
||||
let x = i as f64 / 10.0;
|
||||
assert!((c.eval(x) - x).abs() < 1e-12);
|
||||
}
|
||||
assert!(c.to_lut(256).is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_through_points_and_is_monotone() {
|
||||
let pts = [(0.0, 0.0), (0.25, 0.15), (0.5, 0.5), (0.75, 0.88), (1.0, 1.0)];
|
||||
let c = MonotoneCurve::new(&pts);
|
||||
for (x, y) in pts {
|
||||
assert!((c.eval(x) - y).abs() < 1e-12);
|
||||
}
|
||||
let mut prev = -1.0;
|
||||
for i in 0..=1000 {
|
||||
let y = c.eval(i as f64 / 1000.0);
|
||||
assert!(y >= prev - 1e-12);
|
||||
prev = y;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_overshoot_on_flat_segment() {
|
||||
let c = MonotoneCurve::new(&[(0.0, 0.0), (0.4, 0.5), (0.6, 0.5), (1.0, 1.0)]);
|
||||
for i in 400..=600 {
|
||||
let y = c.eval(i as f64 / 1000.0);
|
||||
assert!((y - 0.5).abs() < 1e-9, "{y}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lut_compose() {
|
||||
let a = Lut1::from_fn(1024, |x| x * x);
|
||||
let b = Lut1::from_fn(1024, |x| x.sqrt());
|
||||
let c = a.compose(&b);
|
||||
assert!((c.eval(0.3) - 0.3).abs() < 2e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nan_input_and_short_luts_do_not_panic() {
|
||||
let c = MonotoneCurve::new(&[(0.0, 0.0), (0.5, 0.6), (1.0, 1.0)]);
|
||||
assert!(c.eval(f64::NAN).is_nan());
|
||||
assert!(c.eval(-f64::NAN).is_nan());
|
||||
for n in [0, 1] {
|
||||
assert_eq!(c.to_lut(n).v.len(), 2, "{n}");
|
||||
assert!(Lut1::identity(n).is_identity(), "{n}");
|
||||
assert_eq!(Lut1::from_fn(n, |x| x).v.len(), 2, "{n}");
|
||||
}
|
||||
assert_eq!(Lut1 { v: vec![] }.eval(0.3), 0.3);
|
||||
assert_eq!(Lut1 { v: vec![] }.eval(-1.0), 0.0, "inputs outside 0..1 clamp, as for any table");
|
||||
assert_eq!(Lut1 { v: vec![] }.eval(2.0), 1.0);
|
||||
assert_eq!(Lut1 { v: vec![0.7] }.eval(0.3), 0.7);
|
||||
}
|
||||
|
||||
proptest::proptest! {
|
||||
#[test]
|
||||
fn monotone_for_increasing_data(ys in proptest::collection::vec(0.0f64..1.0, 3..8)) {
|
||||
let mut ys = ys; ys.sort_by(|a, b| a.total_cmp(b));
|
||||
let n = ys.len();
|
||||
let pts: Vec<(f64, f64)> = ys.iter().enumerate().map(|(i, y)| (i as f64 / (n - 1) as f64, *y)).collect();
|
||||
let c = MonotoneCurve::new(&pts);
|
||||
let mut prev = f64::MIN;
|
||||
for i in 0..=200 { let y = c.eval(i as f64 / 200.0); proptest::prop_assert!(y >= prev - 1e-9); prev = y; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Pure-Rust finishing-stage helpers: sharpening masks/limits, vignette parameters, value film
|
||||
//! grain, gamut mapping, and curve saturation refinement.
|
||||
|
||||
use craft_develop_model::{DevelopSettings, VignetteStyle};
|
||||
|
||||
#[inline]
|
||||
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
/// How much of the sharpening a pixel gets (`0..1`) under Masking `masking` (`0..1`), from its
|
||||
/// fine detail `det` (log luminance minus its texture blur): `1` everywhere at `0`, only stronger
|
||||
/// edges as it rises.
|
||||
#[inline]
|
||||
pub fn sharpen_mask_weight(masking: f32, det: f32) -> f32 {
|
||||
if masking > 0.0 { smooth(masking * 0.25, masking * 0.25 + 0.15, det.abs()) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Masking weight for the V3 pixel-scale sharpening band, also used by its Alt-drag preview.
|
||||
#[inline]
|
||||
pub fn pixel_sharpen_mask_weight(masking: f32, det: f32) -> f32 {
|
||||
if masking > 0.0 { smooth(masking * 0.1, masking * 0.1 + 0.06, det.abs()) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Gain of the sharpening detail term (per unit of `Amount / 150`), in stops of luminance per stop of detail.
|
||||
pub const SHARPEN_GAIN: f32 = 7.0;
|
||||
|
||||
/// Soft-clip limit (stops) of the sharpening detail term for Detail `0..=100`: `0.03` stops (large
|
||||
/// edge detail is flattened so halos stay small) up to `1.5` stops (practically linear).
|
||||
pub fn sharpen_limit(detail: f64) -> f32 {
|
||||
let d = (detail / 100.0).clamp(0.0, 1.0) as f32;
|
||||
0.03 * 50f32.powf(d)
|
||||
}
|
||||
|
||||
/// The sharpening boost (stops) for pixel-scale detail `det` (log luminance minus its blur at the
|
||||
/// sharpen radius): linear for small detail, soft-clipped at `limit`, and gated by the Masking edge
|
||||
/// mask (`mask` = Masking / 100) so flat areas and noise can be left alone.
|
||||
#[inline]
|
||||
pub fn sharpen_term(det: f32, limit: f32, mask: f32) -> f32 {
|
||||
let m = pixel_sharpen_mask_weight(mask, det);
|
||||
SHARPEN_GAIN * m * det / (1.0 + det.abs() / limit)
|
||||
}
|
||||
|
||||
/// Vignette (post-crop) parameters.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Vig {
|
||||
pub amount: f32,
|
||||
pub start: f32,
|
||||
pub width: f32,
|
||||
pub aspect_mix: f32,
|
||||
pub power: f32,
|
||||
pub highlights: f32,
|
||||
pub style: VignetteStyle,
|
||||
}
|
||||
|
||||
/// Resolve post-crop vignette parameters from `s`, returning `None` when `s.vignette.amount == 0.0`.
|
||||
pub fn vignette(s: &DevelopSettings) -> Option<Vig> {
|
||||
let v = &s.vignette;
|
||||
(v.amount != 0.0).then(|| {
|
||||
let r = (v.roundness / 100.0) as f32;
|
||||
Vig {
|
||||
amount: (v.amount / 100.0) as f32,
|
||||
start: 0.15 + (v.midpoint / 100.0) as f32 * 0.95,
|
||||
width: 0.05 + (v.feather / 100.0) as f32 * 1.1,
|
||||
aspect_mix: ((r + 1.0) / 2.0).clamp(0.0, 1.0),
|
||||
power: if r >= 0.0 { 2.0 } else { 2.0 + (-r) * 6.0 },
|
||||
highlights: (v.highlights / 100.0) as f32,
|
||||
style: v.style,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Hash constants of [`grain_noise`] (shared with the GPU kernel).
|
||||
pub const GRAIN_HASH: [u32; 4] = [0x8da6_b343, 0xd816_3841, 0xcb1a_b31f, 0x5bd1_e995];
|
||||
|
||||
/// The grain of processes V1 to V6: two octaves of value noise.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ValueGrain {
|
||||
/// Amplitude (display-encoded).
|
||||
pub amt: f32,
|
||||
/// Noise cell size (output pixels).
|
||||
pub cell: f32,
|
||||
/// Roughness `0..1`: weight of the finer octave.
|
||||
pub rough: f32,
|
||||
pub seed: u32,
|
||||
}
|
||||
|
||||
/// Resolve [`ValueGrain`] parameters from `s` at `px_per_long` output pixels per long edge,
|
||||
/// returning `None` when `s.grain.amount <= 0.0`.
|
||||
pub fn value_grain(s: &DevelopSettings, px_per_long: f64) -> Option<ValueGrain> {
|
||||
let g = &s.grain;
|
||||
(g.amount > 0.0).then(|| {
|
||||
let cell = (0.0006 + (g.size / 100.0) as f32 * 0.0024) * px_per_long as f32;
|
||||
ValueGrain { amt: (g.amount / 100.0) as f32 * 0.13, cell: cell.max(0.6), rough: (g.roughness / 100.0) as f32, seed: g.seed }
|
||||
})
|
||||
}
|
||||
|
||||
/// Smooth value noise in `-1..1` at `(x, y)` for `seed`. Non-finite coordinates return `0.0`.
|
||||
#[inline]
|
||||
pub fn grain_noise(x: f32, y: f32, seed: u32) -> f32 {
|
||||
if !x.is_finite() || !y.is_finite() {
|
||||
return 0.0;
|
||||
}
|
||||
let (x0, y0) = (x.floor(), y.floor());
|
||||
let (fx, fy) = (x - x0, y - y0);
|
||||
let h = |i: i32, j: i32| {
|
||||
let mut v = (i as u32).wrapping_mul(GRAIN_HASH[0]) ^ (j as u32).wrapping_mul(GRAIN_HASH[1]) ^ seed.wrapping_mul(GRAIN_HASH[2]);
|
||||
v ^= v >> 13;
|
||||
v = v.wrapping_mul(GRAIN_HASH[3]);
|
||||
v ^= v >> 15;
|
||||
(v & 0xffff) as f32 / 32768.0 - 1.0
|
||||
};
|
||||
let (i, j) = (x0 as i32, y0 as i32);
|
||||
let (u, v) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));
|
||||
let a = h(i, j) + (h(i + 1, j) - h(i, j)) * u;
|
||||
let b = h(i, j + 1) + (h(i + 1, j + 1) - h(i, j + 1)) * u;
|
||||
a + (b - a) * v
|
||||
}
|
||||
|
||||
/// A colour needing more desaturation than this (scale < `GAMUT_WARN`) to fit is out of gamut for
|
||||
/// the gamut warnings (tolerates rounding at the gamut boundary).
|
||||
pub const GAMUT_WARN: f32 = 0.995;
|
||||
|
||||
/// Desaturate linear `r` towards its luminance (weights `luma`) until every channel is in `0..=1`;
|
||||
/// returns the mapped colour and the chroma scale used (`1.0` = already in gamut).
|
||||
#[inline]
|
||||
pub fn gamut_map(r: [f32; 3], luma: [f32; 3]) -> ([f32; 3], f32) {
|
||||
gamut_map_to(r, luma, 1.0)
|
||||
}
|
||||
|
||||
/// [`gamut_map`] into `0..=peak` (an HDR render's range; `peak = 1.0` is [`gamut_map`]).
|
||||
#[inline]
|
||||
pub fn gamut_map_to(r: [f32; 3], luma: [f32; 3], peak: f32) -> ([f32; 3], f32) {
|
||||
let yy = (luma[0] * r[0] + luma[1] * r[1] + luma[2] * r[2]).clamp(0.0, peak);
|
||||
let mut t = 1.0f32;
|
||||
for c in r {
|
||||
if c < 0.0 {
|
||||
t = t.min(yy / (yy - c).max(1e-9));
|
||||
} else if c > peak {
|
||||
t = t.min((peak - yy) / (c - yy).max(1e-9));
|
||||
}
|
||||
}
|
||||
if t < 1.0 { (r.map(|c| yy + (c - yy) * t), t) } else { (r, 1.0) }
|
||||
}
|
||||
|
||||
/// Refine Saturation: scale the curved colour's chroma (around its luma, encoded values) so its
|
||||
/// saturation (chroma / luma) moves from the curve's towards the pre-curve one: the ratio is
|
||||
/// `(s_curve / s_before)^refine`, so `1` keeps the curve and `0` restores the original saturation.
|
||||
#[inline]
|
||||
pub fn refine_saturation(before: [f32; 3], after: [f32; 3], refine: f32) -> [f32; 3] {
|
||||
let luma = |e: [f32; 3]| 0.2126 * e[0] + 0.7152 * e[1] + 0.0722 * e[2];
|
||||
let chroma = |e: [f32; 3]| e[0].max(e[1]).max(e[2]) - e[0].min(e[1]).min(e[2]);
|
||||
let (y0, y1) = (luma(before), luma(after));
|
||||
let s0 = chroma(before) / y0.max(1e-4);
|
||||
let s1 = chroma(after) / y1.max(1e-4);
|
||||
if s1 <= 1e-6 || s0 <= 1e-6 {
|
||||
return after;
|
||||
}
|
||||
let k = (s0 / s1).powf(1.0 - refine).clamp(0.0, 4.0);
|
||||
after.map(|v| y1 + (v - y1) * k)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sharpen_helpers_behave_smoothly_and_bound_detail() {
|
||||
assert_eq!(sharpen_mask_weight(0.0, 0.0), 1.0);
|
||||
assert_eq!(pixel_sharpen_mask_weight(0.0, 0.0), 1.0);
|
||||
assert_eq!(sharpen_mask_weight(0.8, 0.0), 0.0);
|
||||
assert!(sharpen_mask_weight(0.8, 1.0) == 1.0);
|
||||
assert!((sharpen_limit(0.0) - 0.03).abs() < 1e-6);
|
||||
assert!((sharpen_limit(100.0) - 1.5).abs() < 1e-4);
|
||||
let lim = sharpen_limit(50.0);
|
||||
assert!(sharpen_term(0.0, lim, 0.0) == 0.0);
|
||||
assert!(sharpen_term(10.0, lim, 0.0) < SHARPEN_GAIN * lim);
|
||||
assert!(sharpen_term(0.1, lim, 0.0) > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vignette_resolves_only_when_nonzero() {
|
||||
let mut s = DevelopSettings::default();
|
||||
assert!(vignette(&s).is_none());
|
||||
s.vignette.amount = -50.0;
|
||||
s.vignette.roundness = -100.0;
|
||||
let v = vignette(&s).unwrap();
|
||||
assert!((v.amount - -0.5).abs() < 1e-6);
|
||||
assert!((v.power - 8.0).abs() < 1e-6);
|
||||
assert!((v.aspect_mix - 0.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grain_is_bounded_and_handles_non_finite_coords() {
|
||||
let mut s = DevelopSettings::default();
|
||||
assert!(value_grain(&s, 2000.0).is_none());
|
||||
s.grain.amount = 50.0;
|
||||
s.grain.size = 25.0;
|
||||
s.grain.roughness = 50.0;
|
||||
let g = value_grain(&s, 2000.0).unwrap();
|
||||
assert!(g.amt > 0.0 && g.cell >= 0.6);
|
||||
assert_eq!(grain_noise(f32::NAN, 1.0, 7), 0.0);
|
||||
assert_eq!(grain_noise(1.0, f32::INFINITY, 7), 0.0);
|
||||
for i in 0..20 {
|
||||
let n = grain_noise(i as f32 * 0.37, i as f32 * 0.71, g.seed);
|
||||
assert!((-1.0..=1.0).contains(&n), "{n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gamut_map_clamps_out_of_gamut_towards_luma() {
|
||||
let luma = [0.2126, 0.7152, 0.0722];
|
||||
let (in_gamut, t0) = gamut_map([0.2, 0.5, 0.8], luma);
|
||||
assert_eq!(in_gamut, [0.2, 0.5, 0.8]);
|
||||
assert_eq!(t0, 1.0);
|
||||
|
||||
let (mapped, t1) = gamut_map([1.5, -0.2, 0.3], luma);
|
||||
assert!(t1 < GAMUT_WARN);
|
||||
assert!(mapped.iter().all(|&c| (-1e-6..=1.0 + 1e-6).contains(&c)), "{mapped:?}");
|
||||
|
||||
let (hdr, t2) = gamut_map_to([2.5, 0.5, 0.5], luma, 4.0);
|
||||
assert_eq!(hdr, [2.5, 0.5, 0.5]);
|
||||
assert_eq!(t2, 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refine_saturation_interpolates_between_original_and_curved() {
|
||||
let before = [0.4, 0.2, 0.1];
|
||||
let after = [0.6, 0.3, 0.15];
|
||||
assert_eq!(refine_saturation(before, after, 1.0), after);
|
||||
let neutral = refine_saturation([0.3, 0.3, 0.3], [0.5, 0.5, 0.5], 0.5);
|
||||
assert_eq!(neutral, [0.5, 0.5, 0.5]);
|
||||
}
|
||||
}
|
||||
@@ -5,5 +5,7 @@
|
||||
|
||||
pub mod color;
|
||||
pub mod curve;
|
||||
pub mod finish;
|
||||
pub mod inpaint;
|
||||
pub mod lut;
|
||||
pub mod tone;
|
||||
|
||||
@@ -0,0 +1,696 @@
|
||||
//! The global tone map: scene luminance → display-linear luminance.
|
||||
//!
|
||||
//! Built in the log domain around middle grey (0.18): contrast scales log-exposure about grey,
|
||||
//! whites move the shoulder (white point), blacks move the toe. The shoulder is an extended
|
||||
//! Reinhard curve so highlights roll off smoothly instead of clipping.
|
||||
//!
|
||||
//! Rendered (display-referred) sources such as JPEGs use [`ToneMap::display`] instead: identity at
|
||||
//! neutral settings (an unedited JPEG renders exactly as the file), with contrast/whites/blacks as
|
||||
//! S-curve adjustments in a gamma-2.2 perceptual domain and a short shoulder above 0.95.
|
||||
|
||||
pub const GREY: f32 = 0.18;
|
||||
/// The tone LUT spans `LUT_MIN_EV..LUT_MAX_EV` around grey in `LUT_N` steps.
|
||||
pub const LUT_MIN_EV: f32 = -14.0;
|
||||
pub const LUT_MAX_EV: f32 = 10.0;
|
||||
pub const LUT_N: usize = 4096;
|
||||
/// Nodes of a camera chroma curve, evenly spaced over display luminance 0..=1.
|
||||
pub const CHROMA_N: usize = 8;
|
||||
const NO_CHROMA: [f32; CHROMA_N] = [1.0; CHROMA_N];
|
||||
|
||||
/// A file-local camera look, fitted independently of the scene-linear colour transform.
|
||||
/// Knots are scene/display-linear luminance pairs. Keeping this in the finish stage preserves
|
||||
/// RAW exposure and highlight headroom; it is never baked into the decoded sensor pixels.
|
||||
/// `chroma` scales colourfulness by display luminance after the curve (a camera's per-channel
|
||||
/// curve saturates shadows and bleaches highlights toward white, which a luminance curve can't).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize)]
|
||||
pub struct CameraTone {
|
||||
knots: [[f32; 2]; 32],
|
||||
chroma: [f32; CHROMA_N],
|
||||
}
|
||||
|
||||
impl<'de> serde::Deserialize<'de> for CameraTone {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct Wire {
|
||||
knots: [[f32; 2]; 32],
|
||||
// absent in smart previews written before the chroma curve existed
|
||||
#[serde(default)]
|
||||
chroma: Option<[f32; CHROMA_N]>,
|
||||
}
|
||||
let w = Wire::deserialize(d)?;
|
||||
let tone = Self::new(w.knots).ok_or_else(|| serde::de::Error::custom("invalid camera tone curve"))?;
|
||||
match w.chroma {
|
||||
Some(c) => tone.with_chroma(c).ok_or_else(|| serde::de::Error::custom("invalid camera chroma curve")),
|
||||
None => Ok(tone),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CameraTone {
|
||||
pub fn new(knots: [[f32; 2]; 32]) -> Option<Self> {
|
||||
let mut previous = [0.0, 0.0];
|
||||
for p in knots {
|
||||
if !p.iter().all(|v| v.is_finite()) || p[0] <= previous[0] || p[1] < previous[1] || p[1] >= 1.0 {
|
||||
return None;
|
||||
}
|
||||
previous = p;
|
||||
}
|
||||
Some(Self { knots, chroma: NO_CHROMA })
|
||||
}
|
||||
|
||||
/// The curve with chroma scales at display luminance 0, 1/7 … 1 (each finite, 0..=4).
|
||||
pub fn with_chroma(self, chroma: [f32; CHROMA_N]) -> Option<Self> {
|
||||
chroma.iter().all(|k| k.is_finite() && (0.0..=4.0).contains(k)).then_some(Self { chroma, ..self })
|
||||
}
|
||||
|
||||
pub fn chroma(&self) -> &[f32; CHROMA_N] {
|
||||
&self.chroma
|
||||
}
|
||||
|
||||
/// The (scene, display) luminance knots, in increasing order.
|
||||
pub fn knots(&self) -> &[[f32; 2]; 32] {
|
||||
&self.knots
|
||||
}
|
||||
|
||||
pub fn apply(&self, y: f32) -> f32 {
|
||||
if !y.is_finite() || y <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let mut previous = [0.0, 0.0];
|
||||
for p in self.knots {
|
||||
if y <= p[0] {
|
||||
let t = (y - previous[0]) / (p[0] - previous[0]);
|
||||
return previous[1] + t * (p[1] - previous[1]);
|
||||
}
|
||||
previous = p;
|
||||
}
|
||||
let a = self.knots[30];
|
||||
let b = self.knots[31];
|
||||
// Extend beyond observed (unclipped) highlights with a continuous, bounded shoulder.
|
||||
let slope = ((b[1] - a[1]) / (b[0] - a[0])).clamp(0.1, 16.0);
|
||||
1.0 - (1.0 - b[1]) * (-(y - b[0]) * slope / (1.0 - b[1]).max(0.01)).exp()
|
||||
}
|
||||
|
||||
/// [`CameraTone::apply`] as process V5 extends it past the last knot (issue #1632). The curve is
|
||||
/// fitted only to camera JPEG tones below 0.85, so its last knot lies 1 to 3 stops below the
|
||||
/// sensor's white on most photos and everything above it is extrapolated. [`CameraTone::apply`]
|
||||
/// closes the gap to white exponentially in linear light: it reaches 8-bit 255 within about a
|
||||
/// stop past the sensor's white, and Exposure +1 turns the top stop the sensor recorded white.
|
||||
/// Here the gap shrinks in stops instead, `gap / (1 + c·(2^(k·t) − 1))` at `t` stops past the
|
||||
/// knot, with `c` matching the curve's slope there (so the join is smooth) and the gap halving
|
||||
/// every [`ROLLOFF_STOPS`] stops in the end. Same value as [`CameraTone::apply`] up to the last
|
||||
/// knot, monotone, finite and at most 1. In real numbers it only approaches white; in `f32` the
|
||||
/// gap can round to 0 far up, and within a stop or two for a last knot a few ulps below white.
|
||||
pub fn apply_rolloff(&self, y: f32) -> f32 {
|
||||
let (a, b) = (self.knots[30], self.knots[31]);
|
||||
if !y.is_finite() || y <= b[0] {
|
||||
return self.apply(y);
|
||||
}
|
||||
// the last segment's own slope, so the join is smooth even when it is flat (`new` keeps the
|
||||
// knots non-decreasing, so it is at least 0)
|
||||
let slope = ((b[1] - a[1]) / (b[0] - a[0])).max(0.0);
|
||||
// `CameraTone::new` keeps the last knot below 1, so the gap is positive (no floor: one
|
||||
// would step the curve down past a knot within it of white)
|
||||
rolloff_past(y, b, slope, CAMERA_MIN_SLOPE)
|
||||
}
|
||||
}
|
||||
|
||||
/// The pace [`CameraTone::apply_rolloff`] closes on white at least at, as display per unit of scene
|
||||
/// luminance at the last knot (the floor [`CameraTone::apply`] puts on its slope there). A last
|
||||
/// segment flatter than this still joins with its own slope; [`rolloff_past`] then adds a term that
|
||||
/// has no slope at the knot and reaches this pace further up, so a flat curve does not stay below
|
||||
/// white.
|
||||
const CAMERA_MIN_SLOPE: f32 = 0.1;
|
||||
|
||||
/// Stops in which the gap between a V5 curve and white halves, far past where its shoulder starts
|
||||
/// ([`CameraTone::apply_rolloff`], [`ToneMap::rolloff_hdr`]). With 1, the sensor's white renders at
|
||||
/// 8-bit 239–250 on the CC0 corpus files with a camera curve (Sony, Nikon, Fujifilm) at Exposure 0
|
||||
/// and below 254 up to Exposure +2, where the extension of [`CameraTone::apply`] reaches 254–255 by
|
||||
/// Exposure +1 (issue #1632).
|
||||
pub const ROLLOFF_STOPS: f32 = 1.0;
|
||||
|
||||
/// Process V5's shoulder past a knee at scene luminance `x` and display `o` (below 1), where the
|
||||
/// curve rises at `slope` (display per unit of scene luminance): the gap to white is
|
||||
/// `gap / (1 + c·(2^(k·t) − 1))` at `t = log2(y / x)` stops past the knee, `k = 1 / ROLLOFF_STOPS`,
|
||||
/// so it halves every [`ROLLOFF_STOPS`] stops in the end. `c` gives it the curve's slope at the
|
||||
/// knee: d(display)/d(stop) there is `slope · x · ln 2` on the curve and `gap · c · k · ln 2` on the
|
||||
/// shoulder. When `slope` is below `min_slope`, `d · (u − ln(1 + u))` (with `u = 2^(k·t) − 1`)
|
||||
/// joins the denominator: it adds no slope at the knee, so the join keeps the curve's own slope, and
|
||||
/// far up it grows like `d · u`, so the shoulder closes on white at `min_slope`'s pace (the gap still
|
||||
/// halves every [`ROLLOFF_STOPS`] stops in the end). A term growing faster than `u` would close a
|
||||
/// flat curve on white faster than a steeper one far up, and a darker curve would end up above it.
|
||||
/// Monotone for `y ≥ x`, finite and at most 1; in real numbers it only approaches white, while in
|
||||
/// `f32` the gap rounds to 0 eventually.
|
||||
fn rolloff_past(y: f32, [x, o]: [f32; 2], slope: f32, min_slope: f32) -> f32 {
|
||||
let gap = 1.0 - o;
|
||||
let k = 1.0 / ROLLOFF_STOPS;
|
||||
// bounded, so `c · 0` right past the knee stays 0 for a gap of a few ulps
|
||||
let per = |s: f32| (s * x / (gap * k)).min(1e30);
|
||||
let c = per(slope);
|
||||
let d = (per(min_slope) - c).max(0.0);
|
||||
let u = (k * (y / x).log2()).exp2() - 1.0;
|
||||
// each term only when its coefficient is positive: `0 · ∞` is NaN far up
|
||||
let linear = if c > 0.0 { c * u } else { 0.0 };
|
||||
let floor = if d > 0.0 { d * past_join(u) } else { 0.0 };
|
||||
1.0 - gap / (1.0 + linear + floor)
|
||||
}
|
||||
|
||||
/// `u − ln(1 + u)` for `u ≥ 0`: 0 with no slope at 0, then rising like `u` (infinite for infinite
|
||||
/// `u`). In `f64`, where the difference keeps its digits down to tiny `u`.
|
||||
fn past_join(u: f32) -> f32 {
|
||||
if u.is_infinite() {
|
||||
return u;
|
||||
}
|
||||
let u = f64::from(u);
|
||||
(u - u.ln_1p()).max(0.0) as f32
|
||||
}
|
||||
|
||||
/// Stops below its white point where process V5's generic raw curve ([`ToneMap::rolloff_hdr`])
|
||||
/// leaves the extended Reinhard curve for the [`ROLLOFF_STOPS`] shoulder, instead of clipping at
|
||||
/// the white point. With ½, the sensor's white of a raw without a camera curve (scene 1.0, about
|
||||
/// ¼ stop below that white point at default settings) renders at about 8-bit 235, 248 and 252 at
|
||||
/// Exposure 0, +1 and +2 where V1 to V4 render 239, 255 and 255 (issue #1632).
|
||||
pub const GENERIC_KNEE_STOPS: f32 = 0.5;
|
||||
|
||||
/// Scene EV over grey where [`ToneMap::hdr`] starts lifting highlights above the SDR curve.
|
||||
const HDR_FROM_EV: f32 = 1.5;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ToneMap {
|
||||
lut: Vec<f32>,
|
||||
chroma: [f32; CHROMA_N],
|
||||
}
|
||||
|
||||
impl ToneMap {
|
||||
pub fn camera(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
ToneMap::camera_hdr(curve, contrast, whites, blacks, 1.0)
|
||||
}
|
||||
|
||||
/// [`ToneMap::camera`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR
|
||||
/// exactly): the camera's look up to 1.5 EV over grey, so midtones match the SDR render (and a
|
||||
/// gain map only lifts highlights), then the highlights gain up to `peak − 1` more as in
|
||||
/// [`ToneMap::hdr`].
|
||||
pub fn camera_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::camera_with(|y| curve.apply(y), curve.chroma, contrast, whites, blacks, peak)
|
||||
}
|
||||
|
||||
/// [`ToneMap::camera_hdr`] of process V5: past its last knot the camera curve rolls off in stops
|
||||
/// ([`CameraTone::apply_rolloff`]) instead of closing on white within a stop of the sensor's.
|
||||
pub fn camera_rolloff_hdr(curve: &CameraTone, contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::camera_with(|y| curve.apply_rolloff(y), curve.chroma, contrast, whites, blacks, peak)
|
||||
}
|
||||
|
||||
fn camera_with(curve: impl Fn(f32) -> f32, chroma: [f32; CHROMA_N], contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let adjustment = Self::display(contrast, whites, blacks);
|
||||
let neutral = contrast == 0.0 && whites == 0.0 && blacks == 0.0;
|
||||
let top = (2.9 - 1.6 * (whites as f32 / 100.0) + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5);
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = curve(GREY * 2f32.powf(ev));
|
||||
let o = if neutral { y } else { adjustment.apply(y) };
|
||||
if peak > 1.0 { (o + (peak - 1.0) * smooth(HDR_FROM_EV, top, ev)).clamp(0.0, peak) } else { o }
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma }
|
||||
}
|
||||
/// `contrast`, `whites`, `blacks` in −100..100 (Lightroom slider units).
|
||||
pub fn new(contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
ToneMap::hdr(contrast, whites, blacks, 1.0)
|
||||
}
|
||||
|
||||
/// [`ToneMap::new`] for an HDR render reaching `peak` (linear, SDR white = 1; 1 = SDR exactly).
|
||||
/// Below about half of SDR white the curve is the SDR one; above, the highlights gain up to
|
||||
/// `peak − 1` more along a smoothstep in scene EV, from 1.5 EV over grey to one stop past the
|
||||
/// white point moved up by the headroom, so the result stays monotone, never exceeds `peak`,
|
||||
/// and reaches it there (within the table's range).
|
||||
pub fn hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::generic(contrast, whites, blacks, peak, false)
|
||||
}
|
||||
|
||||
/// [`ToneMap::hdr`] of process V5 (issue #1632): from [`GENERIC_KNEE_STOPS`] below the white
|
||||
/// point the curve rolls off into white in stops, with the same value and slope at the join,
|
||||
/// instead of reaching white about ¼ stop past the sensor's white and clipping there. The SDR
|
||||
/// curve stays below 1 (SDR white) and is the same as [`ToneMap::hdr`]'s below the join; for
|
||||
/// `peak` above 1 the HDR lift then takes highlights up to `peak`, as in [`ToneMap::hdr`].
|
||||
pub fn rolloff_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
ToneMap::generic(contrast, whites, blacks, peak, true)
|
||||
}
|
||||
|
||||
fn generic(contrast: f64, whites: f64, blacks: f64, peak: f32, rolloff: bool) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let c = (contrast / 100.0) as f32;
|
||||
let slope = if c >= 0.0 { 1.0 + 0.55 * c } else { 1.0 + 0.4 * c };
|
||||
// White point: scene luminance (after contrast) that maps to display 1.0.
|
||||
let white_ev = 2.9 - 1.6 * (whites as f32 / 100.0);
|
||||
let wl = GREY * 2f32.powf(white_ev);
|
||||
let pre = 1.0 + GREY / wl; // keep grey near grey
|
||||
let b = (blacks / 100.0) as f32;
|
||||
// extended Reinhard with white point wl: y(1 + y/wl²)/(1 + y), reaching 1 at wl
|
||||
let reinhard = |y: f32| y * (1.0 + y / (wl * wl)) / (1.0 + y);
|
||||
// V5's knee, below the white point, and the curve's slope there: (1 + y(2 + y)/wl²)/(1 + y)²
|
||||
let knee = wl * (-GENERIC_KNEE_STOPS).exp2();
|
||||
let knee_slope = (1.0 + knee * (2.0 + knee) / (wl * wl)) / ((1.0 + knee) * (1.0 + knee));
|
||||
let knee = [knee, reinhard(knee)];
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = GREY * 2f32.powf(ev * slope) * pre;
|
||||
let mut o = if rolloff && y > knee[0] && knee[1] < 1.0 { rolloff_past(y, knee, knee_slope, 0.0) } else { reinhard(y) };
|
||||
o = o.min(1.0);
|
||||
// Toe: blacks < 0 crushes, > 0 lifts.
|
||||
if b < 0.0 {
|
||||
// Smooth max(0, o − k) (a soft knee), renormalized so 1 stays 1.
|
||||
let k = -b * 0.035;
|
||||
let e = 0.004;
|
||||
let soft = |v: f32| ((v - k) + ((v - k) * (v - k) + e * e).sqrt()) * 0.5;
|
||||
o = (soft(o) - soft(0.0)) / (soft(1.0) - soft(0.0));
|
||||
} else if b > 0.0 {
|
||||
let k = b * 0.03;
|
||||
o = k + (1.0 - k) * o;
|
||||
}
|
||||
if peak > 1.0 {
|
||||
let top = (white_ev + peak.log2() + 1.0).max(HDR_FROM_EV + 0.5);
|
||||
o += (peak - 1.0) * smooth(HDR_FROM_EV, top, ev * slope);
|
||||
}
|
||||
o.clamp(0.0, peak)
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma: NO_CHROMA }
|
||||
}
|
||||
|
||||
/// Tone map for display-referred sources: identity at neutral settings.
|
||||
pub fn display(contrast: f64, whites: f64, blacks: f64) -> ToneMap {
|
||||
ToneMap::display_hdr(contrast, whites, blacks, 1.0)
|
||||
}
|
||||
|
||||
/// [`ToneMap::display`] for an HDR render reaching `peak`: values above SDR white (an HDR
|
||||
/// source, e.g. a decoded gain-map image) pass through and roll off softly towards `peak`
|
||||
/// instead of clipping at 1; SDR sources (≤ 1) render as with [`ToneMap::display`].
|
||||
pub fn display_hdr(contrast: f64, whites: f64, blacks: f64, peak: f32) -> ToneMap {
|
||||
let peak = if peak.is_finite() { peak.max(1.0) } else { 1.0 };
|
||||
let c = (contrast / 100.0) as f32;
|
||||
let w = (whites / 100.0) as f32;
|
||||
let b = (blacks / 100.0) as f32;
|
||||
let m = GREY.powf(1.0 / 2.2);
|
||||
// Neutral sliders are the identity up to white (issue #1945): the SDR shoulder below would
|
||||
// pull 1.0 down to 0.9875 (8-bit 255 to 254), so it only shapes an edited curve.
|
||||
let neutral = c == 0.0 && w == 0.0 && b == 0.0;
|
||||
let lut = (0..LUT_N)
|
||||
.map(|i| {
|
||||
let ev = LUT_MIN_EV + (LUT_MAX_EV - LUT_MIN_EV) * i as f32 / (LUT_N - 1) as f32;
|
||||
let y = GREY * 2f32.powf(ev);
|
||||
let mut p = y.powf(1.0 / 2.2);
|
||||
if p <= 1.0 {
|
||||
// S-curve anchored at 0, grey and 1
|
||||
p += c * 0.35 * (p - m) * (1.0 - (2.0 * p - 1.0).powi(2));
|
||||
// whites: lift/lower the upper tones; blacks: the lower tones
|
||||
let up = smooth(0.45, 1.0, p);
|
||||
p += w * 0.12 * up * (1.0 - p * 0.5);
|
||||
let lo = 1.0 - smooth(0.0, 0.45, p);
|
||||
p += b * 0.07 * lo * (p * 2.0).min(1.0);
|
||||
} else {
|
||||
p += w * 0.12 * 0.5;
|
||||
}
|
||||
let mut o = p.max(0.0).powf(2.2);
|
||||
// short shoulder (SDR, edited curves): slope 1 at 0.95, reaching 1.0 at 1.05
|
||||
if peak > 1.0 && o > 0.95 {
|
||||
// exponential shoulder: slope 1 at 0.95, asymptote at `peak`
|
||||
let r = peak - 0.95;
|
||||
o = 0.95 + r * (1.0 - (-(o - 0.95) / r).exp());
|
||||
} else if o > 0.95 && !neutral {
|
||||
let d = (o - 0.95).min(0.1);
|
||||
o = 0.95 + d - d * d / 0.2;
|
||||
}
|
||||
o.clamp(0.0, peak)
|
||||
})
|
||||
.collect();
|
||||
ToneMap { lut, chroma: NO_CHROMA }
|
||||
}
|
||||
|
||||
/// The table (`LUT_N` entries, see [`ToneMap::apply`]).
|
||||
pub fn lut(&self) -> &[f32] {
|
||||
&self.lut
|
||||
}
|
||||
|
||||
/// The chroma curve (`CHROMA_N` entries, see [`ToneMap::chroma_scale`]).
|
||||
pub fn chroma_lut(&self) -> &[f32] {
|
||||
&self.chroma
|
||||
}
|
||||
|
||||
/// Chroma scale at display luminance `o` (exactly 1 everywhere unless a camera look sets it).
|
||||
#[inline]
|
||||
pub fn chroma_scale(&self, o: f32) -> f32 {
|
||||
if !o.is_finite() {
|
||||
return 1.0;
|
||||
}
|
||||
let f = o.clamp(0.0, 1.0) * (CHROMA_N - 1) as f32;
|
||||
let i = (f as usize).min(CHROMA_N - 2);
|
||||
let t = f - i as f32;
|
||||
let (a, b) = (self.chroma.get(i).copied().unwrap_or(1.0), self.chroma.get(i + 1).copied().unwrap_or(1.0));
|
||||
if a == b { a } else { a + (b - a) * t }
|
||||
}
|
||||
|
||||
/// Scene luminance → display-linear luminance.
|
||||
#[inline]
|
||||
pub fn apply(&self, y: f32) -> f32 {
|
||||
if y <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let ev = (y / GREY).log2();
|
||||
let f = ((ev - LUT_MIN_EV) / (LUT_MAX_EV - LUT_MIN_EV)).clamp(0.0, 1.0) * (LUT_N - 1) as f32;
|
||||
let i = (f as usize).min(LUT_N - 2);
|
||||
let t = f - i as f32;
|
||||
let v = self.lut[i] + (self.lut[i + 1] - self.lut[i]) * t;
|
||||
if ev < LUT_MIN_EV { v * (y / (GREY * 2f32.powf(LUT_MIN_EV))) } else { v }
|
||||
}
|
||||
}
|
||||
|
||||
fn smooth(e0: f32, e1: f32, x: f32) -> f32 {
|
||||
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn knots() -> [[f32; 2]; 32] {
|
||||
std::array::from_fn(|i| {
|
||||
let x = 0.004 * 1.18f32.powi(i as i32);
|
||||
[x, 1.0 - (-2.0 * x).exp()]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chroma_curve_is_identity_unless_set_and_survives_serde() {
|
||||
let plain = CameraTone::new(knots()).unwrap();
|
||||
let map = ToneMap::camera(&plain, 0.0, 0.0, 0.0);
|
||||
assert!([0.0, 0.3, 0.77, 1.0, 2.0].iter().all(|o| map.chroma_scale(*o) == 1.0));
|
||||
assert!([0.0, 0.5, 1.0].iter().all(|o| ToneMap::new(0.0, 0.0, 0.0).chroma_scale(*o) == 1.0));
|
||||
// smart previews written before the chroma curve existed still load (identity)
|
||||
let old = serde_json::json!({ "knots": knots() });
|
||||
assert_eq!(serde_json::from_value::<CameraTone>(old).unwrap(), plain);
|
||||
let tone = plain.with_chroma([1.4, 1.3, 1.1, 1.0, 0.7, 0.4, 0.25, 0.2]).unwrap();
|
||||
let back: CameraTone = serde_json::from_value(serde_json::to_value(tone).unwrap()).unwrap();
|
||||
assert_eq!(back, tone);
|
||||
let map = ToneMap::camera(&tone, 0.0, 0.0, 0.0);
|
||||
assert!((map.chroma_scale(0.0) - 1.4).abs() < 1e-6 && (map.chroma_scale(1.0) - 0.2).abs() < 1e-6);
|
||||
assert!((map.chroma_scale(0.5 / 7.0) - 1.35).abs() < 1e-5, "interpolates between nodes");
|
||||
assert_eq!(map.chroma_scale(f32::NAN), 1.0);
|
||||
// hostile values are rejected, also when deserialized
|
||||
assert!(plain.with_chroma([f32::NAN; CHROMA_N]).is_none());
|
||||
assert!(plain.with_chroma([-1.0; CHROMA_N]).is_none());
|
||||
let bad = serde_json::json!({ "knots": knots(), "chroma": [9.0, 1, 1, 1, 1, 1, 1, 1] });
|
||||
assert!(serde_json::from_value::<CameraTone>(bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_curve_preserves_black_and_extends_headroom() {
|
||||
let knots = std::array::from_fn(|i| {
|
||||
let x = 0.005 * 1.15f32.powi(i as i32);
|
||||
[x, 1.0 - (-3.0 * x).exp()]
|
||||
});
|
||||
let curve = CameraTone::new(knots).unwrap();
|
||||
let base = ToneMap::camera(&curve, 0.0, 0.0, 0.0);
|
||||
assert_eq!(base.apply(0.0), 0.0);
|
||||
assert!(base.apply(0.1) < base.apply(0.2));
|
||||
let mut previous = 0.0;
|
||||
for i in 0..2000 {
|
||||
let y = 1e-6 * 1.01f32.powi(i);
|
||||
let v = base.apply(y);
|
||||
assert!((0.0..=1.0).contains(&v));
|
||||
assert!(v >= previous - 1e-6);
|
||||
previous = v;
|
||||
}
|
||||
assert!((base.apply(0.1) - curve.apply(0.1)).abs() < 0.001);
|
||||
assert!(ToneMap::camera(&curve, 50.0, 0.0, 0.0).apply(0.3) > base.apply(0.3));
|
||||
let mut invalid = knots;
|
||||
invalid[1][0] = invalid[0][0];
|
||||
assert!(CameraTone::new(invalid).is_none());
|
||||
assert!(serde_json::from_value::<CameraTone>(serde_json::json!({"knots": invalid})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rolloff_joins_the_curve_smoothly_and_never_reaches_white() {
|
||||
let curve = CameraTone::new(knots()).unwrap();
|
||||
let last = curve.knots()[31];
|
||||
// the camera's curve up to the last knot
|
||||
for i in 0..200 {
|
||||
let y = last[0] * i as f32 / 199.0;
|
||||
assert_eq!(curve.apply_rolloff(y), curve.apply(y), "{y}");
|
||||
}
|
||||
// continuous, with the slope of the last segment, at the knot
|
||||
let a = curve.knots()[30];
|
||||
let slope = (last[1] - a[1]) / (last[0] - a[0]);
|
||||
let h = last[0] * 1e-3;
|
||||
let after = (curve.apply_rolloff(last[0] + h) - curve.apply_rolloff(last[0])) / h;
|
||||
assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}");
|
||||
// monotone, below white, and slower to close on it than the V1/V2 extension
|
||||
let mut previous = last[1];
|
||||
for i in 1..3000 {
|
||||
let y = last[0] * 1.005f32.powi(i);
|
||||
let o = curve.apply_rolloff(y);
|
||||
assert!(o >= previous && o < 1.0, "{y}: {o}");
|
||||
assert!(o <= curve.apply(y) + 1e-6, "{y}");
|
||||
previous = o;
|
||||
}
|
||||
assert!(1.0 - curve.apply_rolloff(last[0] * 8.0) > 4.0 * (1.0 - curve.apply(last[0] * 8.0)));
|
||||
// a steep last segment joins with its own slope, and a last knot next to white without a step
|
||||
for top in [0.9, 0.99995, 1.0 - f32::EPSILON] {
|
||||
let mut k = knots();
|
||||
k[31] = [k[30][0] * 1.01, top];
|
||||
let c = CameraTone::new(k).unwrap();
|
||||
let slope = (k[31][1] - k[30][1]) / (k[31][0] - k[30][0]);
|
||||
assert!(slope > 16.0 || top < 0.99, "{slope}");
|
||||
let mut prev = c.apply_rolloff(k[31][0]);
|
||||
assert_eq!(prev, top);
|
||||
for i in 1..2000 {
|
||||
let o = c.apply_rolloff(k[31][0] * 1.0001f32.powi(i));
|
||||
assert!(o.is_finite() && o >= prev && o <= 1.0, "{top} {i}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
if top == 0.9 {
|
||||
let h = k[31][0] * 1e-5;
|
||||
let after = (c.apply_rolloff(k[31][0] + h) - top) / h;
|
||||
assert!((after - slope).abs() < 0.02 * slope, "{after} vs {slope}");
|
||||
}
|
||||
}
|
||||
// a flat or shallow last segment joins with its own slope (not the 0.1 floor of the V1/V2
|
||||
// extension) and still closes on white further up
|
||||
for s in [0.0f32, 0.05] {
|
||||
let mut k = knots();
|
||||
k[31][1] = k[30][1] + s * (k[31][0] - k[30][0]);
|
||||
let c = CameraTone::new(k).unwrap();
|
||||
let (x, top) = (k[31][0], k[31][1]);
|
||||
let h = x * 1e-4;
|
||||
let after = (c.apply_rolloff(x + h) - top) / h;
|
||||
assert!((after - s).abs() < 0.01, "{s}: right slope {after}");
|
||||
let mut prev = top;
|
||||
for i in 1..3000 {
|
||||
let o = c.apply_rolloff(x * 1.005f32.powi(i));
|
||||
assert!(o.is_finite() && o >= prev && o <= 1.0, "{s} {i}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
assert!(1.0 - c.apply_rolloff(x * 64.0) < (1.0 - top) / 4.0, "{s}");
|
||||
for y in [f32::MAX, f32::INFINITY] {
|
||||
assert!((0.0..=1.0).contains(&c.apply_rolloff(y)), "{s} {y}");
|
||||
}
|
||||
}
|
||||
// hostile input
|
||||
for y in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX] {
|
||||
let o = curve.apply_rolloff(y);
|
||||
assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}");
|
||||
}
|
||||
// the tone map built from it is monotone and bounded, SDR and HDR
|
||||
for peak in [1.0f32, 4.0] {
|
||||
let t = ToneMap::camera_rolloff_hdr(&curve, 0.0, 0.0, 0.0, peak);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let o = t.apply(1e-5 * 1.01f32.powi(i));
|
||||
assert!((0.0..=peak).contains(&o) && o >= prev - 1e-6, "{peak} {i}: {o}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_rolloff_joins_the_curve_smoothly_and_never_reaches_white() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0), (0.0, -100.0, 0.0)] {
|
||||
for peak in [1.0f32, 4.0] {
|
||||
let (clip, roll) = (ToneMap::hdr(c, w, b, peak), ToneMap::rolloff_hdr(c, w, b, peak));
|
||||
let (clip, roll) = (clip.lut(), roll.lut());
|
||||
// the generic curve up to the knee, never brighter past it
|
||||
let join = roll.iter().zip(clip).position(|(r, c)| r != c).expect("the shoulder starts inside the table");
|
||||
assert!(join > 2 && roll[join] < clip[join], "{c} {w} {b} {peak}: {join}");
|
||||
for (i, (r, c)) in roll.iter().zip(clip).enumerate() {
|
||||
assert!(*r <= c + 1e-6, "{c} {w} {b} {peak} {i}: {r} > {c}");
|
||||
}
|
||||
// same value and slope at the join: the step across it is the step before it
|
||||
let (before, across) = (roll[join - 1] - roll[join - 2], roll[join] - roll[join - 1]);
|
||||
assert!((across / before - 1.0).abs() < 0.02, "{c} {w} {b} {peak}: {before} then {across}");
|
||||
// monotone, and below white where the V1/V2 curve clips (SDR) or lifts to `peak` (HDR)
|
||||
assert!(roll.windows(2).all(|p| p[1] >= p[0] - 1e-6), "{c} {w} {b} {peak}");
|
||||
if peak == 1.0 {
|
||||
assert_eq!(clip[LUT_N - 1], 1.0);
|
||||
// close to it at the top of the table at default settings (10 EV over grey);
|
||||
// Whites −100 moves the white point, and so the shoulder, up 1.6 stops
|
||||
let top = roll[LUT_N - 1];
|
||||
assert!(top < 1.0 && (top > 0.999 || w < 0.0), "{c} {w} {b}: {top}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// no kink where V1/V2 clip: there the clipped curve stops rising at once
|
||||
let (clip, roll) = (ToneMap::new(0.0, 0.0, 0.0), ToneMap::rolloff_hdr(0.0, 0.0, 0.0, 1.0));
|
||||
let kink = |lut: &[f32]| lut.windows(3).filter(|p| p[1] - p[0] > 1e-5).map(|p| 1.0 - (p[2] - p[1]) / (p[1] - p[0])).fold(0.0f32, f32::max);
|
||||
assert!(kink(clip.lut()) > 0.9);
|
||||
assert!(kink(roll.lut()) < 0.05, "{}", kink(roll.lut()));
|
||||
// hostile input (NaN passes through `ToneMap::apply` as on every curve)
|
||||
for y in [f32::INFINITY, f32::NEG_INFINITY, -1.0, 0.0, f32::MAX, f32::MIN_POSITIVE] {
|
||||
let o = roll.apply(y);
|
||||
assert!(o.is_finite() && (0.0..=1.0).contains(&o), "{y}: {o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn monotone_and_bounded() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] {
|
||||
let t = ToneMap::new(c, w, b);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2000 {
|
||||
let y = 1e-5 * 1.012f32.powi(i);
|
||||
let o = t.apply(y);
|
||||
assert!((0.0..=1.0).contains(&o));
|
||||
assert!(o >= prev - 1e-6, "{c} {w} {b} at {y}: {o} < {prev}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdr_is_sdr_at_peak_one_and_reaches_peak() {
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (50.0, -30.0, -40.0)] {
|
||||
assert_eq!(ToneMap::hdr(c, w, b, 1.0).lut(), ToneMap::new(c, w, b).lut());
|
||||
for peak in [2.0f32, 8.0, 32.0] {
|
||||
let sdr = ToneMap::new(c, w, b);
|
||||
let t = ToneMap::hdr(c, w, b, peak);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let y = 1e-5 * 1.01f32.powi(i);
|
||||
let o = t.apply(y);
|
||||
assert!((0.0..=peak).contains(&o), "{c} {w} {b} {peak} at {y}: {o}");
|
||||
assert!(o >= prev - 1e-6, "{c} {w} {b} {peak} at {y}: {o} < {prev}");
|
||||
prev = o;
|
||||
if y <= GREY * 2f32.powf(0.9) {
|
||||
assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}");
|
||||
}
|
||||
}
|
||||
assert!(t.apply(4.0) > sdr.apply(4.0));
|
||||
if (c, w, b) == (0.0, 0.0, 0.0) {
|
||||
assert!(t.apply(GREY * 2f32.powf(LUT_MAX_EV)) > peak * 0.99, "{peak}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// a broken peak falls back to SDR
|
||||
assert_eq!(ToneMap::hdr(0.0, 0.0, 0.0, f32::NAN).lut(), ToneMap::new(0.0, 0.0, 0.0).lut());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn camera_hdr_keeps_the_camera_look_and_lifts_highlights() {
|
||||
let curve = CameraTone::new(knots()).unwrap().with_chroma([1.2, 1.1, 1.0, 1.0, 0.9, 0.8, 0.7, 0.6]).unwrap();
|
||||
for (c, w, b) in [(0.0, 0.0, 0.0), (40.0, -30.0, -20.0)] {
|
||||
let sdr = ToneMap::camera(&curve, c, w, b);
|
||||
assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, 1.0).lut(), sdr.lut());
|
||||
assert_eq!(ToneMap::camera_hdr(&curve, c, w, b, f32::NAN).lut(), sdr.lut());
|
||||
for peak in [2.0f32, 8.0] {
|
||||
let t = ToneMap::camera_hdr(&curve, c, w, b, peak);
|
||||
assert_eq!(t.chroma_lut(), sdr.chroma_lut());
|
||||
let mut prev = -1.0;
|
||||
for i in 0..2400 {
|
||||
let y = 1e-5 * 1.01f32.powi(i);
|
||||
let o = t.apply(y);
|
||||
assert!((0.0..=peak).contains(&o), "{peak} at {y}: {o}");
|
||||
assert!(o >= prev - 1e-6, "{peak} at {y}: {o} < {prev}");
|
||||
prev = o;
|
||||
// the camera's midtones, not the generic HDR curve's (issue: dark HDR exports)
|
||||
if y <= GREY * 2f32.powf(HDR_FROM_EV - 0.01) {
|
||||
assert!((o - sdr.apply(y)).abs() < 1e-6, "midtones differ at {y}: {o} vs {}", sdr.apply(y));
|
||||
}
|
||||
}
|
||||
assert!(t.apply(4.0) > 1.0 && t.apply(4.0) > sdr.apply(4.0) + 0.5, "{peak}: highlights lifted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_hdr_passes_hdr_sources_and_keeps_sdr() {
|
||||
assert_eq!(ToneMap::display_hdr(20.0, 10.0, -5.0, 1.0).lut(), ToneMap::display(20.0, 10.0, -5.0).lut());
|
||||
let t = ToneMap::display_hdr(0.0, 0.0, 0.0, 8.0);
|
||||
for i in 1..=90 {
|
||||
let y = i as f32 / 100.0;
|
||||
assert!((t.apply(y) - y).abs() < 2e-3, "{y} -> {}", t.apply(y));
|
||||
}
|
||||
let mut prev = 0.0;
|
||||
for i in 1..2000 {
|
||||
let o = t.apply(i as f32 / 100.0);
|
||||
assert!(o >= prev - 1e-6 && o <= 8.0);
|
||||
prev = o;
|
||||
}
|
||||
assert!(t.apply(3.0) > 2.0 && t.apply(3.0) < 3.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_identity_and_monotone() {
|
||||
let t = ToneMap::display(0.0, 0.0, 0.0);
|
||||
// up to and including white (issue #1945: 1.0 came out as 0.9875, 8-bit 255 as 254); the
|
||||
// tolerance is the LUT's interpolation next to the clip at 1.0, far below an 8-bit level
|
||||
for i in 1..=100 {
|
||||
let y = i as f32 / 100.0;
|
||||
assert!((t.apply(y) - y).abs() < 1e-3, "{y} -> {}", t.apply(y));
|
||||
}
|
||||
assert_eq!(t.apply(4.0), 1.0, "neutral values pushed above white clip");
|
||||
for (c, w, b) in [(100.0, 100.0, -100.0), (-100.0, -100.0, 100.0), (60.0, -40.0, 30.0)] {
|
||||
let t = ToneMap::display(c, w, b);
|
||||
let mut prev = -1.0;
|
||||
for i in 0..1000 {
|
||||
let o = t.apply(i as f32 / 500.0);
|
||||
assert!(o >= prev - 1e-5, "{c} {w} {b}");
|
||||
prev = o;
|
||||
}
|
||||
}
|
||||
let c = ToneMap::display(60.0, 0.0, 0.0);
|
||||
assert!(c.apply(0.05) < 0.05 && c.apply(0.7) > 0.7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn display_shoulder_stays_on_edited_curves() {
|
||||
// The short shoulder is part of the V1 look of edited curves (docs/process-versions.md);
|
||||
// only neutral settings are the identity.
|
||||
for (c, w, b) in [(20.0, 0.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, -5.0)] {
|
||||
let t = ToneMap::display(c, w, b);
|
||||
let o = t.apply(1.0);
|
||||
assert!(o < 0.999 && o > 0.95, "{c} {w} {b}: {o}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grey_stays_near_grey_and_highlights_roll_off() {
|
||||
let t = ToneMap::new(0.0, 0.0, 0.0);
|
||||
let g = t.apply(0.18);
|
||||
assert!((0.15..0.24).contains(&g), "{g}");
|
||||
assert!(t.apply(1.0) < 0.95 && t.apply(1.0) > 0.6);
|
||||
assert!(t.apply(8.0) > 0.97);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sliders_move_the_right_way() {
|
||||
let base = ToneMap::new(0.0, 0.0, 0.0);
|
||||
let contrast = ToneMap::new(60.0, 0.0, 0.0);
|
||||
assert!(contrast.apply(0.05) < base.apply(0.05));
|
||||
assert!(contrast.apply(0.8) > base.apply(0.8));
|
||||
assert!(ToneMap::new(0.0, 60.0, 0.0).apply(0.8) > base.apply(0.8));
|
||||
assert!(ToneMap::new(0.0, 0.0, -60.0).apply(0.01) < base.apply(0.01));
|
||||
assert!(ToneMap::new(0.0, 0.0, 60.0).apply(0.01) > base.apply(0.01));
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,8 @@
|
||||
//! otherwise in the last folder chosen for the same purpose; a Save that names an existing file the
|
||||
//! OS panel did not ask about gets the Replace question (PhotoCraft `file_dialog.rs:193
|
||||
//! replaces_unasked`), a native message box from [`FilePanels::pump`] or, with the `ui` feature, a
|
||||
//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and an uppercase
|
||||
//! extension is lowercased (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two
|
||||
//! prompt on the app's `DialogHost` from `FilePanels::pump_with`; a typed name without an extension gets the suggested one and a new file's
|
||||
//! uppercase extension is lowercased, while an existing file keeps its spelling (`file_dialog.rs:210 lowercased_extension`, `:365 saved_path`); the two
|
||||
//! steps are separate settings of the [`ExtensionPolicy`].
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
@@ -114,7 +114,8 @@ fn same_entry(a: &Path, b: &Path) -> bool {
|
||||
/// PhotoCraft with Lowercase Extension off still adds the suggested extension.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ExtensionPolicy {
|
||||
/// Lowercase an extension typed with capitals (`Photo.PNG` becomes `Photo.png`).
|
||||
/// Lowercase an extension typed with capitals (`Photo.PNG` becomes `Photo.png`), unless the
|
||||
/// typed name is a file that already exists.
|
||||
pub lowercase: bool,
|
||||
/// Add the request's suggested extension to a name that has none.
|
||||
pub add_suggested: bool,
|
||||
@@ -425,11 +426,18 @@ impl FilePanels {
|
||||
|
||||
/// The saved path after the extension policy: `"Photo"` becomes `"Photo.png"` with a
|
||||
/// suggested `png` (when `add_suggested`); `"Photo.PNG"` becomes `"Photo.png"` (when
|
||||
/// `lowercase`); a path with another known extension is kept.
|
||||
/// `lowercase`) unless a file named `"Photo.PNG"` already exists; a path with another known
|
||||
/// extension is kept.
|
||||
///
|
||||
/// An existing file keeps the spelling the panel answered: the panel has just asked whether to
|
||||
/// replace that entry, and `"PHOTO.png"` next to `"PHOTO.PNG"` on a file system that tells
|
||||
/// letter case apart is a second file, so the one the user picked would be left unchanged.
|
||||
// pc: crates/ui-egui/src/file_dialog.rs:210 lowercased_extension, :365 saved_path
|
||||
pub fn settled_save_path(policy: ExtensionPolicy, answered: &Path, suggested: Option<&str>) -> PathBuf {
|
||||
match answered.extension().and_then(|e| e.to_str()) {
|
||||
Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) => answered.with_extension(ext.to_ascii_lowercase()),
|
||||
Some(ext) if policy.lowercase && ext.bytes().any(|b| b.is_ascii_uppercase()) && !answered.exists() => {
|
||||
answered.with_extension(ext.to_ascii_lowercase())
|
||||
}
|
||||
Some(_) => answered.to_path_buf(),
|
||||
None => match suggested {
|
||||
Some(ext) if policy.add_suggested => answered.with_extension(ext),
|
||||
@@ -691,4 +699,22 @@ mod service_tests {
|
||||
assert_eq!(log.borrow().len(), 3, "no question for a path the panel asked about");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
// Saving over an existing `PHOTO.PNG` with Lowercase Extension on writes `PHOTO.PNG`, the
|
||||
// file the panel asked about, not a new `PHOTO.png` beside it (on a file system that tells
|
||||
// letter case apart) or a renamed one (on one that does not). A new name is still lowercased.
|
||||
#[trial]
|
||||
fn an_existing_file_keeps_its_extension_spelling() {
|
||||
let dir = std::env::temp_dir().join(format!("craft-dialogs-existing-case-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).expect("scratch dir");
|
||||
std::fs::write(dir.join("PHOTO.PNG"), b"old").expect("existing file");
|
||||
let typed = |name: &str| Answer::Paths(vec![dir.join(name)]);
|
||||
let (service, mut panels, log) = service_with(vec![typed("PHOTO.PNG"), typed("Other.PNG")]);
|
||||
let lowercase = ExtensionPolicy::default();
|
||||
|
||||
assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("PHOTO.PNG")]), "the existing file is replaced");
|
||||
assert_eq!(log.borrow().len(), 1, "no second question: the panel asked about this file");
|
||||
assert_eq!(saved_as(&service, &mut panels, lowercase), Picked::Paths(vec![dir.join("Other.png")]), "a new file is lowercased");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,14 +71,16 @@ pub enum BezierTool {
|
||||
Convert,
|
||||
/// Anchors drawn, not edited (PhotoCraft's Path Selection and Pen tools).
|
||||
Anchors,
|
||||
/// Add Anchor Point: a press on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
|
||||
/// ([`PathEdit::InsertAnchor`]); a drag moves the new anchor, which is selected. A press on an anchor or a shown
|
||||
/// handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to the selection, ⌥ on a handle moves it
|
||||
/// alone), and a click on empty canvas deselects the anchors and keeps the path. With ⌥ a click on a segment selects
|
||||
/// its whole subpath and a drag moves a copy of it ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that
|
||||
/// takes no copies), and a press on an anchor does nothing. Hover: the segment mark with the anchor a click adds
|
||||
/// ([`HitMark`]) and the pen with "+"; over an anchor the arrow; with ⌥ no mark and the arrow with "+"; the
|
||||
/// crosshair under the canvas's precise cursor ([`CanvasSpace::precise`]).
|
||||
/// Add Anchor Point: a click on a segment, within 5 screen points of it, inserts an anchor at the hit's `t`
|
||||
/// ([`PathEdit::InsertAnchor`]); a drag inserts it and pulls out its handles as the Pen does
|
||||
/// ([`PathEdit::PullAnchor`]: ⇧ turns them to the nearest 45°, ⌥ during the drag breaks the pair); the new anchor is
|
||||
/// selected. A press on an anchor or a shown handle selects and drags it as [`BezierTool::Direct`] does (⇧ adds to
|
||||
/// the selection, ⌥ on a handle moves it alone), and a click on empty canvas deselects the anchors and keeps the
|
||||
/// path. With ⌥ held at the press a click on a segment selects its whole subpath and a drag moves a copy of it
|
||||
/// ([`PathEdit::DuplicateSubpath`]; the subpath itself on a path that takes no copies), and a press on an anchor does
|
||||
/// nothing. Hover: the segment mark with the anchor a click adds ([`HitMark`]) and the pen with "+"; over an anchor
|
||||
/// the arrow; with ⌥ no mark and the arrow with "+"; the crosshair under the canvas's precise cursor
|
||||
/// ([`CanvasSpace::precise`]).
|
||||
AddAnchor,
|
||||
/// Delete Anchor Point: a click on an anchor reports [`delete`](BezierOutput::delete) of that anchor; ⌥ makes it
|
||||
/// Add Anchor Point, except that a ⌥ click on an anchor selects its whole subpath. Hover: the anchor mark.
|
||||
@@ -241,6 +243,17 @@ enum Target {
|
||||
t: f64,
|
||||
from: Point,
|
||||
},
|
||||
/// Add Anchor's drag from a segment: an insert into `segment` at `t`, whose anchor stays at `from`, the point of
|
||||
/// the curve at `t`, and whose handles follow the pointer. `out` is the out handle of the last pass, and
|
||||
/// `in_ctrl` the in handle ⌥ left once it broke the pair.
|
||||
Pull {
|
||||
path: u64,
|
||||
segment: KnotRef,
|
||||
t: f64,
|
||||
from: Point,
|
||||
out: Point,
|
||||
in_ctrl: Option<Point>,
|
||||
},
|
||||
/// Direct Selection's ⌥ drag on a segment: a copy of `subpath` dragged from `from`, the grabbed point.
|
||||
Duplicate {
|
||||
path: u64,
|
||||
@@ -595,6 +608,12 @@ impl<'a> BezierOverlay<'a> {
|
||||
match hit {
|
||||
// Add Anchor with ⌥ takes the whole subpath as Direct's ⌥ does (PhotoCraft #12709).
|
||||
BezierHit::Segment { .. } if self.tool.takes_subpath(mods) => self.target(hit, start, mods, paths),
|
||||
// Add Anchor's drag pulls out the new anchor's handles (PhotoCraft #12707); Auto Add/Delete's, and Delete
|
||||
// Anchor's with ⌥, moves it.
|
||||
BezierHit::Segment { path, segment, t } if self.tool == BezierTool::AddAnchor && self.tool.adds(mods) => {
|
||||
let from = Self::segment_point(paths, path, segment, t);
|
||||
Target::Pull { path, segment, t, from, out: from, in_ctrl: None }
|
||||
}
|
||||
BezierHit::Segment { path, segment, t } if self.tool.adds(mods) => {
|
||||
Target::Insert { path, segment, t, from: Self::segment_point(paths, path, segment, t) }
|
||||
}
|
||||
@@ -719,11 +738,40 @@ impl<'a> BezierOverlay<'a> {
|
||||
PathEdit::InsertCurvature { path, segment, t, by: snapped(from + locked(delta)) - from }
|
||||
}
|
||||
&Target::Insert { path, segment, t, from } => PathEdit::InsertAnchor { path, segment, t, by: snapped(from + locked(delta)) - from },
|
||||
&Target::Pull { path, segment, t, from, in_ctrl, .. } => {
|
||||
let to = from + delta;
|
||||
let out = if mods.shift { handle_45(from, to) } else { snapped(to) };
|
||||
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
|
||||
}
|
||||
&Target::Duplicate { path, subpath, from } => PathEdit::DuplicateSubpath { path, subpath, by: snapped(from + locked(delta)) - from },
|
||||
Target::Nothing | Target::Toggle { .. } | Target::Pick { .. } | Target::Marquee => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// [`edit`](Self::edit), keeping what a [`Target::Pull`] carries from pass to pass: ⌥ pressed during the drag
|
||||
/// leaves the in handle where the last pass had it, and the out handle is remembered for the next pass.
|
||||
fn edit_pulled(
|
||||
view: &CanvasView,
|
||||
snap: Option<&Snap>,
|
||||
tool: BezierTool,
|
||||
target: &mut Target,
|
||||
origin: Pos2,
|
||||
pointer: Pos2,
|
||||
mods: Mods,
|
||||
) -> Option<PathEdit> {
|
||||
if let Target::Pull { from, out, in_ctrl, .. } = target
|
||||
&& mods.alt
|
||||
&& in_ctrl.is_none()
|
||||
{
|
||||
*in_ctrl = Some(*from - (*out - *from));
|
||||
}
|
||||
let edit = Self::edit(view, snap, tool, target, origin, pointer, mods);
|
||||
if let (Target::Pull { out, .. }, Some(PathEdit::PullAnchor { out: pulled, .. })) = (target, &edit) {
|
||||
*out = *pulled;
|
||||
}
|
||||
edit
|
||||
}
|
||||
|
||||
/// Proposes `paths` with `edit` applied to the paths the press began on.
|
||||
fn propose(&mut self, cx: &mut Cx<'_, Self>, start: &[EditPath], edit: PathEdit) {
|
||||
let mut next = start.to_vec();
|
||||
@@ -896,7 +944,9 @@ impl<'a> BezierOverlay<'a> {
|
||||
let moves = !matches!(held.target, Target::Nothing | Target::Toggle { .. } | Target::Pick { .. });
|
||||
if first && moves {
|
||||
held.began = true;
|
||||
if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } = held.target {
|
||||
if let Target::CurvatureInsert { path, segment, .. } | Target::Insert { path, segment, .. } | Target::Pull { path, segment, .. } =
|
||||
held.target
|
||||
{
|
||||
self.report.select = Some(self.inserted(path, segment));
|
||||
}
|
||||
cx.begin();
|
||||
@@ -910,7 +960,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) {
|
||||
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut held.target, start.origin, pos, mods) {
|
||||
self.propose(cx, &held.start, edit);
|
||||
}
|
||||
}
|
||||
@@ -938,7 +988,8 @@ impl<'a> BezierOverlay<'a> {
|
||||
return;
|
||||
}
|
||||
if held.began {
|
||||
if let Some(edit) = Self::edit(view, snap, self.tool, &held.target, start.origin, pos, mods) {
|
||||
let mut target = held.target.clone();
|
||||
if let Some(edit) = Self::edit_pulled(view, snap, self.tool, &mut target, start.origin, pos, mods) {
|
||||
self.propose(cx, &held.start, edit);
|
||||
}
|
||||
// The copy is what was dragged: it ends up selected, not the source.
|
||||
@@ -955,7 +1006,7 @@ impl<'a> BezierOverlay<'a> {
|
||||
self.set(cx, &held.start, PathEdit::InsertCurvature { path, segment, t, by: Vec2::ZERO });
|
||||
self.report.select = Some(self.inserted(path, segment));
|
||||
}
|
||||
Target::Insert { path, segment, t, .. } => {
|
||||
Target::Insert { path, segment, t, .. } | Target::Pull { path, segment, t, .. } => {
|
||||
self.set(cx, &held.start, PathEdit::InsertAnchor { path, segment, t, by: Vec2::ZERO });
|
||||
self.report.select = Some(self.inserted(path, segment));
|
||||
}
|
||||
@@ -1127,6 +1178,27 @@ fn nudge_vector(view: &CanvasView, direction: egui::Vec2, distance: f64) -> Vec2
|
||||
if length > 0.0 { doc / length * distance } else { Vec2::ZERO }
|
||||
}
|
||||
|
||||
/// ⇧ on a handle pulled out of the anchor at `anchor` to `to`, as the reference application turns it: the nearest of
|
||||
/// the eight 45° directions, an axis keeping the drag's offset along it and a diagonal the shorter of the two offsets
|
||||
/// on both axes. `to` itself for a zero or non-finite offset.
|
||||
fn handle_45(anchor: Point, to: Point) -> Point {
|
||||
let d = to - anchor;
|
||||
if !d.x.is_finite() || !d.y.is_finite() || d == Vec2::ZERO {
|
||||
return to;
|
||||
}
|
||||
let (ax, ay) = (d.x.abs(), d.y.abs());
|
||||
// tan 22.5°: nearer the axis than the diagonal.
|
||||
let tan = std::f64::consts::FRAC_PI_8.tan();
|
||||
if ay <= ax * tan {
|
||||
Point::new(to.x, anchor.y)
|
||||
} else if ax <= ay * tan {
|
||||
Point::new(anchor.x, to.y)
|
||||
} else {
|
||||
let shorter = ax.min(ay);
|
||||
anchor + Vec2::new(shorter.copysign(d.x), shorter.copysign(d.y))
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(r: DocRect, p: Point) -> bool {
|
||||
(r.x0..=r.x1).contains(&p.x) && (r.y0..=r.y1).contains(&p.y)
|
||||
}
|
||||
@@ -1145,7 +1217,7 @@ pub struct BezierOutput {
|
||||
pub select: Option<PathSelection>,
|
||||
/// Add an anchor to the segment leaving a knot of a path, at `t` (PhotoCraft's Add Anchor Point): Insert on a
|
||||
/// picked anchor (`t` 0.5). A click or drag of an anchor tool on a segment is the [`change`](Self::change)
|
||||
/// [`PathEdit::InsertAnchor`] instead.
|
||||
/// [`PathEdit::InsertAnchor`] instead ([`PathEdit::PullAnchor`] for Add Anchor's drag).
|
||||
pub insert: Option<(u64, KnotRef, f64)>,
|
||||
/// Delete or Backspace with anchors selected under a tool that deletes (Direct, Convert, Curvature, Add Anchor,
|
||||
/// Delete Anchor): remove these anchors of a path (Delete Anchor Point), `segments` true; a Delete Anchor click
|
||||
|
||||
@@ -348,6 +348,22 @@ pub enum PathEdit {
|
||||
/// The move of the new anchor, in document units.
|
||||
by: Vec2,
|
||||
},
|
||||
/// Add Anchor's drag from a segment: add an anchor to the segment leaving `segment` at `t` and pull out its
|
||||
/// handles, as the Pen does: the out handle at `out` and the in handle opposite it through the anchor, a smooth
|
||||
/// knot; once Alt broke the pair, the in handle at `in_ctrl` and a corner knot.
|
||||
#[non_exhaustive]
|
||||
PullAnchor {
|
||||
/// The path's host key.
|
||||
path: u64,
|
||||
/// The anchor the segment leaves.
|
||||
segment: KnotRef,
|
||||
/// Position along the segment, 0..=1.
|
||||
t: f64,
|
||||
/// The new anchor's out handle.
|
||||
out: Point,
|
||||
/// The new anchor's in handle once Alt broke the pair; `None` mirrors `out`.
|
||||
in_ctrl: Option<Point>,
|
||||
},
|
||||
/// The Curvature tool's double-click or Enter on an anchor: a smooth knot becomes a corner
|
||||
/// with retracted handles and a corner becomes smooth, then the subpath reflows.
|
||||
#[non_exhaustive]
|
||||
@@ -425,6 +441,12 @@ impl PathEdit {
|
||||
PathEdit::InsertAnchor { path, segment, t, by }
|
||||
}
|
||||
|
||||
/// Add Anchor's insert into the segment leaving `segment` at `t` with the new anchor's handles pulled out to `out`
|
||||
/// and mirrored, or with the in handle at `in_ctrl`.
|
||||
pub fn pull_anchor(path: u64, segment: KnotRef, t: f64, out: Point, in_ctrl: Option<Point>) -> Self {
|
||||
PathEdit::PullAnchor { path, segment, t, out, in_ctrl }
|
||||
}
|
||||
|
||||
/// The Curvature tool's toggle of `knot` between smooth and corner.
|
||||
pub fn toggle_curvature(path: u64, knot: KnotRef) -> Self {
|
||||
PathEdit::ToggleCurvature { path, knot }
|
||||
@@ -445,6 +467,7 @@ impl PathEdit {
|
||||
| PathEdit::MoveCurvature { path, .. }
|
||||
| PathEdit::InsertCurvature { path, .. }
|
||||
| PathEdit::InsertAnchor { path, .. }
|
||||
| PathEdit::PullAnchor { path, .. }
|
||||
| PathEdit::ToggleCurvature { path, .. }
|
||||
| PathEdit::DuplicateSubpath { path, .. } => path,
|
||||
}
|
||||
|
||||
@@ -137,6 +137,9 @@ impl PathEdit {
|
||||
/// `by`, then the subpath reflowed.
|
||||
/// - `InsertAnchor`: [`EditSubpath::insert_at`], the new knot with its handles moved by `by`; no
|
||||
/// reflow and no smoothing, so a straight segment gets a corner knot.
|
||||
/// - `PullAnchor`: [`EditSubpath::insert_at`], then the new knot's out handle at `out` and its in
|
||||
/// handle at `in_ctrl` (a corner), or mirrored through the anchor (smooth). Nothing changes when
|
||||
/// a handle is not finite.
|
||||
/// - `ToggleCurvature`: a smooth knot becomes a corner with retracted handles, a corner
|
||||
/// becomes smooth, then the subpath reflows.
|
||||
/// - `DuplicateSubpath`: a copy of the subpath goes last and moves, with its handles, by `by`;
|
||||
@@ -203,6 +206,18 @@ impl PathEdit {
|
||||
k.in_ctrl += *by;
|
||||
k.out_ctrl += *by;
|
||||
}
|
||||
PathEdit::PullAnchor { segment, t, out, in_ctrl, .. } => {
|
||||
let finite = |p: &Point| p.x.is_finite() && p.y.is_finite();
|
||||
if !finite(out) || !in_ctrl.as_ref().is_none_or(finite) {
|
||||
return false;
|
||||
}
|
||||
let Some(sp) = path.subpaths.get_mut(segment.subpath) else { return false };
|
||||
let Some(at) = sp.insert_at(segment.knot, *t) else { return false };
|
||||
let k = &mut sp.knots[at];
|
||||
k.out_ctrl = *out;
|
||||
k.in_ctrl = in_ctrl.unwrap_or(k.anchor - (*out - k.anchor));
|
||||
k.smooth = in_ctrl.is_none();
|
||||
}
|
||||
PathEdit::Convert { knot, out, .. } => {
|
||||
if !knot_ok(path, *knot) {
|
||||
return false;
|
||||
|
||||
@@ -73,6 +73,30 @@ fn edit_subpath_insert_at_splits_a_curve_without_changing_it() {
|
||||
|
||||
// MoveAnchors, MoveHandle (smooth and alone), BendSegment (straight and curved), Convert give PhotoCraft's kernel
|
||||
// results; a wrong key or index changes nothing and returns false.
|
||||
#[trial]
|
||||
fn path_edit_pull_anchor_inserts_and_pulls_out_the_handles() {
|
||||
let straight = || ops_path(EditSubpath::new(vec![Knot::corner(p(0.0, 0.0)), Knot::corner(p(100.0, 0.0))], false));
|
||||
let mut path = straight();
|
||||
assert!(PathEdit::pull_anchor(7, kr(0), 0.5, p(50.0, 30.0), None).apply(&mut path));
|
||||
let k = path.subpaths[0].knots[1];
|
||||
assert!(near(k.anchor, p(50.0, 0.0)) && near(k.out_ctrl, p(50.0, 30.0)) && near(k.in_ctrl, p(50.0, -30.0)) && k.smooth, "{k:?}");
|
||||
let mut path = straight();
|
||||
assert!(PathEdit::pull_anchor(7, kr(0), 0.5, p(50.0, 30.0), Some(p(80.0, 0.0))).apply(&mut path));
|
||||
let k = path.subpaths[0].knots[1];
|
||||
assert!(near(k.in_ctrl, p(80.0, 0.0)) && !k.smooth, "{k:?}");
|
||||
for bad in [
|
||||
PathEdit::pull_anchor(7, kr(0), 0.5, p(f64::NAN, 0.0), None),
|
||||
PathEdit::pull_anchor(7, kr(0), 0.5, p(1.0, 1.0), Some(p(0.0, f64::INFINITY))),
|
||||
PathEdit::pull_anchor(7, kr(0), 1.5, p(1.0, 1.0), None),
|
||||
PathEdit::pull_anchor(7, kr(4), 0.5, p(1.0, 1.0), None),
|
||||
PathEdit::pull_anchor(7, KnotRef::new(3, 0), 0.5, p(1.0, 1.0), None),
|
||||
] {
|
||||
let mut path = straight();
|
||||
assert!(!bad.apply(&mut path), "{bad:?}");
|
||||
assert_eq!(path, straight());
|
||||
}
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn path_edit_apply_matches_the_kernel_for_every_existing_edit() {
|
||||
let base = || {
|
||||
@@ -417,12 +441,13 @@ fn cmd_or_ctrl_with_page_down_on_a_focused_anchor_scrolls_the_canvas_and_picks_n
|
||||
assert_eq!(h.state.borrow().selection, picked, "the page key picks no part");
|
||||
}
|
||||
|
||||
// Add Anchor on a segment: a press, a drag and a release are one gesture that inserts the anchor and moves it, with the
|
||||
// new anchor selected; a click inserts it where the segment was pressed and moves nothing.
|
||||
// The Pen's Auto Add/Delete on a segment: a press, a drag and a release are one gesture that inserts the anchor and
|
||||
// moves it, with the new anchor selected. Add Anchor's click inserts it where the segment was pressed and moves
|
||||
// nothing (its drag pulls out handles: `an_add_anchor_drag_pulls_out_the_new_anchors_handles`).
|
||||
#[trial]
|
||||
fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.tool = BezierTool::AddAnchor);
|
||||
h.update(|st| st.tool = BezierTool::AutoAddDelete);
|
||||
let on = h.screen(p(110.0, 60.0));
|
||||
h.drag(on, vec2(0.0, FAR));
|
||||
{
|
||||
@@ -453,6 +478,73 @@ fn an_add_anchor_drag_inserts_and_moves_the_new_anchor_in_one_gesture() {
|
||||
assert_eq!(st.selection, sel(1, &[(0, 1)]));
|
||||
}
|
||||
|
||||
// Add Anchor's drag from a segment inserts the anchor where the segment was pressed and pulls out its handles, as the
|
||||
// reference application does (PhotoCraft #12707): the out handle follows the pointer and the in handle mirrors it, in
|
||||
// one gesture, the new anchor selected and smooth; ⇧ turns the handle to the nearest 45°, an axis keeping the
|
||||
// drag's offset along it and a diagonal the shorter offset; ⌥ pressed during the drag breaks the pair, so only the
|
||||
// out handle follows from then on.
|
||||
#[trial]
|
||||
fn an_add_anchor_drag_pulls_out_the_new_anchors_handles() {
|
||||
let add_anchor = || {
|
||||
let mut h = two_paths();
|
||||
h.update(|st| st.tool = BezierTool::AddAnchor);
|
||||
h
|
||||
};
|
||||
let close = |a: Vec2, b: Vec2| (a - b).hypot() < 1e-6;
|
||||
let on = p(110.0, 60.0);
|
||||
|
||||
let mut h = add_anchor();
|
||||
let at = h.screen(on);
|
||||
h.drag(at, vec2(0.0, 60.0));
|
||||
{
|
||||
let st = h.state.borrow();
|
||||
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen);
|
||||
assert_eq!((st.seen.first(), st.seen.last()), (Some(&Seen::Begin), Some(&Seen::Commit)), "{:?}", st.seen);
|
||||
assert!(
|
||||
matches!(st.changes.last(), Some(PathEdit::PullAnchor { path: 1, segment, in_ctrl: None, .. }) if *segment == kr(0)),
|
||||
"{:?}",
|
||||
st.changes
|
||||
);
|
||||
let knots = &st.paths[0].subpaths[0].knots;
|
||||
assert_eq!(knots.len(), 5);
|
||||
let k = knots[1];
|
||||
assert!(k.anchor.distance(on) < 1e-3, "the anchor stays where the segment was pressed: {k:?}");
|
||||
assert!(close(k.out_ctrl - k.anchor, Vec2::new(0.0, 60.0)) && close(k.in_ctrl - k.anchor, Vec2::new(0.0, -60.0)), "{k:?}");
|
||||
assert!(k.smooth);
|
||||
assert_eq!(st.selection, sel(1, &[(0, 1)]));
|
||||
}
|
||||
|
||||
// ⇧: the measured drags.
|
||||
for (by, out) in [((30.0, 80.0), (0.0, 80.0)), ((70.0, 40.0), (40.0, 40.0)), ((-50.0, -60.0), (-50.0, -50.0)), ((60.0, -20.0), (60.0, 0.0))] {
|
||||
let mut h = add_anchor();
|
||||
let at = h.screen(on);
|
||||
h.fixture.hold(egui::Modifiers::SHIFT);
|
||||
h.drag(at, vec2(by.0, by.1));
|
||||
h.fixture.hold(egui::Modifiers::NONE);
|
||||
let st = h.state.borrow();
|
||||
let k = st.paths[0].subpaths[0].knots[1];
|
||||
let out = Vec2::new(out.0, out.1);
|
||||
assert!(close(k.out_ctrl - k.anchor, out) && close(k.in_ctrl - k.anchor, -out), "{by:?}: {k:?}");
|
||||
}
|
||||
|
||||
// ⌥ during the drag: the in handle stays where the pair had it, the out handle follows on.
|
||||
let mut h = add_anchor();
|
||||
let at = h.screen(on);
|
||||
h.press_at(at);
|
||||
h.move_to(at + vec2(-30.0, 0.0));
|
||||
h.move_to(at + vec2(-60.0, 0.0));
|
||||
h.fixture.hold(egui::Modifiers::ALT);
|
||||
h.move_to(at + vec2(-60.0, 20.0));
|
||||
h.move_to(at + vec2(-60.0, 40.0));
|
||||
h.release_at(at + vec2(-60.0, 40.0));
|
||||
h.fixture.hold(egui::Modifiers::NONE);
|
||||
let st = h.state.borrow();
|
||||
let k = st.paths[0].subpaths[0].knots[1];
|
||||
assert!(close(k.out_ctrl - k.anchor, Vec2::new(-60.0, 40.0)) && close(k.in_ctrl - k.anchor, Vec2::new(60.0, 0.0)), "{k:?}");
|
||||
assert!(!k.smooth, "a broken pair is a corner");
|
||||
assert_eq!(st.seen.iter().filter(|s| **s == Seen::Begin).count(), 1, "{:?}", st.seen);
|
||||
}
|
||||
|
||||
// Convert on a segment: a drag on a straight one bends it when nothing of the path is selected and moves the path when
|
||||
// every anchor is, a partial selection and a curved segment do nothing; handles within the straightness tolerance of
|
||||
// their anchors still make the segment straight.
|
||||
|
||||
@@ -344,6 +344,26 @@ impl ErrorBars {
|
||||
}
|
||||
}
|
||||
|
||||
/// A chart's data table (`c:dTable`), independent of the chart legend.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct ChartDataTable {
|
||||
pub show_keys: bool,
|
||||
pub horizontal_border: bool,
|
||||
pub vertical_border: bool,
|
||||
pub outline: bool,
|
||||
}
|
||||
|
||||
impl Default for ChartDataTable {
|
||||
fn default() -> Self {
|
||||
Self { show_keys: true, horizontal_border: true, vertical_border: true, outline: true }
|
||||
}
|
||||
}
|
||||
|
||||
fn is_zero_u16(v: &u16) -> bool {
|
||||
*v == 0
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct Chart {
|
||||
@@ -423,6 +443,15 @@ pub struct Chart {
|
||||
/// A histogram's bin width (`cx:binSize`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub bin_size: Option<f64>,
|
||||
/// A chart's data table (`c:dTable`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub data_table: Option<ChartDataTable>,
|
||||
/// Pie/doughnut first slice angle in degrees clockwise from 12 o'clock (0–359).
|
||||
#[serde(skip_serializing_if = "is_zero_u16")]
|
||||
pub first_slice_angle: u16,
|
||||
/// A PivotChart's PivotTable reference (`c:pivotSource/c:name`).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub pivot_source: Option<String>,
|
||||
/// Original chart XML part kept for round-trip of unmodelled options.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub raw: Option<String>,
|
||||
@@ -537,6 +566,9 @@ impl Default for Chart {
|
||||
up_down_bars: false,
|
||||
bin_count: None,
|
||||
bin_size: None,
|
||||
data_table: None,
|
||||
first_slice_angle: 0,
|
||||
pivot_source: None,
|
||||
raw: None,
|
||||
verbatim: false,
|
||||
kept: ChartKept::default(),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Chart parts (`c:chartSpace`) → [`Chart`]. The original XML is kept in `Chart.raw`.
|
||||
|
||||
use crate::chart::{Chart, ChartType, ErrorBars, Series, Trendline, TrendlineType};
|
||||
use crate::chart::{Chart, ChartDataTable, ChartType, ErrorBars, Series, Trendline, TrendlineType};
|
||||
use crate::style::Fill;
|
||||
|
||||
use craft_xml::{El, Local, value};
|
||||
@@ -194,6 +194,16 @@ fn chart_within(root: &El, mut budget: usize) -> Option<Chart> {
|
||||
}
|
||||
}
|
||||
c.lang = root.child(Local("lang")).and_then(|c| c.attr_local("val")).map(str::to_string);
|
||||
c.pivot_source = root.path(&[Local("pivotSource"), Local("name")]).map(|n| n.deep_text().trim().to_string()).filter(|n| !n.is_empty());
|
||||
c.data_table = pa.child(Local("dTable")).map(|t| {
|
||||
let flag = |name: &str| t.child(Local(name)).is_some_and(|e| e.attr_local("val").and_then(value::to_bool).unwrap_or(true));
|
||||
ChartDataTable {
|
||||
show_keys: flag("showKeys"),
|
||||
horizontal_border: flag("showHorzBorder"),
|
||||
vertical_border: flag("showVertBorder"),
|
||||
outline: flag("showOutline"),
|
||||
}
|
||||
});
|
||||
let (val_ax, cat_ax) = read_axes(&mut c, pa, &primary_val);
|
||||
read_text_styles(&mut c, root, ch, val_ax, cat_ax);
|
||||
Some(c)
|
||||
@@ -288,6 +298,9 @@ fn read_group_settings(g: &El, c: &mut Chart) -> Option<bool> {
|
||||
if let Some(v) = g.child(Local("holeSize")).and_then(|c| c.attr_local("val")).and_then(|v| v.parse::<f64>().ok()) {
|
||||
c.hole_size = (v / 100.0).clamp(0.0, 0.9);
|
||||
}
|
||||
if let Some(v) = g.child(Local("firstSliceAng")).and_then(|c| c.attr_local("val")).and_then(|v| v.trim().parse::<u16>().ok()) {
|
||||
c.first_slice_angle = v % 360;
|
||||
}
|
||||
// `<c:showVal/>` without a val attribute means true, as in the schema's default.
|
||||
// The setting belongs to this plot group: a group that asks for no labels keeps them
|
||||
// off, even when another group of a combo chart asks for them (#868).
|
||||
@@ -902,4 +915,30 @@ mod tests {
|
||||
assert!(read_chart_xml(vary_xml(r#"<c:varyColors val="0"/>"#).as_bytes()).is_some_and(|c| !c.vary_colors));
|
||||
assert!(read_chart_xml(vary_xml(r#"<c:varyColors val="1"/>"#).as_bytes()).is_some_and(|c| c.vary_colors));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_table_first_slice_angle_and_pivot_source_roundtrip() {
|
||||
let xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="{NS_C}"><c:pivotSource><c:name>[Book.xlsx]Sheet1!PivotTable1</c:name><c:fmtId val="0"/></c:pivotSource><c:chart><c:plotArea><c:barChart><c:barDir val="col"/><c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:val><c:numLit><c:ptCount val="1"/><c:pt idx="0"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser></c:barChart><c:dTable><c:showHorzBorder/><c:showVertBorder val="0"/><c:showOutline val="1"/><c:showKeys/></c:dTable></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
let c = read_chart_xml(xml.as_bytes()).unwrap();
|
||||
assert_eq!(c.pivot_source.as_deref(), Some("[Book.xlsx]Sheet1!PivotTable1"));
|
||||
assert_eq!(c.data_table, Some(ChartDataTable { show_keys: true, horizontal_border: true, vertical_border: false, outline: true }));
|
||||
let mut edited = c.clone();
|
||||
edited.raw = None;
|
||||
let (written, kept) = crate::chart::write::chart_xml(&edited);
|
||||
assert!(!kept);
|
||||
let back = read_chart_xml(&written).unwrap();
|
||||
assert_eq!(back.pivot_source, c.pivot_source);
|
||||
assert_eq!(back.data_table, c.data_table);
|
||||
|
||||
let pie_xml = format!(
|
||||
r#"<c:chartSpace xmlns:c="{NS_C}"><c:chart><c:plotArea><c:pieChart><c:ser><c:idx val="0"/><c:val><c:numLit><c:ptCount val="1"/><c:pt idx="0"><c:v>5</c:v></c:pt></c:numLit></c:val></c:ser><c:firstSliceAng val="450"/></c:pieChart></c:plotArea></c:chart></c:chartSpace>"#
|
||||
);
|
||||
let mut pie = read_chart_xml(pie_xml.as_bytes()).unwrap();
|
||||
assert_eq!(pie.first_slice_angle, 90);
|
||||
pie.raw = None;
|
||||
let (pie_written, _) = crate::chart::write::chart_xml(&pie);
|
||||
assert_eq!(read_chart_xml(&pie_written).unwrap().first_slice_angle, 90);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -645,9 +645,9 @@ fn plot_group(w: &mut Writer, c: &Chart, kind: ChartType, list: &[(usize, &Serie
|
||||
w.close();
|
||||
}
|
||||
}
|
||||
Group::Pie => w.tag("c:firstSliceAng").attr("val", 0).empty(),
|
||||
Group::Pie => w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty(),
|
||||
Group::Doughnut => {
|
||||
w.tag("c:firstSliceAng").attr("val", 0).empty();
|
||||
w.tag("c:firstSliceAng").attr("val", c.first_slice_angle % 360).empty();
|
||||
w.tag("c:holeSize").attr("val", (c.hole_size.clamp(0.1, 0.9) * 100.0).round() as i64).empty();
|
||||
}
|
||||
_ => {}
|
||||
@@ -733,6 +733,12 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
|
||||
w.tag("c:date1904").attr("val", 0).empty();
|
||||
w.tag("c:roundedCorners").attr("val", 0).empty();
|
||||
w.tag("c:style").attr("val", c.style.clamp(1, 48)).empty();
|
||||
if let Some(pivot) = c.pivot_source.as_deref().map(str::trim).filter(|s| !s.is_empty()) {
|
||||
w.open("c:pivotSource", &[]);
|
||||
w.tag("c:name").text(pivot);
|
||||
w.tag("c:fmtId").attr("val", 0).empty();
|
||||
w.close();
|
||||
}
|
||||
w.open("c:chart", &[]);
|
||||
match &c.title {
|
||||
Some(t) => {
|
||||
@@ -802,6 +808,22 @@ pub fn chart_xml(c: &Chart) -> (Vec<u8>, bool) {
|
||||
axes(&mut w, c, g);
|
||||
}
|
||||
}
|
||||
if let Some(dt) = &c.data_table {
|
||||
w.open("c:dTable", &[]);
|
||||
if dt.horizontal_border {
|
||||
w.empty("c:showHorzBorder", &[]);
|
||||
}
|
||||
if dt.vertical_border {
|
||||
w.empty("c:showVertBorder", &[]);
|
||||
}
|
||||
if dt.outline {
|
||||
w.empty("c:showOutline", &[]);
|
||||
}
|
||||
if dt.show_keys {
|
||||
w.empty("c:showKeys", &[]);
|
||||
}
|
||||
w.close();
|
||||
}
|
||||
if let Some(f) = &c.plot_fill {
|
||||
sp_pr(&mut w, Some(f), None);
|
||||
}
|
||||
|
||||
+179
-20
@@ -83,6 +83,12 @@ impl Default for Table {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells a table may hold after [`Table::normalize`] (PowerPoint's own limit is 75 x 75).
|
||||
pub const MAX_CELLS: usize = 100_000;
|
||||
/// Cell visits [`Table::merge`] may spend growing its rectangle over existing merges: a few
|
||||
/// passes over the largest grid, where a real table needs one or two.
|
||||
const MAX_MERGE_WORK: usize = 16 * MAX_CELLS;
|
||||
|
||||
impl Table {
|
||||
pub fn new(rows: usize, cols: usize, width: f64, row_height: f64) -> Self {
|
||||
let rows = rows.clamp(1, 1000);
|
||||
@@ -113,15 +119,26 @@ impl Table {
|
||||
self.rows.iter().map(|r| r.height).sum()
|
||||
}
|
||||
/// Insert an empty row before `at`. A merge the new row falls inside grows to cover it.
|
||||
pub fn insert_row(&mut self, at: usize) {
|
||||
/// Returns false, leaving the table as it was, when the row would take it past [`MAX_CELLS`].
|
||||
#[must_use]
|
||||
pub fn insert_row(&mut self, at: usize) -> bool {
|
||||
if self.cols.len().saturating_mul(self.rows.len().saturating_add(1)) > MAX_CELLS {
|
||||
return false;
|
||||
}
|
||||
let at = at.min(self.rows.len());
|
||||
let merges = self.merges();
|
||||
let h = self.rows.get(at.saturating_sub(1)).map(|r| r.height).unwrap_or(30.0);
|
||||
self.rows.insert(at, Row { height: h, cells: (0..self.cols.len()).map(|_| Cell::new("")).collect() });
|
||||
self.set_merges(merges.into_iter().map(|m| m.insert_row(at)));
|
||||
true
|
||||
}
|
||||
/// Insert an empty column before `at`. A merge the new column falls inside grows to cover it.
|
||||
pub fn insert_col(&mut self, at: usize) {
|
||||
/// Returns false, leaving the table as it was, when the column would take it past [`MAX_CELLS`].
|
||||
#[must_use]
|
||||
pub fn insert_col(&mut self, at: usize) -> bool {
|
||||
if self.cols.len().saturating_add(1).saturating_mul(self.rows.len()) > MAX_CELLS {
|
||||
return false;
|
||||
}
|
||||
let at = at.min(self.cols.len());
|
||||
let merges = self.merges();
|
||||
let w = self.cols.get(at.saturating_sub(1)).copied().unwrap_or(80.0);
|
||||
@@ -131,6 +148,7 @@ impl Table {
|
||||
r.cells.insert(i, Cell::new(""));
|
||||
}
|
||||
self.set_merges(merges.into_iter().map(|m| m.insert_col(at)));
|
||||
true
|
||||
}
|
||||
/// Delete row `at`. Merges through it shrink; a merge anchored on it moves its anchor (and
|
||||
/// text) to the next row it covers.
|
||||
@@ -170,8 +188,12 @@ impl Table {
|
||||
true
|
||||
}
|
||||
/// The merged areas: every uncovered cell spanning more than one cell, clipped to the grid.
|
||||
/// Merges of a well-formed table do not overlap, so together they cover at most the grid; a
|
||||
/// file's overlapping spans past that are dropped, so rebuilding them cannot revisit cells
|
||||
/// without bound.
|
||||
fn merges(&self) -> Vec<Merge> {
|
||||
let (nr, nc) = (self.rows.len(), self.cols.len());
|
||||
let mut area = nr.saturating_mul(nc);
|
||||
let mut out = vec![];
|
||||
for (r, row) in self.rows.iter().enumerate() {
|
||||
for (c, cell) in row.cells.iter().enumerate().take(nc) {
|
||||
@@ -180,7 +202,10 @@ impl Table {
|
||||
}
|
||||
let rs = (cell.row_span.max(1) as usize).min(nr - r);
|
||||
let gs = (cell.grid_span.max(1) as usize).min(nc - c);
|
||||
if rs > 1 || gs > 1 {
|
||||
if (rs > 1 || gs > 1)
|
||||
&& let Some(left) = area.checked_sub(rs.saturating_mul(gs))
|
||||
{
|
||||
area = left;
|
||||
out.push(Merge { r, c, rs, gs });
|
||||
}
|
||||
}
|
||||
@@ -233,9 +258,17 @@ impl Table {
|
||||
if r1 >= self.rows.len() || c1 >= self.cols.len() || (r0 == r1 && c0 == c1) {
|
||||
return false;
|
||||
}
|
||||
// Grow the rectangle until no existing merge sticks out of it.
|
||||
// Grow the rectangle until no existing merge sticks out of it. Each pass reads the whole
|
||||
// grid and may grow it by one row, so the passes are charged against
|
||||
// [`MAX_MERGE_WORK`]: past it the merge is refused, before anything changed.
|
||||
let (mut r0, mut c0, mut r1, mut c1) = (r0, c0, r1, c1);
|
||||
let pass = self.rows.len().saturating_mul(self.cols.len()).max(1);
|
||||
let mut work = 0usize;
|
||||
loop {
|
||||
work = work.saturating_add(pass);
|
||||
if work > MAX_MERGE_WORK {
|
||||
return false;
|
||||
}
|
||||
let before = (r0, c0, r1, c1);
|
||||
for (r, row) in self.rows.iter().enumerate() {
|
||||
for (c, cell) in row.cells.iter().enumerate().take(self.cols.len()) {
|
||||
@@ -289,21 +322,50 @@ impl Table {
|
||||
return false;
|
||||
}
|
||||
// Spans come from the file and may reach past the table; only walk the cells that exist.
|
||||
for rr in r..r.saturating_add(rs).min(self.rows.len()) {
|
||||
for cc in c..c.saturating_add(gs).min(self.cols.len()) {
|
||||
if let Some(x) = self.cell_mut(rr, cc) {
|
||||
x.h_merge = false;
|
||||
x.v_merge = false;
|
||||
x.grid_span = 1;
|
||||
x.row_span = 1;
|
||||
}
|
||||
let end = r.saturating_add(rs).min(self.rows.len());
|
||||
let gs = gs.min(self.cols.len().saturating_sub(c));
|
||||
for row in self.rows.get_mut(r..end).unwrap_or_default() {
|
||||
for x in row.cells.iter_mut().skip(c).take(gs) {
|
||||
x.h_merge = false;
|
||||
x.v_merge = false;
|
||||
x.grid_span = 1;
|
||||
x.row_span = 1;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Make every row have exactly `cols.len()` cells (repair after loading).
|
||||
pub fn normalize(&mut self) {
|
||||
/// Whether the grid is as [`Table::normalize`] leaves it: within [`MAX_CELLS`], every row
|
||||
/// exactly `cols.len()` cells wide.
|
||||
pub fn is_normalized(&self) -> bool {
|
||||
let n = self.cols.len();
|
||||
n <= MAX_CELLS && self.rows.len() <= (MAX_CELLS / n.max(1)).max(1) && self.rows.iter().all(|r| r.cells.len() == n)
|
||||
}
|
||||
/// Whether [`Table::normalize`] would drop rows or columns to fit [`MAX_CELLS`].
|
||||
pub fn over_cap(&self) -> bool {
|
||||
let n = self.cols.len();
|
||||
n > MAX_CELLS || self.rows.len() > (MAX_CELLS / n.max(1)).max(1)
|
||||
}
|
||||
/// What [`Table::normalize`] would leave of this table, cloning only the rows and cells that
|
||||
/// survive (an oversized table is not copied whole first).
|
||||
pub fn normalized(&self) -> Table {
|
||||
let n = self.cols.len().min(MAX_CELLS);
|
||||
let keep = (MAX_CELLS / n.max(1)).max(1);
|
||||
let rows = self.rows.iter().take(keep).map(|r| Row { height: r.height, cells: r.cells.iter().take(n).cloned().collect() }).collect();
|
||||
let mut t = Table { cols: self.cols[..n].to_vec(), rows, background: self.background.clone(), style: self.style.clone(), ..*self };
|
||||
t.normalize();
|
||||
if self.over_cap() {
|
||||
t.clip_spans();
|
||||
}
|
||||
t
|
||||
}
|
||||
/// Make every row have exactly `cols.len()` cells (repair after loading). A grid over
|
||||
/// [`MAX_CELLS`] loses its last rows (and columns) first, so a file naming many rows and many
|
||||
/// columns but few cells cannot make this allocate their product.
|
||||
pub fn normalize(&mut self) {
|
||||
let truncated = self.over_cap();
|
||||
self.cols.truncate(MAX_CELLS);
|
||||
let n = self.cols.len();
|
||||
self.rows.truncate((MAX_CELLS / n.max(1)).max(1));
|
||||
for r in &mut self.rows {
|
||||
r.cells.resize_with(n, || Cell::new(""));
|
||||
for c in &mut r.cells {
|
||||
@@ -311,6 +373,20 @@ impl Table {
|
||||
c.row_span = c.row_span.max(1);
|
||||
}
|
||||
}
|
||||
if truncated {
|
||||
self.clip_spans();
|
||||
}
|
||||
}
|
||||
/// Cut every merge span to the rows and columns that remain, so no merge reaches past a
|
||||
/// table that lost rows or columns to the cell cap.
|
||||
fn clip_spans(&mut self) {
|
||||
let (nr, nc) = (self.rows.len(), self.cols.len());
|
||||
for (ri, r) in self.rows.iter_mut().enumerate() {
|
||||
for (ci, c) in r.cells.iter_mut().enumerate() {
|
||||
c.row_span = c.row_span.min((nr - ri) as u32).max(1);
|
||||
c.grid_span = c.grid_span.min((nc - ci) as u32).max(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -554,10 +630,10 @@ mod tests {
|
||||
fn row_and_column_edits_keep_merges_consistent() {
|
||||
for at in 0..=4 {
|
||||
let mut t = merged();
|
||||
t.insert_row(at);
|
||||
assert!(t.insert_row(at));
|
||||
assert_topology(&t);
|
||||
let mut t = merged();
|
||||
t.insert_col(at);
|
||||
assert!(t.insert_col(at));
|
||||
assert_topology(&t);
|
||||
}
|
||||
for at in 0..4 {
|
||||
@@ -573,11 +649,11 @@ mod tests {
|
||||
#[test]
|
||||
fn inserting_inside_a_merge_grows_it() {
|
||||
let mut t = merged();
|
||||
t.insert_row(2);
|
||||
assert!(t.insert_row(2));
|
||||
let a = t.cell(1, 1).unwrap();
|
||||
assert_eq!((a.row_span, a.grid_span), (3, 2));
|
||||
assert!(t.cell(2, 2).unwrap().h_merge && t.cell(2, 2).unwrap().v_merge);
|
||||
t.insert_col(0);
|
||||
assert!(t.insert_col(0));
|
||||
assert_eq!(t.cell(1, 2).unwrap().grid_span, 2);
|
||||
assert_eq!(anchor_text(&t, 1, 2), "M");
|
||||
assert_topology(&t);
|
||||
@@ -619,8 +695,8 @@ mod tests {
|
||||
fn insert_delete_merge_split() {
|
||||
let mut t = Table::new(3, 3, 300.0, 30.0);
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (3, 3));
|
||||
t.insert_row(1);
|
||||
t.insert_col(3);
|
||||
assert!(t.insert_row(1));
|
||||
assert!(t.insert_col(3));
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (4, 4));
|
||||
assert!(t.delete_row(0) && t.delete_col(0));
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (3, 3));
|
||||
@@ -646,6 +722,89 @@ mod tests {
|
||||
assert!(t.split(0, 0));
|
||||
assert_eq!(t.cell(0, 0).map(|c| (c.grid_span, c.row_span)), Some((1, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_refuses_work_past_cap() {
|
||||
let mut t = Table::new(1000, 10, 100.0, 10.0);
|
||||
for row in &mut t.rows {
|
||||
for c in &mut row.cells {
|
||||
c.row_span = 2;
|
||||
}
|
||||
}
|
||||
let before = t.clone();
|
||||
assert!(!t.merge(998, 0, 999, 9));
|
||||
assert_eq!(t, before);
|
||||
let mut small = Table::new(4, 4, 400.0, 30.0);
|
||||
assert!(small.merge(0, 0, 1, 1));
|
||||
assert!(small.is_normalized() && !Table { cols: vec![1.0; 3], rows: vec![Row::default(); 2], ..Default::default() }.is_normalized());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_caps_a_sparse_grid_at_max_cells() {
|
||||
let mut t = Table { cols: vec![10.0; 1000], rows: vec![Row::default(); 1000], ..Default::default() };
|
||||
t.normalize();
|
||||
assert_eq!(t.cols.len(), 1000);
|
||||
assert_eq!(t.rows.len(), MAX_CELLS / 1000);
|
||||
assert!(t.rows.iter().all(|r| r.cells.len() == 1000));
|
||||
let mut t = Table { cols: vec![1.0; MAX_CELLS + 5], rows: vec![Row::default(); 3], ..Default::default() };
|
||||
t.normalize();
|
||||
assert_eq!((t.cols.len(), t.rows.len()), (MAX_CELLS, 1));
|
||||
let wide = Table { cols: vec![10.0; 1000], rows: vec![Row { height: 1.0, cells: vec![Cell::new("x"); 1500] }; 150], ..Default::default() };
|
||||
let mut n = wide.clone();
|
||||
n.normalize();
|
||||
assert_eq!(wide.normalized(), n);
|
||||
let mut t = Table::new(4, 4, 400.0, 30.0);
|
||||
t.normalize();
|
||||
assert_eq!((t.n_rows(), t.n_cols()), (4, 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_file_spans_rebuild_in_bounded_work() {
|
||||
let n = 200;
|
||||
let mut t = Table::new(n, n, 400.0, 30.0);
|
||||
for row in &mut t.rows {
|
||||
for c in &mut row.cells {
|
||||
c.grid_span = u32::MAX;
|
||||
c.row_span = u32::MAX;
|
||||
}
|
||||
}
|
||||
assert_eq!(t.merges().len(), 1, "the first anchor already covers the whole grid");
|
||||
assert!(t.insert_row(n));
|
||||
assert_eq!(t.n_rows(), n + 1);
|
||||
assert!(t.split(0, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn insert_past_the_cap_is_refused() {
|
||||
const { assert!(MAX_CELLS >= 75 * 75) };
|
||||
let mut t =
|
||||
Table { cols: vec![1.0; 200], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); 200] }; MAX_CELLS / 200], ..Default::default() };
|
||||
assert!(!t.over_cap());
|
||||
let before = t.clone();
|
||||
assert!(!t.insert_row(0));
|
||||
assert!(!t.insert_col(0));
|
||||
assert_eq!(t, before);
|
||||
assert!(Table::new(75, 75, 100.0, 10.0).insert_row(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merges_are_clipped_when_the_cap_drops_rows() {
|
||||
let cols = 1000;
|
||||
let rows = MAX_CELLS / cols + 1;
|
||||
let mut t = Table { cols: vec![1.0; cols], rows: vec![Row { height: 1.0, cells: vec![Cell::new(""); cols] }; rows], ..Default::default() };
|
||||
t.rows[0].cells[0].row_span = rows as u32;
|
||||
t.rows[0].cells[cols - 1].grid_span = 5;
|
||||
let n = t.normalized();
|
||||
assert_eq!(n.rows.len(), rows - 1);
|
||||
assert_eq!(n.rows[0].cells[0].row_span as usize, rows - 1);
|
||||
assert_eq!(n.rows[0].cells[cols - 1].grid_span, 1);
|
||||
t.normalize();
|
||||
assert_eq!(t.rows[0].cells[0].row_span as usize, rows - 1);
|
||||
let mut small = Table::new(3, 3, 30.0, 10.0);
|
||||
small.rows[2].cells[2].grid_span = 4;
|
||||
small.normalize();
|
||||
assert_eq!(small.rows[2].cells[2].grid_span, 4);
|
||||
}
|
||||
}
|
||||
|
||||
pub mod styles;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
use std::io::Write as _;
|
||||
|
||||
pub mod drawing;
|
||||
pub mod lin_pat;
|
||||
pub mod model;
|
||||
pub mod mtext;
|
||||
pub mod mtext_tokens;
|
||||
|
||||
@@ -0,0 +1,391 @@
|
||||
//! Readers for AutoCAD-compatible linetype (`.lin`) and hatch pattern (`.pat`) text files.
|
||||
//!
|
||||
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
|
||||
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
|
||||
//! a pattern), with `;` starting a comment. Everything here treats the text as hostile: lines,
|
||||
//! definitions, dashes, families and warnings are capped, numbers must be finite and reasonable,
|
||||
//! and nothing panics. Problems become warnings and the definitions that can be read are kept.
|
||||
|
||||
/// Longest line read; longer lines are skipped with a warning.
|
||||
pub const MAX_LINE_CHARS: usize = 4096;
|
||||
/// Most definitions (linetypes or patterns) read from one file.
|
||||
pub const MAX_DEFINITIONS: usize = 4096;
|
||||
/// Most elements in one linetype.
|
||||
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
|
||||
/// Most line families in one hatch pattern.
|
||||
pub const MAX_PATTERN_FAMILIES: usize = 1024;
|
||||
/// Most dashes in one pattern line family.
|
||||
pub const MAX_PATTERN_DASHES: usize = 256;
|
||||
/// Largest magnitude accepted for a length, offset or scale.
|
||||
pub const MAX_VALUE: f64 = 1.0e6;
|
||||
/// Longest name or description kept.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
/// Most warnings collected; the rest are counted in a last line.
|
||||
const MAX_WARNINGS: usize = 100;
|
||||
|
||||
/// One element of a linetype parsed from a `.lin` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinDashElement {
|
||||
/// Dash (`> 0`), gap (`< 0`), or dot (`0`) length in drawing units.
|
||||
pub length: f64,
|
||||
/// Embedded text string, if any.
|
||||
pub text: Option<String>,
|
||||
/// Text style name for embedded text, if any.
|
||||
pub style: Option<String>,
|
||||
/// Text scale factor (`S=`, default `1.0`).
|
||||
pub scale: f64,
|
||||
/// Text rotation in radians (`R=`, `A=`, or `U=`, default `0.0`).
|
||||
pub rotation: f64,
|
||||
/// Text X/Y offset (`X=`, `Y=`, default `[0.0, 0.0]`).
|
||||
pub offset: [f64; 2],
|
||||
/// Whether rotation is absolute (`A=`) rather than relative to the line (`R=` or `U=`).
|
||||
pub absolute: bool,
|
||||
}
|
||||
|
||||
impl LinDashElement {
|
||||
/// A simple dash, gap, or dot element with no embedded text.
|
||||
#[must_use]
|
||||
pub fn dash(length: f64) -> Self {
|
||||
Self { length, text: None, style: None, scale: 1.0, rotation: 0.0, offset: [0.0, 0.0], absolute: false }
|
||||
}
|
||||
}
|
||||
|
||||
/// A linetype definition parsed from a `.lin` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LinDefinition {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub pattern: Vec<LinDashElement>,
|
||||
}
|
||||
|
||||
/// One line family of a hatch pattern parsed from a `.pat` file.
|
||||
///
|
||||
/// Values are in pattern-definition coordinates as written: `angle` in degrees, `origin` as
|
||||
/// `[x, y]`, `delta` as `[delta_x, delta_y]` along/perpendicular to the line direction, and
|
||||
/// `dashes` as dash (`> 0`), gap (`< 0`), and dot (`0`) lengths.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PatLineFamily {
|
||||
pub angle: f64,
|
||||
pub origin: [f64; 2],
|
||||
pub delta: [f64; 2],
|
||||
pub dashes: Vec<f64>,
|
||||
}
|
||||
|
||||
/// A hatch pattern definition parsed from a `.pat` file.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PatDefinition {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub lines: Vec<PatLineFamily>,
|
||||
}
|
||||
|
||||
/// What a file held: the definitions that could be read, and why anything else was skipped.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Parsed<T> {
|
||||
pub items: Vec<T>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl<T> Default for Parsed<T> {
|
||||
fn default() -> Self {
|
||||
Self { items: Vec::new(), warnings: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Parsed<T> {
|
||||
fn warn(&mut self, line: usize, msg: impl Into<String>) {
|
||||
match self.warnings.len() {
|
||||
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
|
||||
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
|
||||
fn header(rest: &str) -> std::result::Result<(String, String), String> {
|
||||
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
return Err("a definition without a name".into());
|
||||
}
|
||||
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
|
||||
return Err("a definition name that is too long or has control characters".into());
|
||||
}
|
||||
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
|
||||
Ok((name.to_string(), desc))
|
||||
}
|
||||
|
||||
/// A finite number within ±[`MAX_VALUE`].
|
||||
fn number(t: &str) -> Option<f64> {
|
||||
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
|
||||
}
|
||||
|
||||
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
|
||||
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
|
||||
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
|
||||
}
|
||||
|
||||
// ---------- LIN ----------
|
||||
|
||||
/// Read the linetypes of a `.lin` file.
|
||||
///
|
||||
/// Simple linetypes and complex ones with embedded text
|
||||
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
|
||||
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
|
||||
/// Lengths are in drawing units as written: a user's file is never rescaled.
|
||||
#[must_use]
|
||||
pub fn parse_lin(text: &str) -> Parsed<LinDefinition> {
|
||||
let mut out = Parsed::default();
|
||||
// The definition being read: name, description, header line.
|
||||
let mut pending: Option<(String, String, usize)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
if line.is_empty() || line.starts_with(';') {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
if let Some((name, _, at)) = pending.take() {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
match header(rest) {
|
||||
Ok((name, desc)) => pending = Some((name, desc, no)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((name, description, _)) = pending.take() else {
|
||||
out.warn(no, "pattern line without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
|
||||
break;
|
||||
}
|
||||
if out.items.iter().any(|l: &LinDefinition| l.name.eq_ignore_ascii_case(&name)) {
|
||||
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
|
||||
continue;
|
||||
}
|
||||
match lin_pattern(line, no, &name, &mut out) {
|
||||
Ok(pattern) => out.items.push(LinDefinition { name, description, pattern }),
|
||||
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
|
||||
}
|
||||
}
|
||||
if let Some((name, _, at)) = pending {
|
||||
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Split a pattern line at commas outside `[…]` and `"…"`.
|
||||
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
|
||||
let mut out = Vec::new();
|
||||
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
|
||||
for (i, c) in line.char_indices() {
|
||||
match c {
|
||||
'"' => quoted = !quoted,
|
||||
'[' if !quoted => depth = depth.saturating_add(1),
|
||||
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
|
||||
',' if !quoted && depth == 0 => {
|
||||
out.push(line.get(start..i).unwrap_or("").trim());
|
||||
start = i.saturating_add(1);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
}
|
||||
if quoted || depth != 0 {
|
||||
return Err("an unclosed [ or \"".into());
|
||||
}
|
||||
out.push(line.get(start..).unwrap_or("").trim());
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The elements of a pattern line `A,dash,gap,[…],…`.
|
||||
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<LinDefinition>) -> std::result::Result<Vec<LinDashElement>, String> {
|
||||
let mut fields = lin_fields(line)?;
|
||||
// The alignment field ("A") comes first; a line of plain numbers is read as well.
|
||||
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
|
||||
fields.remove(0);
|
||||
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
|
||||
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
|
||||
}
|
||||
let mut pattern: Vec<LinDashElement> = Vec::new();
|
||||
for f in fields.into_iter().filter(|f| !f.is_empty()) {
|
||||
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
|
||||
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
|
||||
}
|
||||
let Some(inner) = f.strip_prefix('[') else {
|
||||
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
|
||||
pattern.push(LinDashElement::dash(len));
|
||||
continue;
|
||||
};
|
||||
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
|
||||
match lin_text(inner)? {
|
||||
Some(text) => {
|
||||
// The text sits at the end of the element before it (a zero-length one if none).
|
||||
if pattern.last().is_none_or(|e| e.text.is_some()) {
|
||||
pattern.push(LinDashElement::dash(0.0));
|
||||
}
|
||||
if let Some(last) = pattern.last_mut() {
|
||||
*last = LinDashElement { length: last.length, ..text };
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let shape = inner.split(',').next().unwrap_or("").trim();
|
||||
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which is not supported here; left out"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if pattern.is_empty() {
|
||||
return Err("no dashes".into());
|
||||
}
|
||||
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
|
||||
return Err("every element has zero length".into());
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
|
||||
fn lin_text(inner: &str) -> std::result::Result<Option<LinDashElement>, String> {
|
||||
let inner = inner.trim();
|
||||
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
|
||||
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
|
||||
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
|
||||
return Err("embedded text that is too long or has control characters".into());
|
||||
}
|
||||
let mut parts = rest.split(',').map(str::trim);
|
||||
if !parts.next().unwrap_or("").is_empty() {
|
||||
return Err("text element: expected a comma after the text".into());
|
||||
}
|
||||
let style = parts.next().unwrap_or("").trim();
|
||||
if style.is_empty() || style.contains('=') {
|
||||
return Err("text element: the text style is missing".into());
|
||||
}
|
||||
let mut e = LinDashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..LinDashElement::dash(0.0) };
|
||||
for kv in parts.filter(|p| !p.is_empty()) {
|
||||
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
|
||||
match k.trim().to_ascii_uppercase().as_str() {
|
||||
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
|
||||
"X" => e.offset[0] = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
|
||||
"Y" => e.offset[1] = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
|
||||
// Upright text keeps a rotation relative to the line, like R.
|
||||
k @ ("R" | "A" | "U") => {
|
||||
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
|
||||
e.absolute = k == "A";
|
||||
}
|
||||
other => return Err(format!("text element: unknown option `{other}`")),
|
||||
}
|
||||
}
|
||||
Ok(Some(e))
|
||||
}
|
||||
|
||||
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
|
||||
fn angle(t: &str) -> Option<f64> {
|
||||
let t = t.trim().to_ascii_lowercase();
|
||||
let (num, unit) = match t.char_indices().last() {
|
||||
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
|
||||
_ => (t.as_str(), 'd'),
|
||||
};
|
||||
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
|
||||
Some(match unit {
|
||||
'r' => v,
|
||||
'g' => v * std::f64::consts::PI / 200.0,
|
||||
_ => v.to_radians(),
|
||||
})
|
||||
}
|
||||
|
||||
// ---------- PAT ----------
|
||||
|
||||
/// Read the hatch patterns of a `.pat` file.
|
||||
///
|
||||
/// Values are used as written (an inch file for inch drawings, a millimetre file for metric ones).
|
||||
#[must_use]
|
||||
pub fn parse_pat(text: &str) -> Parsed<PatDefinition> {
|
||||
let mut out: Parsed<PatDefinition> = Parsed::default();
|
||||
// The pattern being read, its header line, and whether it already failed.
|
||||
let mut cur: Option<(PatDefinition, usize, bool)> = None;
|
||||
for (no, line) in lines(text) {
|
||||
// A comment runs to the end of the line.
|
||||
let line = line.split(';').next().unwrap_or("").trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if line.chars().count() > MAX_LINE_CHARS {
|
||||
out.warn(no, "line too long; skipped");
|
||||
continue;
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix('*') {
|
||||
finish_pat(cur.take(), &mut out);
|
||||
match header(rest) {
|
||||
Ok((name, description)) => cur = Some((PatDefinition { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
|
||||
Err(e) => out.warn(no, format!("{e}; skipped")),
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some((p, _, failed)) = cur.as_mut() else {
|
||||
out.warn(no, "line family without a *NAME line before it; skipped");
|
||||
continue;
|
||||
};
|
||||
if *failed {
|
||||
continue;
|
||||
}
|
||||
if p.lines.len() >= MAX_PATTERN_FAMILIES {
|
||||
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
|
||||
*failed = true;
|
||||
continue;
|
||||
}
|
||||
match pat_family(line) {
|
||||
Ok(l) => p.lines.push(l),
|
||||
Err(e) => {
|
||||
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
|
||||
*failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
finish_pat(cur, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn finish_pat(cur: Option<(PatDefinition, usize, bool)>, out: &mut Parsed<PatDefinition>) {
|
||||
let Some((p, at, failed)) = cur else { return };
|
||||
if failed {
|
||||
return;
|
||||
}
|
||||
if p.lines.is_empty() {
|
||||
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
|
||||
} else if out.items.len() >= MAX_DEFINITIONS {
|
||||
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
|
||||
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
|
||||
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
|
||||
} else {
|
||||
out.items.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
|
||||
fn pat_family(line: &str) -> std::result::Result<PatLineFamily, String> {
|
||||
let mut v = Vec::new();
|
||||
for f in line.split(',') {
|
||||
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
|
||||
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
|
||||
}
|
||||
let f = f.trim();
|
||||
if f.is_empty() && v.len() >= 5 {
|
||||
continue;
|
||||
}
|
||||
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
|
||||
}
|
||||
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
|
||||
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
|
||||
};
|
||||
if dy.abs() < 1e-9 {
|
||||
return Err("a line family with zero spacing (delta-y)".into());
|
||||
}
|
||||
Ok(PatLineFamily { angle, origin: [x, y], delta: [dx, dy], dashes: v.get(5..).unwrap_or(&[]).to_vec() })
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Tests for `.lin` and `.pat` text resource parsing.
|
||||
|
||||
use craft_dxf::lin_pat::{MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, parse_lin, parse_pat};
|
||||
|
||||
const LIN: &str = "\
|
||||
;; my own linetypes
|
||||
*MYDASH,My dash __ __ __
|
||||
A,.5,-.25
|
||||
|
||||
*MYDOTS
|
||||
A,0,-.1,0,-.2
|
||||
*MYTEXT,Text line --MY--MY--
|
||||
A,.5,-.2,[\"MY\",STANDARD,S=.1,R=0.0,X=-0.1,Y=-.05],-.2
|
||||
*MYSHAPE,Shape line
|
||||
A,.25,-.1,[MYBOX,myshapes.shx,S=.1],-.1,1
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn simple_and_text_linetypes_are_read() {
|
||||
let r = parse_lin(LIN);
|
||||
let names: Vec<&str> = r.items.iter().map(|l| l.name.as_str()).collect();
|
||||
assert_eq!(names, ["MYDASH", "MYDOTS", "MYTEXT", "MYSHAPE"]);
|
||||
let dash = &r.items[0];
|
||||
assert_eq!(dash.description, "My dash __ __ __");
|
||||
assert_eq!(dash.pattern.iter().map(|e| e.length).collect::<Vec<_>>(), [0.5, -0.25]);
|
||||
assert_eq!(r.items[1].description, "");
|
||||
assert_eq!(r.items[1].pattern.len(), 4);
|
||||
|
||||
// The text belongs to the gap before it: drawn at that gap's end.
|
||||
let text = &r.items[2].pattern;
|
||||
assert_eq!(text.len(), 3);
|
||||
assert_eq!(text[1].length, -0.2);
|
||||
assert_eq!(text[1].text.as_deref(), Some("MY"));
|
||||
assert_eq!(text[1].style.as_deref(), Some("STANDARD"));
|
||||
assert!((text[1].scale - 0.1).abs() < 1e-12);
|
||||
assert!((text[1].offset[0] + 0.1).abs() < 1e-12 && (text[1].offset[1] + 0.05).abs() < 1e-12);
|
||||
assert!(!text[1].absolute);
|
||||
assert!(text[2].text.is_none());
|
||||
|
||||
// Shapes need SHX files: left out with a note, the dashes kept.
|
||||
let shape = &r.items[3].pattern;
|
||||
assert_eq!(shape.iter().map(|e| e.length).collect::<Vec<_>>(), [0.25, -0.1, -0.1, 1.0]);
|
||||
assert!(shape.iter().all(|e| e.text.is_none()));
|
||||
assert!(r.warnings.iter().any(|w| w.contains("MYBOX")), "{:?}", r.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_rotation_units_and_absolute_angles() {
|
||||
let r = parse_lin("*R1\nA,1,[\"x\",S1,A=90,S=1],-1\n*R2\nA,1,[\"x\",S1,R=1.5r],-1\n*R3\nA,1,[\"a,b]\",S1,U=100g],-1\n");
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
let rot = |i: usize| r.items[i].pattern[0].rotation;
|
||||
assert!((rot(0) - std::f64::consts::FRAC_PI_2).abs() < 1e-12 && r.items[0].pattern[0].absolute);
|
||||
assert!((rot(1) - 1.5).abs() < 1e-12);
|
||||
assert!((rot(2) - std::f64::consts::FRAC_PI_2).abs() < 1e-12);
|
||||
// Commas and brackets inside the quoted text are text.
|
||||
assert_eq!(r.items[2].pattern[0].text.as_deref(), Some("a,b]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_linetypes_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
*NOPATTERN
|
||||
*BADNUM
|
||||
A,.5,abc
|
||||
*BADALIGN
|
||||
B,.5,-.5
|
||||
*UNCLOSED
|
||||
A,.5,[\"x\",S1
|
||||
*
|
||||
A,1,-1
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,1,-1
|
||||
*GOOD
|
||||
A,2,-2
|
||||
*ZERO
|
||||
A,0,0
|
||||
*NOSTYLE
|
||||
A,1,[\"x\"],-1
|
||||
";
|
||||
let r = parse_lin(text);
|
||||
assert_eq!(r.items.iter().map(|l| l.name.as_str()).collect::<Vec<_>>(), ["GOOD"]);
|
||||
assert_eq!(r.items[0].pattern[0].length, 1.0, "the first definition is kept");
|
||||
for what in ["NOPATTERN", "BADNUM", "BADALIGN", "UNCLOSED", "without a name", "without a *NAME", "defined twice", "ZERO", "NOSTYLE"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_linetype_files_never_panic_and_stay_capped() {
|
||||
let long_line = format!("*LONG\nA,{}", vec!["1"; 5000].join(","));
|
||||
let many = format!("*MANY\nA,{}", vec!["1,-1"; MAX_LINETYPE_ELEMENTS].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*L{i}\nA,1,-1\n")).collect();
|
||||
let huge = "*HUGE\nA,1e300,-1\n*NAN\nA,NaN,-1\n*INF\nA,inf,-1\n";
|
||||
for text in [long_line.as_str(), many.as_str(), defs.as_str(), huge, "", "\u{feff}", "]]][[[\"", "*\u{0}\nA,1", "A,1,-1\n*X,", "*X\nA,[[[[\"]]]"]
|
||||
{
|
||||
let r = parse_lin(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|l| l.pattern.len() <= MAX_LINETYPE_ELEMENTS && l.pattern.iter().all(|e| e.length.is_finite())));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_lin(huge).items.is_empty());
|
||||
assert_eq!(parse_lin(&defs).items.len(), 4096);
|
||||
}
|
||||
|
||||
const PAT: &str = "\
|
||||
; my own patterns
|
||||
*MYGRID, My grid
|
||||
0, 0,0, 0,.5
|
||||
90, 0,0, 0,.5
|
||||
*MYBRICK,My brick ; trailing comment
|
||||
0, 0,0, 0,.25
|
||||
90, 0,0, .25,.25, .25,-.25
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn hatch_patterns_are_read() {
|
||||
let r = parse_pat(PAT);
|
||||
assert!(r.warnings.is_empty(), "{:?}", r.warnings);
|
||||
assert_eq!(r.items.len(), 2);
|
||||
let grid = &r.items[0];
|
||||
assert_eq!((grid.name.as_str(), grid.description.as_str()), ("MYGRID", "My grid"));
|
||||
assert_eq!(grid.lines.len(), 2);
|
||||
assert_eq!(grid.lines[1].angle, 90.0);
|
||||
assert_eq!(grid.lines[1].delta, [0.0, 0.5]);
|
||||
let brick = &r.items[1];
|
||||
assert_eq!(brick.description, "My brick");
|
||||
assert_eq!(brick.lines[1].origin, [0.0, 0.0]);
|
||||
assert_eq!(brick.lines[1].dashes, [0.25, -0.25]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowercase_pattern_names_are_upper_cased() {
|
||||
let r = parse_pat("*mypat\n45,0,0,0,.125\n");
|
||||
assert_eq!(r.items[0].name, "MYPAT");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn broken_patterns_are_skipped_with_warnings() {
|
||||
let text = "\
|
||||
0,0,0,0,1
|
||||
*EMPTY
|
||||
*SHORT
|
||||
0,0,0
|
||||
*ZEROGAP
|
||||
0,0,0,1,0
|
||||
*BADNUM
|
||||
0,0,0,0,x
|
||||
*OK
|
||||
0,0,0,0,1
|
||||
*OK
|
||||
45,0,0,0,1
|
||||
";
|
||||
let r = parse_pat(text);
|
||||
assert_eq!(r.items.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), ["OK"]);
|
||||
assert_eq!(r.items[0].lines[0].angle, 0.0, "the first definition is kept");
|
||||
for what in ["without a *NAME", "EMPTY", "SHORT", "ZEROGAP", "BADNUM", "defined twice"] {
|
||||
assert!(r.warnings.iter().any(|w| w.contains(what)), "no warning about {what}: {:?}", r.warnings);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_pattern_files_never_panic_and_stay_capped() {
|
||||
let families = format!("*FAM\n{}", "0,0,0,0,1\n".repeat(MAX_PATTERN_FAMILIES + 5));
|
||||
let dashes = format!("*DASH\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES + 1].join(","));
|
||||
let ok_dashes = format!("*DASHOK\n0,0,0,0,1,{}\n", vec!["1"; MAX_PATTERN_DASHES].join(","));
|
||||
let defs: String = (0..5000).map(|i| format!("*P{i}\n0,0,0,0,1\n")).collect();
|
||||
let big = "*BIG\n1e300,0,0,0,1\n*NAN\nNaN,0,0,0,1\n";
|
||||
for text in [families.as_str(), dashes.as_str(), ok_dashes.as_str(), defs.as_str(), big, "", "*", "***\n,,,,,", "*X\n,,,,,,,,,,"] {
|
||||
let r = parse_pat(text);
|
||||
assert!(r.items.len() <= 4096);
|
||||
assert!(r.items.iter().all(|p| p.lines.len() <= MAX_PATTERN_FAMILIES && p.lines.iter().all(|l| l.dashes.len() <= MAX_PATTERN_DASHES)));
|
||||
assert!(r.warnings.len() <= 101);
|
||||
}
|
||||
assert!(parse_pat(&families).items.is_empty());
|
||||
assert!(parse_pat(&dashes).items.is_empty());
|
||||
assert_eq!(parse_pat(&ok_dashes).items.len(), 1);
|
||||
assert!(parse_pat(big).items.is_empty());
|
||||
assert_eq!(parse_pat(&defs).items.len(), 4096);
|
||||
}
|
||||
@@ -39,6 +39,8 @@ pub enum Format {
|
||||
Cineon,
|
||||
Dicom,
|
||||
Iff,
|
||||
/// JPEG-LS (ITU-T T.87). Its files start with the same `FF D8 FF` bytes as JPEG files.
|
||||
JpegLs,
|
||||
Ase,
|
||||
Psd,
|
||||
Affinity,
|
||||
@@ -108,7 +110,7 @@ const fn availability(feature: bool, supported: bool) -> Availability {
|
||||
|
||||
impl Format {
|
||||
/// Every known format, including formats whose reader or writer is not enabled in this build.
|
||||
pub const ALL: [Format; 56] = [
|
||||
pub const ALL: [Format; 57] = [
|
||||
Self::Pdf,
|
||||
Self::Eps,
|
||||
Self::PostScript,
|
||||
@@ -139,6 +141,7 @@ impl Format {
|
||||
Self::Cineon,
|
||||
Self::Dicom,
|
||||
Self::Iff,
|
||||
Self::JpegLs,
|
||||
Self::Ase,
|
||||
Self::Psd,
|
||||
Self::Affinity,
|
||||
@@ -200,6 +203,7 @@ impl Format {
|
||||
Self::Cineon => &["cin"],
|
||||
Self::Dicom => &["dcm", "dicom", "dc3"],
|
||||
Self::Iff => &["iff", "lbm", "ilbm"],
|
||||
Self::JpegLs => &["jls"],
|
||||
Self::Ase => &["ase"],
|
||||
Self::Psd => &["psd", "psb", "psdt"],
|
||||
Self::Affinity => &["afdesign", "afphoto", "afpub", "af"],
|
||||
@@ -270,6 +274,7 @@ impl Format {
|
||||
Self::Cineon => "image/x-cineon",
|
||||
Self::Dicom => "application/dicom",
|
||||
Self::Iff => "image/ilbm",
|
||||
Self::JpegLs => "image/jls",
|
||||
Self::Ase => "application/x-adobe-swatch-exchange",
|
||||
Self::Psd => "image/vnd.adobe.photoshop",
|
||||
Self::Affinity => "application/x-affinity",
|
||||
@@ -327,6 +332,7 @@ impl Format {
|
||||
Self::Cineon => Codec::Cineon,
|
||||
Self::Dicom => Codec::Dicom,
|
||||
Self::Iff => Codec::Iff,
|
||||
Self::JpegLs => Codec::JpegLs,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -381,7 +387,8 @@ impl Format {
|
||||
| Self::Fits
|
||||
| Self::Dpx
|
||||
| Self::Cineon
|
||||
| Self::Iff => capability(raster, true, true, false, false),
|
||||
| Self::Iff
|
||||
| Self::JpegLs => capability(raster, true, true, false, false),
|
||||
Self::Pdf => capability(cfg!(feature = "pdf"), true, true, false, false),
|
||||
Self::Eps | Self::PostScript | Self::Illustrator => capability(cfg!(feature = "pdf"), true, false, false, false),
|
||||
Self::Svg | Self::Svgz => capability(cfg!(feature = "svg"), true, false, false, false),
|
||||
@@ -483,7 +490,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<Format> {
|
||||
if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("af")) {
|
||||
return Some(Format::Affinity);
|
||||
}
|
||||
if let Some(raster) = raster_signature(bytes) {
|
||||
if let Some(raster) = raster_signature(name, bytes) {
|
||||
return Some(raster);
|
||||
}
|
||||
if bytes.starts_with(b"silhouette04;") || bytes.starts_with(b"silhouette05;") {
|
||||
@@ -598,13 +605,18 @@ fn dxf_ascii_prefix(bytes: &[u8]) -> bool {
|
||||
matches!((lines.next(), lines.next(), lines.next(), lines.next()), (Some("0"), Some("SECTION"), Some("2"), Some(section)) if matches!(section, "HEADER" | "CLASSES" | "TABLES" | "BLOCKS" | "ENTITIES" | "OBJECTS"))
|
||||
}
|
||||
|
||||
fn raster_signature(bytes: &[u8]) -> Option<Format> {
|
||||
fn raster_signature(name: &str, bytes: &[u8]) -> Option<Format> {
|
||||
let head = bytes.get(..16).unwrap_or(bytes);
|
||||
if head.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||
return Some(Format::Png);
|
||||
}
|
||||
if head.starts_with(b"\xff\xd8\xff") {
|
||||
return Some(Format::Jpeg);
|
||||
return Some(match jpeg_frame(bytes) {
|
||||
JpegFrame::Ls => Format::JpegLs,
|
||||
JpegFrame::Other => Format::Jpeg,
|
||||
JpegFrame::Unknown if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("jls")) => Format::JpegLs,
|
||||
JpegFrame::Unknown => Format::Jpeg,
|
||||
});
|
||||
}
|
||||
if head.starts_with(b"BM") {
|
||||
return Some(Format::Bmp);
|
||||
@@ -620,3 +632,50 @@ fn raster_signature(bytes: &[u8]) -> Option<Format> {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What the marker segments after a JPEG start-of-image marker lead to.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum JpegFrame {
|
||||
/// An SOF55 frame header (`FF F7`, ITU-T T.87): JPEG-LS.
|
||||
Ls,
|
||||
/// Another frame header, a scan header, an end-of-image marker, or a byte that is not a
|
||||
/// marker where one should be.
|
||||
Other,
|
||||
/// The bytes, or the probe's first 1 MiB, end before a frame or scan header.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// Walk the marker segments from the start-of-image marker to the first frame or scan header.
|
||||
/// Only the first 1 MiB is read, and each step moves forward at least one byte. The walk follows
|
||||
/// `jpeg_frame_from` in craft-image-codecs, which a build without the `raster-codecs` feature does
|
||||
/// not link.
|
||||
fn jpeg_frame(bytes: &[u8]) -> JpegFrame {
|
||||
const LIMIT: usize = 1 << 20;
|
||||
let bytes = bytes.get(..bytes.len().min(LIMIT)).unwrap_or(bytes);
|
||||
let mut pos = 2;
|
||||
loop {
|
||||
let (Some(&prefix), Some(&marker)) = (bytes.get(pos), bytes.get(pos + 1)) else {
|
||||
return if bytes.get(pos).is_none_or(|&prefix| prefix == 0xFF) { JpegFrame::Unknown } else { JpegFrame::Other };
|
||||
};
|
||||
if prefix != 0xFF {
|
||||
return JpegFrame::Other;
|
||||
}
|
||||
match marker {
|
||||
0xF7 => return JpegFrame::Ls,
|
||||
// `FF 00` is a stuffed zero, not a marker.
|
||||
0x00 | 0xDA | 0xD9 => return JpegFrame::Other,
|
||||
// A DRI segment (`FF DD`) may come before an SOF55 frame header, so it is skipped
|
||||
// by its length below.
|
||||
0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return JpegFrame::Other,
|
||||
// A fill byte, or a marker without a length.
|
||||
0xFF => pos += 1,
|
||||
0x01 | 0xD0..=0xD7 => pos += 2,
|
||||
_ => {
|
||||
let Some(length) = bytes.get(pos + 2..pos + 4).map(|length| usize::from(u16::from_be_bytes([length[0], length[1]]))) else {
|
||||
return JpegFrame::Unknown;
|
||||
};
|
||||
pos += 2 + length;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,6 +57,72 @@ fn bounded_probes_prefer_signatures_and_resolve_extensions() {
|
||||
assert_eq!(super::detect("unknown", b""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_ls_is_told_from_jpeg_and_resolves_its_extension() {
|
||||
assert_eq!(super::from_extension("JLS"), Some(Format::JpegLs));
|
||||
assert_eq!(Format::JpegLs.mime_type(), Some("image/jls"));
|
||||
assert_eq!(super::detect("scan.jls", b""), Some(Format::JpegLs));
|
||||
// SOI followed by an SOF55 frame header.
|
||||
assert_eq!(super::detect("scan.jpg", b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"), Some(Format::JpegLs));
|
||||
assert_eq!(super::detect("photo.jls", b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0"), Some(Format::Jpeg));
|
||||
// An APP0 segment, a fill byte and a DRI segment before the SOF55 frame header.
|
||||
let with_segments = b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0";
|
||||
assert_eq!(super::detect("scan.jpg", with_segments), Some(Format::JpegLs));
|
||||
assert_eq!(super::detect("", with_segments), Some(Format::JpegLs));
|
||||
// Bytes that end before any frame header: the name decides.
|
||||
assert_eq!(super::detect("scan.jls", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::JpegLs));
|
||||
assert_eq!(super::detect("photo.jpg", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg));
|
||||
assert_eq!(super::detect("", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_marker_walk_reads_only_the_first_mebibyte() {
|
||||
let mut bytes = vec![0xFF; (1 << 20) + 64];
|
||||
bytes[1] = 0xD8;
|
||||
let len = bytes.len();
|
||||
bytes[len - 2] = 0xF7;
|
||||
assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::Jpeg));
|
||||
assert_eq!(super::detect("scan.jls", &bytes), Some(Format::JpegLs));
|
||||
bytes[1 << 19] = 0xF7;
|
||||
assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::JpegLs));
|
||||
}
|
||||
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
#[test]
|
||||
fn jpeg_marker_walk_matches_the_codec_detection() {
|
||||
let cases: [&[u8]; 6] = [
|
||||
b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0",
|
||||
b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0",
|
||||
b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0",
|
||||
b"\xff\xd8\xff\xd0\xff\x01\xff\xf7\0\x0b",
|
||||
b"\xff\xd8\xff\xe0\0\x04\0\0\x12\x34",
|
||||
b"\xff\xd8\xff\xda\0\x08",
|
||||
];
|
||||
for bytes in cases {
|
||||
let expected = match craft_image_codecs::detect(bytes) {
|
||||
Some(craft_image_codecs::Format::JpegLs) => Format::JpegLs,
|
||||
_ => Format::Jpeg,
|
||||
};
|
||||
assert_eq!(super::detect("", bytes), Some(expected), "{bytes:02x?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_ls_capabilities_follow_the_codec() {
|
||||
#[cfg(feature = "raster-codecs")]
|
||||
{
|
||||
assert_eq!(Format::JpegLs.raster_codec(), Some(craft_image_codecs::Format::JpegLs));
|
||||
assert_eq!(Format::JpegLs.extensions(), craft_image_codecs::Format::JpegLs.extensions());
|
||||
assert_eq!(Format::JpegLs.capabilities().read, Availability::Available);
|
||||
assert_eq!(Format::JpegLs.capabilities().write, Availability::Available);
|
||||
}
|
||||
#[cfg(not(feature = "raster-codecs"))]
|
||||
{
|
||||
assert_eq!(Format::JpegLs.capabilities().read, Availability::BuildDisabled);
|
||||
assert_eq!(Format::JpegLs.capabilities().write, Availability::BuildDisabled);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_mime_and_preferred_extensions_remain_distinct() {
|
||||
assert_eq!(Format::Svg.mime_type(), Format::Svgz.mime_type());
|
||||
|
||||
@@ -18,5 +18,8 @@ kurbo = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
vectorcraft-geom = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-image-codecs = { workspace = true }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
@@ -89,14 +89,15 @@ pub const CAPABILITIES: &[Capability] = &[
|
||||
detected_formats: &[
|
||||
craft_file_formats::Format::Png,
|
||||
craft_file_formats::Format::Jpeg,
|
||||
craft_file_formats::Format::JpegLs,
|
||||
craft_file_formats::Format::Bmp,
|
||||
craft_file_formats::Format::Gif,
|
||||
craft_file_formats::Format::Tiff,
|
||||
craft_file_formats::Format::WebP,
|
||||
],
|
||||
extensions: &["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff", "webp"],
|
||||
extensions: &["png", "jpg", "jpeg", "jls", "bmp", "gif", "tif", "tiff", "webp"],
|
||||
write_extensions: &["png", "jpg", "jpeg"],
|
||||
mime_types: &["image/png", "image/jpeg", "image/bmp", "image/gif", "image/tiff", "image/webp"],
|
||||
mime_types: &["image/png", "image/jpeg", "image/jls", "image/bmp", "image/gif", "image/tiff", "image/webp"],
|
||||
raster: true,
|
||||
vector: false,
|
||||
},
|
||||
@@ -197,7 +198,7 @@ pub fn format_for(name: &str, bytes: &[u8]) -> Option<ImportFormat> {
|
||||
F::Pdf => Some(ImportFormat::Pdf),
|
||||
F::Illustrator if bytes.starts_with(b"%PDF-") => Some(ImportFormat::Pdf),
|
||||
F::Eps | F::PostScript | F::Illustrator => Some(ImportFormat::Eps),
|
||||
F::Png | F::Jpeg | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster),
|
||||
F::Png | F::Jpeg | F::JpegLs | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -402,4 +403,27 @@ mod format_tests {
|
||||
let bytes = b"%PDF-1.7\n/AIPrivateData";
|
||||
assert_eq!(format_for("illustration.ai", bytes), Some(ImportFormat::Pdf));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_ls_is_routed_to_the_raster_reader() {
|
||||
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, encode};
|
||||
let gray: Vec<u8> = (0..6).map(|value| value * 40).collect();
|
||||
let Ok(image) = Image::from_u8(3, 2, ChannelLayout::Gray, gray.clone()) else {
|
||||
panic!("a 3 by 2 gray image");
|
||||
};
|
||||
let Ok(bytes) = encode(&image, Format::JpegLs, &EncodeOptions::default()) else {
|
||||
panic!("JPEG-LS encodes");
|
||||
};
|
||||
for name in ["scan.jls", "scan.jpg", "scan"] {
|
||||
assert_eq!(format_for(name, &bytes), Some(ImportFormat::Raster), "{name}");
|
||||
let Ok(Imported::Raster(raster)) = import(name, &bytes, Limits::default()) else {
|
||||
panic!("{name} imports as a raster image");
|
||||
};
|
||||
assert_eq!((raster.width, raster.height), (3, 2));
|
||||
let red: Vec<u8> = raster.rgba.as_chunks::<4>().0.iter().map(|pixel| pixel[0]).collect();
|
||||
assert_eq!(red, gray, "{name}");
|
||||
}
|
||||
assert!(supported_formats(ImportFormat::Raster).contains(&craft_file_formats::Format::JpegLs));
|
||||
assert!(supported_extensions().contains(&"jls"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,8 @@ workspace = true
|
||||
[features]
|
||||
# HTML documents: read into and written from the craft-flow model and a craft-wordmodel Document.
|
||||
flow = ["dep:craft-codepage", "dep:craft-flow", "dep:craft-math", "dep:craft-mime", "dep:craft-wordmodel", "dep:encoding_rs"]
|
||||
# Standalone portable HTML document writer.
|
||||
standalone = ["dep:craft-mime"]
|
||||
|
||||
[dependencies]
|
||||
craft-codepage = { workspace = true, optional = true }
|
||||
|
||||
@@ -38,6 +38,8 @@ struct ReadmeExamples;
|
||||
pub mod doc;
|
||||
mod entity;
|
||||
mod lex;
|
||||
#[cfg(feature = "standalone")]
|
||||
pub mod standalone;
|
||||
|
||||
pub use entity::{decode_entity, escape, escape_dq, reference, unescape, unescape_attr};
|
||||
pub use lex::{Lexer, Limits, Options, Tag, Token};
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Portable standalone HTML document writer (no PDF layout, reading order, or export policy).
|
||||
|
||||
pub use craft_mime::transfer::base64;
|
||||
|
||||
/// Whether a character may appear in the output. XML 1.0 forbids the C0 controls other than tab,
|
||||
/// line feed and carriage return, and U+FFFE/U+FFFF.
|
||||
pub fn allowed(c: char) -> bool {
|
||||
matches!(c, '\t' | '\n' | '\r') || !(c.is_ascii_control() || c == '\u{FFFE}' || c == '\u{FFFF}')
|
||||
}
|
||||
|
||||
/// Escape text for HTML content and double-quoted attribute values, stripping disallowed characters.
|
||||
pub fn esc(s: &str) -> String {
|
||||
let mut o = String::with_capacity(s.len());
|
||||
for c in s.chars().filter(|c| allowed(*c)) {
|
||||
match c {
|
||||
'&' => o.push_str("&"),
|
||||
'<' => o.push_str("<"),
|
||||
'>' => o.push_str(">"),
|
||||
'"' => o.push_str("""),
|
||||
c => o.push(c),
|
||||
}
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// An inline run of text for portable HTML rendering.
|
||||
pub struct HtmlRun<'a> {
|
||||
pub text: &'a str,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub color: [u8; 3],
|
||||
}
|
||||
|
||||
/// A single table cell for portable HTML rendering.
|
||||
pub struct HtmlCell<'a> {
|
||||
pub text: &'a str,
|
||||
pub bold: bool,
|
||||
pub italic: bool,
|
||||
pub color: [u8; 3],
|
||||
pub span: usize,
|
||||
}
|
||||
|
||||
/// A table of rows of cells for portable HTML rendering.
|
||||
pub struct HtmlTable<'a> {
|
||||
pub rows: Vec<Vec<HtmlCell<'a>>>,
|
||||
}
|
||||
|
||||
/// A block-level element in a portable HTML document.
|
||||
pub enum HtmlBlock<'a> {
|
||||
Para { runs: Vec<HtmlRun<'a>>, level: u8 },
|
||||
Table(HtmlTable<'a>),
|
||||
Image { mime: &'a str, bytes: &'a [u8] },
|
||||
PageBreak,
|
||||
}
|
||||
|
||||
fn rgb_hex(rgb: [u8; 3]) -> Option<String> {
|
||||
let [r, g, b] = rgb;
|
||||
(r | g | b != 0).then(|| format!("{r:02X}{g:02X}{b:02X}"))
|
||||
}
|
||||
|
||||
fn style_color(rgb: [u8; 3], simple: bool) -> String {
|
||||
if simple { String::new() } else { rgb_hex(rgb).map_or(String::new(), |h| format!(" style=\"color:#{h}\"")) }
|
||||
}
|
||||
|
||||
/// Wrap escaped inline text in `<em>` and/or `<strong>` when non-whitespace.
|
||||
pub fn wrap_inline(mut text: String, bold: bool, italic: bool) -> String {
|
||||
if text.trim().is_empty() {
|
||||
return text;
|
||||
}
|
||||
if italic {
|
||||
text = format!("<em>{text}</em>");
|
||||
}
|
||||
if bold {
|
||||
text = format!("<strong>{text}</strong>");
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Render a paragraph or heading (`lvl` clamped to `1..=6`, or `0` for `<p>`).
|
||||
pub fn render_para(runs: &[HtmlRun<'_>], lvl: u8, simple: bool) -> Option<String> {
|
||||
let non_empty: Vec<_> = runs.iter().map(|r| (r, esc(r.text))).filter(|(_, text)| !text.is_empty()).collect();
|
||||
let &(first, _) = non_empty.iter().find(|(_, text)| !text.trim().is_empty())?;
|
||||
let mut t = String::new();
|
||||
for (run, text) in non_empty {
|
||||
if text.trim().is_empty() {
|
||||
t.push_str(&text);
|
||||
continue;
|
||||
}
|
||||
let mut out = wrap_inline(text, run.bold && lvl == 0, run.italic);
|
||||
// The paragraph has its first visible run's colour; a run in another colour says so.
|
||||
if !simple && run.color != first.color {
|
||||
let [red, green, blue] = run.color;
|
||||
out = format!("<span style=\"color:#{red:02X}{green:02X}{blue:02X}\">{out}</span>");
|
||||
}
|
||||
t.push_str(&out);
|
||||
}
|
||||
let style = style_color(first.color, simple);
|
||||
Some(match lvl.min(6) {
|
||||
0 => format!("<p{style}>{t}</p>\n"),
|
||||
l => format!("<h{l}{style}>{t}</h{l}>\n"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Render a table into an HTML `<table>` element.
|
||||
pub fn render_table(t: &HtmlTable<'_>, simple: bool) -> String {
|
||||
let mut s = String::from("<table>\n");
|
||||
for row in &t.rows {
|
||||
s.push_str("<tr>");
|
||||
for c in row {
|
||||
let body = wrap_inline(esc(c.text), c.bold, c.italic);
|
||||
let span = if c.span > 1 { format!(" colspan=\"{}\"", c.span) } else { String::new() };
|
||||
let style = style_color(c.color, simple);
|
||||
s.push_str(&format!("<td{span}{style}>{body}</td>"));
|
||||
}
|
||||
s.push_str("</tr>\n");
|
||||
}
|
||||
s.push_str("</table>\n");
|
||||
s
|
||||
}
|
||||
|
||||
/// Render a sequence of portable HTML blocks into a standalone HTML5 document.
|
||||
pub fn render(blocks: &[HtmlBlock<'_>], title: &str, simple: bool, language: Option<&str>) -> String {
|
||||
let lang = language.map(|tag| format!(" lang=\"{}\"", esc(tag))).unwrap_or_default();
|
||||
let mut s = format!(
|
||||
"<!DOCTYPE html>\n<html{lang}>\n<head>\n<meta charset=\"utf-8\">\n<title>{}</title>\n{}\n</head>\n<body>\n",
|
||||
esc(title),
|
||||
if simple {
|
||||
""
|
||||
} else {
|
||||
"<style>body{max-width:46em;margin:2em auto;font-family:sans-serif;line-height:1.45}img{max-width:100%}hr{border:0;border-top:1px solid #ccc;margin:2em 0}table{border-collapse:collapse;margin:1em 0}td,th{border:1px solid #999;padding:2px 6px;vertical-align:top}</style>"
|
||||
}
|
||||
);
|
||||
for block in blocks {
|
||||
match block {
|
||||
HtmlBlock::Para { runs, level } => {
|
||||
if let Some(p) = render_para(runs, *level, simple) {
|
||||
s.push_str(&p);
|
||||
}
|
||||
}
|
||||
HtmlBlock::Table(t) => s.push_str(&render_table(t, simple)),
|
||||
HtmlBlock::Image { mime, bytes } => {
|
||||
s.push_str(&format!("<p><img alt=\"\" src=\"data:{};base64,{}\"></p>\n", esc(mime), base64(bytes)));
|
||||
}
|
||||
HtmlBlock::PageBreak => s.push_str("<hr>\n"),
|
||||
}
|
||||
}
|
||||
s.push_str("</body>\n</html>\n");
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renders_standalone_document_and_omits_empty_runs() {
|
||||
let blocks = [
|
||||
HtmlBlock::Para {
|
||||
runs: vec![
|
||||
HtmlRun { text: "\u{1}\u{FFFF}", bold: true, italic: true, color: [255, 0, 0] },
|
||||
HtmlRun { text: "Hello", bold: false, italic: false, color: [0, 128, 0] },
|
||||
],
|
||||
level: 0,
|
||||
},
|
||||
HtmlBlock::PageBreak,
|
||||
HtmlBlock::Table(HtmlTable {
|
||||
rows: vec![vec![
|
||||
HtmlCell { text: "\u{1}", bold: true, italic: true, color: [0, 0, 0], span: 1 },
|
||||
HtmlCell { text: "Val", bold: true, italic: false, color: [0, 0, 0], span: 2 },
|
||||
]],
|
||||
}),
|
||||
];
|
||||
let out = render(&blocks, "Clean <Title>", false, Some("en-US"));
|
||||
assert!(out.starts_with("<!DOCTYPE html>\n<html lang=\"en-US\">\n"), "{out}");
|
||||
assert!(out.contains("<title>Clean <Title></title>"), "{out}");
|
||||
assert!(out.contains("<p style=\"color:#008000\">Hello</p>"), "{out}");
|
||||
assert!(out.contains("<hr>\n"), "{out}");
|
||||
assert!(out.contains("<tr><td></td><td colspan=\"2\"><strong>Val</strong></td></tr>"), "{out}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heading_level_clamps_to_h6() {
|
||||
let runs = [HtmlRun { text: "Deep", bold: true, italic: false, color: [0, 0, 0] }];
|
||||
assert_eq!(render_para(&runs, 9, true).as_deref(), Some("<h6>Deep</h6>\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_mime_is_attribute_escaped() {
|
||||
let blocks = [HtmlBlock::Image { mime: "image/png\" onerror=\"alert(1)", bytes: b"abc" }];
|
||||
let out = render(&blocks, "Img", true, None);
|
||||
assert!(out.contains("src=\"data:image/png" onerror="alert(1);base64,YWJj\""), "{out}");
|
||||
assert!(!out.contains("onerror=\"alert(1)\""), "{out}");
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,13 @@
|
||||
|
||||
use craft_xml::El;
|
||||
|
||||
use super::{AlternatingFillValues, AlternatingStrokeValues, Spread, Story, StrokeValues, Values};
|
||||
use super::{AlternatingFillValues, AlternatingStrokeValues, MojikumiRow, Spread, Story, StrokeValues, Values};
|
||||
use crate::value::{escape_id, num};
|
||||
use crate::{prop, with_props};
|
||||
|
||||
fn bool_str(value: bool) -> &'static str {
|
||||
if value { "true" } else { "false" }
|
||||
}
|
||||
|
||||
/// One IDML table-of-contents style entry before document style names are resolved.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
@@ -190,6 +196,20 @@ impl ConditionValues {
|
||||
visible: values.get("Visible") != Some("false"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `Condition` element from these metadata values.
|
||||
pub fn to_el(&self) -> El {
|
||||
let name = self.name.as_deref().unwrap_or("");
|
||||
let self_id = self.self_id.clone().unwrap_or_else(|| format!("Condition/{}", escape_id(name)));
|
||||
let rgb = self.indicator_rgb.unwrap_or([0, 0, 0]);
|
||||
El::new("Condition")
|
||||
.with_attr("Self", self_id)
|
||||
.with_attr("Name", name)
|
||||
.with_attr("IndicatorColor", format!("{} {} {}", rgb[0], rgb[1], rgb[2]))
|
||||
.with_attr("IndicatorMethod", "UseUnderline")
|
||||
.with_attr("UnderlineIndicatorAppearance", "Solid")
|
||||
.with_attr("Visible", bool_str(self.visible))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parsed IDML numbering-list metadata.
|
||||
@@ -292,6 +312,11 @@ impl TableStyleValues {
|
||||
}
|
||||
|
||||
impl NumberingListValues {
|
||||
/// The default IDML numbering list (`$ID/[Default]`).
|
||||
pub fn default_list() -> Self {
|
||||
Self { name: "$ID/[Default]".into(), continue_across_stories: false }
|
||||
}
|
||||
|
||||
/// Reads a `NumberingList` element.
|
||||
pub fn from_el(el: &El) -> Self {
|
||||
let values = Values::of(el);
|
||||
@@ -300,6 +325,15 @@ impl NumberingListValues {
|
||||
continue_across_stories: values.boolean("ContinueNumbersAcrossStories") == Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `NumberingList` element.
|
||||
pub fn to_el(&self) -> El {
|
||||
El::new("NumberingList")
|
||||
.with_attr("Self", format!("NumberingList/{}", escape_id(&self.name)))
|
||||
.with_attr("Name", &self.name)
|
||||
.with_attr("ContinueNumbersAcrossStories", bool_str(self.continue_across_stories))
|
||||
.with_attr("ContinueNumbersAcrossDocuments", "false")
|
||||
}
|
||||
}
|
||||
|
||||
impl EpubSplitValues {
|
||||
@@ -355,6 +389,302 @@ impl TextVariableValues {
|
||||
kind,
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `TextVariable` element with its type-specific preference child.
|
||||
pub fn to_el(&self) -> El {
|
||||
let pref = |name: &str| El::new(name).with_attr("TextBefore", &self.before);
|
||||
let (ty, settings) = match &self.kind {
|
||||
TextVariableKind::CustomText { text } => ("CustomTextType", Some(pref("CustomTextVariablePreference").with_attr("Contents", text))),
|
||||
TextVariableKind::LastPageNumber { section } => (
|
||||
"LastPageNumberType",
|
||||
Some(
|
||||
pref("PageNumberVariablePreference")
|
||||
.with_attr("Format", "Current")
|
||||
.with_attr("Scope", if *section { "SectionScope" } else { "DocumentScope" }),
|
||||
),
|
||||
),
|
||||
TextVariableKind::ChapterNumber => ("ChapterNumberType", Some(pref("ChapterNumberVariablePreference").with_attr("Format", "Current"))),
|
||||
TextVariableKind::FileName { extension } => (
|
||||
"FileNameType",
|
||||
Some(pref("FileNameVariablePreference").with_attr("IncludePath", "false").with_attr("IncludeExtension", bool_str(*extension))),
|
||||
),
|
||||
TextVariableKind::Date { kind, format } => {
|
||||
let ty = match kind {
|
||||
TextDateKind::Creation => "CreationDateType",
|
||||
TextDateKind::Modification => "ModificationDateType",
|
||||
TextDateKind::Output => "OutputDateType",
|
||||
};
|
||||
(ty, Some(pref("DateVariablePreference").with_attr("Format", format)))
|
||||
}
|
||||
TextVariableKind::RunningHeader { style, character, last_on_page } => {
|
||||
let (ty, el, key) = if *character {
|
||||
("MatchCharacterStyleType", "MatchCharacterStylePreference", "AppliedCharacterStyle")
|
||||
} else {
|
||||
("MatchParagraphStyleType", "MatchParagraphStylePreference", "AppliedParagraphStyle")
|
||||
};
|
||||
let strategy = if *last_on_page { "LastOnPage" } else { "FirstOnPage" };
|
||||
(
|
||||
ty,
|
||||
Some(
|
||||
pref(el)
|
||||
.with_attr(key, style)
|
||||
.with_attr("SearchStrategy", strategy)
|
||||
.with_attr("ChangeCase", "None")
|
||||
.with_attr("DeleteEndPunctuation", "false"),
|
||||
),
|
||||
)
|
||||
}
|
||||
TextVariableKind::CrossReference { page_number } => (if *page_number { "XrefPageNumberType" } else { "XrefChapterNumberType" }, None),
|
||||
TextVariableKind::Imported { variable_type, settings_element, settings } => {
|
||||
let el = (!settings_element.is_empty()).then(|| El { name: settings_element.clone(), attrs: settings.clone(), children: Vec::new() });
|
||||
(variable_type.as_str(), el)
|
||||
}
|
||||
};
|
||||
let self_id = self.self_id.clone().unwrap_or_else(|| format!("dTextVariablen{}", self.name));
|
||||
let mut el = El::new("TextVariable").with_attr("Self", self_id).with_attr("Name", &self.name).with_attr("VariableType", ty);
|
||||
if let Some(mut s) = settings {
|
||||
if !matches!(self.kind, TextVariableKind::Imported { .. }) {
|
||||
s.set_attr("TextAfter", &self.after);
|
||||
}
|
||||
el.push(s);
|
||||
}
|
||||
el
|
||||
}
|
||||
}
|
||||
|
||||
/// The standard `[No Language]` and `English: USA` `Language` elements emitted in `designmap.xml`.
|
||||
pub fn default_languages() -> [El; 2] {
|
||||
[
|
||||
El::new("Language")
|
||||
.with_attr("Self", "Language/$ID/[No Language]")
|
||||
.with_attr("Name", "$ID/[No Language]")
|
||||
.with_attr("SingleQuotes", "''")
|
||||
.with_attr("DoubleQuotes", "\"\"")
|
||||
.with_attr("PrimaryLanguageName", "$ID/[No Language]")
|
||||
.with_attr("SublanguageName", "$ID/[No Language]")
|
||||
.with_attr("Id", "0")
|
||||
.with_attr("HyphenationVendor", "$ID/")
|
||||
.with_attr("SpellingVendor", "$ID/"),
|
||||
El::new("Language")
|
||||
.with_attr("Self", "Language/$ID/English%3a USA")
|
||||
.with_attr("Name", "$ID/English: USA")
|
||||
.with_attr("SingleQuotes", "\u{2018}\u{2019}")
|
||||
.with_attr("DoubleQuotes", "\u{201C}\u{201D}")
|
||||
.with_attr("PrimaryLanguageName", "$ID/English")
|
||||
.with_attr("SublanguageName", "$ID/USA")
|
||||
.with_attr("Id", "269")
|
||||
.with_attr("HyphenationVendor", "Hunspell")
|
||||
.with_attr("SpellingVendor", "Hunspell"),
|
||||
]
|
||||
}
|
||||
|
||||
/// The built-in cross-reference chapter/page number `TextVariable` elements.
|
||||
pub fn default_xref_text_variables() -> [El; 2] {
|
||||
[("XRefChapterNumber", "XrefChapterNumberType"), ("XRefPageNumber", "XrefPageNumberType")].map(|(name, ty)| {
|
||||
let full_name = format!("<?AID 001b?>TV {name}");
|
||||
El::new("TextVariable").with_attr("Self", format!("dTextVariablen{full_name}")).with_attr("Name", &full_name).with_attr("VariableType", ty)
|
||||
})
|
||||
}
|
||||
|
||||
/// Reusable IDML `KinsokuTable` schema values.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct KinsokuTableValues {
|
||||
pub name: String,
|
||||
pub cant_begin_line_chars: String,
|
||||
pub cant_end_line_chars: String,
|
||||
pub cant_be_separated_chars: String,
|
||||
pub hanging_punctuation_chars: String,
|
||||
}
|
||||
|
||||
impl KinsokuTableValues {
|
||||
/// Emits a `KinsokuTable` element.
|
||||
pub fn to_el(&self) -> El {
|
||||
El::new("KinsokuTable")
|
||||
.with_attr("Self", format!("KinsokuTable/{}", escape_id(&self.name)))
|
||||
.with_attr("Name", &self.name)
|
||||
.with_attr("CantBeginLineChars", &self.cant_begin_line_chars)
|
||||
.with_attr("CantEndLineChars", &self.cant_end_line_chars)
|
||||
.with_attr("CantBeSeparatedChars", &self.cant_be_separated_chars)
|
||||
.with_attr("HangingPunctuationChars", &self.hanging_punctuation_chars)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable IDML `MojikumiTable` schema values.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct MojikumiTableValues {
|
||||
pub name: String,
|
||||
pub based_on: String,
|
||||
pub overrides: Vec<MojikumiRow>,
|
||||
}
|
||||
|
||||
impl MojikumiTableValues {
|
||||
/// Emits a `MojikumiTable` element with optional spacing overrides.
|
||||
pub fn to_el(&self) -> El {
|
||||
let mut el = El::new("MojikumiTable").with_attr("Self", format!("MojikumiTable/{}", escape_id(&self.name))).with_attr("Name", &self.name);
|
||||
if !self.based_on.is_empty() {
|
||||
el.set_attr("BasedOnMojikumiSet", &self.based_on);
|
||||
}
|
||||
if !self.overrides.is_empty() {
|
||||
let mut list = El::new("OverrideMojikumiAkiList");
|
||||
for r in &self.overrides {
|
||||
list.push(
|
||||
El::new("OverrideMojikumiAkiType")
|
||||
.with_attr("TargetMojikumiClass", r.target_class.to_string())
|
||||
.with_attr("SideMojikumiClass", r.side_class.to_string())
|
||||
.with_attr("SideIsAfterTarget", bool_str(r.after))
|
||||
.with_attr("Minimum", num(r.minimum))
|
||||
.with_attr("Desired", num(r.desired))
|
||||
.with_attr("Maximum", num(r.maximum))
|
||||
.with_attr("CompressionPriority", r.priority.to_string())
|
||||
.with_attr("AkiDoesNotFloat", bool_str(r.does_not_float)),
|
||||
);
|
||||
}
|
||||
let mut props = El::new("Properties");
|
||||
props.push(list);
|
||||
el.push(props);
|
||||
}
|
||||
el
|
||||
}
|
||||
}
|
||||
|
||||
/// IDML `LayerColor` property value: either a named enumeration or an RGB triplet.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum LayerColorValue {
|
||||
Named(String),
|
||||
Rgb([f64; 3]),
|
||||
}
|
||||
|
||||
/// Reusable IDML `Layer` schema values.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LayerValues {
|
||||
pub self_id: String,
|
||||
pub name: String,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
pub ignore_wrap: bool,
|
||||
pub show_guides: bool,
|
||||
pub lock_guides: bool,
|
||||
pub printable: bool,
|
||||
pub color: LayerColorValue,
|
||||
}
|
||||
|
||||
impl LayerValues {
|
||||
/// Emits a `Layer` element with its `<Properties><LayerColor>` child.
|
||||
pub fn to_el(&self) -> El {
|
||||
let color = match &self.color {
|
||||
LayerColorValue::Named(name) => prop("LayerColor", "enumeration", name),
|
||||
LayerColorValue::Rgb(rgb) => {
|
||||
let mut el = El::new("LayerColor").with_attr("type", "list");
|
||||
for c in rgb {
|
||||
el.push(prop("ListItem", "double", num(*c)));
|
||||
}
|
||||
el
|
||||
}
|
||||
};
|
||||
let el = El::new("Layer")
|
||||
.with_attr("Self", &self.self_id)
|
||||
.with_attr("Name", &self.name)
|
||||
.with_attr("Visible", bool_str(self.visible))
|
||||
.with_attr("Locked", bool_str(self.locked))
|
||||
.with_attr("IgnoreWrap", bool_str(self.ignore_wrap))
|
||||
.with_attr("ShowGuides", bool_str(self.show_guides))
|
||||
.with_attr("LockGuides", bool_str(self.lock_guides))
|
||||
.with_attr("UI", "true")
|
||||
.with_attr("Expendable", "true")
|
||||
.with_attr("Printable", bool_str(self.printable));
|
||||
with_props(el, vec![color])
|
||||
}
|
||||
}
|
||||
|
||||
/// Reusable IDML `Section` schema values.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct SectionValues {
|
||||
pub self_id: String,
|
||||
pub length: usize,
|
||||
pub name: String,
|
||||
pub continue_numbering: bool,
|
||||
pub include_section_prefix: bool,
|
||||
pub page_number_start: Option<u32>,
|
||||
pub marker: String,
|
||||
pub page_start: String,
|
||||
pub section_prefix: String,
|
||||
pub alternate_layout: Option<(String, usize)>,
|
||||
pub page_number_style: String,
|
||||
}
|
||||
|
||||
impl SectionValues {
|
||||
/// Emits a `Section` element with its `<Properties><PageNumberStyle>` child.
|
||||
pub fn to_el(&self) -> El {
|
||||
let mut el = El::new("Section")
|
||||
.with_attr("Self", &self.self_id)
|
||||
.with_attr("Length", self.length.to_string())
|
||||
.with_attr("Name", &self.name)
|
||||
.with_attr("ContinueNumbering", bool_str(self.continue_numbering))
|
||||
.with_attr("IncludeSectionPrefix", bool_str(self.include_section_prefix));
|
||||
if let Some(n) = self.page_number_start {
|
||||
el.set_attr("PageNumberStart", n.to_string());
|
||||
}
|
||||
el = el.with_attr("Marker", &self.marker).with_attr("PageStart", &self.page_start).with_attr("SectionPrefix", &self.section_prefix);
|
||||
if let Some((layout, layout_len)) = &self.alternate_layout {
|
||||
el = el.with_attr("AlternateLayout", layout).with_attr("AlternateLayoutLength", layout_len.to_string());
|
||||
}
|
||||
with_props(el, vec![prop("PageNumberStyle", "enumeration", &self.page_number_style)])
|
||||
}
|
||||
}
|
||||
|
||||
/// Emits a `HyperlinkURLDestination` element.
|
||||
pub fn hyperlink_url_destination_el(self_id: &str, name: &str, url: &str) -> El {
|
||||
El::new("HyperlinkURLDestination")
|
||||
.with_attr("Self", self_id)
|
||||
.with_attr("Name", name)
|
||||
.with_attr("DestinationURL", url)
|
||||
.with_attr("Hidden", "false")
|
||||
}
|
||||
|
||||
/// Emits a `HyperlinkPageDestination` element.
|
||||
pub fn hyperlink_page_destination_el(self_id: &str, name: &str, destination_page: &str) -> El {
|
||||
El::new("HyperlinkPageDestination")
|
||||
.with_attr("Self", self_id)
|
||||
.with_attr("Name", name)
|
||||
.with_attr("DestinationPage", destination_page)
|
||||
.with_attr("ViewSetting", "FitPage")
|
||||
.with_attr("Hidden", "false")
|
||||
}
|
||||
|
||||
/// Emits a `HyperlinkPageItemSource` element.
|
||||
pub fn hyperlink_page_item_source_el(self_id: &str, name: &str, source_page_item: &str) -> El {
|
||||
El::new("HyperlinkPageItemSource")
|
||||
.with_attr("Self", self_id)
|
||||
.with_attr("Name", name)
|
||||
.with_attr("SourcePageItem", source_page_item)
|
||||
.with_attr("Hidden", "false")
|
||||
}
|
||||
|
||||
/// Emits a `Hyperlink` element joining `source` and `destination`.
|
||||
pub fn hyperlink_el(self_id: &str, name: &str, source: &str, destination: &str, visible: bool, destination_unique_key: u64) -> El {
|
||||
let el = El::new("Hyperlink")
|
||||
.with_attr("Self", self_id)
|
||||
.with_attr("Name", name)
|
||||
.with_attr("Source", source)
|
||||
.with_attr("Visible", bool_str(visible))
|
||||
.with_attr("Highlight", "None")
|
||||
.with_attr("Width", "Thin")
|
||||
.with_attr("BorderStyle", "Solid")
|
||||
.with_attr("Hidden", "false")
|
||||
.with_attr("DestinationUniqueKey", (destination_unique_key & 0xFFFF_FFFF).to_string());
|
||||
with_props(el, vec![prop("Destination", "object", destination)])
|
||||
}
|
||||
|
||||
/// Emits the root `ColorGroup` (`ColorGroup/[Root Color Group]`) with `ColorGroupSwatch` children.
|
||||
pub fn root_color_group_el(swatch_ids: &[String], swatch_id_prefix: &str) -> El {
|
||||
let mut cg = El::new("ColorGroup")
|
||||
.with_attr("Self", "ColorGroup/[Root Color Group]")
|
||||
.with_attr("Name", "[Root Color Group]")
|
||||
.with_attr("IsRootColorGroup", "true");
|
||||
for (n, id) in swatch_ids.iter().enumerate() {
|
||||
cg.push(El::new("ColorGroupSwatch").with_attr("Self", format!("{swatch_id_prefix}ColorGroupSwatch{n:x}")).with_attr("SwatchItemRef", id));
|
||||
}
|
||||
cg
|
||||
}
|
||||
|
||||
impl TocStyleValues {
|
||||
|
||||
@@ -22,8 +22,10 @@ mod story;
|
||||
|
||||
use craft_xml::{El, Local, Node};
|
||||
pub use document::{
|
||||
CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, ModelDocument, NumberingListValues,
|
||||
TableStyleValues, TextDateKind, TextVariableKind, TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode,
|
||||
CellStyleValues, ConditionValues, CrossReferenceBuildingBlock, CrossReferenceFormatValues, EpubSplitValues, KinsokuTableValues, LayerColorValue,
|
||||
LayerValues, ModelDocument, MojikumiTableValues, NumberingListValues, SectionValues, TableStyleValues, TextDateKind, TextVariableKind,
|
||||
TextVariableValues, TocStyleEntryValues, TocStyleValues, TopLevelKind, TopLevelNode, default_languages, default_xref_text_variables,
|
||||
hyperlink_el, hyperlink_page_destination_el, hyperlink_page_item_source_el, hyperlink_url_destination_el, root_color_group_el,
|
||||
};
|
||||
pub use effects::{
|
||||
DirectionalFeatherValues, DropShadowValues, FeatherValues, GradientFeatherValues, ObjectStyleStack, OpacityStopValues, TransparencySetting,
|
||||
|
||||
@@ -280,3 +280,131 @@ fn text_variable_decoration_uses_preference_and_falls_back_to_legacy_root_values
|
||||
let variable = craft_idml::model::TextVariableValues::from_el(&legacy);
|
||||
assert_eq!((variable.before.as_str(), variable.after.as_str()), ("of ", " pages"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designmap_schema_elements_roundtrip_expected_attributes() {
|
||||
use craft_idml::model::{
|
||||
ConditionValues, KinsokuTableValues, MojikumiRow, MojikumiTableValues, NumberingListValues, TextDateKind, TextVariableKind,
|
||||
TextVariableValues, default_languages, default_xref_text_variables,
|
||||
};
|
||||
|
||||
let langs = default_languages();
|
||||
assert_eq!(langs[0].attr("Self"), Some("Language/$ID/[No Language]"));
|
||||
assert_eq!(langs[1].attr("Self"), Some("Language/$ID/English%3a USA"));
|
||||
assert_eq!(langs[1].attr("Id"), Some("269"));
|
||||
|
||||
let num_list = NumberingListValues::default_list().to_el();
|
||||
assert_eq!(num_list.attr("Self"), Some("NumberingList/$ID/[Default]"));
|
||||
assert_eq!(num_list.attr("ContinueNumbersAcrossDocuments"), Some("false"));
|
||||
|
||||
let kinsoku = KinsokuTableValues {
|
||||
name: "My:Kinsoku".into(),
|
||||
cant_begin_line_chars: "。".into(),
|
||||
cant_end_line_chars: "「".into(),
|
||||
cant_be_separated_chars: "…".into(),
|
||||
hanging_punctuation_chars: "、".into(),
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(kinsoku.attr("Self"), Some("KinsokuTable/My%3aKinsoku"));
|
||||
assert_eq!(kinsoku.attr("CantBeginLineChars"), Some("。"));
|
||||
|
||||
let mojikumi = MojikumiTableValues {
|
||||
name: "Custom%1".into(),
|
||||
based_on: "Base".into(),
|
||||
overrides: vec![MojikumiRow {
|
||||
target_class: 1,
|
||||
side_class: 2,
|
||||
after: true,
|
||||
minimum: 0.0,
|
||||
desired: 0.25,
|
||||
maximum: 0.5,
|
||||
priority: 3,
|
||||
does_not_float: false,
|
||||
}],
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(mojikumi.attr("Self"), Some("MojikumiTable/Custom%251"));
|
||||
assert_eq!(mojikumi.attr("BasedOnMojikumiSet"), Some("Base"));
|
||||
let row = mojikumi.child("Properties").and_then(|p| p.child("OverrideMojikumiAkiList")).and_then(|l| l.child("OverrideMojikumiAkiType")).unwrap();
|
||||
assert_eq!(row.attr("TargetMojikumiClass"), Some("1"));
|
||||
assert_eq!(row.attr("SideIsAfterTarget"), Some("true"));
|
||||
|
||||
let cond = ConditionValues { self_id: None, name: Some("A:B".into()), indicator_rgb: Some([10, 20, 30]), visible: true }.to_el();
|
||||
assert_eq!(cond.attr("Self"), Some("Condition/A%3aB"));
|
||||
assert_eq!(cond.attr("IndicatorColor"), Some("10 20 30"));
|
||||
assert_eq!(cond.attr("Visible"), Some("true"));
|
||||
|
||||
let xrefs = default_xref_text_variables();
|
||||
assert_eq!(xrefs[0].attr("VariableType"), Some("XrefChapterNumberType"));
|
||||
assert_eq!(xrefs[1].attr("VariableType"), Some("XrefPageNumberType"));
|
||||
|
||||
let tv = TextVariableValues {
|
||||
self_id: None,
|
||||
name: "Mod".into(),
|
||||
before: "Updated ".into(),
|
||||
after: "!".into(),
|
||||
kind: TextVariableKind::Date { kind: TextDateKind::Modification, format: "yyyy-MM-dd".into() },
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(tv.attr("VariableType"), Some("ModificationDateType"));
|
||||
let pref = tv.child("DateVariablePreference").unwrap();
|
||||
assert_eq!(pref.attr("TextBefore"), Some("Updated "));
|
||||
assert_eq!(pref.attr("TextAfter"), Some("!"));
|
||||
assert_eq!(pref.attr("Format"), Some("yyyy-MM-dd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn designmap_layers_sections_and_hyperlinks_roundtrip_expected_attributes() {
|
||||
use craft_idml::model::{
|
||||
LayerColorValue, LayerValues, SectionValues, hyperlink_el, hyperlink_page_destination_el, hyperlink_page_item_source_el,
|
||||
hyperlink_url_destination_el, root_color_group_el,
|
||||
};
|
||||
|
||||
let layer = LayerValues {
|
||||
self_id: "u1".into(),
|
||||
name: "Layer 1".into(),
|
||||
visible: true,
|
||||
locked: false,
|
||||
ignore_wrap: false,
|
||||
show_guides: true,
|
||||
lock_guides: false,
|
||||
printable: true,
|
||||
color: LayerColorValue::Rgb([128.0, 64.0, 0.0]),
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(layer.attr("Self"), Some("u1"));
|
||||
assert_eq!(layer.attr("UI"), Some("true"));
|
||||
let list_items: Vec<_> =
|
||||
layer.child("Properties").and_then(|p| p.child("LayerColor")).map(|lc| lc.elements().map(|e| e.deep_text()).collect()).unwrap();
|
||||
assert_eq!(list_items, ["128", "64", "0"]);
|
||||
|
||||
let section = SectionValues {
|
||||
self_id: "u2".into(),
|
||||
length: 4,
|
||||
name: "A".into(),
|
||||
continue_numbering: false,
|
||||
include_section_prefix: true,
|
||||
page_number_start: Some(1),
|
||||
marker: "M".into(),
|
||||
page_start: "u3".into(),
|
||||
section_prefix: "A".into(),
|
||||
alternate_layout: Some(("Phone".into(), 4)),
|
||||
page_number_style: "Arabic".into(),
|
||||
}
|
||||
.to_el();
|
||||
assert_eq!(section.attr("PageNumberStart"), Some("1"));
|
||||
assert_eq!(section.attr("AlternateLayout"), Some("Phone"));
|
||||
|
||||
let url_dest = hyperlink_url_destination_el("HyperlinkURLDestination/u1", "Site", "https://example.com");
|
||||
assert_eq!(url_dest.attr("DestinationURL"), Some("https://example.com"));
|
||||
let page_dest = hyperlink_page_destination_el("HyperlinkPageDestination/p1", "Page", "u3");
|
||||
assert_eq!(page_dest.attr("ViewSetting"), Some("FitPage"));
|
||||
let item_src = hyperlink_page_item_source_el("HyperlinkPageItemSource/i1k0", "Link", "u4");
|
||||
assert_eq!(item_src.attr("SourcePageItem"), Some("u4"));
|
||||
let link = hyperlink_el("u5", "Link", "HyperlinkPageItemSource/i1k0", "HyperlinkURLDestination/u1", true, 0x1_0000_0007);
|
||||
assert_eq!(link.attr("DestinationUniqueKey"), Some("7"));
|
||||
|
||||
let cg = root_color_group_el(&["Color/Black".into(), "Color/Paper".into()], "u10");
|
||||
assert_eq!(cg.attr("IsRootColorGroup"), Some("true"));
|
||||
assert_eq!(cg.elements().count(), 2);
|
||||
}
|
||||
|
||||
@@ -402,9 +402,21 @@ pub(crate) fn encode(src: &Image, plan: Plan, opts: &EncodeOptions) -> Result<Ve
|
||||
let encoding = Encoding { compression, blocks: Blocks::ScanLines, line_order: LineOrder::Increasing };
|
||||
let channels = AnyChannels::sort(list.into_iter().collect());
|
||||
let layer = Layer::new((w, h), LayerAttributes::default(), encoding, channels);
|
||||
let image = exr::image::Image::from_layer(layer);
|
||||
let mut image = exr::image::Image::from_layer(layer);
|
||||
if let Some([red, green, blue, white]) = opts.exr_chromaticities {
|
||||
use exr::math::Vec2;
|
||||
image.attributes.chromaticities = Some(exr::meta::attribute::Chromaticities {
|
||||
red: Vec2(red[0], red[1]),
|
||||
green: Vec2(green[0], green[1]),
|
||||
blue: Vec2(blue[0], blue[1]),
|
||||
white: Vec2(white[0], white[1]),
|
||||
});
|
||||
}
|
||||
let mut cursor = Cursor::new(Vec::new());
|
||||
image.write().to_buffered(&mut cursor).map_err(|e| CodecError::encode(F, e))?;
|
||||
let writer = image.write();
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let writer = writer.non_parallel();
|
||||
writer.to_buffered(&mut cursor).map_err(|e| CodecError::encode(F, e))?;
|
||||
Ok(cursor.into_inner())
|
||||
}
|
||||
|
||||
@@ -448,4 +460,15 @@ mod preview_tests {
|
||||
// A header cut off mid-attribute is left to the crate.
|
||||
check_previews(&good[..at]).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_writes_chromaticities_attribute() {
|
||||
let img = Image::from_f32(2, 2, ChannelLayout::Rgb, &[0.5; 12]).unwrap();
|
||||
let chroma = [[0.713, 0.293], [0.165, 0.830], [0.128, 0.044], [0.32168, 0.33767]];
|
||||
let opts = EncodeOptions { exr_chromaticities: Some(chroma), ..EncodeOptions::default() };
|
||||
let encoded = encode(&img, Plan { layout: ChannelLayout::Rgb, sample: SampleType::F32 }, &opts).unwrap();
|
||||
let meta = MetaData::read_from_buffered(Cursor::new(&encoded), false).unwrap();
|
||||
let c = meta.headers[0].shared_attributes.chromaticities.unwrap();
|
||||
assert_eq!([[c.red.0, c.red.1], [c.green.0, c.green.1], [c.blue.0, c.blue.1], [c.white.0, c.white.1]], chroma);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,7 +236,7 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {
|
||||
}
|
||||
let seg = &b[i + 4..i + 2 + len];
|
||||
match marker {
|
||||
0xE0 if seg.len() >= 12 && seg.starts_with(b"JFIF\0") => {
|
||||
0xE0 if seg.len() >= 12 && seg.starts_with(b"JFIF\0") && jfif_dpi.is_none() => {
|
||||
let unit = seg[7];
|
||||
let x = u16::from_be_bytes([seg[8], seg[9]]) as f32;
|
||||
let y = u16::from_be_bytes([seg[10], seg[11]]) as f32;
|
||||
@@ -278,9 +278,10 @@ pub(crate) fn scan_metadata(b: &[u8]) -> JpegMeta {
|
||||
}
|
||||
m.held_coefficients = sof.map_or(0, |(marker, seg)| held_coefficients(marker, seg, scan_components));
|
||||
m.dpi = photoshop_resolution(&photoshop)
|
||||
.or_else(|| m.xmp.as_deref().and_then(xmp_resolution))
|
||||
.or_else(|| m.exif.as_deref().and_then(exif_resolution))
|
||||
.or(jfif_dpi);
|
||||
.filter(|&d| crate::resolution_probe::usable(d))
|
||||
.or_else(|| m.xmp.as_deref().and_then(xmp_resolution).filter(|&d| crate::resolution_probe::usable(d)))
|
||||
.or_else(|| m.exif.as_deref().and_then(exif_resolution).filter(|&d| crate::resolution_probe::usable(d)))
|
||||
.or_else(|| jfif_dpi.filter(|&d| crate::resolution_probe::usable(d)));
|
||||
m.photoshop = Some(photoshop).filter(|p| !p.is_empty());
|
||||
if !icc_parts.is_empty() {
|
||||
icc_parts.sort_by_key(|p| p.0);
|
||||
|
||||
@@ -276,6 +276,9 @@ pub struct EncodeOptions {
|
||||
/// the full image, which comes first.
|
||||
pub tiff_pyramid: bool,
|
||||
pub exr_compression: ExrCompression,
|
||||
/// OpenEXR `chromaticities` attribute (`[red, green, blue, white]` CIE xy), written into the
|
||||
/// image header when set.
|
||||
pub exr_chromaticities: Option<[[f32; 2]; 4]>,
|
||||
/// DPX bits per sample. `None` follows the image: 8 for 8-bit, 16 otherwise.
|
||||
pub dpx_bits: Option<DpxBits>,
|
||||
/// DDS compression and mip chain.
|
||||
@@ -302,6 +305,7 @@ impl Default for EncodeOptions {
|
||||
tiff_bigtiff: false,
|
||||
tiff_pyramid: false,
|
||||
exr_compression: ExrCompression::Zip16,
|
||||
exr_chromaticities: None,
|
||||
dpx_bits: None,
|
||||
dds: DdsOptions::default(),
|
||||
embed_icc: true,
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
//! non-positive or past [`MAX_PPI`] gives `None`, so the caller keeps its own default.
|
||||
|
||||
use crate::Limits;
|
||||
use crate::codecs::{jpeg, png, webp};
|
||||
use crate::codecs::{jpeg, png};
|
||||
use crate::resolution::exif_resolution;
|
||||
|
||||
/// Resolutions above this many pixels per inch are treated as corrupt.
|
||||
@@ -102,10 +102,28 @@ fn png_exif(bytes: &[u8]) -> Option<(f32, f32)> {
|
||||
exif_resolution(&exif?)
|
||||
}
|
||||
|
||||
/// The resolution of a WebP's `EXIF` chunk, read by the decoder's own container probe.
|
||||
/// The resolution of a WebP's `EXIF` chunk, read from the RIFF container within its declared size.
|
||||
fn webp_exif(bytes: &[u8]) -> Option<(f32, f32)> {
|
||||
let (_, _, exif) = webp::probe(bytes, &Limits::default()).ok()?;
|
||||
exif_resolution(&exif?)
|
||||
let riff = usize::try_from(le_u32(bytes, 4)?).ok()?;
|
||||
let end = 8usize.checked_add(riff)?.min(bytes.len());
|
||||
let mut pos = 12usize;
|
||||
for _ in 0..MAX_CHUNKS {
|
||||
let kind = bytes.get(pos..pos.checked_add(4)?)?;
|
||||
let size = usize::try_from(le_u32(bytes, pos.checked_add(4)?)?).ok()?;
|
||||
let data = pos.checked_add(8)?;
|
||||
if data.checked_add(size)? > end {
|
||||
return None;
|
||||
}
|
||||
if kind == b"EXIF" {
|
||||
let exif = bytes.get(data..data + size)?;
|
||||
let tiff = exif.strip_prefix(b"Exif\0\0").unwrap_or(exif);
|
||||
if let Some(dpi) = exif_resolution(tiff).filter(|&d| usable(d)) {
|
||||
return Some(dpi);
|
||||
}
|
||||
}
|
||||
pos = data.checked_add(size.checked_add(size & 1)?)?;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// BMP: the info header size at 14 (40 or more for a header with resolution fields), then the
|
||||
|
||||
@@ -124,7 +124,15 @@ fn jpeg_exif_wins_over_jfif_and_non_exif_app1_is_skipped() {
|
||||
assert_eq!(file_resolution(&jpeg(&[jfif(1, 72, 72), xmp.clone(), exif])), Some((600.0, 600.0)));
|
||||
// An unusable EXIF value falls back to JFIF.
|
||||
let zero = exif_app1(&tiff(true, 0, 0, None));
|
||||
assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp, zero])), Some((96.0, 96.0)));
|
||||
assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp.clone(), zero])), Some((96.0, 96.0)));
|
||||
let huge = exif_app1(&tiff(true, 1_000_000, 1_000_000, None));
|
||||
assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), huge])), Some((96.0, 96.0)));
|
||||
// Sub-1.0 EXIF rational also falls back to JFIF.
|
||||
let mut sub = tiff(true, 1, 1, None);
|
||||
let len = sub.len();
|
||||
sub[len - 12..len - 8].copy_from_slice(&4u32.to_le_bytes());
|
||||
sub[len - 4..len].copy_from_slice(&4u32.to_le_bytes());
|
||||
assert_eq!(file_resolution(&jpeg(&[jfif(1, 96, 96), xmp, exif_app1(&sub)])), Some((96.0, 96.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -166,6 +174,35 @@ fn webp_without_exif_has_none() {
|
||||
assert_eq!(file_resolution(b"RIFF\x04\0\0\0WEBP"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webp_exif_after_many_frames_and_riff_bounds() {
|
||||
let chunk = |out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]| {
|
||||
out.extend_from_slice(kind);
|
||||
out.extend_from_slice(&u32::try_from(data.len()).unwrap().to_le_bytes());
|
||||
out.extend_from_slice(data);
|
||||
if data.len() % 2 == 1 {
|
||||
out.push(0);
|
||||
}
|
||||
};
|
||||
let mut body = b"WEBP".to_vec();
|
||||
chunk(&mut body, b"VP8X", &[0; 10]);
|
||||
chunk(&mut body, b"ANIM", &[0; 6]);
|
||||
for _ in 0..100 {
|
||||
chunk(&mut body, b"ANMF", &[0; 17]);
|
||||
}
|
||||
chunk(&mut body, b"EXIF", &tiff(true, 300, 300, Some(2)));
|
||||
let riff = |size: usize, trailing: usize| {
|
||||
let mut webp = b"RIFF".to_vec();
|
||||
webp.extend_from_slice(&u32::try_from(size).unwrap().to_le_bytes());
|
||||
webp.extend_from_slice(&body);
|
||||
webp.extend_from_slice(&vec![0xAA; trailing]);
|
||||
webp
|
||||
};
|
||||
assert_eq!(file_resolution(&riff(body.len(), 0)), Some((300.0, 300.0)));
|
||||
assert_eq!(file_resolution(&riff(body.len(), 4)), Some((300.0, 300.0)));
|
||||
assert_eq!(file_resolution(&riff(body.len() - 4, 4)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bmp_pixels_per_metre() {
|
||||
close(file_resolution(&bmp(40, 3_780, 7_559)), (96.0, 192.0));
|
||||
|
||||
@@ -243,6 +243,10 @@ impl<T: Tools> Server<T> {
|
||||
};
|
||||
return Some(error(echoed, INVALID_REQUEST, "missing `method`"));
|
||||
};
|
||||
// A malformed envelope must not dispatch a tool or change notification state.
|
||||
if o.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
|
||||
return Some(error(Value::Null, INVALID_REQUEST, "`jsonrpc` must be \"2.0\""));
|
||||
}
|
||||
let params = o.get("params").cloned().unwrap_or(Value::Null);
|
||||
let Some(id) = id else {
|
||||
if method == "notifications/initialized" {
|
||||
|
||||
@@ -48,6 +48,63 @@ fn serve_with<T: Tools>(tools: T, lines: &[Value]) -> (Server<T>, Vec<Value>) {
|
||||
(s, replies)
|
||||
}
|
||||
|
||||
fn malformed_version_messages() -> Vec<Value> {
|
||||
let mut messages = Vec::new();
|
||||
for version in [None, Some(Value::Null), Some(json!("1.0")), Some(json!(2.0)), Some(json!(true)), Some(json!([])), Some(json!({}))] {
|
||||
for mut message in [
|
||||
json!({"id": 1, "method": "tools/call", "params": {"name": "echo", "arguments": {"text": "changed"}}}),
|
||||
json!({"method": "notifications/initialized"}),
|
||||
] {
|
||||
if let Some(version) = &version {
|
||||
message["jsonrpc"] = version.clone();
|
||||
}
|
||||
messages.push(message);
|
||||
}
|
||||
}
|
||||
messages
|
||||
}
|
||||
|
||||
fn invalid_version_reply() -> Value {
|
||||
json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32600, "message": "`jsonrpc` must be \"2.0\""}})
|
||||
}
|
||||
|
||||
/// Invalid envelopes are refused before listing or calling tools or changing lifecycle state.
|
||||
#[test]
|
||||
fn invalid_jsonrpc_versions_never_dispatch() {
|
||||
for message in malformed_version_messages() {
|
||||
let mut s = Server::new(info(), Echo::default());
|
||||
let response = s.handle(message.clone()).unwrap();
|
||||
assert_eq!(response, invalid_version_reply(), "{message}");
|
||||
assert!(s.tools().log.is_empty(), "{message}");
|
||||
assert!(!s.is_initialized(), "{message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The stdio entry point validates every envelope and still leaves valid notifications unanswered.
|
||||
#[test]
|
||||
fn stdio_refuses_invalid_jsonrpc_versions() {
|
||||
let messages = malformed_version_messages();
|
||||
let (mut s, replies) = serve(&messages);
|
||||
assert_eq!(replies, vec![invalid_version_reply(); messages.len()]);
|
||||
assert!(s.tools().log.is_empty());
|
||||
assert!(!s.is_initialized());
|
||||
assert_eq!(reply(&mut s, &json!({"jsonrpc": "2.0", "method": "notifications/initialized"})), None);
|
||||
assert!(s.is_initialized());
|
||||
}
|
||||
|
||||
/// Batch dispatch uses the same validation while continuing to answer valid requests.
|
||||
#[test]
|
||||
fn batches_refuse_invalid_jsonrpc_versions() {
|
||||
let mut messages = malformed_version_messages();
|
||||
let mut expected = vec![invalid_version_reply(); messages.len()];
|
||||
messages.push(ping(9));
|
||||
expected.push(json!({"jsonrpc": "2.0", "id": 9, "result": {}}));
|
||||
let mut s = Server::new(info(), Echo::default());
|
||||
assert_eq!(reply(&mut s, &Value::Array(messages)), Some(Value::Array(expected)));
|
||||
assert!(s.tools().log.is_empty());
|
||||
assert!(!s.is_initialized());
|
||||
}
|
||||
|
||||
/// A registered tool is listed and called over the stdio transport, with no engine behind it.
|
||||
#[test]
|
||||
fn a_registered_tool_is_served_over_stdio() {
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
use craft_keymap::{Chord, CommandRef, Key, Mods};
|
||||
use craft_ui::contract::MemoProps;
|
||||
use craft_ui::runtime::windows::{KeyEquivalent, WindowAction, WindowHost};
|
||||
|
||||
use crate::layout::{Clash, Layout};
|
||||
@@ -45,8 +46,9 @@ pub enum ClipboardKeys {
|
||||
Raw,
|
||||
}
|
||||
|
||||
/// What may run from the menus this frame, set by the app.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
/// What may run from the menus this frame, set by the app. As props of the runtime's command gate, every flag feeds
|
||||
/// the key.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, MemoProps)]
|
||||
#[non_exhaustive]
|
||||
pub struct Gate {
|
||||
/// A modal dialog is open.
|
||||
|
||||
@@ -12,6 +12,7 @@ use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_keymap::CommandRef;
|
||||
use craft_ui::contract::{MemoKey, MemoProps};
|
||||
|
||||
use crate::driver::Gate;
|
||||
use crate::model::{Builtin, Item};
|
||||
@@ -49,7 +50,8 @@ pub struct ModalRules {
|
||||
/// run. `None`: no pending operation.
|
||||
pub pending: Option<PendingRule>,
|
||||
/// The caller's count of rule changes. A rule holds a closure and cannot be compared, so the
|
||||
/// caller says when the rules changed; the menu skips the resync while it stays the same.
|
||||
/// caller says when the rules changed; the menu skips the resync, and the runtime's command gate keeps its answers,
|
||||
/// while it stays the same.
|
||||
pub revision: u64,
|
||||
}
|
||||
|
||||
@@ -86,6 +88,18 @@ impl ModalRules {
|
||||
}
|
||||
}
|
||||
|
||||
/// As props of the runtime's command gate: the plain fields and [`ModalRules::revision`], which stands for the
|
||||
/// [`ModalRules::pending`] closure. The derive cannot take the closure, and the revision is the caller's count of rule
|
||||
/// changes, so equal keys mean equal rules as long as the caller moves it with every change.
|
||||
impl MemoProps for ModalRules {
|
||||
fn key(&self, key: &mut MemoKey) {
|
||||
let ModalRules { in_dialogs, workspace, pending: _, revision } = self;
|
||||
in_dialogs.key(key);
|
||||
workspace.key(key);
|
||||
revision.key(key);
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ModalRules {
|
||||
// new: `PendingRule` is a closure; print whether one is set.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "craft-mesh"
|
||||
description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX and 3MF readers, bounded on hostile input"
|
||||
description = "3D mesh file formats behind one neutral model: STL and Wavefront OBJ/MTL readers and writers, a glTF 2.0 / GLB reader and GLB writer, and PLY, FBX, 3MF, COLLADA and Alembic readers, bounded on hostile input"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -18,6 +18,8 @@ ply = []
|
||||
gltf = ["dep:serde_json"]
|
||||
fbx = ["dep:miniz_oxide", "dep:craft-zip"]
|
||||
threemf = ["dep:craft-opc", "dep:craft-xml"]
|
||||
dae = ["dep:craft-xml"]
|
||||
abc = []
|
||||
|
||||
[dependencies]
|
||||
serde_json = { workspace = true, optional = true }
|
||||
|
||||
@@ -11,8 +11,10 @@ a `Scene` into bytes. One Cargo feature per format, all on by default.
|
||||
| `gltf` | glTF 2.0 (`.gltf`) and GLB | yes | GLB | `serde_json` |
|
||||
| `threemf` | 3MF, core and materials extension | yes | no | `craft-opc`, `craft-xml` |
|
||||
| `fbx` | FBX 6.x and 7.x, binary and ASCII | yes | no | `miniz_oxide` |
|
||||
| `dae` | COLLADA (`.dae`), scenes, transforms, cameras | yes | no | `craft-xml` |
|
||||
| `abc` | Alembic (`.abc`), Ogawa container | yes | no | none |
|
||||
|
||||
USD, Alembic and COLLADA are not here yet.
|
||||
USD is not here yet.
|
||||
|
||||
## The neutral model
|
||||
|
||||
|
||||
@@ -0,0 +1,709 @@
|
||||
//! Alembic (`.abc`), read: the Ogawa container, `AbcGeom_Xform` hierarchy (matrix, translate,
|
||||
//! rotate, scale ops; `.inherits`), `AbcGeom_PolyMesh` at its first sample (positions `P`,
|
||||
//! polygons `.faceIndices` / `.faceCounts` turned counter-clockwise from Alembic's clockwise
|
||||
//! winding, normals `N` and UVs `uv` at any geometry scope, indexed or not), and
|
||||
//! `AbcGeom_FaceSet` children as materials.
|
||||
//!
|
||||
//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate. HDF5-based
|
||||
//! Alembic files are refused with [`Error::Unsupported`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{Corner, Error, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Result, Scene, malformed, mat_mul, too_large};
|
||||
|
||||
const KIND: &str = "Alembic";
|
||||
const OGAWA_MAGIC: &[u8] = b"Ogawa";
|
||||
const HDF5_MAGIC: &[u8] = b"\x89HDF\r\n\x1a\n";
|
||||
const DATA_BIT: u64 = 1 << 63;
|
||||
const KEY_BYTES: usize = 16;
|
||||
const OBJECT_HASH_BYTES: usize = 32;
|
||||
const MAX_INDEXED_META: usize = 255;
|
||||
|
||||
/// Read an Alembic (`.abc` Ogawa) file into a [`Scene`].
|
||||
pub fn read(bytes: &[u8], limits: &Limits) -> Result<Scene> {
|
||||
if bytes.starts_with(HDF5_MAGIC) {
|
||||
return Err(Error::Unsupported("HDF5-based Alembic (re-export the file as Alembic Ogawa, the default since Alembic 1.5)".into()));
|
||||
}
|
||||
if !bytes.starts_with(OGAWA_MAGIC) || bytes.len() < 16 {
|
||||
return Err(malformed(KIND, "not an Alembic Ogawa file"));
|
||||
}
|
||||
let mut o = Ogawa { b: bytes, budget: limits.max_data_bytes, max_budget: limits.max_data_bytes, indexed_meta: vec![String::new()] };
|
||||
let root_ref = o.u64_at(8)?;
|
||||
let root = o.group(root_ref)?;
|
||||
let is_data = |i: usize| root.get(i).is_some_and(|r| r & DATA_BIT != 0);
|
||||
if root.len() < 6 || !(0..6).all(|i| is_data(i) != (i == 2)) {
|
||||
return Err(malformed(KIND, "the archive group does not have the Alembic layout"));
|
||||
}
|
||||
let block = o.data(root[5])?;
|
||||
read_indexed_meta(block, &mut o.indexed_meta)?;
|
||||
|
||||
let mut walk = Walk { o, limits, scene: Scene::default(), materials: HashMap::new(), visits: 0, triangles: 0, parts: 0 };
|
||||
walk.object(root[2], None, "", 0)?;
|
||||
Ok(walk.scene)
|
||||
}
|
||||
|
||||
struct Ogawa<'a> {
|
||||
b: &'a [u8],
|
||||
budget: usize,
|
||||
max_budget: usize,
|
||||
indexed_meta: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum PropKind {
|
||||
Compound,
|
||||
Scalar,
|
||||
Array,
|
||||
}
|
||||
|
||||
struct Prop {
|
||||
name: String,
|
||||
meta: String,
|
||||
kind: PropKind,
|
||||
pod: u32,
|
||||
extent: usize,
|
||||
group: u64,
|
||||
}
|
||||
|
||||
fn meta_get<'m>(meta: &'m str, key: &str) -> Option<&'m str> {
|
||||
meta.split(';').filter_map(|kv| kv.split_once('=')).find(|(k, _)| *k == key).map(|(_, v)| v)
|
||||
}
|
||||
|
||||
struct Cursor<'a> {
|
||||
b: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Cursor<'a> {
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8]> {
|
||||
let s = self.pos.checked_add(n).and_then(|end| self.b.get(self.pos..end)).ok_or_else(|| malformed(KIND, "header block ends early"))?;
|
||||
self.pos += n;
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn u8(&mut self) -> Result<u8> {
|
||||
Ok(self.take(1)?.first().copied().unwrap_or(0))
|
||||
}
|
||||
|
||||
fn u32(&mut self) -> Result<u32> {
|
||||
let s = self.take(4)?;
|
||||
Ok(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
|
||||
}
|
||||
|
||||
fn hinted(&mut self, hint: u32) -> Result<usize> {
|
||||
Ok(match hint {
|
||||
0 => self.u8()? as usize,
|
||||
1 => {
|
||||
let s = self.take(2)?;
|
||||
u16::from_le_bytes([s[0], s[1]]) as usize
|
||||
}
|
||||
2 => self.u32()? as usize,
|
||||
_ => return Err(malformed(KIND, format!("bad size hint {hint}"))),
|
||||
})
|
||||
}
|
||||
|
||||
fn string(&mut self, n: usize) -> Result<String> {
|
||||
Ok(String::from_utf8_lossy(self.take(n)?).into_owned())
|
||||
}
|
||||
}
|
||||
|
||||
fn f16_to_f64(bits: u16) -> f64 {
|
||||
let sign = if bits & 0x8000 != 0 { -1.0_f64 } else { 1.0_f64 };
|
||||
let exp = (bits >> 10) & 0x1f;
|
||||
let mant = bits & 0x03ff;
|
||||
match exp {
|
||||
0 => sign * (f64::from(mant) * 2.0_f64.powi(-24)),
|
||||
31 => {
|
||||
if mant == 0 {
|
||||
sign * f64::INFINITY
|
||||
} else {
|
||||
f64::NAN
|
||||
}
|
||||
}
|
||||
_ => sign * ((1.0 + f64::from(mant) / 1024.0) * 2.0_f64.powi(i32::from(exp) - 15)),
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Ogawa<'a> {
|
||||
fn charge(&mut self, bytes: usize) -> Result<()> {
|
||||
self.budget = self.budget.checked_sub(bytes).ok_or_else(|| too_large(KIND, format!("decodes to more than {} bytes", self.max_budget)))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn u64_at(&self, pos: u64) -> Result<u64> {
|
||||
let p = usize::try_from(pos).map_err(|_| malformed(KIND, "offset out of range"))?;
|
||||
let s =
|
||||
p.checked_add(8).and_then(|e| self.b.get(p..e)).ok_or_else(|| malformed(KIND, format!("offset {pos} is past the end of the file")))?;
|
||||
let mut a = [0u8; 8];
|
||||
a.copy_from_slice(s);
|
||||
Ok(u64::from_le_bytes(a))
|
||||
}
|
||||
|
||||
fn group(&mut self, r: u64) -> Result<Vec<u64>> {
|
||||
if r & DATA_BIT != 0 {
|
||||
return Err(malformed(KIND, "expected a group, found a data block"));
|
||||
}
|
||||
if r == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let n = self.u64_at(r)?;
|
||||
let room = (self.b.len() as u64).saturating_sub(r.saturating_add(8)) / 8;
|
||||
if n > room {
|
||||
return Err(malformed(KIND, format!("group at {r} claims {n} children")));
|
||||
}
|
||||
self.charge(n as usize * 8)?;
|
||||
(0..n).map(|i| self.u64_at(r + 8 + 8 * i)).collect()
|
||||
}
|
||||
|
||||
fn data(&self, r: u64) -> Result<&'a [u8]> {
|
||||
if r & DATA_BIT == 0 {
|
||||
return Err(malformed(KIND, "expected a data block, found a group"));
|
||||
}
|
||||
let off = r & !DATA_BIT;
|
||||
if off == 0 {
|
||||
return Ok(&[]);
|
||||
}
|
||||
let size = self.u64_at(off)?;
|
||||
let start = usize::try_from(off + 8).map_err(|_| malformed(KIND, "offset out of range"))?;
|
||||
usize::try_from(size)
|
||||
.ok()
|
||||
.and_then(|s| start.checked_add(s))
|
||||
.and_then(|end| self.b.get(start..end))
|
||||
.ok_or_else(|| malformed(KIND, format!("data block at {off} ({size} bytes) overruns the file")))
|
||||
}
|
||||
|
||||
fn meta_at(&self, index: u8) -> String {
|
||||
self.indexed_meta.get(index as usize).cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn compound(&mut self, r: u64) -> Result<Vec<Prop>> {
|
||||
let children = self.group(r)?;
|
||||
let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) };
|
||||
let block = self.data(last)?;
|
||||
self.charge(block.len())?;
|
||||
let mut c = Cursor { b: block, pos: 0 };
|
||||
let mut out = Vec::new();
|
||||
while c.pos < block.len() {
|
||||
let info = c.u32()?;
|
||||
let hint = (info & 0xc) >> 2;
|
||||
let kind = match info & 0x3 {
|
||||
0 => PropKind::Compound,
|
||||
1 => PropKind::Scalar,
|
||||
_ => PropKind::Array,
|
||||
};
|
||||
let (pod, extent) = ((info & 0xf0) >> 4, ((info & 0xff000) >> 12) as usize);
|
||||
if kind != PropKind::Compound {
|
||||
let _samples = c.hinted(hint)?;
|
||||
if info & 0x200 != 0 {
|
||||
c.hinted(hint)?;
|
||||
c.hinted(hint)?;
|
||||
}
|
||||
if info & 0x100 != 0 {
|
||||
c.hinted(hint)?;
|
||||
}
|
||||
}
|
||||
let name_len = c.hinted(hint)?;
|
||||
let name = c.string(name_len)?;
|
||||
let meta_index = ((info & 0xff0_0000) >> 20) as u8;
|
||||
let meta = if meta_index == 0xff {
|
||||
let n = c.hinted(hint)?;
|
||||
c.string(n)?
|
||||
} else {
|
||||
self.meta_at(meta_index)
|
||||
};
|
||||
let group = children.get(out.len()).copied().ok_or_else(|| malformed(KIND, format!("property \"{name}\" has no group")))?;
|
||||
out.push(Prop { name, meta, kind, pod, extent, group });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn values(&mut self, property: &Prop) -> Result<Vec<f64>> {
|
||||
let samples = self.group(property.group)?;
|
||||
let Some(&first) = samples.first() else { return Ok(Vec::new()) };
|
||||
|
||||
let raw = self.data(first)?;
|
||||
let raw = if raw.is_empty() {
|
||||
raw
|
||||
} else {
|
||||
raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))?
|
||||
};
|
||||
|
||||
let value_bytes = match property.pod {
|
||||
0..=2 => 1,
|
||||
3 | 4 | 9 => 2,
|
||||
5 | 6 | 10 => 4,
|
||||
7 | 8 | 11 => 8,
|
||||
other => return Err(Error::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))),
|
||||
};
|
||||
self.charge((raw.len() / value_bytes).saturating_mul(8))?;
|
||||
|
||||
Ok(match property.pod {
|
||||
0 | 1 => raw.iter().map(|v| *v as f64).collect(),
|
||||
2 => raw.iter().map(|v| *v as i8 as f64).collect(),
|
||||
3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(),
|
||||
4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(),
|
||||
5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(),
|
||||
6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(),
|
||||
7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(),
|
||||
8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(),
|
||||
9 => raw.as_chunks::<2>().0.iter().map(|c| f16_to_f64(u16::from_le_bytes(*c))).collect(),
|
||||
10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(),
|
||||
_ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
fn object_headers(&mut self, children: &[u64]) -> Result<Vec<(String, String)>> {
|
||||
let Some(&last) = children.last().filter(|c| **c & DATA_BIT != 0) else { return Ok(Vec::new()) };
|
||||
let block = self.data(last)?;
|
||||
self.charge(block.len())?;
|
||||
let body = block.get(..block.len().saturating_sub(OBJECT_HASH_BYTES)).unwrap_or_default();
|
||||
let mut c = Cursor { b: body, pos: 0 };
|
||||
let mut out = Vec::new();
|
||||
while c.pos < body.len() {
|
||||
let n = c.u32()? as usize;
|
||||
let name = c.string(n)?;
|
||||
let index = c.u8()?;
|
||||
let meta = if index == 0xff {
|
||||
let n = c.u32()? as usize;
|
||||
c.string(n)?
|
||||
} else {
|
||||
self.meta_at(index)
|
||||
};
|
||||
out.push((name, meta));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
fn read_indexed_meta(block: &[u8], out: &mut Vec<String>) -> Result<()> {
|
||||
let mut c = Cursor { b: block, pos: 0 };
|
||||
while c.pos < block.len() && out.len() < MAX_INDEXED_META {
|
||||
let n = c.u8()? as usize;
|
||||
out.push(c.string(n)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Scope {
|
||||
Constant,
|
||||
Uniform,
|
||||
Vertex,
|
||||
FaceVarying,
|
||||
}
|
||||
|
||||
struct Param {
|
||||
vals: Vec<f64>,
|
||||
indices: Option<Vec<f64>>,
|
||||
scope: Scope,
|
||||
}
|
||||
|
||||
impl Param {
|
||||
fn get<const W: usize>(&self, k: usize, p: usize, f: usize) -> Option<[f64; W]> {
|
||||
let i = match self.scope {
|
||||
Scope::Constant => 0,
|
||||
Scope::Uniform => f,
|
||||
Scope::Vertex => p,
|
||||
Scope::FaceVarying => k,
|
||||
};
|
||||
let i = match &self.indices {
|
||||
Some(ix) => Some(*ix.get(i)?).filter(|v| *v >= 0.0)? as usize,
|
||||
None => i,
|
||||
};
|
||||
let start = i.checked_mul(W)?;
|
||||
self.vals.get(start..start.checked_add(W)?)?.try_into().ok()
|
||||
}
|
||||
}
|
||||
|
||||
fn find<'p>(props: &'p [Prop], name: &str) -> Option<&'p Prop> {
|
||||
props.iter().find(|p| p.name == name)
|
||||
}
|
||||
|
||||
fn schema_compound<'p>(props: &'p [Prop], schema: &str, name: &str) -> Option<&'p Prop> {
|
||||
let compounds = || props.iter().filter(|p| p.kind == PropKind::Compound);
|
||||
compounds().find(|p| meta_get(&p.meta, "schema") == Some(schema)).or_else(|| compounds().find(|p| p.name == name))
|
||||
}
|
||||
|
||||
struct Walk<'a> {
|
||||
o: Ogawa<'a>,
|
||||
limits: &'a Limits,
|
||||
scene: Scene,
|
||||
materials: HashMap<String, usize>,
|
||||
visits: usize,
|
||||
triangles: usize,
|
||||
parts: usize,
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
fn warn(&mut self, msg: String) {
|
||||
if !self.scene.warnings.contains(&msg) {
|
||||
self.scene.warnings.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_node(&mut self, node: Node, parent: Option<usize>) -> Result<usize> {
|
||||
if self.scene.nodes.len() >= self.limits.max_nodes {
|
||||
return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes)));
|
||||
}
|
||||
let idx = self.scene.nodes.len();
|
||||
self.scene.nodes.push(node);
|
||||
match parent {
|
||||
Some(p) => self.scene.nodes[p].children.push(idx),
|
||||
None => self.scene.roots.push(idx),
|
||||
}
|
||||
Ok(idx)
|
||||
}
|
||||
|
||||
fn intern_material(&mut self, name: &str) -> Result<usize> {
|
||||
if let Some(&idx) = self.materials.get(name) {
|
||||
return Ok(idx);
|
||||
}
|
||||
if self.scene.materials.len() >= self.limits.max_materials {
|
||||
return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials)));
|
||||
}
|
||||
let idx = self.scene.materials.len();
|
||||
self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() });
|
||||
self.materials.insert(name.to_owned(), idx);
|
||||
Ok(idx)
|
||||
}
|
||||
|
||||
fn object(&mut self, r: u64, parent_node: Option<usize>, xform_name: &str, depth: usize) -> Result<()> {
|
||||
self.visits += 1;
|
||||
if depth > self.limits.max_depth || self.visits > self.limits.max_nodes {
|
||||
return Err(malformed(KIND, "objects are nested too deeply or shared too often"));
|
||||
}
|
||||
let children = self.o.group(r)?;
|
||||
let headers = self.o.object_headers(&children)?;
|
||||
for (i, (name, meta)) in headers.iter().enumerate() {
|
||||
let group = children
|
||||
.get(i + 1)
|
||||
.copied()
|
||||
.filter(|g| g & DATA_BIT == 0)
|
||||
.ok_or_else(|| malformed(KIND, format!("object \"{name}\" has no group")))?;
|
||||
let schema = meta_get(meta, "schema").unwrap_or_default();
|
||||
let kids = self.o.group(group)?;
|
||||
let props = match kids.first() {
|
||||
Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
let mut next_parent = parent_node;
|
||||
if schema.starts_with("AbcGeom_Xform") {
|
||||
if let Some(xf) = schema_compound(&props, schema, ".xform") {
|
||||
let (local, inherits) = self.xform(xf.group)?;
|
||||
let attach_to = if inherits { parent_node } else { None };
|
||||
let node_idx = self.push_node(Node { name: name.clone(), transform: local, ..Node::default() }, attach_to)?;
|
||||
next_parent = Some(node_idx);
|
||||
}
|
||||
} else if schema.starts_with("AbcGeom_PolyMesh")
|
||||
&& let Some(geom) = schema_compound(&props, schema, ".geom")
|
||||
{
|
||||
let part_name = if xform_name.is_empty() { name.clone() } else { xform_name.to_string() };
|
||||
let sets = self.face_sets(&kids)?;
|
||||
let mesh = self.mesh(geom.group, &part_name, &sets)?;
|
||||
if self.scene.meshes.len() >= self.limits.max_meshes {
|
||||
return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes)));
|
||||
}
|
||||
let mesh_idx = self.scene.meshes.len();
|
||||
self.scene.meshes.push(mesh);
|
||||
let node_idx = self.push_node(Node { name: part_name, mesh: Some(mesh_idx), ..Node::default() }, parent_node)?;
|
||||
next_parent = Some(node_idx);
|
||||
}
|
||||
|
||||
if !schema.starts_with("AbcGeom_FaceSet") {
|
||||
let owner = if schema.starts_with("AbcGeom_Xform") { name.as_str() } else { "" };
|
||||
self.object(group, next_parent, owner, depth + 1)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn xform(&mut self, r: u64) -> Result<(Mat4, bool)> {
|
||||
let props = self.o.compound(r)?;
|
||||
let ops = match find(&props, ".ops") {
|
||||
Some(p) => self.o.values(p)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let vals = match find(&props, ".vals") {
|
||||
Some(p) => self.o.values(p)?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let inherits = match find(&props, ".inherits") {
|
||||
Some(p) => self.o.values(p)?.first().is_none_or(|v| *v != 0.0),
|
||||
None => true,
|
||||
};
|
||||
let mut m = IDENTITY;
|
||||
let mut ch = 0usize;
|
||||
for op in ops {
|
||||
let kind = (op as u32) >> 4;
|
||||
let n = match kind {
|
||||
0 | 1 => 3,
|
||||
2 => 4,
|
||||
3 => 16,
|
||||
4..=6 => 1,
|
||||
_ => return Err(malformed(KIND, format!("unknown xform operation {kind}"))),
|
||||
};
|
||||
let Some(v) = vals.get(ch..ch + n) else { return Err(malformed(KIND, "xform has fewer values than its operations need")) };
|
||||
ch += n;
|
||||
let op_m = match kind {
|
||||
0 => [v[0], 0.0, 0.0, 0.0, 0.0, v[1], 0.0, 0.0, 0.0, 0.0, v[2], 0.0, 0.0, 0.0, 0.0, 1.0],
|
||||
1 => [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, v[0], v[1], v[2], 1.0],
|
||||
2 => axis_angle_matrix([v[0], v[1], v[2]], v[3].to_radians()),
|
||||
3 => {
|
||||
let mut a = [0.0; 16];
|
||||
a.copy_from_slice(v);
|
||||
a
|
||||
}
|
||||
4 => rot_x(v[0].to_radians()),
|
||||
5 => rot_y(v[0].to_radians()),
|
||||
_ => rot_z(v[0].to_radians()),
|
||||
};
|
||||
m = mat_mul(&m, &op_m);
|
||||
}
|
||||
if !m.iter().all(|x| x.is_finite()) {
|
||||
return Err(malformed(KIND, "xform has non-finite values"));
|
||||
}
|
||||
Ok((m, inherits))
|
||||
}
|
||||
|
||||
fn face_sets(&mut self, kids: &[u64]) -> Result<Vec<(String, Vec<f64>)>> {
|
||||
let headers = self.o.object_headers(kids)?;
|
||||
let mut out = Vec::new();
|
||||
for (i, (name, meta)) in headers.iter().enumerate() {
|
||||
let schema = meta_get(meta, "schema").unwrap_or_default();
|
||||
if !schema.starts_with("AbcGeom_FaceSet") {
|
||||
continue;
|
||||
}
|
||||
let Some(&g) = kids.get(i + 1).filter(|g| **g & DATA_BIT == 0) else { continue };
|
||||
let props = match self.o.group(g)?.first() {
|
||||
Some(&p) if p & DATA_BIT == 0 => self.o.compound(p)?,
|
||||
_ => continue,
|
||||
};
|
||||
let Some(fs) = schema_compound(&props, schema, ".faceset") else { continue };
|
||||
let inner = self.o.compound(fs.group)?;
|
||||
if let Some(faces) = find(&inner, ".faces") {
|
||||
out.push((name.clone(), self.o.values(faces)?));
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn param(&mut self, props: &[Prop], name: &str, counts: [usize; 3]) -> Result<Option<Param>> {
|
||||
let Some(p) = find(props, name) else { return Ok(None) };
|
||||
let (vals, indices) = match p.kind {
|
||||
PropKind::Array => (self.o.values(p)?, None),
|
||||
PropKind::Compound => {
|
||||
let inner = self.o.compound(p.group)?;
|
||||
let Some(v) = find(&inner, ".vals") else { return Ok(None) };
|
||||
let vals = self.o.values(v)?;
|
||||
let indices = match find(&inner, ".indices") {
|
||||
Some(ix) => Some(self.o.values(ix)?),
|
||||
None => None,
|
||||
};
|
||||
(vals, indices)
|
||||
}
|
||||
PropKind::Scalar => return Ok(None),
|
||||
};
|
||||
let width = p.extent.max(1);
|
||||
let items = indices.as_ref().map_or(vals.len() / width, Vec::len);
|
||||
let [points, faces, corners] = counts;
|
||||
let scope = match meta_get(&p.meta, "geoScope") {
|
||||
Some("con") => Scope::Constant,
|
||||
Some("uni") => Scope::Uniform,
|
||||
Some("vtx" | "var") => Scope::Vertex,
|
||||
Some("fvr") => Scope::FaceVarying,
|
||||
_ if items == corners => Scope::FaceVarying,
|
||||
_ if items == points => Scope::Vertex,
|
||||
_ if items == faces => Scope::Uniform,
|
||||
_ => Scope::Constant,
|
||||
};
|
||||
Ok(Some(Param { vals, indices, scope }))
|
||||
}
|
||||
|
||||
fn mesh(&mut self, r: u64, name: &str, sets: &[(String, Vec<f64>)]) -> Result<Mesh> {
|
||||
let properties = self.o.compound(r)?;
|
||||
let get = |o: &mut Ogawa, prop_name: &str| -> Result<Vec<f64>> {
|
||||
match find(&properties, prop_name) {
|
||||
Some(p) => o.values(p),
|
||||
None => Err(malformed(KIND, format!("PolyMesh has no {prop_name}"))),
|
||||
}
|
||||
};
|
||||
|
||||
let p = get(&mut self.o, "P")?;
|
||||
let indices = get(&mut self.o, ".faceIndices")?;
|
||||
let counts = get(&mut self.o, ".faceCounts")?;
|
||||
let num_points = p.len() / 3;
|
||||
if num_points > self.limits.max_vertices {
|
||||
return Err(too_large(KIND, format!("more than {} vertices", self.limits.max_vertices)));
|
||||
}
|
||||
let positions: Vec<[f64; 3]> = p.as_chunks::<3>().0.to_vec();
|
||||
let n = [positions.len(), counts.len(), indices.len()];
|
||||
let normals_param = self.param(&properties, "N", n)?;
|
||||
let uvs_param = self.param(&properties, "uv", n)?;
|
||||
|
||||
let mut face_material = vec![None::<usize>; counts.len()];
|
||||
for (s, (_, faces)) in sets.iter().enumerate() {
|
||||
for f in faces {
|
||||
if let Some(m) = face_material.get_mut(*f as usize).filter(|m| m.is_none() && *f >= 0.0) {
|
||||
*m = Some(s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut mesh = Mesh { name: name.to_string(), positions, ..Mesh::default() };
|
||||
let mut norm_ids: HashMap<[u64; 3], u32> = HashMap::new();
|
||||
let mut uv_ids: HashMap<[u32; 2], u32> = HashMap::new();
|
||||
let mut uv_pool: Vec<[f32; 2]> = Vec::new();
|
||||
let mut parts_by_mat: HashMap<Option<usize>, Part> = HashMap::new();
|
||||
let mut part_order: Vec<Option<usize>> = Vec::new();
|
||||
|
||||
let (mut k, mut face_corners, mut bad_uvs) = (0usize, Vec::new(), 0usize);
|
||||
for (f, &count) in counts.iter().enumerate() {
|
||||
let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len());
|
||||
let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?;
|
||||
let face_len = end - k;
|
||||
if face_len > self.limits.max_face_corners {
|
||||
return Err(too_large(KIND, format!("face {f} has more than {} corners", self.limits.max_face_corners)));
|
||||
}
|
||||
if face_len >= 3 {
|
||||
self.triangles = self.triangles.saturating_add(face_len - 2);
|
||||
if self.triangles > self.limits.max_triangles {
|
||||
return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles)));
|
||||
}
|
||||
face_corners.clear();
|
||||
for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) {
|
||||
if point_index < 0.0 || (point_index as usize) >= mesh.positions.len() {
|
||||
return Err(malformed(KIND, format!("point index {point_index} out of range")));
|
||||
}
|
||||
let pt = point_index as usize;
|
||||
let norm_idx = match normals_param.as_ref().and_then(|l| l.get::<3>(corner_index, pt, f)) {
|
||||
Some(norm) => intern_norm(&mut mesh.normals, &mut norm_ids, norm, self.limits.max_vertices)?,
|
||||
None => crate::NONE,
|
||||
};
|
||||
let uv_idx = match &uvs_param {
|
||||
Some(l) => {
|
||||
let uv = match l.get::<2>(corner_index, pt, f) {
|
||||
Some([u, v]) => [u as f32, 1.0 - v as f32],
|
||||
None => {
|
||||
bad_uvs += 1;
|
||||
[0.0, 0.0]
|
||||
}
|
||||
};
|
||||
intern_uv(&mut uv_pool, &mut uv_ids, uv, self.limits.max_vertices)?
|
||||
}
|
||||
None => crate::NONE,
|
||||
};
|
||||
face_corners.push(Corner { position: pt as u32, normal: norm_idx, uv: uv_idx });
|
||||
}
|
||||
// Alembic winds polygons clockwise; reverse to counter-clockwise.
|
||||
face_corners.reverse();
|
||||
|
||||
let mat_idx = match face_material.get(f).copied().flatten().and_then(|s| sets.get(s)) {
|
||||
Some((mat_name, _)) => Some(self.intern_material(mat_name)?),
|
||||
None => None,
|
||||
};
|
||||
let part = match parts_by_mat.entry(mat_idx) {
|
||||
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
|
||||
std::collections::hash_map::Entry::Vacant(e) => {
|
||||
self.parts += 1;
|
||||
if self.parts > self.limits.max_parts {
|
||||
return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts)));
|
||||
}
|
||||
part_order.push(mat_idx);
|
||||
e.insert(Part { material: mat_idx, ..Part::default() })
|
||||
}
|
||||
};
|
||||
part.corners.extend_from_slice(&face_corners);
|
||||
part.face_sizes.push(face_corners.len() as u32);
|
||||
}
|
||||
k = end;
|
||||
}
|
||||
|
||||
for mat_idx in part_order {
|
||||
if let Some(mut part) = parts_by_mat.remove(&mat_idx) {
|
||||
if part.face_sizes.iter().all(|&s| s == 3) {
|
||||
part.face_sizes.clear();
|
||||
}
|
||||
mesh.parts.push(part);
|
||||
}
|
||||
}
|
||||
if !uv_pool.is_empty() {
|
||||
mesh.uv_sets.push(uv_pool);
|
||||
}
|
||||
if bad_uvs > 0 {
|
||||
self.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)"));
|
||||
}
|
||||
Ok(mesh)
|
||||
}
|
||||
}
|
||||
|
||||
fn intern_norm(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize) -> Result<u32> {
|
||||
let key = val.map(f64::to_bits);
|
||||
if let Some(&id) = map.get(&key) {
|
||||
return Ok(id);
|
||||
}
|
||||
if pool.len() >= limit {
|
||||
return Err(too_large(KIND, format!("more than {limit} normals")));
|
||||
}
|
||||
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many normals"))?;
|
||||
pool.push(val);
|
||||
map.insert(key, id);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result<u32> {
|
||||
let key = val.map(f32::to_bits);
|
||||
if let Some(&id) = map.get(&key) {
|
||||
return Ok(id);
|
||||
}
|
||||
if pool.len() >= limit {
|
||||
return Err(too_large(KIND, format!("more than {limit} UVs")));
|
||||
}
|
||||
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?;
|
||||
pool.push(val);
|
||||
map.insert(key, id);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Mat4 {
|
||||
let len = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt();
|
||||
if !len.is_finite() || len == 0.0 {
|
||||
return IDENTITY;
|
||||
}
|
||||
let [x, y, z] = axis.map(|v| v / len);
|
||||
let (s, c) = angle.sin_cos();
|
||||
let t = 1.0 - c;
|
||||
[
|
||||
t * x * x + c,
|
||||
t * x * y + s * z,
|
||||
t * x * z - s * y,
|
||||
0.0,
|
||||
t * x * y - s * z,
|
||||
t * y * y + c,
|
||||
t * y * z + s * x,
|
||||
0.0,
|
||||
t * x * z + s * y,
|
||||
t * y * z - s * x,
|
||||
t * z * z + c,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
]
|
||||
}
|
||||
|
||||
fn rot_x(a: f64) -> Mat4 {
|
||||
let (s, c) = a.sin_cos();
|
||||
[1.0, 0.0, 0.0, 0.0, 0.0, c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0]
|
||||
}
|
||||
|
||||
fn rot_y(a: f64) -> Mat4 {
|
||||
let (s, c) = a.sin_cos();
|
||||
[c, 0.0, -s, 0.0, 0.0, 1.0, 0.0, 0.0, s, 0.0, c, 0.0, 0.0, 0.0, 0.0, 1.0]
|
||||
}
|
||||
|
||||
fn rot_z(a: f64) -> Mat4 {
|
||||
let (s, c) = a.sin_cos();
|
||||
[c, s, 0.0, 0.0, -s, c, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
//! COLLADA (`.dae`), read: `triangles`, `polylist` and `polygons` with `VERTEX` / `NORMAL` /
|
||||
//! `TEXCOORD` inputs, materials bound through `instance_geometry` and `instance_controller`, the
|
||||
//! visual scene's node hierarchy and transforms (`matrix`, `translate`, `rotate`, `scale`,
|
||||
//! `lookat`), `instance_node`, `instance_camera`, and the asset's unit (`meter`) and `up_axis`.
|
||||
//!
|
||||
//! [`read_document`] returns the [`Scene`] in the file's own axes and units alongside
|
||||
//! [`Document::meter`] and [`Document::up_axis`] (and [`Document::global_transform`] to convert to
|
||||
//! Y-up metres). [`read`] returns the [`Scene`] directly.
|
||||
//!
|
||||
//! UVs are flipped to top-left origin (`1.0 - v`), matching the rest of this crate.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_xml::{El, Options, UnknownEntity};
|
||||
|
||||
use crate::{Camera, Corner, IDENTITY, Limits, Mat4, Material, Mesh, Node, Part, Projection, Result, Scene, malformed, mat_mul, too_large};
|
||||
|
||||
const KIND: &str = "COLLADA";
|
||||
const MAX_XML_DEPTH: usize = 256;
|
||||
const MAX_XML_NODES: usize = 2_000_000;
|
||||
|
||||
/// Up axis of a COLLADA `<asset>`.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum UpAxis {
|
||||
#[default]
|
||||
YUp,
|
||||
ZUp,
|
||||
XUp,
|
||||
}
|
||||
|
||||
impl UpAxis {
|
||||
/// Rotation matrix that turns this axis into +Y up.
|
||||
pub fn to_y_up(self) -> Mat4 {
|
||||
match self {
|
||||
UpAxis::YUp => IDENTITY,
|
||||
UpAxis::ZUp => [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0],
|
||||
UpAxis::XUp => [0.0, 1.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A COLLADA document: the scene in the file's own axes and units, plus its `<asset>` scale and
|
||||
/// up axis.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Document {
|
||||
pub scene: Scene,
|
||||
/// Metres per file unit (default `1.0`).
|
||||
pub meter: f64,
|
||||
pub up_axis: UpAxis,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Transform from the file's axes and units to Y-up metres.
|
||||
pub fn global_transform(&self) -> Mat4 {
|
||||
let scale = [self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, self.meter, 0.0, 0.0, 0.0, 0.0, 1.0];
|
||||
mat_mul(&self.up_axis.to_y_up(), &scale)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a COLLADA file into a [`Scene`] (in the file's own axes and units).
|
||||
pub fn read(bytes: &[u8], limits: &Limits) -> Result<Scene> {
|
||||
Ok(read_document(bytes, limits)?.scene)
|
||||
}
|
||||
|
||||
/// Read a COLLADA file into a [`Document`].
|
||||
pub fn read_document(bytes: &[u8], limits: &Limits) -> Result<Document> {
|
||||
let mut opts = Options::local();
|
||||
opts.unknown_entity = UnknownEntity::Literal;
|
||||
opts.strict_end_tags = true;
|
||||
opts.limits.max_input = limits.max_data_bytes;
|
||||
opts.limits.max_depth = MAX_XML_DEPTH;
|
||||
opts.limits.max_nodes = MAX_XML_NODES;
|
||||
let root = opts.parse(bytes).map_err(|e| if e.is_limit() { too_large(KIND, e) } else { malformed(KIND, e) })?;
|
||||
if root.name != "COLLADA" {
|
||||
return Err(malformed(KIND, "not a COLLADA document"));
|
||||
}
|
||||
|
||||
let mut ids: HashMap<&str, &El> = HashMap::new();
|
||||
let mut stack = vec![&root];
|
||||
while let Some(el) = stack.pop() {
|
||||
if let Some(id) = el.attr("id") {
|
||||
ids.entry(id).or_insert(el);
|
||||
}
|
||||
stack.extend(el.elements());
|
||||
}
|
||||
|
||||
let asset = root.child("asset");
|
||||
let meter = asset
|
||||
.and_then(|a| a.child("unit"))
|
||||
.and_then(|u| u.attr("meter"))
|
||||
.and_then(|m| m.trim().parse::<f64>().ok())
|
||||
.filter(|m| m.is_finite() && *m > 0.0)
|
||||
.unwrap_or(1.0);
|
||||
let up_axis = match asset.and_then(|a| a.child("up_axis")).map(|u| u.text().trim().to_owned()).as_deref() {
|
||||
Some("Z_UP") => UpAxis::ZUp,
|
||||
Some("X_UP") => UpAxis::XUp,
|
||||
_ => UpAxis::YUp,
|
||||
};
|
||||
|
||||
let mut reader =
|
||||
Reader { ids, sources: HashMap::new(), limits, scene: Scene::default(), materials: HashMap::new(), mesh_cache: HashMap::new(), triangles: 0 };
|
||||
|
||||
let visual_scene = root
|
||||
.child("scene")
|
||||
.and_then(|s| s.child("instance_visual_scene"))
|
||||
.and_then(|i| reader.get(i.attr("url")))
|
||||
.or_else(|| root.child("library_visual_scenes").and_then(|l| l.child("visual_scene")));
|
||||
|
||||
if let Some(vs) = visual_scene {
|
||||
for n in vs.children("node") {
|
||||
let idx = reader.read_node(n, 0)?;
|
||||
reader.scene.roots.push(idx);
|
||||
}
|
||||
} else {
|
||||
for geom in root.children("library_geometries").flat_map(|l| l.children("geometry")) {
|
||||
let mesh_idx = reader.get_or_build_mesh(geom, &[])?;
|
||||
let name = reader.scene.meshes[mesh_idx].name.clone();
|
||||
let node_idx = reader.push_node(Node { name, mesh: Some(mesh_idx), ..Node::default() })?;
|
||||
reader.scene.roots.push(node_idx);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Document { scene: reader.scene, meter, up_axis })
|
||||
}
|
||||
|
||||
struct Source {
|
||||
data: Vec<f64>,
|
||||
stride: usize,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
impl Source {
|
||||
fn get<const W: usize>(&self, i: u32) -> Option<[f64; W]> {
|
||||
let start = (i as usize).checked_mul(self.stride)?.checked_add(self.offset)?;
|
||||
self.data.get(start..start.checked_add(W)?)?.try_into().ok()
|
||||
}
|
||||
}
|
||||
|
||||
struct Input {
|
||||
offset: usize,
|
||||
source: Rc<Source>,
|
||||
}
|
||||
|
||||
struct Reader<'a> {
|
||||
ids: HashMap<&'a str, &'a El>,
|
||||
sources: HashMap<&'a str, Rc<Source>>,
|
||||
limits: &'a Limits,
|
||||
scene: Scene,
|
||||
materials: HashMap<String, usize>,
|
||||
/// Keyed by `(geometry element pointer, sorted (symbol, material_name) bindings)`.
|
||||
mesh_cache: HashMap<(usize, Vec<(String, String)>), usize>,
|
||||
triangles: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
fn get(&self, url: Option<&str>) -> Option<&'a El> {
|
||||
url.and_then(|u| u.strip_prefix('#')).and_then(|id| self.ids.get(id)).copied()
|
||||
}
|
||||
|
||||
fn warn(&mut self, msg: String) {
|
||||
if !self.scene.warnings.contains(&msg) {
|
||||
self.scene.warnings.push(msg);
|
||||
}
|
||||
}
|
||||
|
||||
fn push_node(&mut self, node: Node) -> Result<usize> {
|
||||
if self.scene.nodes.len() >= self.limits.max_nodes {
|
||||
return Err(too_large(KIND, format!("more than {} nodes", self.limits.max_nodes)));
|
||||
}
|
||||
let idx = self.scene.nodes.len();
|
||||
self.scene.nodes.push(node);
|
||||
Ok(idx)
|
||||
}
|
||||
|
||||
fn intern_material(&mut self, name: &str) -> Result<usize> {
|
||||
if let Some(&idx) = self.materials.get(name) {
|
||||
return Ok(idx);
|
||||
}
|
||||
if self.scene.materials.len() >= self.limits.max_materials {
|
||||
return Err(too_large(KIND, format!("more than {} materials", self.limits.max_materials)));
|
||||
}
|
||||
let idx = self.scene.materials.len();
|
||||
self.scene.materials.push(Material { name: name.to_owned(), ..Material::default() });
|
||||
self.materials.insert(name.to_owned(), idx);
|
||||
Ok(idx)
|
||||
}
|
||||
|
||||
fn source(&mut self, url: Option<&str>) -> Result<Rc<Source>> {
|
||||
let el = self.get(url).ok_or_else(|| malformed(KIND, format!("missing source {}", url.unwrap_or("(none)"))))?;
|
||||
let id = el.attr("id").unwrap_or_default();
|
||||
if !id.is_empty()
|
||||
&& let Some(s) = self.sources.get(id)
|
||||
{
|
||||
return Ok(s.clone());
|
||||
}
|
||||
let acc = el.child("technique_common").and_then(|t| t.child("accessor"));
|
||||
let array = acc.and_then(|a| self.get(a.attr("source"))).or_else(|| el.child("float_array"));
|
||||
let array = array.ok_or_else(|| malformed(KIND, format!("source \"{id}\" has no float_array")))?;
|
||||
let num = |k: &str, default: usize| acc.and_then(|a| a.attr(k)).and_then(|v| v.parse().ok()).unwrap_or(default);
|
||||
let data = parse_floats(array)?;
|
||||
if data.len() / 3 > self.limits.max_vertices {
|
||||
return Err(too_large(KIND, format!("source has more than {} vertices", self.limits.max_vertices)));
|
||||
}
|
||||
let s = Rc::new(Source { data, stride: num("stride", 1).max(1), offset: num("offset", 0) });
|
||||
if !id.is_empty() {
|
||||
self.sources.insert(id, s.clone());
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
fn read_node(&mut self, el: &'a El, depth: usize) -> Result<usize> {
|
||||
if depth > self.limits.max_depth {
|
||||
return Err(too_large(KIND, format!("node hierarchy is deeper than {}", self.limits.max_depth)));
|
||||
}
|
||||
let name = el.attr("name").or_else(|| el.attr("id")).unwrap_or_default().to_string();
|
||||
let transform = node_transform(el)?;
|
||||
let mut node = Node { name: name.clone(), transform, ..Node::default() };
|
||||
|
||||
for inst in el.elements() {
|
||||
if inst.name == "instance_camera" {
|
||||
if node.camera.is_none()
|
||||
&& let Some(cam_el) = self.get(inst.attr("url"))
|
||||
&& let Some(cam) = parse_camera(cam_el, &name)
|
||||
&& self.scene.cameras.len() < self.limits.max_extras
|
||||
{
|
||||
let cam_idx = self.scene.cameras.len();
|
||||
self.scene.cameras.push(cam);
|
||||
node.camera = Some(cam_idx);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (geom, bind_shape) = match inst.name.as_str() {
|
||||
"instance_geometry" => (self.get(inst.attr("url")), IDENTITY),
|
||||
"instance_controller" => {
|
||||
let skin = self.get(inst.attr("url")).and_then(|c| c.child("skin"));
|
||||
let bind = skin.and_then(|s| s.child("bind_shape_matrix")).map(parse_floats).transpose()?.and_then(|v| row_major_matrix(&v));
|
||||
(skin.and_then(|s| self.get(s.attr("source"))), bind.unwrap_or(IDENTITY))
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
let Some(geom) = geom else {
|
||||
self.warn("an instanced geometry is missing from the file".into());
|
||||
continue;
|
||||
};
|
||||
let bind = self.bindings(inst);
|
||||
let mesh_idx = self.get_or_build_mesh(geom, &bind)?;
|
||||
if node.mesh.is_none() && bind_shape == IDENTITY {
|
||||
node.mesh = Some(mesh_idx);
|
||||
} else {
|
||||
let child = self.push_node(Node { name: name.clone(), transform: bind_shape, mesh: Some(mesh_idx), ..Node::default() })?;
|
||||
node.children.push(child);
|
||||
}
|
||||
}
|
||||
|
||||
for child_el in el.children("node") {
|
||||
let child = self.read_node(child_el, depth + 1)?;
|
||||
node.children.push(child);
|
||||
}
|
||||
for inst_node in el.children("instance_node") {
|
||||
if let Some(target) = self.get(inst_node.attr("url")) {
|
||||
let child = self.read_node(target, depth + 1)?;
|
||||
node.children.push(child);
|
||||
}
|
||||
}
|
||||
|
||||
self.push_node(node)
|
||||
}
|
||||
|
||||
fn bindings(&self, inst: &El) -> Vec<(String, String)> {
|
||||
let mut out: Vec<(String, String)> = inst
|
||||
.child("bind_material")
|
||||
.and_then(|b| b.child("technique_common"))
|
||||
.into_iter()
|
||||
.flat_map(|t| t.children("instance_material"))
|
||||
.filter_map(|im| {
|
||||
let symbol = im.attr("symbol")?;
|
||||
let mat = self.get(im.attr("target"));
|
||||
let name = mat.and_then(|m| m.attr("name").or_else(|| m.attr("id"))).unwrap_or(symbol);
|
||||
Some((symbol.to_string(), name.to_string()))
|
||||
})
|
||||
.collect();
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
|
||||
fn get_or_build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result<usize> {
|
||||
let key = ((geom as *const El) as usize, bind.to_vec());
|
||||
if let Some(&idx) = self.mesh_cache.get(&key) {
|
||||
return Ok(idx);
|
||||
}
|
||||
if self.scene.meshes.len() >= self.limits.max_meshes {
|
||||
return Err(too_large(KIND, format!("more than {} meshes", self.limits.max_meshes)));
|
||||
}
|
||||
let mesh = self.build_mesh(geom, bind)?;
|
||||
let idx = self.scene.meshes.len();
|
||||
self.scene.meshes.push(mesh);
|
||||
self.mesh_cache.insert(key, idx);
|
||||
Ok(idx)
|
||||
}
|
||||
|
||||
fn build_mesh(&mut self, geom: &'a El, bind: &[(String, String)]) -> Result<Mesh> {
|
||||
let name = geom.attr("name").or_else(|| geom.attr("id")).unwrap_or_default().to_string();
|
||||
let mut mesh = Mesh { name, ..Mesh::default() };
|
||||
let Some(mesh_el) = geom.child("mesh") else { return Ok(mesh) };
|
||||
|
||||
let mut pools = MeshPools::default();
|
||||
let mut part_count: usize = self.scene.meshes.iter().map(|m| m.parts.len()).sum();
|
||||
|
||||
for prim in mesh_el.elements() {
|
||||
if !matches!(prim.name.as_str(), "triangles" | "polylist" | "polygons") {
|
||||
if matches!(prim.name.as_str(), "lines" | "linestrips" | "trifans" | "tristrips") {
|
||||
self.warn(format!("skipped COLLADA <{}> (only triangles and polygons are supported)", prim.name));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let Some(inputs) = self.read_primitive_inputs(prim)? else {
|
||||
self.warn("skipped COLLADA primitives without positions".into());
|
||||
continue;
|
||||
};
|
||||
part_count += 1;
|
||||
if part_count > self.limits.max_parts {
|
||||
return Err(too_large(KIND, format!("more than {} parts", self.limits.max_parts)));
|
||||
}
|
||||
let material = match prim.attr("material") {
|
||||
Some(sym) => {
|
||||
let mat_name = bind.binary_search_by(|(k, _)| k.as_str().cmp(sym)).ok().map_or(sym, |i| bind[i].1.as_str());
|
||||
Some(self.intern_material(mat_name)?)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let lists = read_primitive_lists(prim, inputs.stride)?;
|
||||
let part = self.build_part(material, &inputs, &lists, &mut mesh, &mut pools)?;
|
||||
if !part.corners.is_empty() {
|
||||
mesh.parts.push(part);
|
||||
}
|
||||
}
|
||||
if !pools.uvs.is_empty() {
|
||||
mesh.uv_sets.push(pools.uvs);
|
||||
}
|
||||
Ok(mesh)
|
||||
}
|
||||
|
||||
fn read_primitive_inputs(&mut self, prim: &'a El) -> Result<Option<PrimInputs>> {
|
||||
let (mut position, mut normal, mut uv): (Option<Input>, Option<Input>, Option<(u32, Input)>) = (None, None, None);
|
||||
let mut stride = 1usize;
|
||||
for input in prim.children("input") {
|
||||
let offset: usize = input.attr("offset").and_then(|o| o.parse().ok()).unwrap_or(0);
|
||||
stride = stride.max(offset.saturating_add(1));
|
||||
let nested: Vec<&El> = match input.attr("semantic") {
|
||||
Some("VERTEX") => self.get(input.attr("source")).map(|v| v.children("input").collect()).unwrap_or_default(),
|
||||
_ => vec![input],
|
||||
};
|
||||
for i in nested {
|
||||
let set: u32 = input.attr("set").or_else(|| i.attr("set")).and_then(|s| s.parse().ok()).unwrap_or(0);
|
||||
match i.attr("semantic") {
|
||||
Some("POSITION") => position = Some(Input { offset, source: self.source(i.attr("source"))? }),
|
||||
Some("NORMAL") if normal.is_none() => normal = Some(Input { offset, source: self.source(i.attr("source"))? }),
|
||||
Some("TEXCOORD") if uv.as_ref().is_none_or(|(s, _)| set < *s) => {
|
||||
uv = Some((set, Input { offset, source: self.source(i.attr("source"))? }))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(position.map(|position| PrimInputs { stride, position, normal, uv: uv.map(|(_, i)| i) }))
|
||||
}
|
||||
|
||||
fn build_part(
|
||||
&mut self,
|
||||
material: Option<usize>,
|
||||
inputs: &PrimInputs,
|
||||
lists: &[(Vec<u32>, Vec<usize>)],
|
||||
mesh: &mut Mesh,
|
||||
pools: &mut MeshPools,
|
||||
) -> Result<Part> {
|
||||
let mut part = Part { material, ..Part::default() };
|
||||
let mut all_triangles = true;
|
||||
for (p, sizes) in lists {
|
||||
let mut next = 0usize;
|
||||
for &size in sizes {
|
||||
if size > self.limits.max_face_corners {
|
||||
return Err(too_large(KIND, format!("face has more than {} corners", self.limits.max_face_corners)));
|
||||
}
|
||||
if size >= 3 {
|
||||
self.triangles = self.triangles.saturating_add(size - 2);
|
||||
if self.triangles > self.limits.max_triangles {
|
||||
return Err(too_large(KIND, format!("more than {} triangles", self.limits.max_triangles)));
|
||||
}
|
||||
if size != 3 {
|
||||
all_triangles = false;
|
||||
}
|
||||
for c in next..next.saturating_add(size) {
|
||||
let idx =
|
||||
|input: &Input| c.checked_mul(inputs.stride).and_then(|b| b.checked_add(input.offset)).and_then(|k| p.get(k)).copied();
|
||||
let pos = idx(&inputs.position)
|
||||
.and_then(|i| inputs.position.source.get::<3>(i))
|
||||
.ok_or_else(|| malformed(KIND, "polygon index out of range"))?;
|
||||
let pos_idx = intern_f64_3(&mut mesh.positions, &mut pools.pos_ids, pos, self.limits.max_vertices, "positions")?;
|
||||
let norm_idx = match inputs.normal.as_ref().and_then(|n| idx(n).and_then(|i| n.source.get::<3>(i))) {
|
||||
Some(n) => intern_f64_3(&mut mesh.normals, &mut pools.norm_ids, n, self.limits.max_vertices, "normals")?,
|
||||
None => crate::NONE,
|
||||
};
|
||||
let uv_idx = match inputs.uv.as_ref().and_then(|t| idx(t).and_then(|i| t.source.get::<2>(i))) {
|
||||
Some([u, v]) => intern_uv(&mut pools.uvs, &mut pools.uv_ids, [u as f32, 1.0 - v as f32], self.limits.max_vertices)?,
|
||||
None => crate::NONE,
|
||||
};
|
||||
part.corners.push(Corner { position: pos_idx, normal: norm_idx, uv: uv_idx });
|
||||
}
|
||||
part.face_sizes.push(size as u32);
|
||||
}
|
||||
next = next.saturating_add(size);
|
||||
}
|
||||
}
|
||||
if all_triangles {
|
||||
part.face_sizes.clear();
|
||||
}
|
||||
Ok(part)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MeshPools {
|
||||
pos_ids: HashMap<[u64; 3], u32>,
|
||||
norm_ids: HashMap<[u64; 3], u32>,
|
||||
uv_ids: HashMap<[u32; 2], u32>,
|
||||
uvs: Vec<[f32; 2]>,
|
||||
}
|
||||
|
||||
struct PrimInputs {
|
||||
stride: usize,
|
||||
position: Input,
|
||||
normal: Option<Input>,
|
||||
uv: Option<Input>,
|
||||
}
|
||||
|
||||
fn read_primitive_lists(prim: &El, stride: usize) -> Result<Vec<(Vec<u32>, Vec<usize>)>> {
|
||||
match prim.name.as_str() {
|
||||
"polygons" => prim
|
||||
.children("p")
|
||||
.map(|p| {
|
||||
let p = parse_indices(p)?;
|
||||
let n = p.len() / stride;
|
||||
Ok((p, vec![n]))
|
||||
})
|
||||
.collect(),
|
||||
_ => {
|
||||
let p = prim.child("p").map(parse_indices).transpose()?.unwrap_or_default();
|
||||
let sizes = match prim.child("vcount") {
|
||||
Some(v) if prim.name == "polylist" => parse_indices(v)?.into_iter().map(|c| c as usize).collect(),
|
||||
_ => vec![3; p.len() / stride / 3],
|
||||
};
|
||||
Ok(vec![(p, sizes)])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn intern_f64_3(pool: &mut Vec<[f64; 3]>, map: &mut HashMap<[u64; 3], u32>, val: [f64; 3], limit: usize, what: &str) -> Result<u32> {
|
||||
let key = val.map(f64::to_bits);
|
||||
if let Some(&id) = map.get(&key) {
|
||||
return Ok(id);
|
||||
}
|
||||
if pool.len() >= limit {
|
||||
return Err(too_large(KIND, format!("more than {limit} {what}")));
|
||||
}
|
||||
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, format!("too many {what}")))?;
|
||||
pool.push(val);
|
||||
map.insert(key, id);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn intern_uv(pool: &mut Vec<[f32; 2]>, map: &mut HashMap<[u32; 2], u32>, val: [f32; 2], limit: usize) -> Result<u32> {
|
||||
let key = val.map(f32::to_bits);
|
||||
if let Some(&id) = map.get(&key) {
|
||||
return Ok(id);
|
||||
}
|
||||
if pool.len() >= limit {
|
||||
return Err(too_large(KIND, format!("more than {limit} UVs")));
|
||||
}
|
||||
let id = u32::try_from(pool.len()).map_err(|_| too_large(KIND, "too many UVs"))?;
|
||||
pool.push(val);
|
||||
map.insert(key, id);
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
fn parse_floats(el: &El) -> Result<Vec<f64>> {
|
||||
el.text().split_whitespace().map(|w| w.parse::<f64>().map_err(|_| malformed(KIND, format!("bad number \"{w}\" in <{}>", el.name)))).collect()
|
||||
}
|
||||
|
||||
fn parse_indices(el: &El) -> Result<Vec<u32>> {
|
||||
el.text().split_whitespace().map(|w| w.parse::<u32>().map_err(|_| malformed(KIND, format!("bad index \"{w}\" in <{}>", el.name)))).collect()
|
||||
}
|
||||
|
||||
fn parse_camera(cam: &El, node_name: &str) -> Option<Camera> {
|
||||
let tc = cam.child("optics")?.child("technique_common")?;
|
||||
let num = |e: &El, k: &str| e.child(k).and_then(|v| v.text().trim().parse::<f64>().ok()).filter(|v| v.is_finite() && *v > 0.0);
|
||||
let name = if node_name.is_empty() { cam.attr("name").or_else(|| cam.attr("id")).unwrap_or_default().to_string() } else { node_name.to_string() };
|
||||
if let Some(p) = tc.child("perspective") {
|
||||
let x_to_y = |x: f64| Some(2.0 * ((x * 0.5).to_radians().tan() / num(p, "aspect_ratio")?).atan().to_degrees());
|
||||
let fov_deg = num(p, "yfov").or_else(|| num(p, "xfov").and_then(x_to_y)).or_else(|| num(p, "xfov")).unwrap_or(40.0);
|
||||
let aspect = num(p, "aspect_ratio");
|
||||
let znear = num(p, "znear").unwrap_or(0.1);
|
||||
let zfar = num(p, "zfar");
|
||||
return Some(Camera { name, projection: Projection::Perspective { yfov: fov_deg.to_radians(), aspect, znear, zfar } });
|
||||
}
|
||||
let o = tc.child("orthographic")?;
|
||||
let aspect = num(o, "aspect_ratio");
|
||||
let ymag = num(o, "ymag").or_else(|| Some(num(o, "xmag")? / aspect?)).or_else(|| num(o, "xmag")).unwrap_or(1.0);
|
||||
let xmag = num(o, "xmag").unwrap_or_else(|| ymag * aspect.unwrap_or(1.0));
|
||||
let znear = num(o, "znear").unwrap_or(0.1);
|
||||
let zfar = num(o, "zfar").unwrap_or(1000.0);
|
||||
Some(Camera { name, projection: Projection::Orthographic { xmag, ymag, znear, zfar } })
|
||||
}
|
||||
|
||||
/// Row-major 4×4 floats to a column-major matrix.
|
||||
fn row_major_matrix(v: &[f64]) -> Option<Mat4> {
|
||||
let a: [f64; 16] = v.get(..16)?.try_into().ok()?;
|
||||
Some([a[0], a[4], a[8], a[12], a[1], a[5], a[9], a[13], a[2], a[6], a[10], a[14], a[3], a[7], a[11], a[15]])
|
||||
}
|
||||
|
||||
fn node_transform(node: &El) -> Result<Mat4> {
|
||||
let mut m = IDENTITY;
|
||||
for t in node.elements() {
|
||||
let v = match t.name.as_str() {
|
||||
"matrix" | "translate" | "rotate" | "scale" | "lookat" => parse_floats(t)?,
|
||||
_ => continue,
|
||||
};
|
||||
let step = match (t.name.as_str(), v.as_slice()) {
|
||||
("matrix", _) => row_major_matrix(&v),
|
||||
("translate", [x, y, z, ..]) => Some([1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, *x, *y, *z, 1.0]),
|
||||
("scale", [x, y, z, ..]) => Some([*x, 0.0, 0.0, 0.0, 0.0, *y, 0.0, 0.0, 0.0, 0.0, *z, 0.0, 0.0, 0.0, 0.0, 1.0]),
|
||||
("rotate", [x, y, z, deg, ..]) => axis_angle_matrix([*x, *y, *z], deg.to_radians()),
|
||||
("lookat", [ex, ey, ez, ix, iy, iz, ux, uy, uz, ..]) => lookat_matrix([*ex, *ey, *ez], [*ix, *iy, *iz], [*ux, *uy, *uz]),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(s) = step {
|
||||
m = mat_mul(&m, &s);
|
||||
}
|
||||
}
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
fn normalize(v: [f64; 3]) -> Option<[f64; 3]> {
|
||||
let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
|
||||
(len.is_finite() && len > 0.0).then(|| v.map(|x| x / len))
|
||||
}
|
||||
|
||||
fn cross(a: [f64; 3], b: [f64; 3]) -> [f64; 3] {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
fn axis_angle_matrix(axis: [f64; 3], angle: f64) -> Option<Mat4> {
|
||||
let [x, y, z] = normalize(axis)?;
|
||||
let (s, c) = angle.sin_cos();
|
||||
let t = 1.0 - c;
|
||||
let m = [
|
||||
t * x * x + c,
|
||||
t * x * y + s * z,
|
||||
t * x * z - s * y,
|
||||
0.0,
|
||||
t * x * y - s * z,
|
||||
t * y * y + c,
|
||||
t * y * z + s * x,
|
||||
0.0,
|
||||
t * x * z + s * y,
|
||||
t * y * z - s * x,
|
||||
t * z * z + c,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
0.0,
|
||||
1.0,
|
||||
];
|
||||
m.iter().all(|v| v.is_finite()).then_some(m)
|
||||
}
|
||||
|
||||
fn lookat_matrix(eye: [f64; 3], center: [f64; 3], up: [f64; 3]) -> Option<Mat4> {
|
||||
let f = normalize([center[0] - eye[0], center[1] - eye[1], center[2] - eye[2]])?;
|
||||
let s = normalize(cross(f, up))?;
|
||||
let u = cross(s, f);
|
||||
let m = [s[0], s[1], s[2], 0.0, u[0], u[1], u[2], 0.0, -f[0], -f[1], -f[2], 0.0, eye[0], eye[1], eye[2], 1.0];
|
||||
m.iter().all(|v| v.is_finite()).then_some(m)
|
||||
}
|
||||
+62
-6
@@ -619,6 +619,8 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> {
|
||||
let pbr = m.get("pbrMetallicRoughness").unwrap_or(&null);
|
||||
let ext = m.get("extensions");
|
||||
let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0));
|
||||
let clearcoat = ext.and_then(|e| e.get("KHR_materials_clearcoat"));
|
||||
let sheen = ext.and_then(|e| e.get("KHR_materials_sheen"));
|
||||
scene.materials.push(Material {
|
||||
name: name(m),
|
||||
base_color: nums(pbr, "baseColorFactor", [1.0; 4]).map(|v| v as f32),
|
||||
@@ -639,6 +641,14 @@ fn materials(j: &Value, limits: &Limits, scene: &mut Scene) -> Result<()> {
|
||||
occlusion_texture: tref(m.get("occlusionTexture")),
|
||||
occlusion_strength: m.get("occlusionTexture").map_or(1.0, |n| num(n, "strength", 1.0)) as f32,
|
||||
emissive_texture: tref(m.get("emissiveTexture")),
|
||||
clearcoat: clearcoat.map_or(0.0, |c| num(c, "clearcoatFactor", 0.0)) as f32,
|
||||
clearcoat_roughness: clearcoat.map_or(0.0, |c| num(c, "clearcoatRoughnessFactor", 0.0)) as f32,
|
||||
clearcoat_texture: clearcoat.and_then(|c| tref(c.get("clearcoatTexture"))),
|
||||
clearcoat_roughness_texture: clearcoat.and_then(|c| tref(c.get("clearcoatRoughnessTexture"))),
|
||||
sheen_color: sheen.map_or([0.0; 3], |s| nums(s, "sheenColorFactor", [0.0; 3]).map(|v| v as f32)),
|
||||
sheen_roughness: sheen.map_or(0.0, |s| num(s, "sheenRoughnessFactor", 0.0)) as f32,
|
||||
sheen_color_texture: sheen.and_then(|s| tref(s.get("sheenColorTexture"))),
|
||||
sheen_roughness_texture: sheen.and_then(|s| tref(s.get("sheenRoughnessTexture"))),
|
||||
});
|
||||
// The older specular-glossiness model, as the nearest metallic-roughness material: its
|
||||
// diffuse colour and texture, no metal, and roughness from the glossiness.
|
||||
@@ -816,12 +826,14 @@ fn uv_transform(t: &Value) -> UvTransform {
|
||||
/// the reader handles: the geometry reads without the others being understood.
|
||||
fn check_extensions(j: &Value, scene: &mut Scene) -> Result<()> {
|
||||
const LOOKS: [&str; 3] = ["KHR_texture_basisu", "MSFT_texture_dds", "KHR_lights_punctual"];
|
||||
const READ: [&str; 6] = [
|
||||
const READ: [&str; 8] = [
|
||||
TEXTURE_TRANSFORM,
|
||||
"KHR_mesh_quantization",
|
||||
"KHR_materials_unlit",
|
||||
"KHR_materials_emissive_strength",
|
||||
"KHR_materials_pbrSpecularGlossiness",
|
||||
"KHR_materials_clearcoat",
|
||||
"KHR_materials_sheen",
|
||||
"EXT_texture_webp",
|
||||
];
|
||||
for e in arr(j, "extensionsRequired").iter().filter_map(Value::as_str) {
|
||||
@@ -1021,12 +1033,46 @@ fn material_json(m: &Material, textures: &mut Textures, extensions: &mut Vec<&'s
|
||||
if m.unlit {
|
||||
ext.insert("KHR_materials_unlit".into(), json!({}));
|
||||
}
|
||||
for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit"] {
|
||||
if m.clearcoat > 0.0 || m.clearcoat_texture.is_some() || m.clearcoat_roughness_texture.is_some() {
|
||||
let mut coat = Map::new();
|
||||
coat.insert("clearcoatFactor".into(), json!(m.clearcoat));
|
||||
if let Some(t) = textures.slot(m.clearcoat_texture) {
|
||||
coat.insert("clearcoatTexture".into(), t);
|
||||
}
|
||||
coat.insert("clearcoatRoughnessFactor".into(), json!(m.clearcoat_roughness));
|
||||
if let Some(t) = textures.slot(m.clearcoat_roughness_texture) {
|
||||
coat.insert("clearcoatRoughnessTexture".into(), t);
|
||||
}
|
||||
ext.insert("KHR_materials_clearcoat".into(), Value::Object(coat));
|
||||
}
|
||||
if m.sheen_color != [0.0; 3] || m.sheen_color_texture.is_some() || m.sheen_roughness_texture.is_some() {
|
||||
let mut sheen = Map::new();
|
||||
sheen.insert("sheenColorFactor".into(), json!(m.sheen_color));
|
||||
if let Some(t) = textures.slot(m.sheen_color_texture) {
|
||||
sheen.insert("sheenColorTexture".into(), t);
|
||||
}
|
||||
sheen.insert("sheenRoughnessFactor".into(), json!(m.sheen_roughness));
|
||||
if let Some(t) = textures.slot(m.sheen_roughness_texture) {
|
||||
sheen.insert("sheenRoughnessTexture".into(), t);
|
||||
}
|
||||
ext.insert("KHR_materials_sheen".into(), Value::Object(sheen));
|
||||
}
|
||||
for name in ["KHR_materials_emissive_strength", "KHR_materials_unlit", "KHR_materials_clearcoat", "KHR_materials_sheen"] {
|
||||
if ext.contains_key(name) && !extensions.contains(&name) {
|
||||
extensions.push(name);
|
||||
}
|
||||
}
|
||||
let slots = [m.base_color_texture, m.metallic_roughness_texture, m.normal_texture, m.occlusion_texture, m.emissive_texture];
|
||||
let slots = [
|
||||
m.base_color_texture,
|
||||
m.metallic_roughness_texture,
|
||||
m.normal_texture,
|
||||
m.occlusion_texture,
|
||||
m.emissive_texture,
|
||||
m.clearcoat_texture,
|
||||
m.clearcoat_roughness_texture,
|
||||
m.sheen_color_texture,
|
||||
m.sheen_roughness_texture,
|
||||
];
|
||||
if slots.iter().flatten().any(|t| t.transform.is_some()) && !extensions.contains(&TEXTURE_TRANSFORM) {
|
||||
extensions.push(TEXTURE_TRANSFORM);
|
||||
}
|
||||
@@ -1067,15 +1113,25 @@ fn check_finite(scene: &Scene) -> Result<()> {
|
||||
let positions = scene.meshes.iter().flat_map(|m| m.positions.iter().flatten()).all(|x| (*x as f32).is_finite());
|
||||
let nodes = scene.nodes.iter().flat_map(|n| n.transform.iter()).all(|x| x.is_finite());
|
||||
let materials = scene.materials.iter().all(|m| {
|
||||
let values = [m.metallic, m.roughness, m.normal_scale, m.occlusion_strength];
|
||||
let values = [m.metallic, m.roughness, m.normal_scale, m.occlusion_strength, m.clearcoat, m.clearcoat_roughness, m.sheen_roughness];
|
||||
let cutoff = if let AlphaMode::Mask(c) = m.alpha_mode { c } else { 0.0 };
|
||||
let slots = [&m.base_color_texture, &m.metallic_roughness_texture, &m.normal_texture, &m.occlusion_texture, &m.emissive_texture];
|
||||
let slots = [
|
||||
&m.base_color_texture,
|
||||
&m.metallic_roughness_texture,
|
||||
&m.normal_texture,
|
||||
&m.occlusion_texture,
|
||||
&m.emissive_texture,
|
||||
&m.clearcoat_texture,
|
||||
&m.clearcoat_roughness_texture,
|
||||
&m.sheen_color_texture,
|
||||
&m.sheen_roughness_texture,
|
||||
];
|
||||
let transforms = slots
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|t| t.transform)
|
||||
.all(|t| t.offset.iter().chain(&t.scale).chain([&t.rotation]).all(|x| x.is_finite()));
|
||||
m.base_color.iter().chain(&m.emissive).chain(&values).all(|x| x.is_finite()) && cutoff.is_finite() && transforms
|
||||
m.base_color.iter().chain(&m.emissive).chain(&m.sheen_color).chain(&values).all(|x| x.is_finite()) && cutoff.is_finite() && transforms
|
||||
});
|
||||
if positions && nodes && materials { Ok(()) } else { Err(malformed(KIND, "a position, transform or material value is not finite")) }
|
||||
}
|
||||
|
||||
+43
-2
@@ -31,10 +31,23 @@
|
||||
#![forbid(unsafe_code)]
|
||||
// The helpers the formats share are not all used by every subset of them.
|
||||
#![cfg_attr(
|
||||
not(all(feature = "stl", feature = "obj", feature = "ply", feature = "gltf", feature = "fbx", feature = "threemf")),
|
||||
not(all(
|
||||
feature = "stl",
|
||||
feature = "obj",
|
||||
feature = "ply",
|
||||
feature = "gltf",
|
||||
feature = "fbx",
|
||||
feature = "threemf",
|
||||
feature = "dae",
|
||||
feature = "abc"
|
||||
)),
|
||||
allow(dead_code, unused_imports)
|
||||
)]
|
||||
|
||||
#[cfg(feature = "abc")]
|
||||
pub mod abc;
|
||||
#[cfg(feature = "dae")]
|
||||
pub mod dae;
|
||||
#[cfg(feature = "fbx")]
|
||||
pub mod fbx;
|
||||
#[cfg(feature = "gltf")]
|
||||
@@ -448,6 +461,16 @@ pub struct Material {
|
||||
pub occlusion_texture: Option<TextureRef>,
|
||||
pub occlusion_strength: f32,
|
||||
pub emissive_texture: Option<TextureRef>,
|
||||
/// Clearcoat layer strength in `0..=1` (glTF `KHR_materials_clearcoat`).
|
||||
pub clearcoat: f32,
|
||||
pub clearcoat_roughness: f32,
|
||||
pub clearcoat_texture: Option<TextureRef>,
|
||||
pub clearcoat_roughness_texture: Option<TextureRef>,
|
||||
/// Sheen colour factor (linear RGB) and roughness (glTF `KHR_materials_sheen`).
|
||||
pub sheen_color: [f32; 3],
|
||||
pub sheen_roughness: f32,
|
||||
pub sheen_color_texture: Option<TextureRef>,
|
||||
pub sheen_roughness_texture: Option<TextureRef>,
|
||||
}
|
||||
|
||||
impl Default for Material {
|
||||
@@ -468,6 +491,14 @@ impl Default for Material {
|
||||
occlusion_texture: None,
|
||||
occlusion_strength: 1.0,
|
||||
emissive_texture: None,
|
||||
clearcoat: 0.0,
|
||||
clearcoat_roughness: 0.0,
|
||||
clearcoat_texture: None,
|
||||
clearcoat_roughness_texture: None,
|
||||
sheen_color: [0.0; 3],
|
||||
sheen_roughness: 0.0,
|
||||
sheen_color_texture: None,
|
||||
sheen_roughness_texture: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -742,7 +773,17 @@ impl Scene {
|
||||
}
|
||||
}
|
||||
for m in &self.materials {
|
||||
let slots = [m.base_color_texture, m.metallic_roughness_texture, m.normal_texture, m.occlusion_texture, m.emissive_texture];
|
||||
let slots = [
|
||||
m.base_color_texture,
|
||||
m.metallic_roughness_texture,
|
||||
m.normal_texture,
|
||||
m.occlusion_texture,
|
||||
m.emissive_texture,
|
||||
m.clearcoat_texture,
|
||||
m.clearcoat_roughness_texture,
|
||||
m.sheen_color_texture,
|
||||
m.sheen_roughness_texture,
|
||||
];
|
||||
if slots.iter().flatten().any(|t| t.image >= self.images.len()) {
|
||||
return bad(format!("material `{}` names an image that does not exist", m.name));
|
||||
}
|
||||
|
||||
+15
-3
@@ -646,9 +646,15 @@ pub fn write(scene: &Scene, mtllib: Option<&str>, limits: &Limits) -> Result<Str
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// The scene as OBJ text and its MTL material library (`(obj, mtl)`), with `mtllib` naming
|
||||
/// the material library file to write next to the OBJ.
|
||||
pub fn write_with_mtl(scene: &Scene, mtllib: &str, limits: &Limits) -> Result<(String, String)> {
|
||||
Ok((write(scene, Some(mtllib), limits)?, write_mtl(scene)))
|
||||
}
|
||||
|
||||
/// The scene's materials as an MTL library, named as [`fn@write`] names them: `Kd`, `d`, `Ke`,
|
||||
/// `Ns` (for readers without the PBR extension) with `Pr` and `Pm`, and `map_Kd`, `map_Ke`
|
||||
/// and `norm` for images that have a [`Image::uri`].
|
||||
/// `Ns` (for readers without the PBR extension) with `Pr` and `Pm`, and `map_Kd`, `map_Ke`,
|
||||
/// `norm`, `map_Pc`, and `map_Pcr` for images that have an [`Image::uri`].
|
||||
pub fn write_mtl(scene: &Scene) -> String {
|
||||
let mut mtl = String::new();
|
||||
for (m, name) in scene.materials.iter().zip(material_names(scene)) {
|
||||
@@ -661,7 +667,13 @@ pub fn write_mtl(scene: &Scene) -> String {
|
||||
"newmtl {name}\nKd {} {} {}\nd {}\nKe {} {} {}\nNs {ns}\nPr {r}\nPm {}",
|
||||
kd[0], kd[1], kd[2], m.base_color[3], ke[0], ke[1], ke[2], m.metallic
|
||||
);
|
||||
for (key, tex) in [("map_Kd", m.base_color_texture), ("map_Ke", m.emissive_texture), ("norm", m.normal_texture)] {
|
||||
for (key, tex) in [
|
||||
("map_Kd", m.base_color_texture),
|
||||
("map_Ke", m.emissive_texture),
|
||||
("norm", m.normal_texture),
|
||||
("map_Pc", m.clearcoat_texture),
|
||||
("map_Pcr", m.clearcoat_roughness_texture),
|
||||
] {
|
||||
if let Some(uri) = tex.and_then(|t| scene.images.get(t.image)).and_then(|i| i.uri.as_deref()) {
|
||||
let _ = writeln!(mtl, "{key} {}", uri.replace(['\n', '\r'], " "));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg(feature = "abc")]
|
||||
mod abc;
|
||||
#[cfg(feature = "dae")]
|
||||
mod dae;
|
||||
#[cfg(feature = "fbx")]
|
||||
mod fbx;
|
||||
#[cfg(feature = "gltf")]
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
use super::*;
|
||||
use crate::abc::read;
|
||||
|
||||
const DATA_BIT: u64 = 1 << 63;
|
||||
const OGAWA_MAGIC: &[u8] = b"Ogawa";
|
||||
const KEY_BYTES: usize = 16;
|
||||
const OBJECT_HASH_BYTES: usize = 32;
|
||||
const F32: u32 = 10;
|
||||
const I32: u32 = 6;
|
||||
const U32: u32 = 5;
|
||||
const U8: u32 = 1;
|
||||
const F64: u32 = 11;
|
||||
|
||||
struct Writer {
|
||||
b: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
fn new() -> Writer {
|
||||
Writer { b: vec![0; 16] }
|
||||
}
|
||||
|
||||
fn data(&mut self, bytes: &[u8]) -> u64 {
|
||||
let at = self.b.len() as u64;
|
||||
self.b.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
|
||||
self.b.extend_from_slice(bytes);
|
||||
at | DATA_BIT
|
||||
}
|
||||
|
||||
fn group(&mut self, children: &[u64]) -> u64 {
|
||||
let at = self.b.len() as u64;
|
||||
self.b.extend_from_slice(&(children.len() as u64).to_le_bytes());
|
||||
for c in children {
|
||||
self.b.extend_from_slice(&c.to_le_bytes());
|
||||
}
|
||||
at
|
||||
}
|
||||
|
||||
fn finish(mut self, root: u64) -> Vec<u8> {
|
||||
self.b[..5].copy_from_slice(OGAWA_MAGIC);
|
||||
self.b[5] = 0xff;
|
||||
self.b[6..8].copy_from_slice(&[0, 1]);
|
||||
self.b[8..16].copy_from_slice(&root.to_le_bytes());
|
||||
self.b
|
||||
}
|
||||
}
|
||||
|
||||
struct P {
|
||||
name: &'static str,
|
||||
meta: String,
|
||||
info: u32,
|
||||
group: u64,
|
||||
}
|
||||
|
||||
struct Abc {
|
||||
w: Writer,
|
||||
}
|
||||
|
||||
impl Abc {
|
||||
fn sample(&mut self, raw: &[u8]) -> u64 {
|
||||
let mut v = vec![7u8; KEY_BYTES];
|
||||
v.extend_from_slice(raw);
|
||||
self.w.data(&v)
|
||||
}
|
||||
|
||||
fn array(&mut self, name: &'static str, meta: &str, pod: u32, extent: u32, raw: &[u8]) -> P {
|
||||
let (d, dims) = (self.sample(raw), self.w.data(&[]));
|
||||
let group = self.w.group(&[d, dims]);
|
||||
P { name, meta: meta.into(), info: 2 | (2 << 2) | (pod << 4) | (extent << 12), group }
|
||||
}
|
||||
|
||||
fn scalar(&mut self, name: &'static str, pod: u32, extent: u32, raw: &[u8]) -> P {
|
||||
let d = self.sample(raw);
|
||||
let group = self.w.group(&[d]);
|
||||
P { name, meta: String::new(), info: 1 | (2 << 2) | (pod << 4) | (extent << 12), group }
|
||||
}
|
||||
|
||||
fn compound(&mut self, name: &'static str, meta: &str, props: Vec<P>) -> P {
|
||||
let mut header = Vec::new();
|
||||
for p in &props {
|
||||
let info = p.info | (0xff << 20);
|
||||
header.extend_from_slice(&info.to_le_bytes());
|
||||
if info & 3 != 0 {
|
||||
header.extend_from_slice(&1u32.to_le_bytes());
|
||||
}
|
||||
header.extend_from_slice(&(p.name.len() as u32).to_le_bytes());
|
||||
header.extend_from_slice(p.name.as_bytes());
|
||||
header.extend_from_slice(&(p.meta.len() as u32).to_le_bytes());
|
||||
header.extend_from_slice(p.meta.as_bytes());
|
||||
}
|
||||
let mut children: Vec<u64> = props.iter().map(|p| p.group).collect();
|
||||
children.push(self.w.data(&header));
|
||||
let group = self.w.group(&children);
|
||||
P { name, meta: meta.into(), info: 2 << 2, group }
|
||||
}
|
||||
|
||||
fn object(&mut self, props: Vec<P>, children: &[(&str, &str, u64)]) -> u64 {
|
||||
let props = self.compound("", "", props).group;
|
||||
let mut header = Vec::new();
|
||||
for (name, meta, _) in children {
|
||||
header.extend_from_slice(&(name.len() as u32).to_le_bytes());
|
||||
header.extend_from_slice(name.as_bytes());
|
||||
if meta.is_empty() {
|
||||
header.push(1);
|
||||
} else {
|
||||
header.push(0xff);
|
||||
header.extend_from_slice(&(meta.len() as u32).to_le_bytes());
|
||||
header.extend_from_slice(meta.as_bytes());
|
||||
}
|
||||
}
|
||||
header.extend_from_slice(&[0; OBJECT_HASH_BYTES]);
|
||||
let mut kids = vec![props];
|
||||
kids.extend(children.iter().map(|c| c.2));
|
||||
kids.push(self.w.data(&header));
|
||||
self.w.group(&kids)
|
||||
}
|
||||
|
||||
fn archive(mut self, top: u64, indexed_meta: &[&str]) -> Vec<u8> {
|
||||
let mut im = Vec::new();
|
||||
for m in indexed_meta {
|
||||
im.push(m.len() as u8);
|
||||
im.extend_from_slice(m.as_bytes());
|
||||
}
|
||||
let kids = [
|
||||
self.w.data(&0i32.to_le_bytes()),
|
||||
self.w.data(&10709i32.to_le_bytes()),
|
||||
top,
|
||||
self.w.data(b"_ai_Application=test"),
|
||||
self.w.data(&[]),
|
||||
self.w.data(&im),
|
||||
];
|
||||
let root = self.w.group(&kids);
|
||||
self.w.finish(root)
|
||||
}
|
||||
}
|
||||
|
||||
fn f32s(v: &[f32]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
fn i32s(v: &[i32]) -> Vec<u8> {
|
||||
v.iter().flat_map(|x| x.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
fn sample_file() -> Vec<u8> {
|
||||
let mut a = Abc { w: Writer::new() };
|
||||
let p = f32s(&[0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 2.0, 1.0, 0.0]);
|
||||
let indices = i32s(&[0, 3, 4, 1, 1, 4, 5, 2]);
|
||||
let counts = i32s(&[4, 4]);
|
||||
let pp = a.array("P", "interpretation=point", F32, 3, &p);
|
||||
let fi = a.array(".faceIndices", "", I32, 1, &indices);
|
||||
let fc = a.array(".faceCounts", "", I32, 1, &counts);
|
||||
let vals = a.array(".vals", "", F32, 2, &f32s(&[0.0, 0.0, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 0.5, 1.0, 1.0, 1.0]));
|
||||
let uvi = a.array(".indices", "", U32, 1, &i32s(&[0, 3, 4, 1, 1, 4, 5, 2]));
|
||||
let uv = a.compound("uv", "geoScope=fvr;podName=float32_t;podExtent=2", vec![vals, uvi]);
|
||||
let n = a.array("N", "geoScope=vtx", F32, 3, &f32s(&[0.0, 0.0, 1.0].repeat(6)));
|
||||
let geom = a.compound(".geom", "schema=AbcGeom_PolyMesh_v1", vec![pp, fi, fc, uv, n]);
|
||||
let left_faces = a.array(".faces", "", I32, 1, &i32s(&[0]));
|
||||
let left_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![left_faces]);
|
||||
let left = a.object(vec![left_fs], &[]);
|
||||
let right_faces = a.array(".faces", "", I32, 1, &i32s(&[1]));
|
||||
let right_fs = a.compound(".faceset", "schema=AbcGeom_FaceSet_v1", vec![right_faces]);
|
||||
let right = a.object(vec![right_fs], &[]);
|
||||
let fs_meta = "schema=AbcGeom_FaceSet_v1;schemaObjTitle=AbcGeom_FaceSet_v1:.faceset";
|
||||
let mesh = a.object(vec![geom], &[("left", fs_meta, left), ("right", fs_meta, right)]);
|
||||
let ops = a.scalar(".ops", U8, 2, &[0x10, 0x00]);
|
||||
let xv: Vec<u8> = [1.0f64, 2.0, 3.0, 2.0, 2.0, 2.0].iter().flat_map(|x| x.to_le_bytes()).collect();
|
||||
let vals = a.scalar(".vals", F64, 6, &xv);
|
||||
let xform = a.compound(".xform", "schema=AbcGeom_Xform_v3", vec![ops, vals]);
|
||||
let xf = a.object(vec![xform], &[("stripShape", "schema=AbcGeom_PolyMesh_v1;schemaObjTitle=AbcGeom_PolyMesh_v1:.geom", mesh)]);
|
||||
let top = a.object(vec![], &[("strip", "schema=AbcGeom_Xform_v3", xf)]);
|
||||
a.archive(top, &["schema=AbcGeom_PolyMesh_v1"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_polymesh_xform_face_sets_and_uvs() {
|
||||
let scene = read(&sample_file(), &Limits::default()).unwrap();
|
||||
scene.validate().unwrap();
|
||||
assert_eq!(scene.materials.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["left", "right"]);
|
||||
assert_eq!(scene.meshes.len(), 1);
|
||||
assert_eq!(scene.meshes[0].name, "strip");
|
||||
assert_eq!(scene.meshes[0].triangle_count(), 4);
|
||||
let inst = scene.instances(&Limits::default()).unwrap();
|
||||
assert_eq!(inst.len(), 1);
|
||||
let p0 = transform_point(&inst[0].1, scene.meshes[0].positions[0]);
|
||||
assert_eq!(p0, [1.0, 2.0, 3.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hdf5_returns_unsupported() {
|
||||
let err = read(b"\x89HDF\r\n\x1a\n rest", &Limits::default()).unwrap_err();
|
||||
assert!(matches!(err, Error::Unsupported(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hammer_never_panics() {
|
||||
hammer(&sample_file(), &|b| read(b, &Limits::default()));
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
use super::*;
|
||||
use crate::dae::{UpAxis, read, read_document};
|
||||
|
||||
const DAE: &str = r##"<?xml version="1.0" encoding="utf-8"?>
|
||||
<COLLADA xmlns="http://www.collada.org/2005/11/COLLADASchema" version="1.4.1">
|
||||
<asset><unit name="centimeter" meter="0.5"/><up_axis>Z_UP</up_axis></asset>
|
||||
<library_materials>
|
||||
<material id="red-mat" name="Red"/>
|
||||
<material id="blue-mat" name="Blue"/>
|
||||
</library_materials>
|
||||
<library_geometries>
|
||||
<geometry id="quad" name="Quad">
|
||||
<mesh>
|
||||
<source id="quad-pos">
|
||||
<float_array id="quad-pos-array" count="12">0 0 0 2 0 0 2 2 0 0 2 0</float_array>
|
||||
<technique_common><accessor source="#quad-pos-array" count="4" stride="3"/></technique_common>
|
||||
</source>
|
||||
<source id="quad-nrm">
|
||||
<float_array id="quad-nrm-array" count="3">0 0 1</float_array>
|
||||
<technique_common><accessor source="#quad-nrm-array" count="1" stride="3"/></technique_common>
|
||||
</source>
|
||||
<source id="quad-uv">
|
||||
<float_array id="quad-uv-array" count="8">0 0 1 0 1 1 0 1</float_array>
|
||||
<technique_common><accessor source="#quad-uv-array" count="4" stride="2"/></technique_common>
|
||||
</source>
|
||||
<vertices id="quad-verts"><input semantic="POSITION" source="#quad-pos"/></vertices>
|
||||
<polylist material="mat0" count="1">
|
||||
<input semantic="VERTEX" source="#quad-verts" offset="0"/>
|
||||
<input semantic="NORMAL" source="#quad-nrm" offset="1"/>
|
||||
<input semantic="TEXCOORD" source="#quad-uv" offset="2" set="0"/>
|
||||
<vcount>4</vcount>
|
||||
<p>0 0 0 1 0 1 2 0 2 3 0 3</p>
|
||||
</polylist>
|
||||
</mesh>
|
||||
</geometry>
|
||||
<geometry id="tris" name="Tris">
|
||||
<mesh>
|
||||
<source id="tris-pos">
|
||||
<float_array id="tris-pos-array" count="21">4 0 0 6 0 0 4 2 0 8 0 0 10 0 0 10 2 0 8 2 0</float_array>
|
||||
<technique_common><accessor source="#tris-pos-array" count="7" stride="3"/></technique_common>
|
||||
</source>
|
||||
<source id="tris-uv">
|
||||
<float_array id="tris-uv-array" count="14">0 0 1 0 0 1 0 0 1 0 1 1 0 1</float_array>
|
||||
<technique_common><accessor source="#tris-uv-array" count="7" stride="2"/></technique_common>
|
||||
</source>
|
||||
<vertices id="tris-verts">
|
||||
<input semantic="POSITION" source="#tris-pos"/>
|
||||
<input semantic="TEXCOORD" source="#tris-uv"/>
|
||||
</vertices>
|
||||
<triangles material="mat1" count="1"><input semantic="VERTEX" source="#tris-verts" offset="0"/><p>0 1 2</p></triangles>
|
||||
<polygons material="mat1" count="1"><input semantic="VERTEX" source="#tris-verts" offset="0"/><p>3 4 5 6</p></polygons>
|
||||
<lines count="1"><input semantic="VERTEX" source="#tris-verts" offset="0"/><p>0 1</p></lines>
|
||||
</mesh>
|
||||
</geometry>
|
||||
</library_geometries>
|
||||
<library_cameras>
|
||||
<camera id="lens"><optics><technique_common><perspective><yfov>30</yfov></perspective></technique_common></optics></camera>
|
||||
</library_cameras>
|
||||
<library_visual_scenes>
|
||||
<visual_scene id="scene">
|
||||
<node id="parent">
|
||||
<translate>0 0 2</translate>
|
||||
<rotate>0 0 1 90</rotate>
|
||||
<node id="child">
|
||||
<scale>2 2 2</scale>
|
||||
<instance_geometry url="#quad">
|
||||
<bind_material><technique_common><instance_material symbol="mat0" target="#red-mat"/></technique_common></bind_material>
|
||||
</instance_geometry>
|
||||
</node>
|
||||
</node>
|
||||
<node id="cam" name="Overview">
|
||||
<lookat>0 -10 0 0 0 0 0 0 1</lookat>
|
||||
<instance_camera url="#lens"/>
|
||||
</node>
|
||||
<node id="other">
|
||||
<instance_geometry url="#tris">
|
||||
<bind_material><technique_common><instance_material symbol="mat1" target="#blue-mat"/></technique_common></bind_material>
|
||||
</instance_geometry>
|
||||
</node>
|
||||
</visual_scene>
|
||||
</library_visual_scenes>
|
||||
<scene><instance_visual_scene url="#scene"/></scene>
|
||||
</COLLADA>
|
||||
"##;
|
||||
|
||||
#[test]
|
||||
fn reads_polylist_transforms_units_and_cameras() {
|
||||
let doc = read_document(DAE.as_bytes(), &Limits::default()).unwrap();
|
||||
doc.scene.validate().unwrap();
|
||||
assert_eq!(doc.meter, 0.5);
|
||||
assert_eq!(doc.up_axis, UpAxis::ZUp);
|
||||
assert_eq!(doc.scene.materials.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(), ["Red", "Blue"]);
|
||||
assert!(doc.scene.warnings.iter().any(|w| w.contains("lines")));
|
||||
assert_eq!(doc.scene.cameras.len(), 1);
|
||||
assert_eq!(doc.scene.cameras[0].name, "Overview");
|
||||
|
||||
let global = doc.global_transform();
|
||||
let inst = doc.scene.instances(&Limits::default()).unwrap();
|
||||
assert_eq!(inst.len(), 2);
|
||||
let mut tris = 0usize;
|
||||
for (m_idx, xform) in inst {
|
||||
let m = &doc.scene.meshes[m_idx];
|
||||
tris += m.triangle_count();
|
||||
let w = mat_mul(&global, &xform);
|
||||
for p in &m.positions {
|
||||
let wp = transform_point(&w, *p);
|
||||
assert!(wp.iter().all(|v| v.is_finite()));
|
||||
}
|
||||
}
|
||||
assert_eq!(tris, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entities_and_limits_are_enforced() {
|
||||
let dae = DAE
|
||||
.replace(r#"<node id="other">"#, r#"<node id="other" name="Tom & Jerry <"'AB">"#)
|
||||
.replace(r#"name="Red""#, r#"name="R&D""#);
|
||||
let scene = read(dae.as_bytes(), &Limits::default()).unwrap();
|
||||
scene.validate().unwrap();
|
||||
assert!(scene.nodes.iter().any(|n| n.name == "Tom & Jerry <\"'AB"));
|
||||
assert_eq!(scene.materials[0].name, "R&D");
|
||||
|
||||
let tight = Limits { max_triangles: 2, ..Limits::default() };
|
||||
assert!(matches!(read(DAE.as_bytes(), &tight), Err(Error::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hammer_never_panics() {
|
||||
hammer(DAE.as_bytes(), &|b| read(b, &Limits::default()));
|
||||
}
|
||||
@@ -482,7 +482,7 @@ fn what_is_not_read_is_refused_or_named() {
|
||||
assert!(matches!(parse(&doc(json!({ "extensionsRequired": ["VENDOR_something_new"] }))), Err(Error::Unsupported(_))));
|
||||
// Extensions that only change looks are named in a warning; the ones the reader handles are not.
|
||||
let s = parse(&doc(
|
||||
json!({ "extensionsRequired": ["KHR_texture_transform", "KHR_materials_clearcoat", "KHR_mesh_quantization", "KHR_materials_unlit"] }),
|
||||
json!({ "extensionsRequired": ["KHR_texture_transform", "KHR_materials_transmission", "KHR_mesh_quantization", "KHR_materials_unlit"] }),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(s.warnings.len(), 1, "texture transforms are read: {:?}", s.warnings);
|
||||
@@ -953,3 +953,38 @@ fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() {
|
||||
assert_eq!(decoded, "A%GG+é".repeat(100_000));
|
||||
assert!(decoded.len() <= input.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clearcoat_and_sheen_round_trip_through_write_glb() {
|
||||
let mut mesh = Mesh { name: "card".into(), ..Mesh::default() };
|
||||
mesh.positions = vec![[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]];
|
||||
mesh.parts = vec![Part { material: Some(0), corners: [0, 1, 2].map(Corner::at).to_vec(), ..Part::default() }];
|
||||
let mat = Material {
|
||||
name: "CoatedVelvet".into(),
|
||||
clearcoat: 0.8,
|
||||
clearcoat_roughness: 0.25,
|
||||
clearcoat_texture: Some(TextureRef { image: 0, ..TextureRef::default() }),
|
||||
clearcoat_roughness_texture: Some(TextureRef { image: 0, ..TextureRef::default() }),
|
||||
sheen_color: [0.9, 0.2, 0.1],
|
||||
sheen_roughness: 0.5,
|
||||
sheen_color_texture: Some(TextureRef { image: 1, ..TextureRef::default() }),
|
||||
sheen_roughness_texture: Some(TextureRef { image: 1, ..TextureRef::default() }),
|
||||
..Material::default()
|
||||
};
|
||||
let mut scene = Scene::from_meshes(vec![mesh], vec![mat.clone()]);
|
||||
scene.images = vec![
|
||||
Image { name: "coat".into(), data: Some(b"\x89PNG coat".to_vec()), ..Image::default() },
|
||||
Image { name: "sheen".into(), data: Some(b"\x89PNG sheen".to_vec()), ..Image::default() },
|
||||
];
|
||||
let glb = write_glb(&scene, &Limits::default()).unwrap();
|
||||
let back = parse(&glb).unwrap();
|
||||
assert!(back.warnings.is_empty(), "{:?}", back.warnings);
|
||||
assert_eq!(back.materials[0].clearcoat, mat.clearcoat);
|
||||
assert_eq!(back.materials[0].clearcoat_roughness, mat.clearcoat_roughness);
|
||||
assert_eq!(back.materials[0].clearcoat_texture.map(|t| t.image), Some(0));
|
||||
assert_eq!(back.materials[0].clearcoat_roughness_texture.map(|t| t.image), Some(0));
|
||||
assert_eq!(back.materials[0].sheen_color, mat.sheen_color);
|
||||
assert_eq!(back.materials[0].sheen_roughness, mat.sheen_roughness);
|
||||
assert_eq!(back.materials[0].sheen_color_texture.map(|t| t.image), Some(1));
|
||||
assert_eq!(back.materials[0].sheen_roughness_texture.map(|t| t.image), Some(1));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::hammer;
|
||||
use crate::obj::{material_names, read, read_mtl, sibling_name, write, write_mtl};
|
||||
use crate::{AlphaMode, Corner, Error, Limits, Material, Mesh, NONE, Part, Scene, no_external};
|
||||
use crate::{AlphaMode, Corner, Error, Image, Limits, Material, Mesh, NONE, Part, Scene, TextureRef, no_external};
|
||||
|
||||
/// A unit cube with texture coordinates, normals, two materials and one face written with
|
||||
/// negative references.
|
||||
@@ -364,3 +364,14 @@ fn group_boundaries_keep_repeated_names_separate() {
|
||||
assert_eq!(scene.meshes.len(), 2);
|
||||
assert!(scene.meshes.iter().all(|m| m.name == "Same"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_with_mtl_links_library_and_clearcoat_maps() {
|
||||
let mut scene = cube();
|
||||
scene.images = vec![Image { uri: Some("coat.png".into()), ..Image::default() }];
|
||||
scene.materials[0].clearcoat_texture = Some(TextureRef { image: 0, ..TextureRef::default() });
|
||||
scene.materials[0].clearcoat_roughness_texture = Some(TextureRef { image: 0, ..TextureRef::default() });
|
||||
let (obj, mtl) = crate::obj::write_with_mtl(&scene, "cube.mtl", &Limits::default()).unwrap();
|
||||
assert!(obj.contains("mtllib cube.mtl\n"));
|
||||
assert!(mtl.contains("map_Pc coat.png\n") && mtl.contains("map_Pcr coat.png\n"), "{mtl}");
|
||||
}
|
||||
|
||||
@@ -30,6 +30,8 @@ content = ["cos", "dep:hayro-syntax"]
|
||||
crypt = ["dep:aes", "dep:md-5", "dep:sha2", "dep:stringprep", "dep:zeroize", "dep:thiserror"]
|
||||
# `testing`: a builder of small synthetic PDF files, for the tests of crates that read them.
|
||||
test-support = ["cos"]
|
||||
# Standard-14 font metrics and ISO 32000-2 Annex D single-byte encodings.
|
||||
fonts = []
|
||||
|
||||
[dependencies]
|
||||
hayro-syntax = { workspace = true, optional = true }
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
//! PDF single-byte encodings (ISO 32000-2 Annex D), WinAnsi/Unicode CMap encoding helpers,
|
||||
//! and Standard-14 font metrics.
|
||||
|
||||
pub mod encodings;
|
||||
mod std14;
|
||||
mod std14_metrics;
|
||||
|
||||
pub use std14::{Match as Std14Match, Std14};
|
||||
|
||||
/// The WinAnsiEncoding (ISO 32000-2 Annex D) code for `c`, if the encoding has one.
|
||||
///
|
||||
/// Codes 0x80–0x9F come from the same table the text extractor decodes with, so encoding and
|
||||
/// decoding agree (Š š Ž ž Œ œ Ÿ ƒ † ‡ ˆ ˜ ‰ ‹ › as well as quotes, dashes, € and ™).
|
||||
pub fn win_ansi_byte(c: char) -> Option<u8> {
|
||||
match c {
|
||||
'\u{20}'..='\u{7e}' | '\u{a0}'..='\u{ff}' => u8::try_from(u32::from(c)).ok(),
|
||||
_ => {
|
||||
let high = encodings::WIN_ANSI.get(0x80..0xa0)?;
|
||||
let i = high.iter().position(|&u| u != 0 && u == u32::from(c))?;
|
||||
u8::try_from(0x80 + i).ok()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode text in WinAnsiEncoding (ISO 32000-2 Annex D); tabs become spaces and unmappable
|
||||
/// characters become `?`.
|
||||
pub fn win_ansi(s: &str) -> Vec<u8> {
|
||||
s.chars().map(|c| if c == '\t' { b' ' } else { win_ansi_byte(c).unwrap_or(b'?') }).collect()
|
||||
}
|
||||
|
||||
/// The byte used by Unicode text plans, from the shared WinAnsi table (tabs become spaces).
|
||||
pub fn win_ansi_char(c: char) -> Option<u8> {
|
||||
if c == '\t' { Some(b' ') } else { win_ansi_byte(c) }
|
||||
}
|
||||
|
||||
/// Whether [`win_ansi`] keeps `c` rather than writing `?` (a tab becomes a space).
|
||||
pub fn win_ansi_encodable(c: char) -> bool {
|
||||
c == '\t' || win_ansi_byte(c).is_some()
|
||||
}
|
||||
|
||||
/// The first character of `s` that [`win_ansi`] can't encode and would write as `?`.
|
||||
pub fn first_non_win_ansi(s: &str) -> Option<char> {
|
||||
s.chars().find(|c| !win_ansi_encodable(*c))
|
||||
}
|
||||
|
||||
/// Whether every character can be represented without substitution in WinAnsi.
|
||||
pub fn fits_win_ansi(s: &str) -> bool {
|
||||
s.chars().all(win_ansi_encodable)
|
||||
}
|
||||
|
||||
/// The character encoding of a predefined Unicode CMap (`UniJIS-UTF16-H`, `UniGB-UCS2-H`, …;
|
||||
/// ISO 32000-2 §9.7.5.2), which maps Unicode text straight to codes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum UnicodeCMap {
|
||||
Ucs2,
|
||||
Utf16,
|
||||
Utf8,
|
||||
Utf32,
|
||||
}
|
||||
|
||||
impl UnicodeCMap {
|
||||
/// The encoding of the predefined CMap `name`, if it is a horizontal Unicode one. Vertical
|
||||
/// (`-V`) CMaps are refused: field appearances are laid out horizontally, so their glyphs
|
||||
/// would be drawn stacked down the field instead of across it.
|
||||
pub fn from_name(name: &[u8]) -> Option<Self> {
|
||||
let name = std::str::from_utf8(name).ok()?;
|
||||
if !name.starts_with("Uni") || !name.ends_with("-H") {
|
||||
return None;
|
||||
}
|
||||
name.split('-').find_map(|part| match part {
|
||||
"UCS2" => Some(Self::Ucs2),
|
||||
"UTF16" => Some(Self::Utf16),
|
||||
"UTF8" => Some(Self::Utf8),
|
||||
"UTF32" => Some(Self::Utf32),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The first character of `s` this encoding can't hold, which [`Self::encode`] would write as
|
||||
/// `?`: a character beyond U+FFFF in UCS-2 (`𠀋`). UTF-16, UTF-8 and UTF-32 hold every one.
|
||||
pub fn first_unencodable(self, s: &str) -> Option<char> {
|
||||
match self {
|
||||
Self::Ucs2 => s.chars().find(|c| u16::try_from(u32::from(*c)).is_err()),
|
||||
Self::Utf16 | Self::Utf8 | Self::Utf32 => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode `s`; tabs become spaces, and characters UCS-2 can't hold become `?` (check them
|
||||
/// first with [`Self::first_unencodable`]: callers should refuse such text rather than write `?`).
|
||||
pub fn encode(self, s: &str) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(s.len().saturating_mul(2));
|
||||
let mut units = [0u16; 2];
|
||||
let mut buf = [0u8; 4];
|
||||
for c in s.chars() {
|
||||
let c = if c == '\t' { ' ' } else { c };
|
||||
match self {
|
||||
Self::Ucs2 => {
|
||||
let unit = u16::try_from(u32::from(c)).unwrap_or(u16::from(b'?'));
|
||||
out.extend_from_slice(&unit.to_be_bytes());
|
||||
}
|
||||
Self::Utf16 => {
|
||||
for unit in c.encode_utf16(&mut units) {
|
||||
out.extend_from_slice(&unit.to_be_bytes());
|
||||
}
|
||||
}
|
||||
Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()),
|
||||
Self::Utf32 => out.extend_from_slice(&u32::from(c).to_be_bytes()),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_alias_codes_read_as_the_glyph_they_draw() {
|
||||
assert_eq!(encodings::WIN_ANSI.get(0xAD), Some(&u32::from('-')));
|
||||
assert_eq!(encodings::WIN_ANSI.get(0x2D), Some(&u32::from('-')));
|
||||
assert_eq!(encodings::WIN_ANSI.get(0xA0), Some(&u32::from(' ')));
|
||||
assert_eq!(encodings::WIN_ANSI.get(0x20), Some(&u32::from(' ')));
|
||||
assert_eq!(encodings::MAC_ROMAN.get(0xCA), Some(&u32::from(' ')));
|
||||
assert_eq!(encodings::MAC_ROMAN.get(0x20), Some(&u32::from(' ')));
|
||||
// MacRoman has no soft hyphen; 0xAD there is `notequal`, and keeps it.
|
||||
assert_eq!(encodings::MAC_ROMAN.get(0xAD), Some(&0x2260));
|
||||
// Writing is unaffected: '-' and ' ' take the canonical low codes, and a caller holding a
|
||||
// literal U+00AD or U+00A0 still writes the high byte, which is the one that draws them.
|
||||
assert_eq!(win_ansi_byte('-'), Some(0x2D));
|
||||
assert_eq!(win_ansi_byte(' '), Some(0x20));
|
||||
assert_eq!(win_ansi_byte('\u{00ad}'), Some(0xAD));
|
||||
assert_eq!(win_ansi_byte('\u{00a0}'), Some(0xA0));
|
||||
assert_eq!(win_ansi("a-b c"), b"a-b c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn win_ansi_covers_the_0x80_to_0x9f_glyphs() {
|
||||
const ALIASES: &[u8] = &[0xA0, 0xAD];
|
||||
for (code, &u) in encodings::WIN_ANSI.iter().enumerate() {
|
||||
let Some(c) = char::from_u32(u).filter(|_| u != 0) else { continue };
|
||||
if ALIASES.contains(&(code as u8)) {
|
||||
let canonical = win_ansi_byte(c).expect("an aliased glyph still encodes");
|
||||
assert!(canonical < code as u8, "{c:?}: the canonical code is the lower one");
|
||||
assert_eq!(encodings::WIN_ANSI.get(usize::from(canonical)), Some(&u), "both codes mean the same character");
|
||||
continue;
|
||||
}
|
||||
assert_eq!(win_ansi_byte(c), Some(code as u8), "{c:?} (U+{u:04X})");
|
||||
assert_eq!(win_ansi(&c.to_string()), [code as u8]);
|
||||
}
|
||||
assert_eq!(
|
||||
win_ansi("Šta? žaba, œuvre — „ok“ ‰ ƒ † ‡ ˆ ˜ ‹›Ÿ"),
|
||||
b"\x8ata? \x9eaba, \x9cuvre \x97 \x84ok\x93 \x89 \x83 \x86 \x87 \x88 \x98 \x8b\x9b\x9f"
|
||||
);
|
||||
assert_eq!(win_ansi("čć\u{81}\u{8d}\t"), b"???? ");
|
||||
assert_eq!(win_ansi_byte('\0'), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unicode_cmaps_encode_cjk_text() {
|
||||
assert_eq!(UnicodeCMap::from_name(b"UniJIS-UTF16-H"), Some(UnicodeCMap::Utf16));
|
||||
assert_eq!(UnicodeCMap::from_name(b"UniGB-UCS2-V"), None);
|
||||
assert_eq!(UnicodeCMap::from_name(b"UniJIS-UCS2-HW-H"), Some(UnicodeCMap::Ucs2));
|
||||
assert_eq!(UnicodeCMap::from_name(b"UniKS-UTF8-H"), Some(UnicodeCMap::Utf8));
|
||||
assert_eq!(UnicodeCMap::from_name(b"UniJIS2004-UTF32-H"), Some(UnicodeCMap::Utf32));
|
||||
assert_eq!(UnicodeCMap::from_name(b"Identity-H"), None);
|
||||
assert_eq!(UnicodeCMap::from_name(b"90ms-RKSJ-H"), None);
|
||||
assert_eq!(UnicodeCMap::from_name(b"\xff\xfe"), None);
|
||||
assert_eq!(UnicodeCMap::Utf16.encode("令A"), [0x4e, 0xe4, 0x00, 0x41]);
|
||||
assert_eq!(UnicodeCMap::Utf16.encode("𠀋"), [0xd8, 0x40, 0xdc, 0x0b]);
|
||||
assert_eq!(UnicodeCMap::Ucs2.encode("𠀋\t"), [0x00, b'?', 0x00, b' ']);
|
||||
assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和𠀋"), Some('𠀋'));
|
||||
assert_eq!(UnicodeCMap::Ucs2.first_unencodable("令和"), None);
|
||||
for cmap in [UnicodeCMap::Utf16, UnicodeCMap::Utf8, UnicodeCMap::Utf32] {
|
||||
assert_eq!(cmap.first_unencodable("令和𠀋"), None, "{cmap:?}");
|
||||
}
|
||||
assert_eq!(UnicodeCMap::Utf8.encode("令"), "令".as_bytes());
|
||||
assert_eq!(UnicodeCMap::Utf32.encode("令"), [0, 0, 0x4e, 0xe4]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
//! Single-byte encodings (ISO 32000-2 Annex D) as code → Unicode tables (0 = undefined).
|
||||
|
||||
pub static WIN_ANSI: [u32; 256] = [
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
|
||||
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
|
||||
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
|
||||
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 8364, 0, 8218, 402, 8222, 8230, 8224, 8225, 710, 8240, 352, 8249, 338,
|
||||
// 0xA0 is `space` and 0xAD is `hyphen`, not U+00A0 and U+00AD: WinAnsiEncoding's table
|
||||
// (Annex D.2) gives those codes the same glyph names as 0x20 and 0x2D, so the bytes a Windows
|
||||
// codepage calls a non-breaking space and a soft hyphen draw, and extract as, an ordinary
|
||||
// space and hyphen. Emitting the formatting characters instead hides them from search and
|
||||
// from redaction's pattern matching: a soft hyphen is invisible and matches nothing, and a
|
||||
// non-breaking space does not match the space a reader typed.
|
||||
0, 381, 0, 0, 8216, 8217, 8220, 8221, 8226, 8211, 8212, 732, 8482, 353, 8250, 339, 0, 382, 376, 32, 161, 162, 163, 164, 165, 166, 167, 168, 169,
|
||||
170, 171, 172, 45, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198,
|
||||
199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227,
|
||||
228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255,
|
||||
];
|
||||
pub static MAC_ROMAN: [u32; 256] = [
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43,
|
||||
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
|
||||
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112,
|
||||
113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 196, 197, 199, 201, 209, 214, 220, 225, 224, 226, 228, 227, 229, 231,
|
||||
233, 232, 234, 235, 237, 236, 238, 239, 241, 243, 242, 244, 246, 245, 250, 249, 251, 252, 8224, 176, 162, 163, 167, 8226, 182, 223, 174, 169,
|
||||
8482, 180, 168, 8800, 198, 216, 8734, 177, 8804, 8805, 165, 181, 8706, 8721, 8719, 960, 8747, 170, 186, 937, 230, 248, 191, 161, 172, 8730, 402,
|
||||
// 0xCA is `space`, the same glyph name Annex D.2 gives 0x20, for the reason WinAnsi 0xA0 is.
|
||||
8776, 8710, 171, 187, 8230, 32, 192, 195, 213, 338, 339, 8211, 8212, 8220, 8221, 8216, 8217, 247, 9674, 255, 376, 8260, 8364, 8249, 8250, 64257,
|
||||
64258, 8225, 183, 8218, 8222, 8240, 194, 202, 193, 203, 200, 205, 206, 207, 204, 211, 212, 63743, 210, 218, 219, 217, 305, 710, 732, 175, 728,
|
||||
729, 730, 184, 733, 731, 711,
|
||||
];
|
||||
pub static STANDARD: [u32; 256] = [
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 33, 34, 35, 36, 37, 38, 8217, 40, 41, 42, 43,
|
||||
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
|
||||
80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 8216, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111,
|
||||
112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 161, 162, 163, 8260, 165, 402, 167, 164, 39, 8220, 171, 8249, 8250, 64257, 64258, 0, 8211, 8224, 8225, 183, 0,
|
||||
182, 8226, 8218, 8222, 8221, 187, 8230, 8240, 0, 191, 0, 96, 180, 710, 732, 175, 728, 729, 168, 0, 730, 184, 0, 733, 731, 711, 8212, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 198, 0, 170, 0, 0, 0, 0, 321, 216, 338, 186, 0, 0, 0, 0, 0, 230, 0, 0, 0, 305, 0, 0, 322, 248, 339, 223, 0,
|
||||
0, 0, 0,
|
||||
];
|
||||
|
||||
/// Glyph names of the Latin character set (Annex D) → Unicode.
|
||||
pub static NAMES: &[(&str, u32)] = &[
|
||||
("A", 0x41),
|
||||
("AE", 0xc6),
|
||||
("Aacute", 0xc1),
|
||||
("Acircumflex", 0xc2),
|
||||
("Adieresis", 0xc4),
|
||||
("Agrave", 0xc0),
|
||||
("Aring", 0xc5),
|
||||
("Atilde", 0xc3),
|
||||
("B", 0x42),
|
||||
("C", 0x43),
|
||||
("Ccedilla", 0xc7),
|
||||
("D", 0x44),
|
||||
("E", 0x45),
|
||||
("Eacute", 0xc9),
|
||||
("Ecircumflex", 0xca),
|
||||
("Edieresis", 0xcb),
|
||||
("Egrave", 0xc8),
|
||||
("Eth", 0xd0),
|
||||
("Euro", 0x20ac),
|
||||
("F", 0x46),
|
||||
("G", 0x47),
|
||||
("H", 0x48),
|
||||
("I", 0x49),
|
||||
("Iacute", 0xcd),
|
||||
("Icircumflex", 0xce),
|
||||
("Idieresis", 0xcf),
|
||||
("Igrave", 0xcc),
|
||||
("J", 0x4a),
|
||||
("K", 0x4b),
|
||||
("L", 0x4c),
|
||||
("Lslash", 0x141),
|
||||
("M", 0x4d),
|
||||
("N", 0x4e),
|
||||
("Ntilde", 0xd1),
|
||||
("O", 0x4f),
|
||||
("OE", 0x152),
|
||||
("Oacute", 0xd3),
|
||||
("Ocircumflex", 0xd4),
|
||||
("Odieresis", 0xd6),
|
||||
("Ograve", 0xd2),
|
||||
("Oslash", 0xd8),
|
||||
("Otilde", 0xd5),
|
||||
("P", 0x50),
|
||||
("Q", 0x51),
|
||||
("R", 0x52),
|
||||
("S", 0x53),
|
||||
("Scaron", 0x160),
|
||||
("T", 0x54),
|
||||
("Thorn", 0xde),
|
||||
("U", 0x55),
|
||||
("Uacute", 0xda),
|
||||
("Ucircumflex", 0xdb),
|
||||
("Udieresis", 0xdc),
|
||||
("Ugrave", 0xd9),
|
||||
("V", 0x56),
|
||||
("W", 0x57),
|
||||
("X", 0x58),
|
||||
("Y", 0x59),
|
||||
("Yacute", 0xdd),
|
||||
("Ydieresis", 0x178),
|
||||
("Z", 0x5a),
|
||||
("Zcaron", 0x17d),
|
||||
("a", 0x61),
|
||||
("aacute", 0xe1),
|
||||
("acircumflex", 0xe2),
|
||||
("acute", 0xb4),
|
||||
("adieresis", 0xe4),
|
||||
("ae", 0xe6),
|
||||
("agrave", 0xe0),
|
||||
("ampersand", 0x26),
|
||||
("aring", 0xe5),
|
||||
("asciicircum", 0x5e),
|
||||
("asciitilde", 0x7e),
|
||||
("asterisk", 0x2a),
|
||||
("at", 0x40),
|
||||
("atilde", 0xe3),
|
||||
("b", 0x62),
|
||||
("backslash", 0x5c),
|
||||
("bar", 0x7c),
|
||||
("braceleft", 0x7b),
|
||||
("braceright", 0x7d),
|
||||
("bracketleft", 0x5b),
|
||||
("bracketright", 0x5d),
|
||||
("breve", 0x2d8),
|
||||
("brokenbar", 0xa6),
|
||||
("bullet", 0x2022),
|
||||
("c", 0x63),
|
||||
("caron", 0x2c7),
|
||||
("ccedilla", 0xe7),
|
||||
("cedilla", 0xb8),
|
||||
("cent", 0xa2),
|
||||
("circumflex", 0x2c6),
|
||||
("colon", 0x3a),
|
||||
("comma", 0x2c),
|
||||
("copyright", 0xa9),
|
||||
("currency", 0xa4),
|
||||
("d", 0x64),
|
||||
("dagger", 0x2020),
|
||||
("daggerdbl", 0x2021),
|
||||
("degree", 0xb0),
|
||||
("dieresis", 0xa8),
|
||||
("divide", 0xf7),
|
||||
("dollar", 0x24),
|
||||
("dotaccent", 0x2d9),
|
||||
("dotlessi", 0x131),
|
||||
("e", 0x65),
|
||||
("eacute", 0xe9),
|
||||
("ecircumflex", 0xea),
|
||||
("edieresis", 0xeb),
|
||||
("egrave", 0xe8),
|
||||
("eight", 0x38),
|
||||
("ellipsis", 0x2026),
|
||||
("emdash", 0x2014),
|
||||
("endash", 0x2013),
|
||||
("equal", 0x3d),
|
||||
("eth", 0xf0),
|
||||
("exclam", 0x21),
|
||||
("exclamdown", 0xa1),
|
||||
("f", 0x66),
|
||||
("fi", 0xfb01),
|
||||
("five", 0x35),
|
||||
("fl", 0xfb02),
|
||||
("florin", 0x192),
|
||||
("four", 0x34),
|
||||
("fraction", 0x2044),
|
||||
("g", 0x67),
|
||||
("germandbls", 0xdf),
|
||||
("grave", 0x60),
|
||||
("greater", 0x3e),
|
||||
("guillemotleft", 0xab),
|
||||
("guillemotright", 0xbb),
|
||||
("guilsinglleft", 0x2039),
|
||||
("guilsinglright", 0x203a),
|
||||
("h", 0x68),
|
||||
("hungarumlaut", 0x2dd),
|
||||
("hyphen", 0x2d),
|
||||
("i", 0x69),
|
||||
("iacute", 0xed),
|
||||
("icircumflex", 0xee),
|
||||
("idieresis", 0xef),
|
||||
("igrave", 0xec),
|
||||
("j", 0x6a),
|
||||
("k", 0x6b),
|
||||
("l", 0x6c),
|
||||
("less", 0x3c),
|
||||
("logicalnot", 0xac),
|
||||
("lslash", 0x142),
|
||||
("m", 0x6d),
|
||||
("macron", 0xaf),
|
||||
("minus", 0x2212),
|
||||
("mu", 0xb5),
|
||||
("multiply", 0xd7),
|
||||
("n", 0x6e),
|
||||
("nbspace", 0xa0),
|
||||
("nine", 0x39),
|
||||
("ntilde", 0xf1),
|
||||
("numbersign", 0x23),
|
||||
("o", 0x6f),
|
||||
("oacute", 0xf3),
|
||||
("ocircumflex", 0xf4),
|
||||
("odieresis", 0xf6),
|
||||
("oe", 0x153),
|
||||
("ogonek", 0x2db),
|
||||
("ograve", 0xf2),
|
||||
("one", 0x31),
|
||||
("onehalf", 0xbd),
|
||||
("onequarter", 0xbc),
|
||||
("onesuperior", 0xb9),
|
||||
("ordfeminine", 0xaa),
|
||||
("ordmasculine", 0xba),
|
||||
("oslash", 0xf8),
|
||||
("otilde", 0xf5),
|
||||
("p", 0x70),
|
||||
("paragraph", 0xb6),
|
||||
("parenleft", 0x28),
|
||||
("parenright", 0x29),
|
||||
("percent", 0x25),
|
||||
("period", 0x2e),
|
||||
("periodcentered", 0xb7),
|
||||
("perthousand", 0x2030),
|
||||
("plus", 0x2b),
|
||||
("plusminus", 0xb1),
|
||||
("q", 0x71),
|
||||
("question", 0x3f),
|
||||
("questiondown", 0xbf),
|
||||
("quotedbl", 0x22),
|
||||
("quotedblbase", 0x201e),
|
||||
("quotedblleft", 0x201c),
|
||||
("quotedblright", 0x201d),
|
||||
("quoteleft", 0x2018),
|
||||
("quoteright", 0x2019),
|
||||
("quotesinglbase", 0x201a),
|
||||
("quotesingle", 0x27),
|
||||
("r", 0x72),
|
||||
("registered", 0xae),
|
||||
("ring", 0x2da),
|
||||
("s", 0x73),
|
||||
("scaron", 0x161),
|
||||
("section", 0xa7),
|
||||
("semicolon", 0x3b),
|
||||
("seven", 0x37),
|
||||
("sfthyphen", 0xad),
|
||||
("six", 0x36),
|
||||
("slash", 0x2f),
|
||||
("space", 0x20),
|
||||
("sterling", 0xa3),
|
||||
("t", 0x74),
|
||||
("thorn", 0xfe),
|
||||
("three", 0x33),
|
||||
("threequarters", 0xbe),
|
||||
("threesuperior", 0xb3),
|
||||
("tilde", 0x2dc),
|
||||
("trademark", 0x2122),
|
||||
("two", 0x32),
|
||||
("twosuperior", 0xb2),
|
||||
("u", 0x75),
|
||||
("uacute", 0xfa),
|
||||
("ucircumflex", 0xfb),
|
||||
("udieresis", 0xfc),
|
||||
("ugrave", 0xf9),
|
||||
("underscore", 0x5f),
|
||||
("v", 0x76),
|
||||
("w", 0x77),
|
||||
("x", 0x78),
|
||||
("y", 0x79),
|
||||
("yacute", 0xfd),
|
||||
("ydieresis", 0xff),
|
||||
("yen", 0xa5),
|
||||
("z", 0x7a),
|
||||
("zcaron", 0x17e),
|
||||
("zero", 0x30),
|
||||
];
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Standard-14 font metrics (ISO 32000-2 Annex D; the Adobe Core14 AFM metrics), as advance
|
||||
//! widths in glyph space — thousandths of an em.
|
||||
//!
|
||||
//! A PDF may name any of the fourteen standard fonts without embedding a program, and the viewer
|
||||
//! has to supply the metrics. These are those metrics, exactly, replacing the character-class
|
||||
//! estimate that generated appearances used before: that estimate had Times at 0.9 x Helvetica,
|
||||
//! which makes a capital A 600 where the specification says 722.
|
||||
//!
|
||||
//! **Generated.** The tables are data, not typefaces, and are the item AGENTS.md §1.1 permits as
|
||||
//! Adobe-authored non-visual technical data; `ATTRIBUTION.toml` carries the entry with
|
||||
//! `adobe_data = true`. Each row is indexed by character **code**, not by Unicode: the twelve text
|
||||
//! fonts are indexed by WinAnsiEncoding, which is what PdfCraft writes into the appearance streams
|
||||
//! it generates, and Symbol and ZapfDingbats by their own built-in encodings. A zero means the
|
||||
//! encoding leaves that code undefined.
|
||||
|
||||
/// One of the fourteen standard fonts (ISO 32000-2 §9.6.2.2).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Std14 {
|
||||
Helvetica,
|
||||
HelveticaBold,
|
||||
HelveticaOblique,
|
||||
HelveticaBoldOblique,
|
||||
TimesRoman,
|
||||
TimesBold,
|
||||
TimesItalic,
|
||||
TimesBoldItalic,
|
||||
Courier,
|
||||
CourierBold,
|
||||
CourierOblique,
|
||||
CourierBoldOblique,
|
||||
Symbol,
|
||||
ZapfDingbats,
|
||||
}
|
||||
|
||||
/// How [`Std14::recognise`] matched a `/BaseFont` name.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Match {
|
||||
/// A standard-14 face or a well-known alias of one (Arial for Helvetica, CourierNew for
|
||||
/// Courier). The document is asking for this face.
|
||||
Alias,
|
||||
/// Only a family hint matched -- "Serif", "Roman" or "Mono" in an otherwise unknown name.
|
||||
/// The face is a guess from the name, not the one the document asked for.
|
||||
FamilyHint,
|
||||
}
|
||||
|
||||
impl Std14 {
|
||||
/// The font a `/BaseFont` name selects, by the spec's names and the common aliases viewers
|
||||
/// accept (`Arial` for `Helvetica`, `TimesNewRoman` for `Times`, `CourierNew` for `Courier`).
|
||||
/// A subset prefix such as `ABCDEF+Helvetica` is ignored.
|
||||
pub fn from_base_font(base: &str) -> Option<Self> {
|
||||
Self::recognise(base).map(|(face, _)| face)
|
||||
}
|
||||
|
||||
/// [`Std14::from_base_font`], also saying *how* the name matched.
|
||||
///
|
||||
/// Reporting needs the difference. "Arial" really is a request for Helvetica, but
|
||||
/// "SomeHouseSerif" is a house font whose name merely contains "Serif"; choosing Times for it
|
||||
/// is a reasonable guess from the name, not the face the document asked for, and a substitution
|
||||
/// report that called it a standard-14 name would be telling the reader something untrue.
|
||||
pub fn recognise(base: &str) -> Option<(Self, Match)> {
|
||||
let base = base.rsplit('+').next().unwrap_or(base);
|
||||
let flat: String = base.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect();
|
||||
let has = |w: &str| flat.contains(w);
|
||||
let (bold, italic) = (has("bold"), has("italic") || has("oblique"));
|
||||
// Two bools index a four-element array, so the subscript is provably 0..=3.
|
||||
let styled = |faces: [Self; 4]| faces[usize::from(bold) | usize::from(italic) << 1];
|
||||
let courier = || styled([Self::Courier, Self::CourierBold, Self::CourierOblique, Self::CourierBoldOblique]);
|
||||
let times = || styled([Self::TimesRoman, Self::TimesBold, Self::TimesItalic, Self::TimesBoldItalic]);
|
||||
if has("symbol") {
|
||||
return Some((Self::Symbol, Match::Alias));
|
||||
}
|
||||
if has("zapf") || has("dingbat") {
|
||||
return Some((Self::ZapfDingbats, Match::Alias));
|
||||
}
|
||||
if has("courier") {
|
||||
return Some((courier(), Match::Alias));
|
||||
}
|
||||
if has("mono") {
|
||||
return Some((courier(), Match::FamilyHint));
|
||||
}
|
||||
if has("times") {
|
||||
return Some((times(), Match::Alias));
|
||||
}
|
||||
if (has("serif") && !has("sans")) || has("roman") {
|
||||
return Some((times(), Match::FamilyHint));
|
||||
}
|
||||
if has("helvetica") || has("arial") {
|
||||
return Some((styled([Self::Helvetica, Self::HelveticaBold, Self::HelveticaOblique, Self::HelveticaBoldOblique]), Match::Alias));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The advance of one character `code`, in thousandths of an em. Zero where the font's
|
||||
/// encoding leaves the code undefined.
|
||||
pub fn width(self, code: u8) -> f64 {
|
||||
f64::from(super::std14_metrics::WIDTHS[self as usize][code as usize])
|
||||
}
|
||||
|
||||
/// The advance of `code` at `size` points.
|
||||
pub fn advance(self, code: u8, size: f64) -> f64 {
|
||||
self.width(code) * size / 1000.0
|
||||
}
|
||||
|
||||
/// The advance of `text` at `size` points, encoded as the twelve text fonts are written:
|
||||
/// WinAnsiEncoding, with characters it cannot represent replaced as `win_ansi` replaces them.
|
||||
///
|
||||
/// Symbol and ZapfDingbats have their own built-in encodings and are not WinAnsi, so this
|
||||
/// measures them as if they were; pass codes to [`Std14::width`] for those.
|
||||
pub fn text_width(self, text: &str, size: f64) -> f64 {
|
||||
super::win_ansi(text).iter().map(|&c| self.width(c)).sum::<f64>() * size / 1000.0
|
||||
}
|
||||
|
||||
/// Courier is the only fixed-pitch family of the fourteen.
|
||||
pub fn is_fixed_pitch(self) -> bool {
|
||||
matches!(self, Self::Courier | Self::CourierBold | Self::CourierOblique | Self::CourierBoldOblique)
|
||||
}
|
||||
|
||||
/// The `/BaseFont` name for this font, as it is written into a PDF.
|
||||
pub fn base_font(self) -> &'static str {
|
||||
super::std14_metrics::BASE_FONTS[self as usize]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sans_serif_names_are_not_mapped_to_times() {
|
||||
assert!(!matches!(Std14::recognise("SansSerif"), Some((Std14::TimesRoman, _))));
|
||||
assert_eq!(Std14::recognise("Arial-SansSerif"), Some((Std14::Helvetica, Match::Alias)));
|
||||
}
|
||||
|
||||
/// Widths from the published Core14 metrics, typed in here by hand so the table is checked
|
||||
/// against the specification rather than against whatever produced it.
|
||||
#[test]
|
||||
fn widths_match_the_published_metrics() {
|
||||
let cases: &[(Std14, char, u16)] = &[
|
||||
// Helvetica
|
||||
(Std14::Helvetica, ' ', 278),
|
||||
(Std14::Helvetica, 'A', 667),
|
||||
(Std14::Helvetica, 'W', 944),
|
||||
(Std14::Helvetica, 'i', 222),
|
||||
(Std14::Helvetica, 'm', 833),
|
||||
(Std14::Helvetica, '0', 556),
|
||||
(Std14::Helvetica, '@', 1015),
|
||||
(Std14::HelveticaBold, 'A', 722),
|
||||
(Std14::HelveticaBold, 'i', 278),
|
||||
// Times: not Helvetica scaled by 0.9, which is what the old estimate assumed.
|
||||
(Std14::TimesRoman, ' ', 250),
|
||||
(Std14::TimesRoman, 'A', 722),
|
||||
(Std14::TimesRoman, 'W', 944),
|
||||
(Std14::TimesRoman, 'i', 278),
|
||||
(Std14::TimesRoman, 'm', 778),
|
||||
(Std14::TimesBold, 'A', 722),
|
||||
(Std14::TimesItalic, 'A', 611),
|
||||
// Courier is fixed pitch at 600 for every glyph.
|
||||
(Std14::Courier, ' ', 600),
|
||||
(Std14::Courier, 'A', 600),
|
||||
(Std14::Courier, 'm', 600),
|
||||
(Std14::CourierBoldOblique, 'W', 600),
|
||||
];
|
||||
for &(font, ch, want) in cases {
|
||||
let code = crate::fonts::win_ansi(&ch.to_string());
|
||||
assert_eq!(code.len(), 1, "{ch:?} is one WinAnsi byte");
|
||||
assert_eq!(font.width(code[0]) as u16, want, "{font:?} {ch:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn courier_is_fixed_pitch_everywhere_it_is_defined() {
|
||||
for font in [Std14::Courier, Std14::CourierBold, Std14::CourierOblique, Std14::CourierBoldOblique] {
|
||||
assert!(font.is_fixed_pitch());
|
||||
for code in 0..=255u8 {
|
||||
let w = font.width(code);
|
||||
assert!(w == 0.0 || w == 600.0, "{font:?} code {code} has width {w}");
|
||||
}
|
||||
}
|
||||
assert!(!Std14::Helvetica.is_fixed_pitch());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_text_font_covers_printable_ascii_and_latin1() {
|
||||
for font in [Std14::Helvetica, Std14::TimesRoman, Std14::Courier, Std14::TimesBoldItalic] {
|
||||
for code in 0x20..=0x7Eu8 {
|
||||
assert!(font.width(code) > 0.0, "{font:?} has no width for ASCII {code}");
|
||||
}
|
||||
for code in 0xA0..=0xFFu8 {
|
||||
assert!(font.width(code) > 0.0, "{font:?} has no width for Latin-1 {code}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbol_and_dingbats_have_their_own_encodings() {
|
||||
// Symbol's code 0x61 is alpha, not 'a'; ZapfDingbats' is a scissors glyph.
|
||||
assert!(Std14::Symbol.width(0x61) > 0.0);
|
||||
assert!(Std14::ZapfDingbats.width(0x61) > 0.0);
|
||||
// Neither defines the Latin-1 upper half the text fonts do.
|
||||
assert_eq!(Std14::Symbol.width(0xFF), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_font_names_round_trip() {
|
||||
for i in 0..14usize {
|
||||
let font = [
|
||||
Std14::Helvetica,
|
||||
Std14::HelveticaBold,
|
||||
Std14::HelveticaOblique,
|
||||
Std14::HelveticaBoldOblique,
|
||||
Std14::TimesRoman,
|
||||
Std14::TimesBold,
|
||||
Std14::TimesItalic,
|
||||
Std14::TimesBoldItalic,
|
||||
Std14::Courier,
|
||||
Std14::CourierBold,
|
||||
Std14::CourierOblique,
|
||||
Std14::CourierBoldOblique,
|
||||
Std14::Symbol,
|
||||
Std14::ZapfDingbats,
|
||||
][i];
|
||||
assert_eq!(Std14::from_base_font(font.base_font()), Some(font), "{}", font.base_font());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base_font_aliases_and_subset_prefixes_resolve() {
|
||||
assert_eq!(Std14::from_base_font("ABCDEF+Helvetica-Bold"), Some(Std14::HelveticaBold));
|
||||
assert_eq!(Std14::from_base_font("Arial"), Some(Std14::Helvetica));
|
||||
assert_eq!(Std14::from_base_font("Arial,BoldItalic"), Some(Std14::HelveticaBoldOblique));
|
||||
assert_eq!(Std14::from_base_font("TimesNewRoman,Bold"), Some(Std14::TimesBold));
|
||||
assert_eq!(Std14::from_base_font("CourierNew-Oblique"), Some(Std14::CourierOblique));
|
||||
assert_eq!(Std14::from_base_font("ZapfDingbats"), Some(Std14::ZapfDingbats));
|
||||
assert_eq!(Std14::from_base_font("Wingdings"), None);
|
||||
assert_eq!(Std14::from_base_font(""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_width_sums_the_glyphs_and_scales_with_size() {
|
||||
let h = Std14::Helvetica;
|
||||
// "AW" = 667 + 944 = 1611 thousandths of an em.
|
||||
assert!((h.text_width("AW", 1000.0) - 1611.0).abs() < 1e-9);
|
||||
assert!((h.text_width("AW", 12.0) - 1611.0 * 12.0 / 1000.0).abs() < 1e-9);
|
||||
assert_eq!(h.text_width("", 12.0), 0.0);
|
||||
// Courier: every character is 600, so the width is purely a count.
|
||||
assert!((Std14::Courier.text_width("hello", 10.0) - 5.0 * 6.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_text_does_not_panic_and_stays_finite() {
|
||||
for font in [Std14::Helvetica, Std14::Symbol, Std14::Courier] {
|
||||
for s in ["", "\0", "\u{202E}", "💥", &"a".repeat(10_000), "\u{FFFD}"] {
|
||||
let w = font.text_width(s, 12.0);
|
||||
assert!(w.is_finite() && w >= 0.0, "{font:?} {s:?} -> {w}");
|
||||
}
|
||||
assert!(font.advance(0, 12.0).is_finite());
|
||||
assert!(font.advance(255, 0.0).is_finite());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
//! The generated standard-14 tables: the fourteen base font names and their per-code advance
|
||||
//! widths. **Data only, no logic** -- see `std14.rs` for everything that interprets it.
|
||||
//!
|
||||
//! This file is the closed-list item in AGENTS.md 1.1 and carries a SHA-256 in `ATTRIBUTION.toml`,
|
||||
//! so `cargo xtask assets` fails until a change to it is re-attested. It is kept separate from the
|
||||
//! code that reads it for exactly that reason: if ordinary edits churned the hash, re-attesting
|
||||
//! would become reflexive and the check would stop meaning anything.
|
||||
//!
|
||||
//! Widths are in thousandths of an em, indexed by character code in each face's own encoding --
|
||||
//! WinAnsi for the twelve text faces, and their built-in encodings for Symbol and ZapfDingbats.
|
||||
//! A zero means the encoding leaves that code undefined. Verified against the published
|
||||
//! specification by the tests in `std14.rs`, which type the expected values in by hand.
|
||||
|
||||
pub(crate) static BASE_FONTS: [&str; 14] = [
|
||||
"Helvetica",
|
||||
"Helvetica-Bold",
|
||||
"Helvetica-Oblique",
|
||||
"Helvetica-BoldOblique",
|
||||
"Times-Roman",
|
||||
"Times-Bold",
|
||||
"Times-Italic",
|
||||
"Times-BoldItalic",
|
||||
"Courier",
|
||||
"Courier-Bold",
|
||||
"Courier-Oblique",
|
||||
"Courier-BoldOblique",
|
||||
"Symbol",
|
||||
"ZapfDingbats",
|
||||
];
|
||||
|
||||
/// Advance widths by code, one row per [`Std14`] variant in declaration order.
|
||||
#[rustfmt::skip]
|
||||
pub(crate) static WIDTHS: [[u16; 256]; 14] = [
|
||||
// Helvetica
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
|
||||
1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,
|
||||
333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,
|
||||
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0,
|
||||
556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
|
||||
0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667,
|
||||
278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333,
|
||||
400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611,
|
||||
667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
|
||||
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
|
||||
556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500,
|
||||
],
|
||||
// HelveticaBold
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611,
|
||||
975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556,
|
||||
333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611,
|
||||
611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0,
|
||||
556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
|
||||
0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667,
|
||||
278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333,
|
||||
400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611,
|
||||
722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
|
||||
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
|
||||
556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278,
|
||||
611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556,
|
||||
],
|
||||
// HelveticaOblique
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556,
|
||||
1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556,
|
||||
333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556,
|
||||
556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 0,
|
||||
556, 0, 222, 556, 333, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
|
||||
0, 222, 222, 333, 333, 350, 556, 1000, 333, 1000, 500, 333, 944, 0, 500, 667,
|
||||
278, 333, 556, 556, 556, 556, 260, 556, 333, 737, 370, 556, 584, 333, 737, 333,
|
||||
400, 584, 333, 333, 333, 556, 537, 278, 333, 333, 365, 556, 834, 834, 834, 611,
|
||||
667, 667, 667, 667, 667, 667, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
|
||||
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
|
||||
556, 556, 556, 556, 556, 556, 889, 500, 556, 556, 556, 556, 278, 278, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 584, 611, 556, 556, 556, 556, 500, 556, 500,
|
||||
],
|
||||
// HelveticaBoldOblique
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
278, 333, 474, 556, 556, 889, 722, 238, 333, 333, 389, 584, 278, 333, 278, 278,
|
||||
556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611,
|
||||
975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778,
|
||||
667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556,
|
||||
333, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611,
|
||||
611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 0,
|
||||
556, 0, 278, 556, 500, 1000, 556, 556, 333, 1000, 667, 333, 1000, 0, 611, 0,
|
||||
0, 278, 278, 500, 500, 350, 556, 1000, 333, 1000, 556, 333, 944, 0, 500, 667,
|
||||
278, 333, 556, 556, 556, 556, 280, 556, 333, 737, 370, 556, 584, 333, 737, 333,
|
||||
400, 584, 333, 333, 333, 611, 556, 278, 333, 333, 365, 556, 834, 834, 834, 611,
|
||||
722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 278, 278, 278, 278,
|
||||
722, 722, 778, 778, 778, 778, 778, 584, 778, 722, 722, 722, 722, 667, 667, 611,
|
||||
556, 556, 556, 556, 556, 556, 889, 556, 556, 556, 556, 556, 278, 278, 278, 278,
|
||||
611, 611, 611, 611, 611, 611, 611, 584, 611, 611, 611, 611, 611, 556, 611, 556,
|
||||
],
|
||||
// TimesRoman
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
250, 333, 408, 500, 500, 833, 778, 180, 333, 333, 500, 564, 250, 333, 250, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444,
|
||||
921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722,
|
||||
556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500,
|
||||
333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500,
|
||||
500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, 0,
|
||||
500, 0, 333, 500, 444, 1000, 500, 500, 333, 1000, 556, 333, 889, 0, 611, 0,
|
||||
0, 333, 333, 444, 444, 350, 500, 1000, 333, 980, 389, 333, 722, 0, 444, 722,
|
||||
250, 333, 500, 500, 500, 500, 200, 500, 333, 760, 276, 500, 564, 333, 760, 333,
|
||||
400, 564, 300, 300, 333, 500, 453, 250, 333, 300, 310, 500, 750, 750, 750, 444,
|
||||
722, 722, 722, 722, 722, 722, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333,
|
||||
722, 722, 722, 722, 722, 722, 722, 564, 722, 722, 722, 722, 722, 722, 556, 500,
|
||||
444, 444, 444, 444, 444, 444, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 564, 500, 500, 500, 500, 500, 500, 500, 500,
|
||||
],
|
||||
// TimesBold
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
250, 333, 555, 500, 500, 1000, 833, 278, 333, 333, 500, 570, 250, 333, 250, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500,
|
||||
930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778,
|
||||
611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500,
|
||||
333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500,
|
||||
556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 0,
|
||||
500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 1000, 0, 667, 0,
|
||||
0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 444, 722,
|
||||
250, 333, 500, 500, 500, 500, 220, 500, 333, 747, 300, 500, 570, 333, 747, 333,
|
||||
400, 570, 300, 300, 333, 556, 540, 250, 333, 300, 330, 500, 750, 750, 750, 500,
|
||||
722, 722, 722, 722, 722, 722, 1000, 722, 667, 667, 667, 667, 389, 389, 389, 389,
|
||||
722, 722, 778, 778, 778, 778, 778, 570, 778, 722, 722, 722, 722, 722, 611, 556,
|
||||
500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278,
|
||||
500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 500, 556, 500,
|
||||
],
|
||||
// TimesItalic
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
250, 333, 420, 500, 500, 833, 778, 214, 333, 333, 500, 675, 250, 333, 250, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500,
|
||||
920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722,
|
||||
611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500,
|
||||
333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500,
|
||||
500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 0,
|
||||
500, 0, 333, 500, 556, 889, 500, 500, 333, 1000, 500, 333, 944, 0, 556, 0,
|
||||
0, 333, 333, 556, 556, 350, 500, 889, 333, 980, 389, 333, 667, 0, 389, 556,
|
||||
250, 389, 500, 500, 500, 500, 275, 500, 333, 760, 276, 500, 675, 333, 760, 333,
|
||||
400, 675, 300, 300, 333, 500, 523, 250, 333, 300, 310, 500, 750, 750, 750, 500,
|
||||
611, 611, 611, 611, 611, 611, 889, 667, 611, 611, 611, 611, 333, 333, 333, 333,
|
||||
722, 667, 722, 722, 722, 722, 722, 675, 722, 722, 722, 722, 722, 556, 611, 500,
|
||||
500, 500, 500, 500, 500, 500, 667, 444, 444, 444, 444, 444, 278, 278, 278, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 675, 500, 500, 500, 500, 500, 444, 500, 444,
|
||||
],
|
||||
// TimesBoldItalic
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
250, 389, 555, 500, 500, 833, 778, 278, 333, 333, 500, 570, 250, 333, 250, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500,
|
||||
832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722,
|
||||
611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500,
|
||||
333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500,
|
||||
500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570, 0,
|
||||
500, 0, 333, 500, 500, 1000, 500, 500, 333, 1000, 556, 333, 944, 0, 611, 0,
|
||||
0, 333, 333, 500, 500, 350, 500, 1000, 333, 1000, 389, 333, 722, 0, 389, 611,
|
||||
250, 389, 500, 500, 500, 500, 220, 500, 333, 747, 266, 500, 606, 333, 747, 333,
|
||||
400, 570, 300, 300, 333, 576, 500, 250, 333, 300, 300, 500, 750, 750, 750, 500,
|
||||
667, 667, 667, 667, 667, 667, 944, 667, 667, 667, 667, 667, 389, 389, 389, 389,
|
||||
722, 722, 722, 722, 722, 722, 722, 570, 722, 722, 722, 722, 722, 611, 611, 500,
|
||||
500, 500, 500, 500, 500, 500, 722, 444, 444, 444, 444, 444, 278, 278, 278, 278,
|
||||
500, 556, 500, 500, 500, 500, 500, 570, 500, 556, 556, 556, 556, 444, 500, 444,
|
||||
],
|
||||
// Courier
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
|
||||
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0,
|
||||
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
],
|
||||
// CourierBold
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
|
||||
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0,
|
||||
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
],
|
||||
// CourierOblique
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
|
||||
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0,
|
||||
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
],
|
||||
// CourierBoldOblique
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0,
|
||||
600, 0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 0,
|
||||
0, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 0, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600,
|
||||
],
|
||||
// Symbol
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278,
|
||||
500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444,
|
||||
549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722,
|
||||
768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500,
|
||||
500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549,
|
||||
549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
750, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603,
|
||||
400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658,
|
||||
823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713,
|
||||
768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603,
|
||||
494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494,
|
||||
0, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, 0,
|
||||
],
|
||||
// ZapfDingbats
|
||||
[
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933,
|
||||
911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537,
|
||||
577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831,
|
||||
923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826,
|
||||
815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762,
|
||||
762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 0,
|
||||
390, 390, 317, 317, 276, 276, 509, 509, 410, 410, 234, 234, 334, 334, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788,
|
||||
788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,
|
||||
788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788,
|
||||
788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834,
|
||||
873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874,
|
||||
0, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918, 0,
|
||||
],
|
||||
];
|
||||
@@ -36,6 +36,9 @@ pub mod write_raster;
|
||||
|
||||
/// Low-level, direct-to-output framing of new classic-xref PDF files.
|
||||
pub mod classic;
|
||||
/// PDF single-byte encodings (ISO 32000-2 Annex D), WinAnsi/Unicode CMap helpers, and Standard-14 metrics.
|
||||
#[cfg(feature = "fonts")]
|
||||
pub mod fonts;
|
||||
|
||||
#[cfg(test)]
|
||||
extern crate self as craft_pdf;
|
||||
|
||||
@@ -52,6 +52,21 @@ pub enum Error {
|
||||
Xml(String),
|
||||
}
|
||||
|
||||
/// Errors returned by presentation model editing helpers.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ModelError {
|
||||
#[error("no slide {0}")]
|
||||
NoSlide(String),
|
||||
#[error("no shape {0}")]
|
||||
NoShape(ShapeId),
|
||||
#[error("no layout {0}")]
|
||||
NoLayout(LayoutId),
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
pub type ModelResult<T> = std::result::Result<T, ModelError>;
|
||||
|
||||
/// What the caller supplies where a file or a presentation leaves something out. The reader asks
|
||||
/// for a master when a file has none it can read, and for the theme of a master that names none;
|
||||
/// the writer for a master when the presentation has none, and for the text styles a master or
|
||||
@@ -112,6 +127,12 @@ pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presenta
|
||||
read::import_checked(bytes, defaults)
|
||||
}
|
||||
|
||||
/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a
|
||||
/// table past the cell cap keeps its leading rows).
|
||||
pub fn import_report(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec<String>, Vec<String>), Error> {
|
||||
read::import_report(bytes, defaults)
|
||||
}
|
||||
|
||||
/// [`import`] with a lower presentation-wide chart point budget, so tests reach the over-budget
|
||||
/// path without a multi-million-point chart.
|
||||
#[doc(hidden)]
|
||||
@@ -688,6 +709,9 @@ pub struct Slide {
|
||||
pub animations: Vec<Animation>,
|
||||
/// Speaker notes.
|
||||
pub notes: TextBody,
|
||||
/// Whether the slide has an associated notes slide even if its text is empty.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub has_notes_slide: bool,
|
||||
pub comments: Vec<Comment>,
|
||||
/// `clrMapOvr`: a colour map replacing the layout's or master's (`bg1`→`dk1`…); None follows
|
||||
/// the layout.
|
||||
@@ -714,6 +738,7 @@ impl Default for Slide {
|
||||
transition: None,
|
||||
animations: vec![],
|
||||
notes: TextBody::default(),
|
||||
has_notes_slide: false,
|
||||
comments: vec![],
|
||||
color_map: None,
|
||||
tags: vec![],
|
||||
|
||||
+31
-2
@@ -58,8 +58,13 @@ pub struct Imp<'a> {
|
||||
/// Whether a part has relationships of its own, by normalized part name: looked up once
|
||||
/// however many embedded objects point at the part.
|
||||
pub has_rels: HashMap<String, bool>,
|
||||
/// Warnings for content cut to fit a limit during import.
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
/// Import warnings kept; a hostile file with many oversized tables adds no more than this.
|
||||
const MAX_IMPORT_WARNINGS: usize = 32;
|
||||
|
||||
impl<'a> Imp<'a> {
|
||||
fn new(pkg: &'a Package, defaults: &'a dyn Defaults, next: u32, chart_points_cap: usize) -> Self {
|
||||
Imp {
|
||||
@@ -82,6 +87,14 @@ impl<'a> Imp<'a> {
|
||||
tag_bytes: 0,
|
||||
tags_capped: false,
|
||||
has_rels: HashMap::new(),
|
||||
warnings: vec![],
|
||||
}
|
||||
}
|
||||
/// Record something the file lost, and log it.
|
||||
pub fn warn(&mut self, msg: String) {
|
||||
log::warn!("pptx: {msg}");
|
||||
if self.warnings.len() < MAX_IMPORT_WARNINGS {
|
||||
self.warnings.push(msg);
|
||||
}
|
||||
}
|
||||
pub fn alloc(&mut self) -> u32 {
|
||||
@@ -392,11 +405,26 @@ pub fn import(bytes: &[u8], defaults: &dyn Defaults) -> Result<Presentation, Err
|
||||
/// [`import`], plus the parts of the slide list the file names but that couldn't be read (a
|
||||
/// missing or truncated slide): those slides are left out, so a caller can say so.
|
||||
pub fn import_checked(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec<String>), Error> {
|
||||
import_with_chart_points(bytes, defaults, chart::MAX_PRESENTATION_CHART_POINTS)
|
||||
import_report(bytes, defaults).map(|(p, lost, _)| (p, lost))
|
||||
}
|
||||
|
||||
/// [`import_checked`], plus warnings for content the file had that was cut to fit a limit (a
|
||||
/// table past the cell cap keeps its leading rows).
|
||||
pub fn import_report(bytes: &[u8], defaults: &dyn Defaults) -> Result<(Presentation, Vec<String>, Vec<String>), Error> {
|
||||
import_report_with_chart_points(bytes, defaults, chart::MAX_PRESENTATION_CHART_POINTS)
|
||||
}
|
||||
|
||||
/// [`import_checked`] with the presentation's chart point budget set (tests lower it).
|
||||
pub(crate) fn import_with_chart_points(bytes: &[u8], defaults: &dyn Defaults, chart_points_cap: usize) -> Result<(Presentation, Vec<String>), Error> {
|
||||
import_report_with_chart_points(bytes, defaults, chart_points_cap).map(|(p, lost, _)| (p, lost))
|
||||
}
|
||||
|
||||
/// [`import_report`] with the presentation's chart point budget set.
|
||||
fn import_report_with_chart_points(
|
||||
bytes: &[u8],
|
||||
defaults: &dyn Defaults,
|
||||
chart_points_cap: usize,
|
||||
) -> Result<(Presentation, Vec<String>, Vec<String>), Error> {
|
||||
let mut lost_slides: Vec<String> = vec![];
|
||||
let pkg = Package::open(bytes)?;
|
||||
let root_rels = pkg.rels("");
|
||||
@@ -438,7 +466,7 @@ pub(crate) fn import_with_chart_points(bytes: &[u8], defaults: &dyn Defaults, ch
|
||||
p.media = std::mem::take(&mut imp.media);
|
||||
p.next_id = imp.next;
|
||||
p.fix_next_id();
|
||||
Ok((p, lost_slides))
|
||||
Ok((p, lost_slides, imp.warnings))
|
||||
}
|
||||
|
||||
/// Masters, layouts and slides to read, in file order and without duplicates: (master paths,
|
||||
@@ -602,6 +630,7 @@ fn read_slides(
|
||||
let mut slide = read_slide(imp, &part, doc, *id, layout);
|
||||
if let Some(notes) = slide_notes(imp, &part, &mut owned_parts) {
|
||||
slide.notes = notes;
|
||||
slide.has_notes_slide = true;
|
||||
}
|
||||
read_slide_comments(pkg, pres_part, &part, &mut slide, &mut owned_parts);
|
||||
file_slide_ids.insert(*file_id, *id);
|
||||
|
||||
@@ -805,6 +805,9 @@ fn table(imp: &mut Imp, part: &Part, tbl: &El) -> Table {
|
||||
let n = t.rows.iter().map(|r| r.cells.len()).max().unwrap_or(0);
|
||||
t.cols = vec![72.0; n];
|
||||
}
|
||||
if t.over_cap() {
|
||||
imp.warn(format!("a table in {} is over {} cells; its last rows were left out", part.name, craft_drawingml::table::MAX_CELLS));
|
||||
}
|
||||
t.normalize();
|
||||
t
|
||||
}
|
||||
|
||||
@@ -458,7 +458,7 @@ struct NotesMasterWrite {
|
||||
fn notes_master_write(p: &Presentation) -> Option<NotesMasterWrite> {
|
||||
let nm = p.notes_master.as_deref();
|
||||
let kept = nm.filter(|m| !m.shapes.is_empty());
|
||||
let has_notes = p.slides.iter().any(|s| !s.notes.is_empty());
|
||||
let has_notes = p.slides.iter().any(|s| !s.notes.is_empty() || s.has_notes_slide);
|
||||
if !has_notes && nm.is_none() {
|
||||
return None;
|
||||
}
|
||||
@@ -694,7 +694,7 @@ pub fn export(p: &Presentation, defaults: &dyn Defaults, main_ct: &str) -> Resul
|
||||
if let Some(lp) = layout_parts.get(&s.layout) {
|
||||
so.rels.add("slideLayout", &craft_opc::relative(&sname, lp), false);
|
||||
}
|
||||
if !s.notes.is_empty() {
|
||||
if !s.notes.is_empty() || s.has_notes_slide {
|
||||
let nname = format!("ppt/notesSlides/notesSlide{}.xml", i + 1);
|
||||
so.rels.add("notesSlide", &craft_opc::relative(&sname, &nname), false);
|
||||
let mut no = Out::new(&nname);
|
||||
@@ -1360,7 +1360,7 @@ fn app_xml(p: &Presentation, application: &str) -> Vec<u8> {
|
||||
.open();
|
||||
w.leaf("Application", &[], application);
|
||||
w.leaf("Slides", &[], &p.slides.len().to_string());
|
||||
w.leaf("Notes", &[], &p.slides.iter().filter(|s| !s.notes.is_empty()).count().to_string());
|
||||
w.leaf("Notes", &[], &p.slides.iter().filter(|s| !s.notes.is_empty() || s.has_notes_slide).count().to_string());
|
||||
w.leaf("HiddenSlides", &[], &p.slides.iter().filter(|s| s.hidden).count().to_string());
|
||||
if !p.props.company.is_empty() {
|
||||
w.leaf("Company", &[], &p.props.company);
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! PostScript token scanner over an in-memory byte slice, tracking the unread whitespace
|
||||
//! boundary for `currentfile` data reads (`read`, `readstring`, filters, `token`, `eexec`).
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Deepest procedure nesting the scanner reads.
|
||||
const MAX_NESTING: usize = 256;
|
||||
|
||||
/// Most bytes an ASCII85 string literal may decode to.
|
||||
const MAX_ASCII85: usize = 1 << 28;
|
||||
|
||||
/// How an immediately evaluated name (`//name`) is prefixed in [`Token::Exec`], until the
|
||||
/// interpreter replaces it.
|
||||
pub const IMMEDIATE: &str = "//";
|
||||
|
||||
/// A scanned PostScript token.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Token {
|
||||
Int(i64),
|
||||
Real(f64),
|
||||
/// A literal name (`/name`).
|
||||
Name(String),
|
||||
/// An executable name (operator, `[`, `]`, `<<`, `>>`, or `//name` prefixed with [`IMMEDIATE`]).
|
||||
Exec(String),
|
||||
/// A byte string (`(...)`, `<...>`, or `<~...~>`).
|
||||
Str(Vec<u8>),
|
||||
/// A procedure (`{ ... }`).
|
||||
Proc(Vec<Token>),
|
||||
}
|
||||
|
||||
/// A finite number parsed from a PostScript numeric token.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Number {
|
||||
Int(i64),
|
||||
Real(f64),
|
||||
}
|
||||
|
||||
/// An error returned by [`Lexer::next`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum LexError {
|
||||
Syntax(String),
|
||||
Limit(&'static str),
|
||||
}
|
||||
|
||||
impl fmt::Display for LexError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Syntax(what) => write!(f, "syntaxerror: {what}"),
|
||||
Self::Limit(msg) => f.write_str(msg),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LexError {}
|
||||
|
||||
/// PostScript byte-slice scanner with `currentfile` data boundary tracking.
|
||||
pub struct Lexer<'a> {
|
||||
src: &'a [u8],
|
||||
pos: usize,
|
||||
/// The whitespace character that ended the last token is still unread (data the program
|
||||
/// reads from itself starts after it).
|
||||
fresh: bool,
|
||||
/// The last object read has immediately evaluated names (`//name`) in it, read as executable
|
||||
/// names starting with [`IMMEDIATE`] for the interpreter to replace by their values.
|
||||
pub immediate: bool,
|
||||
}
|
||||
|
||||
/// Whether `b` is PostScript whitespace.
|
||||
pub fn is_space(b: u8) -> bool {
|
||||
matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b'\x0c' | b'\0')
|
||||
}
|
||||
|
||||
/// Whether `b` is a PostScript delimiter.
|
||||
pub fn is_delim(b: u8) -> bool {
|
||||
matches!(b, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%')
|
||||
}
|
||||
|
||||
fn syntax<T>(what: &str) -> Result<T, LexError> {
|
||||
Err(LexError::Syntax(what.to_string()))
|
||||
}
|
||||
|
||||
impl<'a> Lexer<'a> {
|
||||
/// Create a scanner over `src`.
|
||||
pub fn new(src: &'a [u8]) -> Self {
|
||||
Self { src, pos: 0, fresh: false, immediate: false }
|
||||
}
|
||||
|
||||
/// What is left to read.
|
||||
pub fn rest(&self) -> &'a [u8] {
|
||||
self.src.get(self.pos..).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// What is left to read as data: after the whitespace that ended the last token (a CR LF
|
||||
/// pair counts as one).
|
||||
pub fn data(&mut self) -> &'a [u8] {
|
||||
if std::mem::take(&mut self.fresh) {
|
||||
match self.peek() {
|
||||
Some(b'\r') => {
|
||||
self.pos += 1;
|
||||
if self.peek() == Some(b'\n') {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
Some(b) if is_space(b) => self.pos += 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.rest()
|
||||
}
|
||||
|
||||
/// Skip `n` bytes (the data a filter or `readstring` took).
|
||||
pub fn advance(&mut self, n: usize) {
|
||||
self.fresh = false;
|
||||
self.pos = self.pos.saturating_add(n).min(self.src.len());
|
||||
}
|
||||
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.src.get(self.pos).copied()
|
||||
}
|
||||
|
||||
fn skip_space(&mut self) {
|
||||
while let Some(b) = self.peek() {
|
||||
if is_space(b) {
|
||||
self.pos += 1;
|
||||
} else if b == b'%' {
|
||||
while let Some(c) = self.peek() {
|
||||
if c == b'\n' || c == b'\r' {
|
||||
break;
|
||||
}
|
||||
self.pos += 1;
|
||||
}
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next token at the top level (`None` at the end of the file).
|
||||
#[allow(clippy::should_implement_trait)]
|
||||
pub fn next(&mut self) -> Result<Option<Token>, LexError> {
|
||||
self.immediate = false;
|
||||
let t = self.token(0)?;
|
||||
self.fresh = true;
|
||||
Ok(t)
|
||||
}
|
||||
|
||||
fn token(&mut self, depth: usize) -> Result<Option<Token>, LexError> {
|
||||
self.skip_space();
|
||||
let Some(b) = self.peek() else { return Ok(None) };
|
||||
self.pos += 1;
|
||||
Ok(Some(match b {
|
||||
b'(' => Token::Str(self.string()?),
|
||||
b'<' => self.angle_string()?,
|
||||
b'>' => {
|
||||
if self.peek() != Some(b'>') {
|
||||
return syntax(">");
|
||||
}
|
||||
self.pos += 1;
|
||||
Token::Exec(">>".to_string())
|
||||
}
|
||||
b'[' => Token::Exec("[".to_string()),
|
||||
b']' => Token::Exec("]".to_string()),
|
||||
b'{' => self.proc(depth)?,
|
||||
b'}' | b')' => return syntax(&char::from(b).to_string()),
|
||||
b'/' => self.name(),
|
||||
_ => {
|
||||
self.pos -= 1;
|
||||
let w = self.word();
|
||||
match number(&w) {
|
||||
Some(Number::Int(i)) => Token::Int(i),
|
||||
Some(Number::Real(r)) => Token::Real(r),
|
||||
None => Token::Exec(w),
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
fn angle_string(&mut self) -> Result<Token, LexError> {
|
||||
match self.peek() {
|
||||
Some(b'<') => {
|
||||
self.pos += 1;
|
||||
Ok(Token::Exec("<<".to_string()))
|
||||
}
|
||||
Some(b'~') => {
|
||||
self.pos += 1;
|
||||
Ok(Token::Str(self.ascii85()?))
|
||||
}
|
||||
_ => Ok(Token::Str(self.hex()?)),
|
||||
}
|
||||
}
|
||||
|
||||
fn proc(&mut self, depth: usize) -> Result<Token, LexError> {
|
||||
if depth >= MAX_NESTING {
|
||||
return Err(LexError::Limit("procedures nested too deeply"));
|
||||
}
|
||||
let mut items = vec![];
|
||||
loop {
|
||||
self.skip_space();
|
||||
match self.peek() {
|
||||
None => return syntax("{"),
|
||||
Some(b'}') => {
|
||||
self.pos += 1;
|
||||
break;
|
||||
}
|
||||
_ => match self.token(depth + 1)? {
|
||||
Some(o) => items.push(o),
|
||||
None => return syntax("{"),
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(Token::Proc(items))
|
||||
}
|
||||
|
||||
fn name(&mut self) -> Token {
|
||||
// `//name` stands for the name's value when it is read.
|
||||
let immediate = self.peek() == Some(b'/');
|
||||
if immediate {
|
||||
self.pos += 1;
|
||||
self.immediate = true;
|
||||
}
|
||||
let name = self.word();
|
||||
if immediate { Token::Exec(format!("{IMMEDIATE}{name}")) } else { Token::Name(name) }
|
||||
}
|
||||
|
||||
/// A regular token's characters.
|
||||
fn word(&mut self) -> String {
|
||||
let start = self.pos;
|
||||
while let Some(b) = self.peek() {
|
||||
if is_space(b) || is_delim(b) {
|
||||
break;
|
||||
}
|
||||
self.pos += 1;
|
||||
}
|
||||
String::from_utf8_lossy(self.src.get(start..self.pos).unwrap_or_default()).into_owned()
|
||||
}
|
||||
|
||||
/// A literal string after its `(`.
|
||||
fn string(&mut self) -> Result<Vec<u8>, LexError> {
|
||||
let mut out = vec![];
|
||||
let mut depth = 0usize;
|
||||
loop {
|
||||
let Some(b) = self.peek() else { return syntax("(") };
|
||||
self.pos += 1;
|
||||
match b {
|
||||
b'(' => {
|
||||
depth += 1;
|
||||
out.push(b);
|
||||
}
|
||||
b')' if depth == 0 => return Ok(out),
|
||||
b')' => {
|
||||
depth -= 1;
|
||||
out.push(b);
|
||||
}
|
||||
b'\\' => self.string_escape(&mut out)?,
|
||||
_ => out.push(b),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn string_escape(&mut self, out: &mut Vec<u8>) -> Result<(), LexError> {
|
||||
let Some(e) = self.peek() else { return syntax("(") };
|
||||
self.pos += 1;
|
||||
match e {
|
||||
b'n' => out.push(b'\n'),
|
||||
b'r' => out.push(b'\r'),
|
||||
b't' => out.push(b'\t'),
|
||||
b'b' => out.push(8),
|
||||
b'f' => out.push(12),
|
||||
b'\r' => {
|
||||
if self.peek() == Some(b'\n') {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
b'\n' => {}
|
||||
b'0'..=b'7' => {
|
||||
let mut v = u32::from(e - b'0');
|
||||
for _ in 0..2 {
|
||||
match self.peek() {
|
||||
Some(d @ b'0'..=b'7') => {
|
||||
v = v * 8 + u32::from(d - b'0');
|
||||
self.pos += 1;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
out.push((v & 0xff) as u8);
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A hexadecimal string after its `<`.
|
||||
fn hex(&mut self) -> Result<Vec<u8>, LexError> {
|
||||
let Some(end) = self.rest().iter().position(|b| *b == b'>') else {
|
||||
return syntax("<");
|
||||
};
|
||||
let body = self.rest().get(..end).unwrap_or_default();
|
||||
let Some(out) = hex_decode(body) else {
|
||||
return syntax("<");
|
||||
};
|
||||
self.advance(end + 1);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// An ASCII85 string after its `<~`.
|
||||
fn ascii85(&mut self) -> Result<Vec<u8>, LexError> {
|
||||
let Some(end) = find(self.rest(), b"~>") else {
|
||||
return syntax("<~");
|
||||
};
|
||||
let text = String::from_utf8_lossy(self.rest().get(..end + 2).unwrap_or_default()).into_owned();
|
||||
self.advance(end + 2);
|
||||
let Some(out) = craft_eps::ascii85::decode(text.as_bytes(), MAX_ASCII85) else {
|
||||
return syntax("<~");
|
||||
};
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `needle` first starts in `hay`.
|
||||
pub fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
if needle.is_empty() {
|
||||
return Some(0);
|
||||
}
|
||||
hay.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
/// Hexadecimal digits (whitespace ignored, an odd last digit padded with 0); `None` on others.
|
||||
pub fn hex_decode(body: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut out = Vec::with_capacity(body.len() / 2);
|
||||
let mut high: Option<u8> = None;
|
||||
for &b in body {
|
||||
if is_space(b) {
|
||||
continue;
|
||||
}
|
||||
let v = char::from(b).to_digit(16)? as u8;
|
||||
match high.take() {
|
||||
Some(h) => out.push(h << 4 | v),
|
||||
None => high = Some(v),
|
||||
}
|
||||
}
|
||||
if let Some(h) = high {
|
||||
out.push(h << 4);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// A number token (`12`, `-3.5`, `.5`, `1e-3`, `16#ff`), or `None`.
|
||||
pub fn number(w: &str) -> Option<Number> {
|
||||
let first = w.bytes().next()?;
|
||||
if !(first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.')) {
|
||||
return None;
|
||||
}
|
||||
if let Ok(i) = w.parse::<i64>() {
|
||||
return Some(Number::Int(i));
|
||||
}
|
||||
if let Some((base, digits)) = w.split_once('#') {
|
||||
let base: u32 = base.parse().ok().filter(|b| (2..=36).contains(b))?;
|
||||
// `from_str_radix` accepts a leading sign; a PostScript radix number has digits only.
|
||||
if digits.starts_with(['+', '-']) {
|
||||
return None;
|
||||
}
|
||||
return i64::from_str_radix(digits, base).ok().map(Number::Int);
|
||||
}
|
||||
// Rust reads `inf` and `nan`; PostScript doesn't.
|
||||
if w.bytes().any(|b| b.is_ascii_alphabetic() && !matches!(b, b'e' | b'E')) {
|
||||
return None;
|
||||
}
|
||||
let v: f64 = w.parse().ok()?;
|
||||
v.is_finite().then_some(Number::Real(v))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{LexError, Lexer, Number, Token, find, hex_decode, number};
|
||||
|
||||
#[test]
|
||||
fn radix_number_with_sign_after_hash_is_not_a_number() {
|
||||
assert!(number("16#+ff").is_none());
|
||||
assert!(number("16#-ff").is_none());
|
||||
assert_eq!(number("16#ff"), Some(Number::Int(255)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn currentfile_data_consumes_single_whitespace_or_crlf() {
|
||||
let mut lex = Lexer::new(b"image\r\nDATA");
|
||||
assert_eq!(lex.next(), Ok(Some(Token::Exec("image".into()))));
|
||||
assert_eq!(lex.rest(), b"\r\nDATA");
|
||||
assert_eq!(lex.data(), b"DATA");
|
||||
lex.advance(2);
|
||||
assert_eq!(lex.rest(), b"TA");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_lines_and_eof() {
|
||||
let mut lex = Lexer::new(b"1 2 add");
|
||||
assert_eq!(lex.next(), Ok(Some(Token::Int(1))));
|
||||
assert_eq!(lex.next(), Ok(Some(Token::Int(2))));
|
||||
assert_eq!(lex.next(), Ok(Some(Token::Exec("add".into()))));
|
||||
assert_eq!(lex.next(), Ok(None));
|
||||
assert_eq!(lex.data(), b"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_names_and_procedures() {
|
||||
let mut lex = Lexer::new(b"{ //foo /bar }");
|
||||
assert_eq!(lex.next(), Ok(Some(Token::Proc(vec![Token::Exec("//foo".into()), Token::Name("bar".into())]))));
|
||||
assert!(lex.immediate);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_and_hex_decode() {
|
||||
assert_eq!(find(b"abcdef", b"cd"), Some(2));
|
||||
assert_eq!(find(b"abcdef", b""), Some(0));
|
||||
assert_eq!(find(b"abcdef", b"xy"), None);
|
||||
assert_eq!(hex_decode(b"41 4"), Some(vec![0x41, 0x40]));
|
||||
assert_eq!(hex_decode(b"4g"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unterminated_string_is_syntax_error() {
|
||||
let mut lex = Lexer::new(b"(open");
|
||||
assert_eq!(lex.next(), Err(LexError::Syntax("(".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_does_not_mark_fresh() {
|
||||
let mut lex = Lexer::new(b") rest");
|
||||
assert_eq!(lex.next(), Err(LexError::Syntax(")".into())));
|
||||
assert_eq!(lex.data(), b" rest");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ mod encodings;
|
||||
mod font;
|
||||
mod gstate;
|
||||
mod interp;
|
||||
pub mod lex;
|
||||
mod obj;
|
||||
mod ops;
|
||||
mod pdf;
|
||||
|
||||
@@ -68,6 +68,19 @@ pub fn alternate_spot_colors(data: &[u8]) -> impl ExactSizeIterator<Item = Alter
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode unpadded legacy Pascal channel names (resource 1006).
|
||||
///
|
||||
/// Each name is encoded with [`crate::resources::encode_legacy_name`] (printable ASCII, max 255
|
||||
/// bytes) and prefixed with its 1-byte length without per-string padding.
|
||||
pub fn pascal_names<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for name in names {
|
||||
let legacy = crate::io::encode_legacy_name(name);
|
||||
crate::io::write_pascal(&mut out, &legacy, 1);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -108,4 +121,10 @@ mod tests {
|
||||
bytes[2..4].copy_from_slice(&0u16.to_be_bytes());
|
||||
assert_eq!(alternate_spot_colors(&bytes).len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pascal_names_encodes_unpadded_legacy_strings() {
|
||||
assert_eq!(pascal_names(["Spot Color 1"]), b"\x0cSpot Color 1");
|
||||
assert_eq!(pascal_names(["café", "A\nB"]), b"\x04caf?\x03A?B");
|
||||
}
|
||||
}
|
||||
|
||||
+249
-4
@@ -1,5 +1,8 @@
|
||||
//! Borrowed, merged-only PSD reader that skips layer records and decodes selected planes.
|
||||
use crate::{Head, PsdError, Result};
|
||||
use crate::{Head, HeadView, PsdError, Result};
|
||||
|
||||
mod rows;
|
||||
pub use rows::{ChannelRows, EncodedRow, EncodedRows};
|
||||
|
||||
/// Dimensions in the fixed header fields, for reporting a preflight limit error.
|
||||
/// This does not validate the PSD signature or remaining header.
|
||||
@@ -40,17 +43,83 @@ fn u64_at(bytes: &[u8], at: &mut usize) -> Result<u64> {
|
||||
Ok(u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
|
||||
}
|
||||
|
||||
fn has_merged_transparency(layer: &[u8], version: crate::Version) -> bool {
|
||||
let mut at = 0usize;
|
||||
let info_len = if version.is_psb() { u64_at(layer, &mut at).ok() } else { u32_at(layer, &mut at).ok().map(u64::from) };
|
||||
let Some(info_len) = info_len else { return false };
|
||||
if info_len >= 2 {
|
||||
return layer.get(at..at + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0);
|
||||
}
|
||||
let Ok(info_len) = usize::try_from(info_len) else { return false };
|
||||
let Some(next) = at.checked_add(info_len) else { return false };
|
||||
at = next;
|
||||
let Ok(mask_len) = u32_at(layer, &mut at) else { return false };
|
||||
let Some(next) = at.checked_add(mask_len as usize) else { return false };
|
||||
at = next;
|
||||
while let Some(head) = at.checked_add(12).and_then(|end| layer.get(at..end)) {
|
||||
let sig = &head[..4];
|
||||
let key = &head[4..8];
|
||||
if sig != b"8BIM" && sig != b"8B64" {
|
||||
return false;
|
||||
}
|
||||
let Ok(key_arr): std::result::Result<&[u8; 4], _> = key.try_into() else { return false };
|
||||
let len = if crate::tagged::uses_long_length(version, key_arr) {
|
||||
let Ok(l) = u64_at(layer, &mut { at + 8 }) else { return false };
|
||||
let Ok(l) = usize::try_from(l) else { return false };
|
||||
at += 16;
|
||||
l
|
||||
} else {
|
||||
at += 12;
|
||||
u32::from_be_bytes([head[8], head[9], head[10], head[11]]) as usize
|
||||
};
|
||||
if (key == b"Lr16" || key == b"Lr32") && layer.get(at..at + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0) {
|
||||
return true;
|
||||
}
|
||||
if matches!(key, b"Mtrn" | b"MTrn" | b"Mt16" | b"Mt32") {
|
||||
return true;
|
||||
}
|
||||
// Global tagged blocks pad their data to 4 bytes (per psd-tools and craft-psd).
|
||||
let Some(next) = len.checked_add(3).map(|v| v & !3).and_then(|p| at.checked_add(p)) else { return false };
|
||||
at = next;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
impl<'a> Merged<'a> {
|
||||
/// Open the merged section with a pixel limit. This skips layer records, preserving the ability
|
||||
/// to read a composite when its layer data is not understood. No image planes are allocated.
|
||||
pub fn open(bytes: &'a [u8], max_pixels: u64) -> Result<Self> {
|
||||
Self::check_pixel_limit(bytes, max_pixels)?;
|
||||
Self::from_head(bytes, Head::from_bytes(bytes)?, max_pixels)
|
||||
}
|
||||
|
||||
/// Open the merged section while omitting all image resources, including valid records.
|
||||
///
|
||||
/// This validates the header and declared section boundaries but skips the resource records.
|
||||
/// Callers choose when to use it, for example after detecting damaged resources during a strict
|
||||
/// open. The returned reader borrows the original file and only copies its color-mode data;
|
||||
/// no resource payloads or image planes are allocated.
|
||||
pub fn open_without_resources(bytes: &'a [u8], max_pixels: u64) -> Result<Self> {
|
||||
Self::check_pixel_limit(bytes, max_pixels)?;
|
||||
let view = HeadView::from_bytes(bytes)?;
|
||||
let mut color_mode_data = Vec::new();
|
||||
color_mode_data.try_reserve_exact(view.color_mode_data.len()).map_err(|_| PsdError::OutOfMemory("color-mode data"))?;
|
||||
color_mode_data.extend_from_slice(view.color_mode_data);
|
||||
let head = Head { header: view.header, color_mode_data, resources: Vec::new(), layer_section_offset: view.layer_section_offset };
|
||||
Self::from_head(bytes, head, max_pixels)
|
||||
}
|
||||
|
||||
fn check_pixel_limit(bytes: &[u8], max_pixels: u64) -> Result<()> {
|
||||
// Refuse a declared oversized canvas before copying color-mode data or resources.
|
||||
if let Some((w, h)) = declared_dimensions(bytes)
|
||||
&& u64::from(w) * u64::from(h) > max_pixels
|
||||
{
|
||||
return Err(PsdError::LimitExceeded("pixel count"));
|
||||
}
|
||||
let head = Head::from_bytes(bytes)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn from_head(bytes: &'a [u8], head: Head, max_pixels: u64) -> Result<Self> {
|
||||
let h = &head.header;
|
||||
if u64::from(h.width) * u64::from(h.height) > max_pixels {
|
||||
return Err(PsdError::LimitExceeded("pixel count"));
|
||||
@@ -59,8 +128,7 @@ impl<'a> Merged<'a> {
|
||||
let mut at = usize::try_from(head.layer_section_offset).map_err(|_| PsdError::LimitExceeded("offset"))?;
|
||||
let len = if psb { u64_at(bytes, &mut at)? } else { u64::from(u32_at(bytes, &mut at)?) };
|
||||
let layer = take(bytes, &mut at, usize::try_from(len).map_err(|_| PsdError::LimitExceeded("layer section"))?)?;
|
||||
let offset = if psb { 8 } else { 4 };
|
||||
let transparency = layer.get(offset..offset + 2).is_some_and(|b| i16::from_be_bytes([b[0], b[1]]) < 0);
|
||||
let transparency = has_merged_transparency(layer, h.version);
|
||||
let compression = u16_at(bytes, &mut at)?;
|
||||
Ok(Self { head, transparency, compression, bytes, data_offset: at })
|
||||
}
|
||||
@@ -248,4 +316,181 @@ mod tests {
|
||||
assert_eq!(row, [7, 8, 0, 0]);
|
||||
assert!(unpackbits(&[0x81, 1], &mut row).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_lr16_and_mt16_merged_transparency() {
|
||||
let with_layer = |layer: &[u8]| {
|
||||
let mut b = head(2, 0);
|
||||
b.splice(34..38, (layer.len() as u32).to_be_bytes().iter().copied().chain(layer.iter().copied()));
|
||||
b
|
||||
};
|
||||
let mut lr16 = Vec::new();
|
||||
lr16.extend_from_slice(&0u32.to_be_bytes());
|
||||
lr16.extend_from_slice(&0u32.to_be_bytes());
|
||||
lr16.extend_from_slice(b"8BIMPatt");
|
||||
lr16.extend_from_slice(&6u32.to_be_bytes());
|
||||
lr16.extend_from_slice(&[1, 2, 3, 4, 5, 6, 0, 0]);
|
||||
lr16.extend_from_slice(b"8BIMLr16");
|
||||
lr16.extend_from_slice(&2u32.to_be_bytes());
|
||||
lr16.extend_from_slice(&(-1i16).to_be_bytes());
|
||||
assert!(Merged::open(&with_layer(&lr16), 4).unwrap().transparency);
|
||||
|
||||
let n = lr16.len();
|
||||
lr16[n - 2..].copy_from_slice(&1i16.to_be_bytes());
|
||||
assert!(!Merged::open(&with_layer(&lr16), 4).unwrap().transparency);
|
||||
|
||||
let mut mt16 = vec![0; 8];
|
||||
mt16.extend_from_slice(b"8BIMMt16\0\0\0\0");
|
||||
assert!(Merged::open(&with_layer(&mt16), 4).unwrap().transparency);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_skipping_open_reads_psd_raw_and_psb_packbits_from_original_bytes() {
|
||||
for (version, compression) in [(1, 0), (2, 1)] {
|
||||
let valid_resources = recovery_resource();
|
||||
let mut damaged_resources = valid_resources.clone();
|
||||
damaged_resources.extend_from_slice(b"BAD!");
|
||||
let (bytes, data_offset) = recovery_file(version, compression, &damaged_resources);
|
||||
let (control_bytes, _) = recovery_file(version, compression, &[]);
|
||||
let control = Merged::open(&control_bytes, 4).unwrap();
|
||||
|
||||
assert!(Head::from_bytes(&bytes).is_err());
|
||||
assert!(Merged::open(&bytes, 4).is_err());
|
||||
let recovered = Merged::open_without_resources(&bytes, 4).unwrap();
|
||||
assert!(std::ptr::eq(recovered.bytes, bytes.as_slice()));
|
||||
assert_eq!(recovered.data_offset, data_offset);
|
||||
assert_eq!(recovered.head.header, control.head.header);
|
||||
assert_eq!(recovered.head.color_mode_data, [9, 8]);
|
||||
assert!(recovered.head.resources.is_empty());
|
||||
assert_eq!(recovered.compression, compression);
|
||||
assert!(recovered.transparency);
|
||||
assert_eq!(recovered.transparency, control.transparency);
|
||||
assert_eq!(recovered.read_planes(2).unwrap(), vec![vec![1, 2, 3, 4], vec![5, 6, 7, 8]]);
|
||||
assert_eq!(recovered.read_planes(2).unwrap(), control.read_planes(2).unwrap());
|
||||
recovered.validate_all().unwrap();
|
||||
|
||||
let (valid_bytes, _) = recovery_file(version, compression, &valid_resources);
|
||||
let strict = Merged::open(&valid_bytes, 4).unwrap();
|
||||
assert_eq!(strict.head.resources.len(), 1);
|
||||
assert_eq!(strict.head.resources[0].id, 1039);
|
||||
assert_eq!(strict.head.resources[0].data, [7, 6]);
|
||||
let skipped = Merged::open_without_resources(&valid_bytes, 4).unwrap();
|
||||
assert!(skipped.head.resources.is_empty());
|
||||
assert_eq!(skipped.read_planes(2).unwrap(), strict.read_planes(2).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_skipping_open_ignores_truncated_resource_payload() {
|
||||
for version in [1, 2] {
|
||||
let mut resources = recovery_resource();
|
||||
resources[8..12].copy_from_slice(&100u32.to_be_bytes());
|
||||
let (bytes, _) = recovery_file(version, 0, &resources);
|
||||
assert!(Merged::open(&bytes, 4).is_err());
|
||||
let recovered = Merged::open_without_resources(&bytes, 4).unwrap();
|
||||
assert!(recovered.head.resources.is_empty());
|
||||
assert_eq!(recovered.read_planes(1).unwrap(), vec![vec![1, 2, 3, 4]]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_skipping_open_checks_pixel_limit_before_malformed_head() {
|
||||
let (mut bytes, _) = recovery_file(1, 0, b"BAD!");
|
||||
bytes.truncate(22);
|
||||
bytes[..4].copy_from_slice(b"BAD!");
|
||||
assert!(matches!(Merged::open_without_resources(&bytes, 3), Err(PsdError::LimitExceeded("pixel count"))));
|
||||
assert!(matches!(Merged::open(&bytes, 3), Err(PsdError::LimitExceeded("pixel count"))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_skipping_open_rejects_out_of_bounds_sections_and_tail_framing() {
|
||||
for version in [1, 2] {
|
||||
let (bytes, data_offset) = recovery_file(version, 0, b"BAD!");
|
||||
let mut invalid_header = bytes.clone();
|
||||
invalid_header[..4].copy_from_slice(b"BAD!");
|
||||
assert!(Merged::open_without_resources(&invalid_header, 4).is_err());
|
||||
|
||||
let mut color_outside_file = bytes.clone();
|
||||
color_outside_file[26..30].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(Merged::open_without_resources(&color_outside_file, 4).is_err());
|
||||
let mut resources_outside_file = bytes.clone();
|
||||
resources_outside_file[32..36].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert!(Merged::open_without_resources(&resources_outside_file, 4).is_err());
|
||||
|
||||
let layer_offset = crate::HeadView::from_bytes(&bytes).unwrap().layer_section_offset as usize;
|
||||
let length_width = if version == 2 { 8 } else { 4 };
|
||||
assert!(Merged::open_without_resources(&bytes[..layer_offset + length_width - 1], 4).is_err());
|
||||
let mut layer_outside_file = bytes.clone();
|
||||
layer_outside_file[layer_offset..layer_offset + length_width].fill(0xff);
|
||||
assert!(Merged::open_without_resources(&layer_outside_file, 4).is_err());
|
||||
assert!(Merged::open_without_resources(&bytes[..data_offset - 1], 4).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_skipping_open_preserves_selected_plane_and_full_validation_distinction() {
|
||||
for (version, compression) in [(1, 0), (2, 1)] {
|
||||
let (mut bytes, _) = recovery_file(version, compression, b"BAD!");
|
||||
bytes.truncate(bytes.len() - if compression == 0 { 4 } else { 6 });
|
||||
let recovered = Merged::open_without_resources(&bytes, 4).unwrap();
|
||||
assert_eq!(recovered.read_planes(1).unwrap(), vec![vec![1, 2, 3, 4]]);
|
||||
assert!(recovered.read_planes(2).is_err());
|
||||
assert!(recovered.validate_all().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
fn recovery_resource() -> Vec<u8> {
|
||||
let mut bytes = b"8BIM".to_vec();
|
||||
bytes.extend_from_slice(&1039u16.to_be_bytes());
|
||||
bytes.extend_from_slice(&[0, 0]);
|
||||
bytes.extend_from_slice(&2u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&[7, 6]);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn recovery_file(version: u16, compression: u16, resources: &[u8]) -> (Vec<u8>, usize) {
|
||||
let mut bytes = b"8BPS".to_vec();
|
||||
bytes.extend_from_slice(&version.to_be_bytes());
|
||||
bytes.extend_from_slice(&[0; 6]);
|
||||
bytes.extend_from_slice(&2u16.to_be_bytes());
|
||||
bytes.extend_from_slice(&2u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&2u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&8u16.to_be_bytes());
|
||||
bytes.extend_from_slice(&1u16.to_be_bytes());
|
||||
bytes.extend_from_slice(&2u32.to_be_bytes());
|
||||
bytes.extend_from_slice(&[9, 8]);
|
||||
bytes.extend_from_slice(&(resources.len() as u32).to_be_bytes());
|
||||
bytes.extend_from_slice(resources);
|
||||
let mut layer = Vec::new();
|
||||
if version == 2 {
|
||||
layer.extend_from_slice(&2u64.to_be_bytes());
|
||||
} else {
|
||||
layer.extend_from_slice(&2u32.to_be_bytes());
|
||||
}
|
||||
layer.extend_from_slice(&(-1i16).to_be_bytes());
|
||||
if version == 2 {
|
||||
bytes.extend_from_slice(&(layer.len() as u64).to_be_bytes());
|
||||
} else {
|
||||
bytes.extend_from_slice(&(layer.len() as u32).to_be_bytes());
|
||||
}
|
||||
bytes.extend_from_slice(&layer);
|
||||
bytes.extend_from_slice(&compression.to_be_bytes());
|
||||
let data_offset = bytes.len();
|
||||
if compression == 0 {
|
||||
bytes.extend_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
} else {
|
||||
for _ in 0..4 {
|
||||
if version == 2 {
|
||||
bytes.extend_from_slice(&3u32.to_be_bytes());
|
||||
} else {
|
||||
bytes.extend_from_slice(&3u16.to_be_bytes());
|
||||
}
|
||||
}
|
||||
for row in [[1, 2], [3, 4], [5, 6], [7, 8]] {
|
||||
bytes.push(1);
|
||||
bytes.extend_from_slice(&row);
|
||||
}
|
||||
}
|
||||
(bytes, data_offset)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,284 @@
|
||||
//! Allocation-free access to the selected composite channels, one encoded row at a time.
|
||||
|
||||
use super::{Merged, take};
|
||||
use crate::{PsdError, Result};
|
||||
|
||||
/// Validated locations of the first requested composite channels.
|
||||
///
|
||||
/// This view allocates no plane or row index. Unselected channel payloads need not be present.
|
||||
pub struct EncodedRows<'a> {
|
||||
table: &'a [u8],
|
||||
payload: &'a [u8],
|
||||
entry_bytes: usize,
|
||||
row_bytes: usize,
|
||||
height: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
/// A sequential cursor over one selected channel, without a decoded plane allocation.
|
||||
pub struct ChannelRows<'a> {
|
||||
table: &'a [u8],
|
||||
payload: &'a [u8],
|
||||
entry_bytes: usize,
|
||||
row_bytes: usize,
|
||||
remaining: usize,
|
||||
}
|
||||
|
||||
/// A borrowed raw or PackBits row with its declared decoded length.
|
||||
pub struct EncodedRow<'a> {
|
||||
bytes: &'a [u8],
|
||||
row_bytes: usize,
|
||||
rle: bool,
|
||||
}
|
||||
|
||||
fn row_length(entry: &[u8]) -> Result<usize> {
|
||||
match *entry {
|
||||
[a, b] => Ok(usize::from(u16::from_be_bytes([a, b]))),
|
||||
[a, b, c, d] => usize::try_from(u32::from_be_bytes([a, b, c, d])).map_err(|_| PsdError::LimitExceeded("RLE row size")),
|
||||
_ => Err(PsdError::invalid("RLE row table entry")),
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Merged<'a> {
|
||||
/// Borrow the first `used` raw or PackBits channels for row-at-a-time decoding.
|
||||
///
|
||||
/// Checks the full declared row table and the selected payload extents before returning,
|
||||
/// without allocating. Eight-, sixteen- and thirty-two-bit samples remain big-endian.
|
||||
/// `max_row_bytes` limits one decoded row. RLE packet contents are checked on decoding;
|
||||
/// a short or malformed row is an error, not zero-padded recovery. Existing
|
||||
/// [`read_planes`](Self::read_planes) keeps its tolerant recovery behaviour.
|
||||
pub fn encoded_rows(&self, used: usize, max_row_bytes: usize) -> Result<EncodedRows<'a>> {
|
||||
let h = &self.head.header;
|
||||
let channels = usize::from(h.channels);
|
||||
if used > channels {
|
||||
return Err(PsdError::invalid("too few channels"));
|
||||
}
|
||||
let bpc = match h.depth {
|
||||
8 => 1usize,
|
||||
16 => 2,
|
||||
32 => 4,
|
||||
_ => return Err(PsdError::Unsupported("merged depth".into())),
|
||||
};
|
||||
let width = usize::try_from(h.width).map_err(|_| PsdError::LimitExceeded("row size"))?;
|
||||
let height = usize::try_from(h.height).map_err(|_| PsdError::LimitExceeded("row count"))?;
|
||||
let row_bytes = width.checked_mul(bpc).ok_or(PsdError::LimitExceeded("row size"))?;
|
||||
if row_bytes > max_row_bytes || row_bytes as u64 > crate::compression::MAX_DECODED_BYTES {
|
||||
return Err(PsdError::LimitExceeded("merged row size"));
|
||||
}
|
||||
let mut at = self.data_offset;
|
||||
let (table, entry_bytes, payload_bytes) = match self.compression {
|
||||
0 => {
|
||||
let len = used.checked_mul(height).and_then(|n| n.checked_mul(row_bytes)).ok_or(PsdError::LimitExceeded("merged data"))?;
|
||||
(&[][..], 0, len)
|
||||
}
|
||||
1 => {
|
||||
let entry = if h.version.is_psb() { 4 } else { 2 };
|
||||
// Even when only the first channel is requested, every declared row-length
|
||||
// entry precedes the payload. Skipping only selected entries reads table bytes.
|
||||
let table_len = channels.checked_mul(height).and_then(|n| n.checked_mul(entry)).ok_or(PsdError::LimitExceeded("row table"))?;
|
||||
let full_table = take(self.bytes, &mut at, table_len)?;
|
||||
let selected_len = used.checked_mul(height).and_then(|n| n.checked_mul(entry)).ok_or(PsdError::LimitExceeded("row table"))?;
|
||||
let table = full_table.get(..selected_len).ok_or_else(|| PsdError::invalid("row table"))?;
|
||||
let minimum = row_bytes.div_ceil(128).checked_mul(2).ok_or(PsdError::LimitExceeded("row size"))?;
|
||||
let mut total = 0usize;
|
||||
for entry in table.chunks_exact(entry) {
|
||||
let len = row_length(entry)?;
|
||||
// Reject impossible expansion before callers allocate the final image.
|
||||
if len < minimum {
|
||||
return Err(PsdError::invalid("RLE row too short for its width"));
|
||||
}
|
||||
total = total.checked_add(len).ok_or(PsdError::LimitExceeded("merged data"))?;
|
||||
}
|
||||
(table, entry, total)
|
||||
}
|
||||
_ => return Err(PsdError::Unsupported("merged compression".into())),
|
||||
};
|
||||
let payload = take(self.bytes, &mut at, payload_bytes)?;
|
||||
Ok(EncodedRows { table, payload, entry_bytes, row_bytes, height, used })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> EncodedRows<'a> {
|
||||
/// Number of decoded bytes in each row.
|
||||
pub fn row_bytes(&self) -> usize {
|
||||
self.row_bytes
|
||||
}
|
||||
|
||||
/// Cursor for a selected channel. RLE setup scans preceding row lengths, without allocating.
|
||||
pub fn channel(&self, channel: usize) -> Result<ChannelRows<'a>> {
|
||||
if channel >= self.used {
|
||||
return Err(PsdError::invalid("channel was not selected"));
|
||||
}
|
||||
let first = channel.checked_mul(self.height).ok_or(PsdError::LimitExceeded("row count"))?;
|
||||
let (table, offset) = if self.entry_bytes == 0 {
|
||||
(&[][..], first.checked_mul(self.row_bytes).ok_or(PsdError::LimitExceeded("channel offset"))?)
|
||||
} else {
|
||||
let start = first.checked_mul(self.entry_bytes).ok_or(PsdError::LimitExceeded("row table"))?;
|
||||
let before = self.table.get(..start).ok_or_else(|| PsdError::invalid("row table"))?;
|
||||
let mut offset = 0usize;
|
||||
for entry in before.chunks_exact(self.entry_bytes) {
|
||||
offset = offset.checked_add(row_length(entry)?).ok_or(PsdError::LimitExceeded("channel offset"))?;
|
||||
}
|
||||
(self.table.get(start..).ok_or_else(|| PsdError::invalid("row table"))?, offset)
|
||||
};
|
||||
let payload = self.payload.get(offset..).ok_or_else(|| PsdError::invalid("channel offset"))?;
|
||||
Ok(ChannelRows { table, payload, entry_bytes: self.entry_bytes, row_bytes: self.row_bytes, remaining: self.height })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ChannelRows<'a> {
|
||||
/// Read the next encoded row, or `None` after the declared channel height.
|
||||
pub fn next_row(&mut self) -> Result<Option<EncodedRow<'a>>> {
|
||||
if self.remaining == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let len = if self.entry_bytes == 0 {
|
||||
self.row_bytes
|
||||
} else {
|
||||
let entry = self.table.get(..self.entry_bytes).ok_or_else(|| PsdError::invalid("row table"))?;
|
||||
row_length(entry)?
|
||||
};
|
||||
let bytes = self.payload.get(..len).ok_or_else(|| PsdError::invalid("truncated row"))?;
|
||||
self.payload = self.payload.get(len..).ok_or_else(|| PsdError::invalid("truncated row"))?;
|
||||
if self.entry_bytes != 0 {
|
||||
self.table = self.table.get(self.entry_bytes..).ok_or_else(|| PsdError::invalid("row table"))?;
|
||||
}
|
||||
self.remaining -= 1;
|
||||
Ok(Some(EncodedRow { bytes, row_bytes: self.row_bytes, rle: self.entry_bytes != 0 }))
|
||||
}
|
||||
}
|
||||
|
||||
impl EncodedRow<'_> {
|
||||
/// Decode into exactly one row of caller-owned storage, without allocating.
|
||||
///
|
||||
/// Truncated PackBits packets and underfilled/overfilled rows are errors. Bytes after a
|
||||
/// complete row remain tolerated, matching [`crate::compression::packbits::decode_to_slice`].
|
||||
/// On error, the output may contain a partially decoded prefix.
|
||||
pub fn decode_to_slice(&self, output: &mut [u8]) -> Result<()> {
|
||||
if output.len() != self.row_bytes {
|
||||
return Err(PsdError::invalid("decoded row has wrong length"));
|
||||
}
|
||||
if self.rle {
|
||||
crate::compression::packbits::decode_to_slice(self.bytes, output)
|
||||
} else {
|
||||
output.copy_from_slice(self.bytes);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn file(psb: bool, depth: u16, channels: u16, height: u32, compression: u16) -> Vec<u8> {
|
||||
let mut b = b"8BPS".to_vec();
|
||||
b.extend_from_slice(&(if psb { 2u16 } else { 1 }).to_be_bytes());
|
||||
b.extend_from_slice(&[0; 6]);
|
||||
b.extend_from_slice(&channels.to_be_bytes());
|
||||
b.extend_from_slice(&height.to_be_bytes());
|
||||
b.extend_from_slice(&2u32.to_be_bytes());
|
||||
b.extend_from_slice(&depth.to_be_bytes());
|
||||
b.extend_from_slice(&1u16.to_be_bytes());
|
||||
b.extend_from_slice(&[0; 8]);
|
||||
b.extend(std::iter::repeat_n(0, if psb { 8 } else { 4 }));
|
||||
b.extend_from_slice(&compression.to_be_bytes());
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_rows_skip_full_table_and_allow_missing_spot_payload() {
|
||||
for psb in [false, true] {
|
||||
for depth in [8, 16, 32] {
|
||||
let row_bytes = 2 * usize::from(depth / 8);
|
||||
let mut b = file(psb, depth, 3, 2, 1);
|
||||
for _ in 0..6 {
|
||||
if psb {
|
||||
b.extend_from_slice(&2u32.to_be_bytes());
|
||||
} else {
|
||||
b.extend_from_slice(&2u16.to_be_bytes());
|
||||
}
|
||||
}
|
||||
for value in 1..=4 {
|
||||
b.extend_from_slice(&[(1i16 - row_bytes as i16) as u8, value]);
|
||||
}
|
||||
let merged = Merged::open(&b, 4).unwrap();
|
||||
let rows = merged.encoded_rows(2, row_bytes).unwrap();
|
||||
assert_eq!(rows.row_bytes(), row_bytes);
|
||||
assert!(rows.channel(2).is_err());
|
||||
for c in 0..2 {
|
||||
let mut channel = rows.channel(c).unwrap();
|
||||
for y in 0..2 {
|
||||
let mut out = vec![0; row_bytes];
|
||||
channel.next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap();
|
||||
assert_eq!(out, vec![(c * 2 + y + 1) as u8; row_bytes]);
|
||||
}
|
||||
assert!(channel.next_row().unwrap().is_none());
|
||||
}
|
||||
assert!(merged.encoded_rows(3, row_bytes).is_err());
|
||||
assert!(merged.encoded_rows(2, row_bytes - 1).is_err());
|
||||
assert!(merged.encoded_rows(4, row_bytes).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_rows_are_borrowed_and_require_exact_output_length() {
|
||||
let mut b = file(false, 16, 2, 2, 0);
|
||||
b.extend(0..16);
|
||||
let merged = Merged::open(&b, 4).unwrap();
|
||||
let rows = merged.encoded_rows(2, 4).unwrap();
|
||||
let mut channel = rows.channel(1).unwrap();
|
||||
let row = channel.next_row().unwrap().unwrap();
|
||||
assert!(row.decode_to_slice(&mut [0; 3]).is_err());
|
||||
let mut out = [0; 4];
|
||||
row.decode_to_slice(&mut out).unwrap();
|
||||
assert_eq!(out, [8, 9, 10, 11]);
|
||||
channel.next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap();
|
||||
assert_eq!(out, [12, 13, 14, 15]);
|
||||
assert!(channel.next_row().unwrap().is_none());
|
||||
b.pop();
|
||||
assert!(Merged::open(&b, 4).unwrap().encoded_rows(2, 4).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_rows_reject_short_packets_but_keep_trailing_bytes_and_recovery() {
|
||||
for encoded in [&[3, 7, 8][..], &[0, 7, 128], &[255, 7, 255], &[252, 7]] {
|
||||
let mut b = file(false, 16, 1, 1, 1);
|
||||
b.extend_from_slice(&(encoded.len() as u16).to_be_bytes());
|
||||
b.extend_from_slice(encoded);
|
||||
let merged = Merged::open(&b, 2).unwrap();
|
||||
let rows = merged.encoded_rows(1, 4).unwrap();
|
||||
let row = rows.channel(0).unwrap().next_row().unwrap().unwrap();
|
||||
assert!(row.decode_to_slice(&mut [0; 4]).is_err(), "{encoded:?}");
|
||||
}
|
||||
let mut b = file(false, 16, 1, 1, 1);
|
||||
b.extend_from_slice(&3u16.to_be_bytes());
|
||||
b.extend_from_slice(&[253, 7, 127]);
|
||||
let merged = Merged::open(&b, 2).unwrap();
|
||||
let rows = merged.encoded_rows(1, 4).unwrap();
|
||||
let mut out = [0; 4];
|
||||
rows.channel(0).unwrap().next_row().unwrap().unwrap().decode_to_slice(&mut out).unwrap();
|
||||
assert_eq!(out, [7; 4]);
|
||||
b.truncate(b.len() - 3);
|
||||
b.extend_from_slice(&[3, 7, 8]);
|
||||
let merged = Merged::open(&b, 2).unwrap();
|
||||
assert_eq!(merged.read_planes(1).unwrap(), vec![vec![7, 8, 0, 0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_incomplete_table_payload_and_impossible_expansion_before_output() {
|
||||
let mut b = file(false, 16, 2, 1, 1);
|
||||
b.extend_from_slice(&2u16.to_be_bytes());
|
||||
assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err());
|
||||
b.extend_from_slice(&2u16.to_be_bytes());
|
||||
b.extend_from_slice(&[253]);
|
||||
assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err());
|
||||
b.push(7);
|
||||
assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_ok());
|
||||
let mut b = file(false, 16, 1, 1, 1);
|
||||
b.extend_from_slice(&1u16.to_be_bytes());
|
||||
b.push(128);
|
||||
assert!(Merged::open(&b, 2).unwrap().encoded_rows(1, 4).is_err());
|
||||
}
|
||||
}
|
||||
@@ -252,6 +252,24 @@ impl VectorMaskBlock {
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the raw Pascal-string path name bytes from a Clipping Path Name resource (2999).
|
||||
///
|
||||
/// Returns `None` if the resource is empty or truncated before the declared name length.
|
||||
pub fn clipping_path_name(data: &[u8]) -> Option<&[u8]> {
|
||||
let len = usize::from(*data.first()?);
|
||||
data.get(1..1 + len)
|
||||
}
|
||||
|
||||
/// Encode a Clipping Path Name resource (2999): legacy Pascal name followed by 16.16 unsigned
|
||||
/// fixed-point flatness.
|
||||
pub fn clipping_path_resource(name: &str, flatness: f32) -> Vec<u8> {
|
||||
let legacy = crate::io::encode_legacy_name(name);
|
||||
let mut out = Vec::with_capacity(1 + legacy.len() + 4);
|
||||
crate::io::write_pascal(&mut out, &legacy, 1);
|
||||
out.extend_from_slice(&((flatness.max(0.0) * 65536.0) as u32).to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -339,4 +357,13 @@ mod tests {
|
||||
assert_eq!(s.len(), 2);
|
||||
assert_eq!(s[0].knots.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipping_path_resource_roundtrip_and_truncation() {
|
||||
let bytes = clipping_path_resource("Outline", 1.5);
|
||||
assert_eq!(bytes, b"\x07Outline\x00\x01\x80\x00");
|
||||
assert_eq!(clipping_path_name(&bytes), Some(b"Outline".as_slice()));
|
||||
assert_eq!(clipping_path_name(&[]), None);
|
||||
assert_eq!(clipping_path_name(&[5, b'a', b'b']), None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,10 +8,14 @@ use crate::io::{Reader, WriteExt, write_pascal};
|
||||
pub mod ids {
|
||||
/// Resolution info (`ResolutionInfo` structure).
|
||||
pub const RESOLUTION_INFO: u16 = 1005;
|
||||
/// Alpha channel names as unpadded Pascal strings.
|
||||
pub const ALPHA_NAMES: u16 = 1006;
|
||||
/// Target layer index.
|
||||
pub const LAYER_STATE: u16 = 1024;
|
||||
/// Layer group ids (one u16 per layer).
|
||||
pub const LAYER_GROUP_INFO: u16 = 1026;
|
||||
/// Grid and guides (legacy v1).
|
||||
pub const GUIDES: u16 = 1032;
|
||||
/// Legacy (Photoshop 4) thumbnail, BGR.
|
||||
pub const THUMBNAIL_PS4: u16 = 1033;
|
||||
/// Thumbnail (JFIF).
|
||||
@@ -20,6 +24,8 @@ pub mod ids {
|
||||
pub const GLOBAL_ANGLE: u16 = 1037;
|
||||
/// ICC profile.
|
||||
pub const ICC_PROFILE: u16 = 1039;
|
||||
/// Unicode alpha channel names.
|
||||
pub const UNICODE_ALPHA_NAMES: u16 = 1045;
|
||||
/// Global altitude.
|
||||
pub const GLOBAL_ALTITUDE: u16 = 1049;
|
||||
/// Version info (has real merged data flag).
|
||||
@@ -32,6 +38,14 @@ pub mod ids {
|
||||
pub const TIMELINE_INFO: u16 = 1075;
|
||||
/// Selected layer ids (`u16` count followed by `u32` ids).
|
||||
pub const LAYER_SELECTION_IDS: u16 = 1069;
|
||||
/// Clipping path name and flatness.
|
||||
pub const CLIPPING_PATH: u16 = 2999;
|
||||
}
|
||||
|
||||
/// Encode a name for a legacy Pascal field: printable ASCII up to 255 bytes, with other
|
||||
/// characters replaced by `?`.
|
||||
pub fn encode_legacy_name(s: &str) -> Vec<u8> {
|
||||
crate::io::encode_legacy_name(s)
|
||||
}
|
||||
|
||||
/// One image resource block.
|
||||
|
||||
@@ -24,6 +24,20 @@ pub fn records(mut data: &[u8]) -> impl Iterator<Item = &[u8]> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode counted NUL-terminated big-endian UTF-16 name records (resource 1045).
|
||||
pub fn write<'a>(names: impl IntoIterator<Item = &'a str>) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
for name in names {
|
||||
let count = name.encode_utf16().count().saturating_add(1);
|
||||
let count_u32 = u32::try_from(count).unwrap_or(u32::MAX);
|
||||
out.extend_from_slice(&count_u32.to_be_bytes());
|
||||
for unit in name.encode_utf16().take(count_u32 as usize - 1).chain(std::iter::once(0)) {
|
||||
out.extend_from_slice(&unit.to_be_bytes());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -51,4 +65,13 @@ mod tests {
|
||||
assert_eq!(records(&first[..end]).count(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_roundtrips_with_nul_terminator() {
|
||||
let bytes = write(["Alpha 1", "café"]);
|
||||
let decoded: Vec<_> = records(&bytes).collect();
|
||||
assert_eq!(decoded.len(), 2);
|
||||
assert_eq!(decoded[0], [0, b'A', 0, b'l', 0, b'p', 0, b'h', 0, b'a', 0, b' ', 0, b'1', 0, 0]);
|
||||
assert_eq!(decoded[1], [0, b'c', 0, b'a', 0, b'f', 0, 0xe9, 0, 0]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,3 +216,59 @@ decode bit-exactly; lossy tiles are made with `jpeg-encoder`, JPEG XL tiles with
|
||||
(tests only). Hostile input: every truncation of each sample, byte mutations across the
|
||||
header, 400 random mutations per property, random TIFF-like, lossless-JPEG, opcode-list and CIFF
|
||||
bytes, and a test per limit.
|
||||
|
||||
## Decoder comparison reports
|
||||
|
||||
The native `decode_report` example records the decoded sensor samples and selected metadata for an
|
||||
explicit, ordered list of local files. It reads one regular file at a time, accepts at most 512 MiB
|
||||
of encoded bytes per file, and uses `Limits::default()` for decoding.
|
||||
|
||||
```sh
|
||||
cargo run --quiet --locked --release -p craft-raw --example decode_report -- fixture-a.dng fixture-b.nef > report.tsv
|
||||
```
|
||||
|
||||
Use shell redirection that preserves native stdout bytes. The report is UTF-8 TSV with LF line
|
||||
endings, a header, and one row per argument, indexed from 1. Schema version 1 has these columns in
|
||||
this order.
|
||||
|
||||
```text
|
||||
schema input status format sample_type sample_count sensor_sha256 width height cpp bits cfa active_area crop orientation baseline_exposure_bits
|
||||
```
|
||||
|
||||
`format` is a fixed lowercase decoder label, such as `dng` or `cfa_tiff`. `sample_type` is `u16` or
|
||||
`f32`. `sensor_sha256` hashes the complete decoded sample sequence (`RawImage::data`), encoding
|
||||
each integer as two little-endian bytes and each float's IEEE 754 bits as four little-endian bytes.
|
||||
The digest is 64 lowercase hexadecimal digits. It reflects any mapping the decoder has already
|
||||
applied, such as a DNG `LinearizationTable`, so two stored codes that map to the same value give the
|
||||
same digest. Shape and metadata have their own columns, so an orientation change
|
||||
can be distinguished from a sample change.
|
||||
|
||||
`cfa` is `width,height,origin_x,origin_y:pattern`, where the pattern is a comma-separated row-major
|
||||
sequence. It is empty for images without a CFA. Active area and crop are `x,y,width,height`, with
|
||||
crop coordinates relative to the active area. Orientation is the Exif integer code, and baseline
|
||||
exposure is the `f64` bit pattern as 16 lowercase hexadecimal digits.
|
||||
|
||||
Each row's status is `ok`, `read_error`, `input_limit`, `not_raw`, `unsupported`, `corrupt`,
|
||||
`decode_limit`, or `tiff_error`. `input_limit` means the encoded-byte cap was exceeded.
|
||||
`decode_limit` covers RAW and TIFF decoder limits. A failed input has empty fields after `status`,
|
||||
and processing continues. The report contains input ordinals, with paths and free-form diagnostics
|
||||
omitted. A completed batch exits successfully even when inputs fail. No arguments or a report
|
||||
write or flush failure produces a nonzero exit and a concise diagnostic on stderr.
|
||||
|
||||
To compare two pinned decoder revisions, use separate clean checkouts and keep the example source,
|
||||
enabled features, and ordered fixture list identical. If a revision predates the example, copy both
|
||||
`examples/decode_report/main.rs` and `examples/decode_report/report.rs` at the same relative paths
|
||||
under that checkout's `crates/raw/` directory. The example uses the crate's existing `sha2` dev
|
||||
dependency. It builds on `main` from
|
||||
[`ecee6933`](https://github.com/storytold/craft-libs/commit/ecee693322c27acdbcafed4b57066356404e8378)
|
||||
(#1171, 2026-11-13) onwards, the first revision whose `Cfa` has `origin_x` and `origin_y`. Older
|
||||
revisions fail to build it. Build and save one report from each checkout, then compare them.
|
||||
|
||||
```sh
|
||||
git diff --no-index -- before.tsv after.tsv
|
||||
```
|
||||
|
||||
Repeat on the same revision to check deterministic output. Record both decoder revisions, the
|
||||
example source revision, enabled features, fixture checksums and order with the reports. A diff
|
||||
exit status of 1 indicates differing reports. Inspect the status, sample digest, shape and metadata
|
||||
columns to identify the change.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Report the decoded samples and selected metadata of explicitly supplied RAW files.
|
||||
//! `cargo run --locked -p craft-raw --example decode_report -- <file> [<file> ...]`
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod report;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() -> std::process::ExitCode {
|
||||
use std::io::{self, Write};
|
||||
use std::process::ExitCode;
|
||||
|
||||
let stdout = io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
match report::run(std::env::args_os().skip(1), &mut out, report::MAX_INPUT_BYTES, &craft_raw::Limits::default()) {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(error) => {
|
||||
let stderr = io::stderr();
|
||||
let mut err = stderr.lock();
|
||||
match error {
|
||||
report::RunError::Usage => {
|
||||
let _ = writeln!(err, "usage: decode_report <file> [<file> ...]");
|
||||
}
|
||||
report::RunError::Output(error) => {
|
||||
let _ = writeln!(err, "decode_report: report output failed ({:?})", error.kind());
|
||||
}
|
||||
}
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn main() {}
|
||||
@@ -0,0 +1,154 @@
|
||||
use std::ffi::OsString;
|
||||
use std::fs::{self, File};
|
||||
use std::io::{self, Read, Write};
|
||||
use std::path::Path;
|
||||
|
||||
use craft_raw::{Limits, RawData, RawError, RawFormat, RawImage, Rect};
|
||||
use craft_tiff::TiffError;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub(super) const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024;
|
||||
const SCHEMA: u8 = 1;
|
||||
const HEADER: &str = "schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\tactive_area\tcrop\torientation\tbaseline_exposure_bits";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum RunError {
|
||||
Usage,
|
||||
Output(io::Error),
|
||||
}
|
||||
|
||||
pub(super) fn run(paths: impl IntoIterator<Item = OsString>, out: &mut impl Write, max_input_bytes: u64, limits: &Limits) -> Result<(), RunError> {
|
||||
let mut paths = paths.into_iter().peekable();
|
||||
if paths.peek().is_none() {
|
||||
return Err(RunError::Usage);
|
||||
}
|
||||
writeln!(out, "{HEADER}").map_err(RunError::Output)?;
|
||||
for (index, path) in paths.enumerate() {
|
||||
let input = index + 1;
|
||||
let result = read_input(Path::new(&path), max_input_bytes)
|
||||
.map_err(|failure| match failure {
|
||||
InputFailure::Read => "read_error",
|
||||
InputFailure::Limit => "input_limit",
|
||||
})
|
||||
.and_then(|bytes| craft_raw::decode_with(&bytes, limits).map_err(decode_status));
|
||||
match result {
|
||||
Ok(raw) => write_success(out, input, &raw),
|
||||
Err(status) => write_failure(out, input, status),
|
||||
}
|
||||
.map_err(RunError::Output)?;
|
||||
}
|
||||
out.flush().map_err(RunError::Output)
|
||||
}
|
||||
|
||||
enum InputFailure {
|
||||
Read,
|
||||
Limit,
|
||||
}
|
||||
|
||||
fn read_input(path: &Path, max_input_bytes: u64) -> Result<Vec<u8>, InputFailure> {
|
||||
// Reject non-regular paths before opening, and check the opened file again.
|
||||
check_input(&fs::metadata(path).map_err(|_| InputFailure::Read)?, max_input_bytes)?;
|
||||
let file = File::open(path).map_err(|_| InputFailure::Read)?;
|
||||
check_input(&file.metadata().map_err(|_| InputFailure::Read)?, max_input_bytes)?;
|
||||
let mut bytes = Vec::new();
|
||||
// A file may grow after the metadata check. Read at most one extra byte to detect it.
|
||||
file.take(max_input_bytes.saturating_add(1)).read_to_end(&mut bytes).map_err(|_| InputFailure::Read)?;
|
||||
if bytes.len() as u64 > max_input_bytes {
|
||||
return Err(InputFailure::Limit);
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn check_input(metadata: &fs::Metadata, max_input_bytes: u64) -> Result<(), InputFailure> {
|
||||
if !metadata.is_file() {
|
||||
return Err(InputFailure::Read);
|
||||
}
|
||||
if metadata.len() > max_input_bytes {
|
||||
return Err(InputFailure::Limit);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_status(error: RawError) -> &'static str {
|
||||
match error {
|
||||
RawError::NotRaw => "not_raw",
|
||||
RawError::Unsupported(_) => "unsupported",
|
||||
RawError::Corrupt(_) => "corrupt",
|
||||
RawError::Limit(_) | RawError::Tiff(TiffError::Limit(_)) => "decode_limit",
|
||||
RawError::Tiff(_) => "tiff_error",
|
||||
}
|
||||
}
|
||||
|
||||
fn write_failure(out: &mut impl Write, input: usize, status: &str) -> io::Result<()> {
|
||||
// Keep all 13 success-only fields present and empty.
|
||||
writeln!(out, "{SCHEMA}\t{input}\t{status}\t\t\t\t\t\t\t\t\t\t\t\t\t")
|
||||
}
|
||||
|
||||
fn write_success(out: &mut impl Write, input: usize, raw: &RawImage) -> io::Result<()> {
|
||||
let mut hash = Sha256::new();
|
||||
let (sample_type, count) = match &raw.data {
|
||||
RawData::U16(samples) => {
|
||||
for sample in samples {
|
||||
hash.update(sample.to_le_bytes());
|
||||
}
|
||||
("u16", samples.len())
|
||||
}
|
||||
RawData::F32(samples) => {
|
||||
for sample in samples {
|
||||
hash.update(sample.to_bits().to_le_bytes());
|
||||
}
|
||||
("f32", samples.len())
|
||||
}
|
||||
};
|
||||
let digest = hash.finalize();
|
||||
write!(
|
||||
out,
|
||||
"{SCHEMA}\t{input}\tok\t{}\t{sample_type}\t{count}\t{digest:x}\t{}\t{}\t{}\t{}\t",
|
||||
format_label(raw.format),
|
||||
raw.width,
|
||||
raw.height,
|
||||
raw.cpp,
|
||||
raw.bits,
|
||||
)?;
|
||||
if let Some(cfa) = &raw.cfa {
|
||||
write!(out, "{},{},{},{}:", cfa.width, cfa.height, cfa.origin_x, cfa.origin_y)?;
|
||||
let mut pattern = cfa.pattern.iter();
|
||||
if let Some(first) = pattern.next() {
|
||||
write!(out, "{first}")?;
|
||||
for channel in pattern {
|
||||
write!(out, ",{channel}")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
write_rect(out, raw.active_area)?;
|
||||
write_rect(out, raw.crop)?;
|
||||
writeln!(out, "\t{}\t{:016x}", raw.orientation.to_exif(), raw.color.baseline_exposure.to_bits())
|
||||
}
|
||||
|
||||
fn write_rect(out: &mut impl Write, rect: Rect) -> io::Result<()> {
|
||||
write!(out, "\t{},{},{},{}", rect.x, rect.y, rect.width, rect.height)
|
||||
}
|
||||
|
||||
fn format_label(format: RawFormat) -> &'static str {
|
||||
match format {
|
||||
RawFormat::Dng => "dng",
|
||||
RawFormat::Cr2 => "cr2",
|
||||
RawFormat::Cr3 => "cr3",
|
||||
RawFormat::Nef => "nef",
|
||||
RawFormat::Nrw => "nrw",
|
||||
RawFormat::Arw => "arw",
|
||||
RawFormat::Raf => "raf",
|
||||
RawFormat::Orf => "orf",
|
||||
RawFormat::Rw2 => "rw2",
|
||||
RawFormat::Pef => "pef",
|
||||
RawFormat::Srw => "srw",
|
||||
RawFormat::Crw => "crw",
|
||||
RawFormat::Mrw => "mrw",
|
||||
RawFormat::X3f => "x3f",
|
||||
RawFormat::CfaTiff => "cfa_tiff",
|
||||
RawFormat::KodakDcs => "kodak_dcs",
|
||||
RawFormat::Erf => "erf",
|
||||
RawFormat::Mef => "mef",
|
||||
RawFormat::OtherTiff => "other_tiff",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
use super::dng::{base_ifd, dng, synthetic};
|
||||
use craft_raw::{BlackLevel, Cfa, DngCompression, DngWriteOptions, Limits, Orientation, RawData, RawImage, write_dng};
|
||||
use craft_tiff::{ByteOrder, ImageData, Value, tags};
|
||||
use std::ffi::OsString;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[path = "../../examples/decode_report/report.rs"]
|
||||
mod report;
|
||||
|
||||
const HEADER: &str = concat!(
|
||||
"schema\tinput\tstatus\tformat\tsample_type\tsample_count\tsensor_sha256\twidth\theight\tcpp\tbits\tcfa\t",
|
||||
"active_area\tcrop\torientation\tbaseline_exposure_bits\n",
|
||||
);
|
||||
|
||||
struct FixtureDir(PathBuf);
|
||||
|
||||
impl FixtureDir {
|
||||
fn new(test: &str) -> Self {
|
||||
let root = Path::new(env!("CARGO_TARGET_TMPDIR"));
|
||||
for attempt in 0..1000 {
|
||||
let path = root.join(format!("decode-report-{test}-{}-{attempt}", std::process::id()));
|
||||
// Only clean up a directory this test created, even if a process ID was reused.
|
||||
match std::fs::create_dir(&path) {
|
||||
Ok(()) => return Self(path),
|
||||
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
|
||||
Err(error) => panic!("create fixture directory {}: {error}", path.display()),
|
||||
}
|
||||
}
|
||||
panic!("no free fixture directory for {test}");
|
||||
}
|
||||
|
||||
fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FixtureDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn integer_raw() -> RawImage {
|
||||
let mut raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1);
|
||||
raw.data = RawData::U16((256..512).collect());
|
||||
raw.color.baseline_exposure = 0.5;
|
||||
raw
|
||||
}
|
||||
|
||||
fn float_raw() -> RawImage {
|
||||
let mut raw = synthetic(16, 16, None, 3);
|
||||
raw.data = RawData::F32((0..16 * 16 * 3).map(|i| (i % 16) as f32 / 16.0).collect());
|
||||
raw.black = BlackLevel::uniform(0.0);
|
||||
raw.white = vec![1.0];
|
||||
raw.color.baseline_exposure = 0.5;
|
||||
raw
|
||||
}
|
||||
|
||||
fn write_fixture(dir: &Path, name: &str, raw: &RawImage, order: ByteOrder) -> OsString {
|
||||
let bytes = write_dng(raw, &DngWriteOptions { compression: DngCompression::Uncompressed, order, ..Default::default() }).unwrap();
|
||||
write_bytes(dir, name, &bytes)
|
||||
}
|
||||
|
||||
fn write_bytes(dir: &Path, name: &str, bytes: &[u8]) -> OsString {
|
||||
let path = dir.join(name);
|
||||
std::fs::write(&path, bytes).unwrap();
|
||||
path.into_os_string()
|
||||
}
|
||||
|
||||
fn run_report(paths: &[OsString], max_input_bytes: u64, limits: &Limits) -> Vec<u8> {
|
||||
let mut output = Vec::new();
|
||||
assert!(report::run(paths.iter().cloned(), &mut output, max_input_bytes, limits).is_ok());
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_exact_samples_shape_and_metadata_in_argument_order() {
|
||||
let fixtures = FixtureDir::new("success");
|
||||
let dir = fixtures.path();
|
||||
let original = integer_raw();
|
||||
let integer = write_fixture(dir, "integer.dng", &original, ByteOrder::Little);
|
||||
let float = write_fixture(dir, "float.dng", &float_raw(), ByteOrder::Big);
|
||||
|
||||
let mut changed_sample = original.clone();
|
||||
let RawData::U16(samples) = &mut changed_sample.data else {
|
||||
panic!("integer fixture must contain integer samples");
|
||||
};
|
||||
samples[127] += 1;
|
||||
let changed_sample = write_fixture(dir, "changed-sample.dng", &changed_sample, ByteOrder::Little);
|
||||
|
||||
let mut rotated = original;
|
||||
rotated.orientation = Orientation::Normal;
|
||||
let rotated = write_fixture(dir, "changed-orientation.dng", &rotated, ByteOrder::Little);
|
||||
|
||||
let paths = [integer.clone(), float, changed_sample, rotated, integer];
|
||||
let limits = Limits::default();
|
||||
let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits);
|
||||
assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits));
|
||||
|
||||
// The digests were generated independently from the known little-endian u16 and f32 bytes.
|
||||
let rows = concat!(
|
||||
"1\t1\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n",
|
||||
"1\t2\tok\tdng\tf32\t768\tc50a4d270d6140ad9988fd8002c5b5de4a78b0b8d598b4db1a5a5385bd4119fd\t16\t16\t3\t32\t\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n",
|
||||
"1\t3\tok\tdng\tu16\t256\t3ebf95a27aa36848dc2fc39f537625913e29fd1d390c41b50a527f27f1d5ce91\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n",
|
||||
"1\t4\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t1\t3fe0000000000000\n",
|
||||
"1\t5\tok\tdng\tu16\t256\ta1894fbab0b9500f55baa534f974a5c943578668482a5d3cb8fa4a7b5267deee\t16\t16\t1\t16\t2,2,0,0:0,1,1,2\t2,1,12,14\t3,2,4,8\t6\t3fe0000000000000\n",
|
||||
);
|
||||
assert_eq!(String::from_utf8(first).unwrap(), format!("{HEADER}{rows}"));
|
||||
}
|
||||
|
||||
fn report_rows(text: &str) -> Vec<Vec<&str>> {
|
||||
text.strip_prefix(HEADER)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let fields: Vec<_> = line.split('\t').collect();
|
||||
assert_eq!(fields.len(), 16);
|
||||
fields
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_mixed_failures_and_keeps_the_last_success() {
|
||||
let fixtures = FixtureDir::new("mixed");
|
||||
let dir = fixtures.path();
|
||||
let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little);
|
||||
let unreadable = dir.join("missing.dng").into_os_string();
|
||||
let text = write_bytes(dir, "private-fixture-name.txt", b"not a recognized RAW header");
|
||||
|
||||
let mut unsupported = base_ifd(8, 6, 16, 2, false);
|
||||
unsupported.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2 * 2]] });
|
||||
let unsupported = write_bytes(dir, "unsupported.dng", &dng(unsupported, ByteOrder::Little));
|
||||
|
||||
let mut corrupt = base_ifd(8, 6, 16, 1, true);
|
||||
corrupt.set(tags::CFA_PATTERN_EP, Value::Byte(vec![0, 1, 2]));
|
||||
corrupt.set_image(ImageData::Strips { rows_per_strip: 6, strips: vec![vec![0; 8 * 6 * 2]] });
|
||||
let corrupt = write_bytes(dir, "corrupt.dng", &dng(corrupt, ByteOrder::Little));
|
||||
|
||||
let missing_strips = dng(base_ifd(8, 6, 16, 1, true), ByteOrder::Little);
|
||||
let tiff_error = write_bytes(dir, "missing-strips.dng", &missing_strips);
|
||||
let paths = [integer.clone(), unreadable, text, unsupported, corrupt, tiff_error, integer];
|
||||
let limits = Limits::default();
|
||||
let first = run_report(&paths, report::MAX_INPUT_BYTES, &limits);
|
||||
assert_eq!(first, run_report(&paths, report::MAX_INPUT_BYTES, &limits));
|
||||
|
||||
let text = String::from_utf8(first).unwrap();
|
||||
assert!(!text.contains("private-fixture-name"));
|
||||
assert!(!text.contains("CFAPattern size mismatch"));
|
||||
let rows = report_rows(&text);
|
||||
let statuses = ["ok", "read_error", "not_raw", "unsupported", "corrupt", "tiff_error", "ok"];
|
||||
assert_eq!(rows.len(), statuses.len());
|
||||
for (index, (row, status)) in rows.iter().zip(statuses).enumerate() {
|
||||
assert_eq!(row[0], "1");
|
||||
assert_eq!(row[1], (index + 1).to_string());
|
||||
assert_eq!(row[2], status);
|
||||
if status != "ok" {
|
||||
assert!(row[3..].iter().all(|field| field.is_empty()));
|
||||
}
|
||||
}
|
||||
assert_eq!(rows[0][2..], rows[6][2..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn separates_encoded_file_and_shared_decoder_limits() {
|
||||
let fixtures = FixtureDir::new("limits");
|
||||
let dir = fixtures.path();
|
||||
let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little);
|
||||
let size = std::fs::metadata(Path::new(&integer)).unwrap().len();
|
||||
let paths = [integer];
|
||||
for (max_input_bytes, max_samples, status) in [(size, 256, "ok"), (size - 1, 256, "input_limit"), (size, 255, "decode_limit")] {
|
||||
let mut limits = Limits::default();
|
||||
limits.max_samples = max_samples;
|
||||
let output = String::from_utf8(run_report(&paths, max_input_bytes, &limits)).unwrap();
|
||||
let rows = report_rows(&output);
|
||||
assert_eq!(rows.len(), 1);
|
||||
assert_eq!(rows[0][..3], ["1", "1", status]);
|
||||
if status != "ok" {
|
||||
assert!(rows[0][3..].iter().all(|field| field.is_empty()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_arguments_report_usage_without_writing_a_header() {
|
||||
let mut output = Vec::new();
|
||||
let result = report::run([], &mut output, report::MAX_INPUT_BYTES, &Limits::default());
|
||||
assert!(matches!(result, Err(report::RunError::Usage)));
|
||||
assert!(output.is_empty());
|
||||
}
|
||||
|
||||
struct BrokenOutput {
|
||||
write_error: bool,
|
||||
}
|
||||
|
||||
impl Write for BrokenOutput {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if self.write_error { Err(io::Error::from(io::ErrorKind::BrokenPipe)) } else { Ok(bytes.len()) }
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Err(io::Error::from(io::ErrorKind::WriteZero))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_and_flush_errors_fail_the_invocation() {
|
||||
let fixtures = FixtureDir::new("output-error");
|
||||
let dir = fixtures.path();
|
||||
let integer = write_fixture(dir, "integer.dng", &integer_raw(), ByteOrder::Little);
|
||||
for (write_error, kind) in [(true, io::ErrorKind::BrokenPipe), (false, io::ErrorKind::WriteZero)] {
|
||||
let mut out = BrokenOutput { write_error };
|
||||
let result = report::run([integer.clone()], &mut out, report::MAX_INPUT_BYTES, &Limits::default());
|
||||
assert!(matches!(result, Err(report::RunError::Output(error)) if error.kind() == kind));
|
||||
}
|
||||
}
|
||||
@@ -749,6 +749,7 @@ fn malformed_profile_look_tags_are_ignored() {
|
||||
}
|
||||
|
||||
/// Lossless JPEG XL codestream of `px` (`w × h × cpp` interleaved), 16-bit unless `eight`.
|
||||
#[cfg(feature = "jxl")]
|
||||
fn jxl_encode(px: &[u16], w: usize, h: usize, cpp: usize, eight: bool) -> Vec<u8> {
|
||||
use zune_core::bit_depth::BitDepth;
|
||||
use zune_core::colorspace::ColorSpace;
|
||||
@@ -765,6 +766,7 @@ fn jxl_encode(px: &[u16], w: usize, h: usize, cpp: usize, eight: bool) -> Vec<u8
|
||||
}
|
||||
|
||||
/// A bare codestream wrapped in the ISO-BMFF container (signature, `ftyp`, `jxlc`).
|
||||
#[cfg(feature = "jxl")]
|
||||
fn jxl_container(cs: &[u8]) -> Vec<u8> {
|
||||
let mut b = vec![0, 0, 0, 0x0c, b'J', b'X', b'L', b' ', 0x0d, 0x0a, 0x87, 0x0a, 0, 0, 0, 0x14];
|
||||
b.extend_from_slice(b"ftypjxl \0\0\0\0jxl ");
|
||||
@@ -777,6 +779,7 @@ fn jxl_container(cs: &[u8]) -> Vec<u8> {
|
||||
/// A tiled JPEG XL raw IFD of `px`. Edge tiles alternate between being coded at their in-image size
|
||||
/// and padded to the nominal tile size (with junk the decoder must drop); tiles alternate between bare
|
||||
/// codestreams and containers.
|
||||
#[cfg(feature = "jxl")]
|
||||
fn jxl_tiled(px: &[u16], w: usize, h: usize, cpp: usize, bits: u16, cfa: bool, tile: (usize, usize)) -> IfdBuilder {
|
||||
let (tw, th) = tile;
|
||||
let mut tiles = Vec::new();
|
||||
@@ -804,6 +807,7 @@ fn jxl_tiled(px: &[u16], w: usize, h: usize, cpp: usize, bits: u16, cfa: bool, t
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "jxl")]
|
||||
fn jpeg_xl_tiles_decode_bit_exactly() {
|
||||
let (w, h) = (37, 29);
|
||||
// LinearRaw 3 × 16-bit, the full code range
|
||||
@@ -831,6 +835,7 @@ fn jpeg_xl_tiles_decode_bit_exactly() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "jxl")]
|
||||
fn malformed_jpeg_xl_tiles_are_errors() {
|
||||
use craft_raw::RawError;
|
||||
let (w, h) = (16, 16);
|
||||
@@ -868,6 +873,7 @@ fn malformed_jpeg_xl_tiles_are_errors() {
|
||||
|
||||
/// One undecodable tile makes the whole image an error: it is never returned with a black tile.
|
||||
#[test]
|
||||
#[cfg(feature = "jxl")]
|
||||
fn a_jpeg_xl_tile_that_fails_is_an_error_for_the_image() {
|
||||
use craft_raw::RawError;
|
||||
let (w, h) = (32, 16);
|
||||
@@ -890,6 +896,7 @@ fn a_jpeg_xl_tile_that_fails_is_an_error_for_the_image() {
|
||||
/// about twice what one plane may use, and is an error rather than an allocation the header asks
|
||||
/// for. The same samples without the alpha channel decode.
|
||||
#[test]
|
||||
#[cfg(feature = "jxl")]
|
||||
fn jpeg_xl_tiles_beyond_their_decode_budget_are_errors() {
|
||||
use craft_raw::RawError;
|
||||
use zune_core::bit_depth::BitDepth;
|
||||
@@ -911,6 +918,7 @@ fn jpeg_xl_tiles_beyond_their_decode_budget_are_errors() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(feature = "jxl")]
|
||||
fn jpeg_xl_preview_ifd_is_offered() {
|
||||
let raw = synthetic(16, 16, Some(Cfa::bayer("RGGB").unwrap()), 1);
|
||||
let RawData::U16(px) = &raw.data else { unreachable!() };
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
//! The integration tests, one module per file, linked into one test binary.
|
||||
|
||||
#[cfg(all(feature = "dng", not(target_arch = "wasm32")))]
|
||||
mod decode_report;
|
||||
#[cfg(feature = "dng")]
|
||||
mod dng;
|
||||
#[cfg(feature = "line-dng")]
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "craft-sqlite"
|
||||
description = "Bounded wire-format helpers for SQLite database readers."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,87 @@
|
||||
#![no_std]
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
//! Wire helpers for the [SQLite database file format](https://www.sqlite.org/fileformat.html).
|
||||
//!
|
||||
//! The caller owns cursor advancement, field bounds, and interpretation of stored values.
|
||||
|
||||
use core::fmt;
|
||||
|
||||
const MAX_VARINT_BYTES: usize = 9;
|
||||
|
||||
/// A failure to decode part of a SQLite record or page.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum Error {
|
||||
/// Input ended before the integer was complete.
|
||||
TruncatedVarint,
|
||||
/// The serial type is reserved and has no defined field width.
|
||||
ReservedSerialType(u64),
|
||||
}
|
||||
|
||||
impl fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::TruncatedVarint => f.write_str("truncated SQLite varint"),
|
||||
Self::ReservedSerialType(code) => write!(f, "reserved SQLite serial type {code}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl core::error::Error for Error {}
|
||||
|
||||
/// Decode the leading SQLite varint and return its raw bit pattern and byte count.
|
||||
///
|
||||
/// The first eight bytes each contribute seven bits. If all eight have the high bit set,
|
||||
/// the ninth contributes all eight bits. The caller interprets the bits as signed when needed.
|
||||
/// Decoding ends at the first complete representation, including non-minimal encodings.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::TruncatedVarint`] if the slice ends before the integer is complete.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_sqlite::read_varint;
|
||||
///
|
||||
/// assert_eq!(read_varint(&[0x81, 0x00, 0xff]), Ok((128, 2)));
|
||||
/// ```
|
||||
pub fn read_varint(input: &[u8]) -> Result<(u64, usize), Error> {
|
||||
let mut value = 0;
|
||||
for (index, &byte) in input.iter().take(MAX_VARINT_BYTES).enumerate() {
|
||||
if index == MAX_VARINT_BYTES - 1 {
|
||||
return Ok(((value << 8) | u64::from(byte), MAX_VARINT_BYTES));
|
||||
}
|
||||
value = (value << 7) | u64::from(byte & 0x7f);
|
||||
if byte & 0x80 == 0 {
|
||||
return Ok((value, index + 1));
|
||||
}
|
||||
}
|
||||
Err(Error::TruncatedVarint)
|
||||
}
|
||||
|
||||
/// Return the encoded body width in bytes for a SQLite record serial type.
|
||||
///
|
||||
/// The width is independent of the host's pointer size. The caller checks it against the
|
||||
/// available body bytes before reading a field.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns [`Error::ReservedSerialType`] for codes 10 and 11.
|
||||
///
|
||||
/// ```
|
||||
/// use craft_sqlite::serial_type_len;
|
||||
///
|
||||
/// assert_eq!(serial_type_len(3), Ok(3));
|
||||
/// assert_eq!(serial_type_len(17), Ok(2));
|
||||
/// ```
|
||||
pub const fn serial_type_len(serial_type: u64) -> Result<u64, Error> {
|
||||
match serial_type {
|
||||
0 | 8 | 9 => Ok(0),
|
||||
1..=4 => Ok(serial_type),
|
||||
5 => Ok(6),
|
||||
6 | 7 => Ok(8),
|
||||
10 | 11 => Err(Error::ReservedSerialType(serial_type)),
|
||||
// Integer division accounts for the one-code difference between BLOB and text.
|
||||
_ => Ok((serial_type - 12) / 2),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use craft_sqlite::{Error, read_varint, serial_type_len};
|
||||
|
||||
#[test]
|
||||
fn varints_decode_at_each_width() {
|
||||
let cases: &[(&[u8], u64)] = &[
|
||||
(&[0x7f], 127),
|
||||
(&[0x81, 0], 1 << 7),
|
||||
(&[0x81, 0x80, 0], 1 << 14),
|
||||
(&[0x81, 0x80, 0x80, 0], 1 << 21),
|
||||
(&[0x81, 0x80, 0x80, 0x80, 0], 1 << 28),
|
||||
(&[0x81, 0x80, 0x80, 0x80, 0x80, 0], 1 << 35),
|
||||
(&[0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 42),
|
||||
(&[0x81, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 49),
|
||||
(&[0x80, 0xc0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0], 1 << 56),
|
||||
];
|
||||
for &(bytes, expected) in cases {
|
||||
assert_eq!(read_varint(bytes), Ok((expected, bytes.len())), "{bytes:x?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ninth_byte_keeps_all_bits_and_leaves_trailing_bytes() {
|
||||
let bytes = [0xc0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x42];
|
||||
assert_eq!(read_varint(&bytes), Ok((0x8000_0000_0000_0080, 9)));
|
||||
assert_eq!(read_varint(&[0xff; 9]), Ok((u64::MAX, 9)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leading_varint_preserves_following_bytes_and_accepts_padding() {
|
||||
assert_eq!(read_varint(&[0, 0xff]), Ok((0, 1)));
|
||||
assert_eq!(read_varint(&[0x81, 0, 0xff]), Ok((128, 2)));
|
||||
assert_eq!(read_varint(&[0x80, 1, 0xff]), Ok((1, 2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn varint_refuses_every_incomplete_prefix() {
|
||||
let bytes = [0xff; 9];
|
||||
for len in 0..bytes.len() {
|
||||
assert_eq!(read_varint(&bytes[..len]), Err(Error::TruncatedVarint), "length {len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixed_serial_types_have_exact_widths() {
|
||||
for (serial_type, width) in (0..).zip([0, 1, 2, 3, 4, 6, 8, 8, 0, 0]) {
|
||||
assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_serial_types_are_refused() {
|
||||
for serial_type in [10, 11] {
|
||||
assert_eq!(serial_type_len(serial_type), Err(Error::ReservedSerialType(serial_type)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_serial_type_widths_are_portable() {
|
||||
for (serial_type, width) in [
|
||||
(12, 0),
|
||||
(13, 0),
|
||||
(14, 1),
|
||||
(15, 1),
|
||||
(12_012, 6_000),
|
||||
(12_013, 6_000),
|
||||
(u64::MAX - 1, 9_223_372_036_854_775_801),
|
||||
(u64::MAX, 9_223_372_036_854_775_801),
|
||||
] {
|
||||
assert_eq!(serial_type_len(serial_type), Ok(width), "code {serial_type}");
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@
|
||||
//! contrast without them). A value that is not one of these is refused. `stories.tsv` lists the scale of every image.
|
||||
|
||||
use craft_behavior::ColumnWidth;
|
||||
use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface};
|
||||
use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface, Tracked};
|
||||
use craft_ui::fonts::{I18nScripts, UiFonts};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::runtime::commands::CommandInput;
|
||||
@@ -312,7 +312,7 @@ fn render(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options)
|
||||
// The command states of the story shown, as the gallery gives them, before the first frame. The Overview gives its
|
||||
// cards none, so a card is rendered under none.
|
||||
frames.commands(match &job.shown {
|
||||
Shown::Story(registration) => Story::command_input([®istration.story]),
|
||||
Shown::Story(registration) => CommandInput::new().states(&Tracked::new(Story::command_states([®istration.story]))),
|
||||
Shown::Card(_) => CommandInput::new(),
|
||||
});
|
||||
let (shown, dialog) = match &job.shown {
|
||||
|
||||
@@ -17,6 +17,13 @@ The shared adapter adds an aggregate 64 MiB stylesheet-text limit and idempotent
|
||||
### Transform compatibility
|
||||
`transform_compat::parse_transform` preserves EffectCraft transform-list recovery and exact composition. It retains six numeric arguments per operation; scanning is not time/byte capped and matrix overflow behavior is unchanged. The strict geometry reader is unchanged. Source: Brandon Thomas, EffectCraft94e1c86d89a866771f80ad1610afda9aa12e85d8; bounded safe argument matching by Altynzhan Karybai,4035d181329e847d7a57bf3d059502ea2c91b560.
|
||||
|
||||
### Document and CSS style compatibility
|
||||
|
||||
`doc_style` preserves EffectCraft's presentation-attribute + stylesheet + inline-`style`
|
||||
cascade, unit/percentage length resolution, `PaintRef`/`resolve_paint`, and
|
||||
`viewBox`/`preserveAspectRatio` transform helpers while leaving scene-graph mapping
|
||||
with the importer. Note that `doc_style::length()` treats unknown units as `px` (`_ => v`).
|
||||
|
||||
|
||||
### Opt-in validated embedded images
|
||||
|
||||
|
||||
@@ -0,0 +1,457 @@
|
||||
//! Compatibility SVG document/CSS interpretation helpers extracted from EffectCraft.
|
||||
//!
|
||||
//! Provides presentation-attribute + stylesheet + inline-`style` declaration collection
|
||||
//! ([`declared`](crate::doc_style::declared)), property cascading ([`cascade`](crate::doc_style::cascade)), unit/percentage length resolution
|
||||
//! ([`length`](crate::doc_style::length), [`attr_len`](crate::doc_style::attr_len)), paint reference parsing/resolution ([`PaintRef`](crate::doc_style::PaintRef), [`paint_ref`](crate::doc_style::paint_ref),
|
||||
//! [`resolve_paint`](crate::doc_style::resolve_paint)), and `viewBox` / `preserveAspectRatio` transforms ([`viewbox`](crate::doc_style::viewbox),
|
||||
//! [`viewbox_transform`](crate::doc_style::viewbox_transform)).
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use kurbo::Affine;
|
||||
|
||||
use crate::{
|
||||
color::parse_rgba_compat,
|
||||
prefix_path::numbers_bounded,
|
||||
simple_css::{StyleSheet, declarations},
|
||||
};
|
||||
|
||||
/// SVG `fill-rule` property.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum FillRule {
|
||||
#[default]
|
||||
NonZero,
|
||||
EvenOdd,
|
||||
}
|
||||
|
||||
/// SVG `stroke-linecap` property.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Cap {
|
||||
#[default]
|
||||
Butt,
|
||||
Round,
|
||||
Square,
|
||||
}
|
||||
|
||||
/// SVG `stroke-linejoin` property.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Join {
|
||||
#[default]
|
||||
Miter,
|
||||
Round,
|
||||
Bevel,
|
||||
}
|
||||
|
||||
/// Parsed SVG paint reference (`none`, `currentColor`, `url(#id) [fallback]`, or RGBA color).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum PaintRef {
|
||||
/// Solid straight RGBA color `[r, g, b, a]` in `0.0..=1.0`.
|
||||
Color([f64; 4]),
|
||||
/// Paint server reference `url(#id)` with an optional fallback RGBA color.
|
||||
Url(String, Option<[f64; 4]>),
|
||||
/// `currentColor`.
|
||||
Current,
|
||||
}
|
||||
|
||||
/// Caller outcome when resolving a `url(#id)` paint reference.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum UrlPaint<S> {
|
||||
/// Resolved to a caller paint server (for example, a gradient or pattern).
|
||||
Server(S),
|
||||
/// Resolved to a solid RGBA color (for example, a single-stop gradient).
|
||||
Color([f64; 4]),
|
||||
/// No paint server found; fall back to the `url(#id) fallback` color if present.
|
||||
Fallback,
|
||||
/// Paint server found but empty or invalid; do not fall back.
|
||||
None,
|
||||
}
|
||||
|
||||
/// Result of resolving a [`PaintRef`] without committing to a caller's paint-server type.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ResolvedPaint<S> {
|
||||
/// Solid RGB color `[r, g, b]` with alpha `a`.
|
||||
Color([f64; 3], f64),
|
||||
/// A caller-resolved paint server (`url(#id)`).
|
||||
Server(S),
|
||||
}
|
||||
|
||||
/// Inherited SVG style state.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Style {
|
||||
pub fill: Option<PaintRef>,
|
||||
pub fill_opacity: f64,
|
||||
pub fill_rule: FillRule,
|
||||
pub stroke: Option<PaintRef>,
|
||||
pub stroke_opacity: f64,
|
||||
pub stroke_width: f64,
|
||||
pub cap: Cap,
|
||||
pub join: Join,
|
||||
pub miter: f64,
|
||||
pub dash: Option<Vec<f64>>,
|
||||
pub dash_offset: f64,
|
||||
pub color: [f64; 4],
|
||||
pub visible: bool,
|
||||
pub font_size: f64,
|
||||
}
|
||||
|
||||
impl Default for Style {
|
||||
fn default() -> Self {
|
||||
Style {
|
||||
fill: Some(PaintRef::Color([0.0, 0.0, 0.0, 1.0])),
|
||||
fill_opacity: 1.0,
|
||||
fill_rule: FillRule::NonZero,
|
||||
stroke: None,
|
||||
stroke_opacity: 1.0,
|
||||
stroke_width: 1.0,
|
||||
cap: Cap::Butt,
|
||||
join: Join::Miter,
|
||||
miter: 4.0,
|
||||
dash: None,
|
||||
dash_offset: 0.0,
|
||||
color: [0.0, 0.0, 0.0, 1.0],
|
||||
visible: true,
|
||||
font_size: 16.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Presentation attributes recognised by [`declared`].
|
||||
pub const STYLE_PROPS: &[&str] = &[
|
||||
"fill",
|
||||
"fill-opacity",
|
||||
"fill-rule",
|
||||
"stroke",
|
||||
"stroke-width",
|
||||
"stroke-opacity",
|
||||
"stroke-linecap",
|
||||
"stroke-linejoin",
|
||||
"stroke-miterlimit",
|
||||
"stroke-dasharray",
|
||||
"stroke-dashoffset",
|
||||
"opacity",
|
||||
"display",
|
||||
"visibility",
|
||||
"color",
|
||||
"font-size",
|
||||
"transform",
|
||||
"stop-color",
|
||||
"stop-opacity",
|
||||
];
|
||||
|
||||
/// Collect the declared properties of an element: presentation attributes, then CSS rules
|
||||
/// (by specificity and source order, bounded by `charge_css`), then the inline `style` attribute.
|
||||
pub fn declared(n: roxmltree::Node, css: &StyleSheet, charge_css: impl FnMut(usize) -> bool) -> HashMap<String, String> {
|
||||
let mut out = HashMap::new();
|
||||
for a in n.attributes() {
|
||||
if STYLE_PROPS.contains(&a.name()) && a.name() != "transform" {
|
||||
out.insert(a.name().to_string(), a.value().to_string());
|
||||
}
|
||||
}
|
||||
css.apply(n.tag_name().name(), n.attribute("id"), n.attribute("class").unwrap_or_default(), &mut out, charge_css);
|
||||
if let Some(st) = n.attribute("style") {
|
||||
for (k, v) in declarations(st) {
|
||||
out.insert(k, v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Parse an SVG length or percentage into user-space pixels.
|
||||
///
|
||||
/// `axis` selects the percentage reference base: `'x'` uses `vw`, `'y'` uses `vh`, and any
|
||||
/// other value uses the normalized diagonal `((vw^2 + vh^2) / 2).sqrt()`.
|
||||
pub fn length(s: &str, axis: char, font: f64, vw: f64, vh: f64) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
let num_end = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(s.len());
|
||||
// "e" also starts "em"/"ex": back off if the number does not parse.
|
||||
let (mut num, mut unit) = (&s[..num_end], &s[num_end..]);
|
||||
if num.parse::<f64>().is_err() && (num.ends_with('e') || num.ends_with('E')) {
|
||||
let back = num_end.saturating_sub(1);
|
||||
num = &s[..back];
|
||||
unit = &s[back..];
|
||||
}
|
||||
let v: f64 = num.parse().ok()?;
|
||||
let value = match unit.trim() {
|
||||
"" | "px" => v,
|
||||
"pt" => v * 4.0 / 3.0,
|
||||
"pc" => v * 16.0,
|
||||
"mm" => v * 96.0 / 25.4,
|
||||
"cm" => v * 96.0 / 2.54,
|
||||
"in" => v * 96.0,
|
||||
"em" => v * font,
|
||||
"ex" => v * font / 2.0,
|
||||
"%" => {
|
||||
let base = match axis {
|
||||
'x' => vw,
|
||||
'y' => vh,
|
||||
_ => ((vw * vw + vh * vh) / 2.0).sqrt(),
|
||||
};
|
||||
v / 100.0 * base
|
||||
}
|
||||
_ => v,
|
||||
};
|
||||
value.is_finite().then_some(value)
|
||||
}
|
||||
|
||||
/// Parse a length attribute on `n`, returning `0.0` if missing or invalid.
|
||||
pub fn attr_len(n: roxmltree::Node, name: &str, axis: char, st: &Style, vw: f64, vh: f64) -> f64 {
|
||||
n.attribute(name).and_then(|v| length(v, axis, st.font_size, vw, vh)).unwrap_or(0.0)
|
||||
}
|
||||
|
||||
/// Parse an SVG paint value (`none`, `currentColor`, `url(#id) [fallback]`, `inherit`, or color).
|
||||
///
|
||||
/// Returns `None` for `"inherit"` or unrecognized values, `Some(None)` for `"none"`, and
|
||||
/// `Some(Some(PaintRef))` for concrete paints or `url(...)` / `currentColor` references.
|
||||
pub fn paint_ref(v: &str) -> Option<Option<PaintRef>> {
|
||||
let v = v.trim();
|
||||
if v == "none" {
|
||||
return Some(None);
|
||||
}
|
||||
if v == "currentColor" || v == "currentcolor" {
|
||||
return Some(Some(PaintRef::Current));
|
||||
}
|
||||
if let Some(rest) = v.strip_prefix("url(") {
|
||||
let (url, fallback) = rest.split_once(')').unwrap_or((rest, ""));
|
||||
let url = url.trim().trim_matches(['"', '\'']);
|
||||
let id = url.strip_prefix('#').filter(|id| !id.is_empty()).unwrap_or_default().to_string();
|
||||
let fb = fallback.trim();
|
||||
let fb = if fb.is_empty() || fb == "none" { None } else { parse_rgba_compat(fb) };
|
||||
return Some(Some(PaintRef::Url(id, fb)));
|
||||
}
|
||||
if v == "inherit" {
|
||||
return None;
|
||||
}
|
||||
parse_rgba_compat(v).map(|c| Some(PaintRef::Color(c)))
|
||||
}
|
||||
|
||||
/// Apply an element's declared inherited properties to `st`.
|
||||
///
|
||||
/// Returns `(opacity, display)` where `display` is `false` when `display: none` is set.
|
||||
pub fn cascade(n: roxmltree::Node, css: &StyleSheet, st: &mut Style, vw: f64, vh: f64, charge_css: impl FnMut(usize) -> bool) -> (f64, bool) {
|
||||
let d = declared(n, css, charge_css);
|
||||
let num = |k: &str| {
|
||||
d.get(k)
|
||||
.and_then(|v| v.trim().trim_end_matches('%').parse::<f64>().ok().map(|x| if v.trim().ends_with('%') { x / 100.0 } else { x }))
|
||||
.filter(|x| x.is_finite())
|
||||
};
|
||||
if let Some(c) = d.get("color").and_then(|v| parse_rgba_compat(v)) {
|
||||
st.color = c;
|
||||
}
|
||||
let font_size = d.get("font-size").and_then(|v| match v.trim().strip_suffix('%') {
|
||||
Some(p) => p.trim().parse::<f64>().ok().map(|p| p / 100.0 * st.font_size),
|
||||
None => length(v, 'o', st.font_size, vw, vh),
|
||||
});
|
||||
if let Some(v) = font_size.filter(|v| v.is_finite()) {
|
||||
st.font_size = v;
|
||||
}
|
||||
if let Some(p) = d.get("fill").and_then(|v| paint_ref(v)) {
|
||||
st.fill = p;
|
||||
}
|
||||
if let Some(p) = d.get("stroke").and_then(|v| paint_ref(v)) {
|
||||
st.stroke = p;
|
||||
}
|
||||
if let Some(v) = num("fill-opacity") {
|
||||
st.fill_opacity = v.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = num("stroke-opacity") {
|
||||
st.stroke_opacity = v.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = d.get("stroke-width").and_then(|v| length(v, 'o', st.font_size, vw, vh)) {
|
||||
st.stroke_width = v.max(0.0);
|
||||
}
|
||||
if let Some(v) = num("stroke-miterlimit") {
|
||||
st.miter = v.max(1.0);
|
||||
}
|
||||
if let Some(v) = d.get("fill-rule") {
|
||||
st.fill_rule = if v.trim() == "evenodd" { FillRule::EvenOdd } else { FillRule::NonZero };
|
||||
}
|
||||
if let Some(v) = d.get("stroke-linecap") {
|
||||
st.cap = match v.trim() {
|
||||
"round" => Cap::Round,
|
||||
"square" => Cap::Square,
|
||||
_ => Cap::Butt,
|
||||
};
|
||||
}
|
||||
if let Some(v) = d.get("stroke-linejoin") {
|
||||
st.join = match v.trim() {
|
||||
"round" => Join::Round,
|
||||
"bevel" => Join::Bevel,
|
||||
_ => Join::Miter,
|
||||
};
|
||||
}
|
||||
if let Some(v) = d.get("stroke-dasharray") {
|
||||
st.dash = if v.trim() == "none" {
|
||||
None
|
||||
} else {
|
||||
let a: Vec<f64> = v
|
||||
.split(|c: char| c == ',' || c.is_whitespace())
|
||||
.filter(|t| !t.is_empty())
|
||||
.filter_map(|t| length(t, 'o', st.font_size, vw, vh))
|
||||
.collect();
|
||||
if a.iter().all(|x| *x >= 0.0) && a.iter().any(|x| *x > 0.0) { Some(a) } else { None }
|
||||
};
|
||||
}
|
||||
if let Some(v) = d.get("stroke-dashoffset").and_then(|v| length(v, 'o', st.font_size, vw, vh)) {
|
||||
st.dash_offset = v;
|
||||
}
|
||||
if let Some(v) = d.get("visibility") {
|
||||
st.visible = !matches!(v.trim(), "hidden" | "collapse");
|
||||
}
|
||||
let display = d.get("display").is_none_or(|v| v.trim() != "none");
|
||||
(num("opacity").unwrap_or(1.0).clamp(0.0, 1.0), display)
|
||||
}
|
||||
|
||||
/// Resolve a [`PaintRef`] against `st` and a caller-supplied `url(#id)` resolver.
|
||||
pub fn resolve_paint<S>(paint: &PaintRef, st: &Style, resolve_url: impl FnOnce(&str, Option<[f64; 4]>) -> UrlPaint<S>) -> Option<ResolvedPaint<S>> {
|
||||
match paint {
|
||||
PaintRef::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])),
|
||||
PaintRef::Current => Some(ResolvedPaint::Color([st.color[0], st.color[1], st.color[2]], st.color[3])),
|
||||
PaintRef::Url(id, fallback) => match resolve_url(id, *fallback) {
|
||||
UrlPaint::Server(s) => Some(ResolvedPaint::Server(s)),
|
||||
UrlPaint::Color(c) => Some(ResolvedPaint::Color([c[0], c[1], c[2]], c[3])),
|
||||
UrlPaint::Fallback => fallback.map(|c| ResolvedPaint::Color([c[0], c[1], c[2]], c[3])),
|
||||
UrlPaint::None => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse an element's `viewBox` attribute into `([min_x, min_y], width, height)`.
|
||||
pub fn viewbox(n: roxmltree::Node) -> Option<([f64; 2], f64, f64)> {
|
||||
let (v, exceeded) = numbers_bounded(n.attribute("viewBox")?, 5);
|
||||
if exceeded || !v.iter().all(|x| x.is_finite()) {
|
||||
return None;
|
||||
}
|
||||
let [x, y, width, height] = v.as_slice() else { return None };
|
||||
(*width > 0.0 && *height > 0.0).then_some(([*x, *y], *width, *height))
|
||||
}
|
||||
|
||||
/// The `viewBox` -> viewport transform (`preserveAspectRatio`, default `xMidYMid meet`).
|
||||
pub fn viewbox_transform(n: roxmltree::Node, w: f64, h: f64) -> Affine {
|
||||
let Some(([x, y], vw, vh)) = viewbox(n) else { return Affine::IDENTITY };
|
||||
let par = n.attribute("preserveAspectRatio").unwrap_or("xMidYMid meet");
|
||||
let mut parts = par.split_whitespace();
|
||||
let mut align = parts.next().unwrap_or("xMidYMid");
|
||||
if align == "defer" {
|
||||
align = parts.next().unwrap_or("xMidYMid");
|
||||
}
|
||||
let slice = parts.next() == Some("slice");
|
||||
let (sx, sy) = (w / vw, h / vh);
|
||||
if align == "none" {
|
||||
return Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y));
|
||||
}
|
||||
let s = if slice { sx.max(sy) } else { sx.min(sy) };
|
||||
let fx = if align.contains("xMid") {
|
||||
0.5
|
||||
} else if align.contains("xMax") {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let fy = if align.contains("YMid") {
|
||||
0.5
|
||||
} else if align.contains("YMax") {
|
||||
1.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let tx = (w - vw * s) * fx;
|
||||
let ty = (h - vh * s) * fy;
|
||||
Affine::translate((tx, ty)) * Affine::scale(s) * Affine::translate((-x, -y))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::simple_css::parse as parse_css;
|
||||
|
||||
#[test]
|
||||
fn declared_precedence_and_transform_exclusion() {
|
||||
let doc = roxmltree::Document::parse(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg"><rect id="r" class="a" fill="black" transform="translate(5)" style="fill:blue"/></svg>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap();
|
||||
let mut css = StyleSheet::default();
|
||||
parse_css(".a { fill: green; stroke: red; }", &mut css).unwrap();
|
||||
css.index();
|
||||
let d = declared(rect, &css, |_| true);
|
||||
assert_eq!(d.get("fill").map(String::as_str), Some("blue"));
|
||||
assert_eq!(d.get("stroke").map(String::as_str), Some("red"));
|
||||
assert!(!d.contains_key("transform"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_units_and_exponents() {
|
||||
assert_eq!(length("10", 'x', 16.0, 200.0, 100.0), Some(10.0));
|
||||
assert_eq!(length("12pt", 'x', 16.0, 200.0, 100.0), Some(16.0));
|
||||
assert_eq!(length("1in", 'x', 16.0, 200.0, 100.0), Some(96.0));
|
||||
assert_eq!(length("2em", 'x', 16.0, 200.0, 100.0), Some(32.0));
|
||||
assert_eq!(length("2ex", 'x', 16.0, 200.0, 100.0), Some(16.0));
|
||||
assert_eq!(length("1e2em", 'x', 10.0, 200.0, 100.0), Some(1000.0));
|
||||
assert_eq!(length("50%", 'x', 16.0, 200.0, 100.0), Some(100.0));
|
||||
assert_eq!(length("50%", 'y', 16.0, 200.0, 100.0), Some(50.0));
|
||||
assert_eq!(length("nan", 'x', 16.0, 200.0, 100.0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attr_len_reads_or_defaults_to_zero() {
|
||||
let doc = roxmltree::Document::parse(r#"<svg xmlns="http://www.w3.org/2000/svg"><rect x="50%" y="bad"/></svg>"#).unwrap();
|
||||
let rect = doc.descendants().find(|n| n.tag_name().name() == "rect").unwrap();
|
||||
let st = Style::default();
|
||||
assert_eq!(attr_len(rect, "x", 'x', &st, 200.0, 100.0), 100.0);
|
||||
assert_eq!(attr_len(rect, "y", 'y', &st, 200.0, 100.0), 0.0);
|
||||
assert_eq!(attr_len(rect, "width", 'x', &st, 200.0, 100.0), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cascade_applies_inheritance_and_display() {
|
||||
let doc = roxmltree::Document::parse(
|
||||
r##"<svg xmlns="http://www.w3.org/2000/svg"><g color="red" font-size="20" fill="currentColor" stroke="#00ff00" stroke-width="2em" stroke-dasharray="4 2" fill-rule="evenodd" stroke-linecap="round" stroke-linejoin="bevel" opacity="50%" display="none" visibility="hidden"/></svg>"##,
|
||||
)
|
||||
.unwrap();
|
||||
let g = doc.descendants().find(|n| n.tag_name().name() == "g").unwrap();
|
||||
let css = StyleSheet::default();
|
||||
let mut st = Style::default();
|
||||
let (opacity, display) = cascade(g, &css, &mut st, 100.0, 100.0, |_| true);
|
||||
assert_eq!(opacity, 0.5);
|
||||
assert!(!display);
|
||||
assert!(!st.visible);
|
||||
assert_eq!(st.font_size, 20.0);
|
||||
assert_eq!(st.stroke_width, 40.0);
|
||||
assert_eq!(st.fill, Some(PaintRef::Current));
|
||||
assert_eq!(st.fill_rule, FillRule::EvenOdd);
|
||||
assert_eq!(st.cap, Cap::Round);
|
||||
assert_eq!(st.join, Join::Bevel);
|
||||
assert_eq!(st.dash, Some(vec![4.0, 2.0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_ref_and_resolve_paint_handle_fallbacks() {
|
||||
assert_eq!(paint_ref("none"), Some(None));
|
||||
assert_eq!(paint_ref("inherit"), None);
|
||||
assert_eq!(paint_ref("currentColor"), Some(Some(PaintRef::Current)));
|
||||
assert_eq!(paint_ref("url(#grad) red"), Some(Some(PaintRef::Url("grad".into(), Some([1.0, 0.0, 0.0, 1.0])))));
|
||||
|
||||
let st = Style { color: [0.0, 1.0, 0.0, 0.5], ..Style::default() };
|
||||
assert_eq!(resolve_paint(&PaintRef::Current, &st, |_, _| UrlPaint::<()>::None), Some(ResolvedPaint::Color([0.0, 1.0, 0.0], 0.5)));
|
||||
|
||||
let url = PaintRef::Url("g".into(), Some([1.0, 0.0, 0.0, 1.0]));
|
||||
assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Server("ok")), Some(ResolvedPaint::Server("ok")));
|
||||
assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::Fallback), Some(ResolvedPaint::Color([1.0, 0.0, 0.0], 1.0)));
|
||||
assert_eq!(resolve_paint(&url, &st, |_, _| UrlPaint::<&str>::None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn viewbox_and_transform_preserve_aspect_ratio() {
|
||||
let doc = roxmltree::Document::parse(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="10 20 100 50" preserveAspectRatio="defer xMaxYMid meet"/>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let root = doc.root_element();
|
||||
assert_eq!(viewbox(root), Some(([10.0, 20.0], 100.0, 50.0)));
|
||||
let m = viewbox_transform(root, 200.0, 200.0);
|
||||
// Scale is min(2, 4) = 2; tx = (200 - 200) * 1.0 = 0; ty = (200 - 100) * 0.5 = 50.
|
||||
let p = m * kurbo::Point::new(10.0, 20.0);
|
||||
assert_eq!(p, kurbo::Point::new(0.0, 50.0));
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,6 @@ pub mod simple_css;
|
||||
|
||||
/// Prefix-preserving SVG transform-list compatibility.
|
||||
pub mod transform_compat;
|
||||
|
||||
/// Compatibility SVG document/CSS interpretation helpers (style cascade, lengths, paints, viewBox).
|
||||
pub mod doc_style;
|
||||
|
||||
+81
-14
@@ -125,6 +125,26 @@ pub enum Segment {
|
||||
Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point },
|
||||
}
|
||||
|
||||
/// One `M …` run of a `d` attribute, preserving quadratic (`Q`/`T`) segments.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct QuadSubpath {
|
||||
/// Start point.
|
||||
pub start: Point,
|
||||
/// Segments in drawing order.
|
||||
pub segs: Vec<QuadSegment>,
|
||||
/// Whether a close-path command closed this subpath.
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// A path segment that preserves quadratic Bézier curves alongside lines, cubics, and arcs.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum QuadSegment {
|
||||
Line(Point),
|
||||
Quad(Point, Point),
|
||||
Cubic(Point, Point, Point),
|
||||
Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point },
|
||||
}
|
||||
|
||||
/// Tokens of a `d` attribute: command letters and numbers, in order.
|
||||
enum Tok {
|
||||
Cmd(u8),
|
||||
@@ -174,15 +194,51 @@ impl<'a> Tokenizer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `d` into subpaths, resolving relative commands and the S/T control reflections.
|
||||
/// Split `d` into subpaths, resolving relative commands and S/T control reflections while
|
||||
/// raising quadratic (`Q`/`T`) segments to cubics.
|
||||
pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
Ok(parse_path_with_quads(d)?
|
||||
.into_iter()
|
||||
.map(|sub| {
|
||||
let mut cur = sub.start;
|
||||
let segs = sub
|
||||
.segs
|
||||
.into_iter()
|
||||
.map(|seg| match seg {
|
||||
QuadSegment::Line(p) => {
|
||||
cur = p;
|
||||
Segment::Line(p)
|
||||
}
|
||||
QuadSegment::Quad(q, p) => {
|
||||
let out = Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p);
|
||||
cur = p;
|
||||
out
|
||||
}
|
||||
QuadSegment::Cubic(c1, c2, p) => {
|
||||
cur = p;
|
||||
Segment::Cubic(c1, c2, p)
|
||||
}
|
||||
QuadSegment::Arc { rx, ry, rot, large, sweep, end } => {
|
||||
cur = end;
|
||||
Segment::Arc { rx, ry, rot, large, sweep, end }
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
Subpath { start: sub.start, segs, closed: sub.closed }
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Split `d` into subpaths, resolving relative commands and S/T control reflections while
|
||||
/// preserving quadratic (`Q`/`T`) segments.
|
||||
pub fn parse_path_with_quads(d: &str) -> Result<Vec<QuadSubpath>> {
|
||||
let mut tk = Tokenizer::new(d);
|
||||
let mut lookahead: Option<Tok> = None;
|
||||
let mut cmd = 0u8;
|
||||
let mut cur = Point::ZERO;
|
||||
let mut start = Point::ZERO;
|
||||
let mut segs: Vec<Segment> = Vec::new();
|
||||
let mut out: Vec<Subpath> = Vec::new();
|
||||
let mut segs: Vec<QuadSegment> = Vec::new();
|
||||
let mut out: Vec<QuadSubpath> = Vec::new();
|
||||
let closed = false;
|
||||
let mut prev_cubic: Option<Point> = None;
|
||||
let mut prev_quad: Option<Point> = None;
|
||||
@@ -214,7 +270,7 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
Tok::Cmd(c) => {
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed: true });
|
||||
out.push(QuadSubpath { start, segs, closed: true });
|
||||
segs = Vec::new();
|
||||
}
|
||||
cur = start;
|
||||
@@ -264,7 +320,7 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
match abs {
|
||||
b'M' => {
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed: false });
|
||||
out.push(QuadSubpath { start, segs, closed: false });
|
||||
segs = Vec::new();
|
||||
}
|
||||
cur = point(args[0], args[1]);
|
||||
@@ -275,25 +331,25 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
}
|
||||
b'L' => {
|
||||
cur = point(args[0], args[1]);
|
||||
segs.push(Segment::Line(cur));
|
||||
segs.push(QuadSegment::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'H' => {
|
||||
cur = Point::new(if rel { cur.x + args[0] } else { args[0] }, cur.y);
|
||||
segs.push(Segment::Line(cur));
|
||||
segs.push(QuadSegment::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'V' => {
|
||||
cur = Point::new(cur.x, if rel { cur.y + args[0] } else { args[0] });
|
||||
segs.push(Segment::Line(cur));
|
||||
segs.push(QuadSegment::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, p) = (point(args[0], args[1]), point(args[2], args[3]), point(args[4], args[5]));
|
||||
segs.push(Segment::Cubic(c1, c2, p));
|
||||
segs.push(QuadSegment::Cubic(c1, c2, p));
|
||||
prev_cubic = Some(c2);
|
||||
prev_quad = None;
|
||||
cur = p;
|
||||
@@ -301,14 +357,14 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
b'S' => {
|
||||
let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2);
|
||||
let (c2, p) = (point(args[0], args[1]), point(args[2], args[3]));
|
||||
segs.push(Segment::Cubic(c1, c2, p));
|
||||
segs.push(QuadSegment::Cubic(c1, c2, p));
|
||||
prev_cubic = Some(c2);
|
||||
prev_quad = None;
|
||||
cur = p;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, p) = (point(args[0], args[1]), point(args[2], args[3]));
|
||||
segs.push(Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p));
|
||||
segs.push(QuadSegment::Quad(q, p));
|
||||
prev_quad = Some(q);
|
||||
prev_cubic = None;
|
||||
cur = p;
|
||||
@@ -316,14 +372,14 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
b'T' => {
|
||||
let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q);
|
||||
let p = point(args[0], args[1]);
|
||||
segs.push(Segment::Cubic(cur + (reflect - cur) * (2.0 / 3.0), p + (reflect - p) * (2.0 / 3.0), p));
|
||||
segs.push(QuadSegment::Quad(reflect, p));
|
||||
prev_quad = Some(reflect);
|
||||
prev_cubic = None;
|
||||
cur = p;
|
||||
}
|
||||
b'A' => {
|
||||
let end = point(args[5], args[6]);
|
||||
segs.push(Segment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end });
|
||||
segs.push(QuadSegment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end });
|
||||
cur = end;
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
@@ -339,7 +395,7 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
}
|
||||
}
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed });
|
||||
out.push(QuadSubpath { start, segs, closed });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -443,6 +499,17 @@ mod tests {
|
||||
assert_eq!(paths[0].segs[1], Segment::Cubic(Point::new(8.0, -2.0), Point::new(10.0, -2.0), Point::new(12.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_path_with_quads_preserves_quadratic_control_points() {
|
||||
let paths = parse_path_with_quads("M0 10 Q5 20 10 10 T20 10 Z").unwrap();
|
||||
assert_eq!(paths.len(), 1);
|
||||
assert!(paths[0].closed);
|
||||
assert_eq!(
|
||||
paths[0].segs,
|
||||
vec![QuadSegment::Quad(Point::new(5.0, 20.0), Point::new(10.0, 10.0)), QuadSegment::Quad(Point::new(15.0, 0.0), Point::new(20.0, 10.0)),]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn close_resets_smooth_control_history() {
|
||||
// After Z, S must not reflect the preceding C's control (20,20) → (0,0).
|
||||
|
||||
+30
-1
@@ -229,12 +229,22 @@ pub fn path_data(path: &BezPath) -> String {
|
||||
/// Path data with `decimals` decimals per coordinate, written compactly: `M1.00 2.00L3.50 2.00Z`.
|
||||
/// Coordinates that are not finite are written as zero.
|
||||
pub fn path_data_fixed(path: &BezPath, decimals: usize) -> String {
|
||||
path_data_with_format(path, |value| num(value, decimals))
|
||||
}
|
||||
|
||||
/// Compact absolute path commands with caller-owned coordinate formatting.
|
||||
///
|
||||
/// The formatter is called once per coordinate, in path order. It must produce a valid SVG
|
||||
/// number (including handling nonfinite inputs); it controls rounding and negative zero.
|
||||
/// Command letters and separators are shared, while the application's precision policy stays
|
||||
/// with the caller. No intermediate geometry or coordinate collection is allocated.
|
||||
pub fn path_data_with_format<T: Display>(path: &BezPath, mut format: impl FnMut(f64) -> T) -> String {
|
||||
let mut d = String::new();
|
||||
let mut command = |letter: char, points: &[Point]| {
|
||||
d.push(letter);
|
||||
for (i, p) in points.iter().enumerate() {
|
||||
let sep = if i == 0 { "" } else { " " };
|
||||
let _ = write!(d, "{sep}{} {}", num(p.x, decimals), num(p.y, decimals));
|
||||
let _ = write!(d, "{sep}{} {}", format(p.x), format(p.y));
|
||||
}
|
||||
};
|
||||
for el in path.elements() {
|
||||
@@ -400,6 +410,25 @@ mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_path_format_keeps_commands_and_coordinate_order() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((1.0, 2.0));
|
||||
path.line_to((3.0, 4.0));
|
||||
path.quad_to((5.0, 6.0), (7.0, 8.0));
|
||||
path.curve_to((9.0, 10.0), (11.0, 12.0), (13.0, 14.0));
|
||||
path.close_path();
|
||||
let mut seen = Vec::new();
|
||||
let output = path_data_with_format(&path, |v| {
|
||||
seen.push(v);
|
||||
v
|
||||
});
|
||||
assert_eq!(output, "M1 2L3 4Q5 6 7 8C9 10 11 12 13 14Z");
|
||||
assert_eq!(seen, (1..=14).map(f64::from).collect::<Vec<_>>());
|
||||
assert_eq!(BezPath::from_svg(&output).unwrap(), path);
|
||||
assert_eq!(path_data_with_format(&BezPath::new(), |_: f64| -> String { panic!("empty path") }), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scene_can_keep_fixed_view_box_without_changing_default_output() {
|
||||
let scene = Scene { width_mm: 100.0, height_mm: 150.0, view_box: [0.0, 0.0, 100.0, 150.0], elements: vec![] };
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user