mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 12:47:25 +00:00
Merge upstream/main into feat/6820-chartex-placeholder
This commit is contained in:
Generated
+12
@@ -1785,9 +1785,12 @@ name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"fontique",
|
||||
"harfrust 0.13.3",
|
||||
"kurbo 0.13.1",
|
||||
"skrifa 0.47.0",
|
||||
"thiserror 2.0.21",
|
||||
"unicode-bidi",
|
||||
"unicode-segmentation",
|
||||
"windows-registry",
|
||||
"write-fonts 0.54.1",
|
||||
]
|
||||
@@ -1868,6 +1871,15 @@ dependencies = [
|
||||
"image",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gzip"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -41,6 +41,7 @@ bytemuck = "1"
|
||||
kurbo = "0.13"
|
||||
thiserror = "2"
|
||||
craft-gzip = { path = "crates/gzip" }
|
||||
craft-gridcraft-format = { path = "crates/gridcraft-format" }
|
||||
craft-aaf = { path = "crates/aaf" }
|
||||
craft-atomic = { path = "crates/atomic" }
|
||||
craft-captions = { path = "crates/captions" }
|
||||
|
||||
@@ -176,6 +176,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
every frame's position, delay, disposal and transparent colour, the loop count and the first
|
||||
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
|
||||
a file can hold the picture it declares before a decoder runs.
|
||||
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
|
||||
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
|
||||
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
|
||||
- [`craft-hdr`](crates/hdr/src/lib.rs): Radiance HDR (RGBE) picture reader, from FilmCraft: flat,
|
||||
old and new run-length scan lines and all eight axis orders, to linear float RGB. Scan lines are
|
||||
validated before the picture is allocated.
|
||||
|
||||
@@ -29,6 +29,7 @@ pub mod lut3d;
|
||||
pub mod lutfile;
|
||||
pub mod math;
|
||||
pub mod named;
|
||||
mod normalize;
|
||||
pub mod pipeline;
|
||||
pub mod profile;
|
||||
pub mod sony_lut;
|
||||
@@ -45,6 +46,7 @@ pub use gamut::GamutCheck;
|
||||
pub use gpu_matrix_shaper::GpuMatrixShaper;
|
||||
pub use lut3d::Lut3d;
|
||||
pub use named::{NamedColor, NamedColors};
|
||||
pub use normalize::normalize_for_embedding;
|
||||
pub use profile::{ColorSpace, Pcs, Profile, ProfileClass};
|
||||
pub use transform::{SampleKind, Transform, TransformOptions, black_point, cached};
|
||||
pub use write::profile_id;
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
//! Bounded encoded ICC layout normalization, originating in LightCraft.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Zero the creation date, align tag payloads to four bytes, preserve shared payloads,
|
||||
/// update the profile length and clear its stale profile ID. No colour tags are interpreted.
|
||||
///
|
||||
/// This is a layout operation, not profile validation. Malformed tables or layouts exceeding
|
||||
/// 4096 tags or 64 MiB output are returned unchanged except for the creation date. The owned
|
||||
/// input is reused on failure, so rejected input does not require an additional full copy.
|
||||
/// Consumers needing rejection of invalid profiles must separately use `Profile::parse`.
|
||||
pub fn normalize_for_embedding(mut bytes: Vec<u8>) -> Vec<u8> {
|
||||
if let Some(date) = bytes.get_mut(24..36) {
|
||||
date.fill(0);
|
||||
}
|
||||
align(&bytes).unwrap_or(bytes)
|
||||
}
|
||||
|
||||
const MAX_BYTES: usize = 64 * 1024 * 1024;
|
||||
const MAX_TAGS: usize = 4096;
|
||||
|
||||
fn be(bytes: &[u8], at: usize) -> Option<usize> {
|
||||
let s = bytes.get(at..at.checked_add(4)?)?;
|
||||
usize::try_from(u32::from_be_bytes([s[0], s[1], s[2], s[3]])).ok()
|
||||
}
|
||||
|
||||
fn align(bytes: &[u8]) -> Option<Vec<u8>> {
|
||||
if bytes.len() > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let count = be(bytes, 128)?;
|
||||
if count > MAX_TAGS {
|
||||
return None;
|
||||
}
|
||||
let end = 132usize.checked_add(count.checked_mul(12)?)?;
|
||||
bytes.get(..end)?;
|
||||
let mut placements = BTreeMap::new();
|
||||
let mut offsets = Vec::new();
|
||||
offsets.try_reserve_exact(count).ok()?;
|
||||
let mut size = end;
|
||||
for index in 0..count {
|
||||
let entry = 132 + index * 12;
|
||||
let off = be(bytes, entry + 4)?;
|
||||
let len = be(bytes, entry + 8)?;
|
||||
if off < end {
|
||||
return None;
|
||||
}
|
||||
bytes.get(off..off.checked_add(len)?)?;
|
||||
let new_off = if let Some(&placed) = placements.get(&(off, len)) {
|
||||
placed
|
||||
} else {
|
||||
let aligned = size.checked_add(3)? & !3;
|
||||
size = aligned.checked_add(len)?;
|
||||
if size > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
placements.insert((off, len), aligned);
|
||||
aligned
|
||||
};
|
||||
offsets.push(new_off);
|
||||
}
|
||||
size = size.checked_add(3)? & !3;
|
||||
if size > MAX_BYTES {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(size).ok()?;
|
||||
out.resize(size, 0);
|
||||
out[..end].copy_from_slice(&bytes[..end]);
|
||||
for ((off, len), target) in placements {
|
||||
out[target..target + len].copy_from_slice(&bytes[off..off + len]);
|
||||
}
|
||||
for (index, off) in offsets.into_iter().enumerate() {
|
||||
let field = 132 + index * 12 + 4;
|
||||
out[field..field + 4].copy_from_slice(&u32::try_from(off).ok()?.to_be_bytes());
|
||||
}
|
||||
out[..4].copy_from_slice(&u32::try_from(size).ok()?.to_be_bytes());
|
||||
out[84..100].fill(0);
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
#[path = "normalize_legacy_tests.rs"]
|
||||
mod legacy;
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn matches_frozen_writer_and_preserves_aliases() {
|
||||
for count in 0..20usize {
|
||||
let end = 132 + count * 12;
|
||||
let mut bytes = vec![17; end + 31];
|
||||
bytes[128..132].copy_from_slice(&(count as u32).to_be_bytes());
|
||||
for index in 0..count {
|
||||
let field = 132 + index * 12 + 4;
|
||||
let off = end + index % 3;
|
||||
bytes[field..field + 4].copy_from_slice(&(off as u32).to_be_bytes());
|
||||
bytes[field + 4..field + 8].copy_from_slice(&7u32.to_be_bytes());
|
||||
}
|
||||
let expected = legacy::align_tags(&legacy::fixed_date(bytes.clone()));
|
||||
let result = normalize_for_embedding(bytes);
|
||||
assert_eq!(result, expected);
|
||||
assert_eq!(normalize_for_embedding(result.clone()), result);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_profile_preserves_color_tags_and_legacy_bytes() {
|
||||
let encoded = crate::Builtin::Srgb.profile().clone().with_encoded_bytes();
|
||||
let input = encoded.to_bytes().to_vec();
|
||||
let normalized = normalize_for_embedding(input.clone());
|
||||
assert_eq!(normalized, legacy::align_tags(&legacy::fixed_date(input)));
|
||||
assert_eq!(&normalized[24..36], &[0; 12]);
|
||||
assert_eq!(&normalized[84..100], &[0; 16]);
|
||||
assert!(crate::Profile::parse(&normalized).is_ok());
|
||||
for index in 0..be(&normalized, 128).unwrap() {
|
||||
assert_eq!(be(&normalized, 136 + index * 12).unwrap() % 4, 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_tables_return_owned_input_without_expansion() {
|
||||
for len in 0..132 {
|
||||
let bytes = vec![1; len];
|
||||
assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes));
|
||||
}
|
||||
for count in [4097u32, u32::MAX] {
|
||||
let mut bytes = vec![1; 144];
|
||||
bytes[128..132].copy_from_slice(&count.to_be_bytes());
|
||||
assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes));
|
||||
}
|
||||
let mut bytes = vec![1; 144];
|
||||
bytes[128..132].copy_from_slice(&1u32.to_be_bytes());
|
||||
bytes[136..140].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
bytes[140..144].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert_eq!(normalize_for_embedding(bytes.clone()), legacy::fixed_date(bytes));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Encoded ICC normalization extracted from LightCraft.
|
||||
pub(super) fn align_tags(b: &[u8]) -> Vec<u8> {
|
||||
let be = |i: usize| b.get(i..i + 4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]) as usize);
|
||||
let Some(n) = be(128) else { return b.to_vec() };
|
||||
let table_end = 132 + 12 * n;
|
||||
let tags: Option<Vec<(usize, usize)>> = (0..n).map(|t| Some((be(132 + 12 * t + 4)?, be(132 + 12 * t + 8)?))).collect();
|
||||
let Some(tags) = tags.filter(|t| table_end <= b.len() && t.iter().all(|&(o, l)| o >= table_end && o + l <= b.len())) else {
|
||||
return b.to_vec();
|
||||
};
|
||||
let mut out = b[..table_end].to_vec();
|
||||
let mut placed: Vec<((usize, usize), usize)> = Vec::new();
|
||||
for (t, &(off, len)) in tags.iter().enumerate() {
|
||||
let new_off = match placed.iter().find(|(k, _)| *k == (off, len)) {
|
||||
// tags sharing data keep sharing it
|
||||
Some(&(_, o)) => o,
|
||||
None => {
|
||||
while !out.len().is_multiple_of(4) {
|
||||
out.push(0);
|
||||
}
|
||||
let o = out.len();
|
||||
out.extend_from_slice(&b[off..off + len]);
|
||||
placed.push(((off, len), o));
|
||||
o
|
||||
}
|
||||
};
|
||||
out[132 + 12 * t + 4..132 + 12 * t + 8].copy_from_slice(&(new_off as u32).to_be_bytes());
|
||||
}
|
||||
while !out.len().is_multiple_of(4) {
|
||||
out.push(0);
|
||||
}
|
||||
let size = out.len() as u32;
|
||||
out[0..4].copy_from_slice(&size.to_be_bytes());
|
||||
// the profile ID (MD5) would no longer match: clear it (= "not computed")
|
||||
out[84..100].fill(0);
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn fixed_date(mut b: Vec<u8>) -> Vec<u8> {
|
||||
if let Some(date) = b.get_mut(24..36) {
|
||||
date.fill(0);
|
||||
}
|
||||
b
|
||||
}
|
||||
@@ -34,6 +34,9 @@
|
||||
//! Input is treated as hostile: every header read is bounds-checked, the picture size is capped
|
||||
//! by [`Limits`] and the image data must be present in full before anything is allocated.
|
||||
|
||||
/// RGBA8-to-10-bit DPX encoding.
|
||||
pub mod rgba8_dpx10;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
//! Uncompressed RGB(A) output from top-down RGBA8 pixels.
|
||||
/// Why the supplied frame cannot be encoded.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Rgba8EncodeError {
|
||||
/// Empty, overflowing, or mismatched dimensions.
|
||||
FrameSize,
|
||||
/// A dimension cannot fit the output format.
|
||||
TooLarge,
|
||||
/// The output buffer could not be allocated.
|
||||
OutOfMemory,
|
||||
}
|
||||
fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result<usize, Rgba8EncodeError> {
|
||||
let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?;
|
||||
if w == 0 || h == 0 || rgba.len() != n {
|
||||
return Err(Rgba8EncodeError::FrameSize);
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
/// Header size of the DPX files we write (file + image + orientation + film + TV headers).
|
||||
const DPX_HEADER: usize = 2048;
|
||||
|
||||
/// A DPX file: 10-bit RGB (8-bit values widened by bit replication, so 0 → 0 and 255 → 1023).
|
||||
pub fn encode_rgba8_dpx10(rgba: &[u8], w: u32, h: u32, creator: &str) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
|
||||
let n = checked_len(rgba, w, h)?;
|
||||
// one 32-bit word per pixel; `n` is already `w * h * 4`
|
||||
let size = n.checked_add(DPX_HEADER).ok_or(Rgba8EncodeError::FrameSize)?;
|
||||
let file_size = u32::try_from(size).map_err(|_| Rgba8EncodeError::TooLarge)?;
|
||||
// SMPTE ST 268: undefined numeric fields are all ones, undefined text fields are NUL
|
||||
let mut hd = vec![0xFF_u8; DPX_HEADER];
|
||||
for (a, b) in [
|
||||
(36, 660), // file name, creation time, creator, project, copyright
|
||||
(664, 768), // reserved
|
||||
(1356, 1408), // reserved
|
||||
(1432, 1620), // source file name, time, input device, serial number
|
||||
(1644, 1664), // reserved
|
||||
(1664, 1712), // film manufacturer, type, offset, prefix, count, format
|
||||
(1732, 1920), // frame id, slate, reserved
|
||||
(1972, 2048), // reserved
|
||||
] {
|
||||
hd[a..b].fill(0);
|
||||
}
|
||||
for e in 0..8 {
|
||||
let d = 780 + e * 72 + 40;
|
||||
hd[d..d + 32].fill(0); // element descriptions
|
||||
}
|
||||
let put32 = |hd: &mut Vec<u8>, at: usize, v: u32| hd[at..at + 4].copy_from_slice(&v.to_be_bytes());
|
||||
let put16 = |hd: &mut Vec<u8>, at: usize, v: u16| hd[at..at + 2].copy_from_slice(&v.to_be_bytes());
|
||||
// file information header
|
||||
hd[0..4].copy_from_slice(b"SDPX");
|
||||
put32(&mut hd, 4, DPX_HEADER as u32); // offset to the image data
|
||||
hd[8..16].copy_from_slice(b"V2.0\0\0\0\0");
|
||||
put32(&mut hd, 16, file_size);
|
||||
put32(&mut hd, 20, 1); // ditto key: new frame
|
||||
put32(&mut hd, 24, 1664); // generic header length
|
||||
put32(&mut hd, 28, 384); // industry header length
|
||||
put32(&mut hd, 32, 0); // user data length
|
||||
let creator = creator.as_bytes();
|
||||
let n = creator.len().min(100);
|
||||
hd[160..160 + n].copy_from_slice(&creator[..n]);
|
||||
// image information header
|
||||
put16(&mut hd, 768, 0); // orientation: left to right, top to bottom
|
||||
put16(&mut hd, 770, 1); // one image element
|
||||
put32(&mut hd, 772, w);
|
||||
put32(&mut hd, 776, h);
|
||||
let el = 780;
|
||||
put32(&mut hd, el, 0); // unsigned
|
||||
put32(&mut hd, el + 4, 0); // reference low data code
|
||||
put32(&mut hd, el + 12, 1023); // reference high data code
|
||||
hd[el + 20] = 50; // descriptor: RGB
|
||||
hd[el + 21] = 6; // transfer: ITU-R BT.709
|
||||
hd[el + 22] = 6; // colorimetric: ITU-R BT.709
|
||||
hd[el + 23] = 10; // bit depth
|
||||
put16(&mut hd, el + 24, 1); // packing: filled to 32-bit words, method A
|
||||
put16(&mut hd, el + 26, 0); // no encoding (uncompressed)
|
||||
put32(&mut hd, el + 28, DPX_HEADER as u32); // offset to the element's data
|
||||
put32(&mut hd, el + 32, 0); // end-of-line padding
|
||||
put32(&mut hd, el + 36, 0); // end-of-image padding
|
||||
// image orientation header: no offset, square pixels
|
||||
put32(&mut hd, 1408, 0);
|
||||
put32(&mut hd, 1412, 0);
|
||||
put32(&mut hd, 1424, w);
|
||||
put32(&mut hd, 1428, h);
|
||||
put32(&mut hd, 1628, 1);
|
||||
put32(&mut hd, 1632, 1);
|
||||
// television header: progressive
|
||||
hd[1928] = 0;
|
||||
// The caller already holds the frame; reserve the output fallibly so a large export reports
|
||||
// an error instead of aborting the process.
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(size).map_err(|_| Rgba8EncodeError::OutOfMemory)?;
|
||||
out.extend_from_slice(&hd);
|
||||
let ten = |v: u8| (u32::from(v) << 2) | (u32::from(v) >> 6);
|
||||
for &[r, g, b, _] in rgba.as_chunks::<4>().0 {
|
||||
out.extend_from_slice(&((ten(r) << 22) | (ten(g) << 12) | (ten(b) << 2)).to_be_bytes());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn packed_rgb_and_creator() {
|
||||
let bytes = encode_rgba8_dpx10(&[255, 0, 128, 255], 1, 1, "FilmCraft").unwrap();
|
||||
assert_eq!(&bytes[..4], b"SDPX");
|
||||
assert_eq!(&bytes[160..169], b"FilmCraft");
|
||||
assert_eq!(&bytes[2048..], &((1023u32 << 22) | (514u32 << 2)).to_be_bytes());
|
||||
assert_eq!(encode_rgba8_dpx10(&[], 0, 1, ""), Err(Rgba8EncodeError::FrameSize));
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,12 @@ default = ["system"]
|
||||
system = ["dep:fontique"]
|
||||
|
||||
[dependencies]
|
||||
harfrust = "0.13"
|
||||
kurbo = { workspace = true }
|
||||
skrifa = { version = "0.47", default-features = false, features = ["std"] }
|
||||
thiserror = { workspace = true }
|
||||
unicode-bidi = "0.3.18"
|
||||
unicode-segmentation = "1.13"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
fontique = { version = "0.11.1", default-features = false, features = ["system", "fontconfig-dlopen"], optional = true }
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Face choice for a grapheme cluster.
|
||||
|
||||
/// Characters requiring their own glyph, after numeral or other caller-supplied mapping.
|
||||
/// Controls, joiners and variation selectors affect shaping but do not need a separate glyph.
|
||||
pub fn drawable_characters<'a>(cluster: &'a str, map: impl Fn(char) -> char + Copy + 'a) -> impl Iterator<Item = char> + 'a {
|
||||
cluster
|
||||
.chars()
|
||||
.map(map)
|
||||
.filter(|&c| !(c.is_control() || matches!(c, '\u{200C}' | '\u{200D}' | '\u{2028}' | '\u{FE00}'..='\u{FE0F}' | '\u{E0100}'..='\u{E01EF}')))
|
||||
}
|
||||
|
||||
/// Select one face for a cluster: prefer the primary if it covers every drawable character;
|
||||
/// otherwise try each character's fallback until a face covers the whole cluster. If none does,
|
||||
/// use the first character's fallback when the primary lacks it, or keep the primary.
|
||||
/// The caller controls the font catalog, ordering and style matching.
|
||||
pub fn cluster_face<F: Clone>(
|
||||
cluster: &str,
|
||||
primary: &F,
|
||||
map: impl Fn(char) -> char + Copy,
|
||||
primary_covers: impl Fn(char) -> bool,
|
||||
mut fallback: impl FnMut(char) -> Option<F>,
|
||||
covers: impl Fn(&F, char) -> bool,
|
||||
) -> F {
|
||||
let characters = || drawable_characters(cluster, map);
|
||||
if characters().all(&primary_covers) {
|
||||
return primary.clone();
|
||||
}
|
||||
for c in characters() {
|
||||
if let Some(face) = fallback(c)
|
||||
&& characters().all(|ch| covers(&face, ch))
|
||||
{
|
||||
return face;
|
||||
}
|
||||
}
|
||||
if let Some(c) = characters().next()
|
||||
&& !primary_covers(c)
|
||||
&& let Some(face) = fallback(c)
|
||||
{
|
||||
return face;
|
||||
}
|
||||
primary.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn chooses_one_face_for_a_base_and_mark() {
|
||||
let fallback = |c| match c {
|
||||
'a' => Some(1),
|
||||
'\u{301}' => Some(2),
|
||||
_ => None,
|
||||
};
|
||||
let covers = |face: &u8, c| *face == 2 || (*face == 1 && c == 'a');
|
||||
assert_eq!(cluster_face("a\u{301}\u{200d}", &0, |c| c, |_| false, fallback, covers), 2);
|
||||
assert_eq!(drawable_characters("a\u{200d}\u{fe0f}", |c| c).collect::<String>(), "a");
|
||||
}
|
||||
#[test]
|
||||
fn uses_first_character_fallback_when_no_face_covers_cluster() {
|
||||
assert_eq!(cluster_face("ab", &0, |c| c, |_| false, |c| if c == 'a' { Some(1) } else { Some(2) }, |face, c| (*face, c) == (1, 'a')), 1);
|
||||
}
|
||||
}
|
||||
@@ -23,21 +23,33 @@
|
||||
mod catalog;
|
||||
mod embedding;
|
||||
mod env;
|
||||
mod fallback;
|
||||
mod fontconfig;
|
||||
mod ligature;
|
||||
mod line_break;
|
||||
mod outline;
|
||||
mod registry;
|
||||
mod scan;
|
||||
mod segments;
|
||||
/// Bounded SFNT face metadata discovery over caller-provided random-access readers.
|
||||
pub mod sfnt;
|
||||
mod shape;
|
||||
mod suitcase;
|
||||
pub mod system;
|
||||
mod visual_order;
|
||||
|
||||
pub use catalog::{Catalog, FontData, FontFileError, Limits, Lister, LoadedFace, Match, Watch};
|
||||
pub use embedding::{SubsetEmbedding, subset_embedding};
|
||||
pub use env::{FontEnv, Os, font_dirs, font_store_dir, office_font_dirs};
|
||||
pub use fallback::{cluster_face, drawable_characters};
|
||||
pub use fontconfig::fontconfig_dirs;
|
||||
pub use ligature::ligature_caret_stops;
|
||||
pub use line_break::settle_line_break;
|
||||
pub use outline::{FontOutline, GlyphPen, OutlineError};
|
||||
pub use scan::{FaceInfo, LocalizedName, Source, is_font_file, style_italic, style_weight, style_width};
|
||||
pub use segments::SegmentBoundary;
|
||||
pub use shape::{RunGlyph, RunInput, ShapeRunError, shape_run};
|
||||
pub use visual_order::{VisualGlyph, visual_order};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Map ligature caret fractions to grapheme boundaries.
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
/// Return logical source-byte caret stops inside a shaped cluster. `font_carets` receives the
|
||||
/// number of stops and may return their normalized positions along the glyph's logical width.
|
||||
/// Missing or incorrectly sized font data falls back to equal divisions of the width.
|
||||
pub fn ligature_caret_stops(text: &str, byte: usize, len: usize, font_carets: impl FnOnce(usize) -> Option<Vec<f64>>) -> Vec<(usize, f64)> {
|
||||
let Some(s) = byte.checked_add(len).and_then(|end| text.get(byte..end)).filter(|_| len > 1) else { return Vec::new() };
|
||||
let starts: Vec<usize> = s.grapheme_indices(true).skip(1).map(|(i, _)| byte + i).collect();
|
||||
if starts.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let parts = starts.len() + 1;
|
||||
let mut at =
|
||||
font_carets(starts.len()).filter(|c| c.len() == starts.len()).unwrap_or_else(|| (1..parts).map(|j| j as f64 / parts as f64).collect());
|
||||
at.sort_by(f64::total_cmp);
|
||||
starts.into_iter().zip(at).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn maps_graphemes_and_sorts_font_positions() {
|
||||
assert_eq!(ligature_caret_stops("ábc", 0, 5, |_| Some(vec![0.8, 0.3])), vec![(3, 0.3), (4, 0.8)]);
|
||||
}
|
||||
#[test]
|
||||
fn falls_back_and_rejects_invalid_ranges() {
|
||||
assert_eq!(ligature_caret_stops("abc", 0, 3, |_| Some(vec![0.5])), vec![(1, 1.0 / 3.0), (2, 2.0 / 3.0)]);
|
||||
assert!(ligature_caret_stops("abc", usize::MAX, 2, |_| None).is_empty());
|
||||
assert!(ligature_caret_stops("é", 1, 1, |_| None).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
//! Choose a line break after measuring candidate lines as drawn.
|
||||
|
||||
/// Choose the latest candidate that fits when a tab changes the line's drawn width.
|
||||
///
|
||||
/// `breaks` must be sorted by glyph index and the boolean marks hyphenated breaks.
|
||||
/// `checks` limits the candidates measured individually from the end; older non-hyphenated
|
||||
/// candidates are bisected, assuming their drawn widths are nondecreasing. If none fits,
|
||||
/// the earliest eligible break is returned. Without a tab or a measurement callback the
|
||||
/// original `chosen` break is returned.
|
||||
pub fn settle_line_break(
|
||||
tabbed: bool,
|
||||
checks: usize,
|
||||
start: usize,
|
||||
chosen: (usize, bool),
|
||||
breaks: &[(usize, bool)],
|
||||
fits: Option<&dyn Fn(usize, bool) -> bool>,
|
||||
) -> (usize, bool) {
|
||||
let Some(fits) = fits.filter(|_| tabbed) else { return chosen };
|
||||
if fits(chosen.0, chosen.1) {
|
||||
return chosen;
|
||||
}
|
||||
let earlier = breaks.get(breaks.partition_point(|b| b.0 <= start)..breaks.partition_point(|b| b.0 < chosen.0)).unwrap_or_default();
|
||||
if let Some(&b) = earlier.iter().rev().take(checks).find(|b| fits(b.0, b.1)) {
|
||||
return b;
|
||||
}
|
||||
let rest = earlier.get(..earlier.len().saturating_sub(checks)).unwrap_or_default();
|
||||
let plain: Vec<&(usize, bool)> = rest.iter().filter(|b| !b.1).collect();
|
||||
let fitting = plain.partition_point(|b| fits(b.0, b.1));
|
||||
fitting.checked_sub(1).and_then(|k| plain.get(k).copied()).or(earlier.first()).copied().unwrap_or(chosen)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn measures_latest_candidates_and_preserves_hyphenation() {
|
||||
let breaks = [(1, false), (2, false), (3, true), (4, false)];
|
||||
let fits = |i, hyphen| i <= 2 || (i == 3 && hyphen);
|
||||
assert_eq!(settle_line_break(true, 2, 0, (4, false), &breaks, Some(&fits)), (3, true));
|
||||
assert_eq!(settle_line_break(false, 2, 0, (4, false), &breaks, Some(&fits)), (4, false));
|
||||
}
|
||||
#[test]
|
||||
fn bisects_older_plain_breaks_and_falls_back_to_first_eligible() {
|
||||
let breaks = [(1, false), (2, true), (3, false), (4, false), (5, false)];
|
||||
assert_eq!(settle_line_break(true, 1, 0, (5, false), &breaks, Some(&|i, _| i <= 3)), (3, false));
|
||||
assert_eq!(settle_line_break(true, 1, 1, (5, false), &breaks, Some(&|_, _| false)), (2, true));
|
||||
assert_eq!(settle_line_break(true, 1, 5, (5, false), &breaks, Some(&|_, _| false)), (5, false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Boundaries between runs that need separate shaping.
|
||||
|
||||
/// Tracks the properties of the current shaping segment while walking grapheme clusters.
|
||||
/// The caller resolves font faces, bidi levels and script classification; marks stay with the
|
||||
/// preceding segment even when their face, level or case differs.
|
||||
pub struct SegmentBoundary<F, L, S> {
|
||||
face: F,
|
||||
level: L,
|
||||
small_caps: bool,
|
||||
strong_script: Option<S>,
|
||||
}
|
||||
|
||||
impl<F: Copy + Eq, L: Copy + Eq, S: Copy + Eq> SegmentBoundary<F, L, S> {
|
||||
/// Begin at the first segment's face and bidi level.
|
||||
pub fn new(face: F, level: L) -> Self {
|
||||
Self { face, level, small_caps: false, strong_script: None }
|
||||
}
|
||||
|
||||
/// Observe a cluster and return whether it begins a new shaping segment. Pass `None` for
|
||||
/// common or inherited script and `true` for marks, joiners and variation selectors.
|
||||
pub fn advance(&mut self, face: F, level: L, small_caps: bool, strong_script: Option<S>, mark: bool) -> bool {
|
||||
let script_change = matches!((self.strong_script, strong_script), (Some(a), Some(b)) if a != b);
|
||||
let split = (self.face != face || self.level != level || self.small_caps != small_caps || script_change) && !mark;
|
||||
if split {
|
||||
self.face = face;
|
||||
self.level = level;
|
||||
self.small_caps = small_caps;
|
||||
}
|
||||
if let Some(script) = strong_script {
|
||||
self.strong_script = Some(script);
|
||||
}
|
||||
split
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn preserves_marks_and_splits_on_face_direction_case_and_script() {
|
||||
let mut state = SegmentBoundary::<u8, u8, u8>::new(1, 0);
|
||||
assert!(!state.advance(1, 0, false, Some(1), false));
|
||||
assert!(!state.advance(2, 1, true, None, true));
|
||||
assert!(state.advance(2, 1, true, Some(2), false));
|
||||
assert!(!state.advance(2, 1, true, None, false));
|
||||
assert!(state.advance(2, 1, true, Some(1), false));
|
||||
}
|
||||
#[test]
|
||||
fn strong_script_on_a_mark_updates_the_following_boundary() {
|
||||
let mut state = SegmentBoundary::<u8, u8, u8>::new(1, 0);
|
||||
assert!(!state.advance(1, 0, false, Some(1), false));
|
||||
assert!(!state.advance(1, 0, false, Some(2), true));
|
||||
assert!(!state.advance(1, 0, false, Some(2), false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
//! Shape a run with its source clusters and surrounding text context.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use harfrust::{BufferClusterLevel, Direction, Feature, Language, Script, ShapeOptions, ShapePlan, Shaper, UnicodeBuffer};
|
||||
|
||||
/// Parameters for a single directional run. Text is in logical order and `source_start` is its
|
||||
/// byte offset in the complete source. Context influences joining but emits no glyphs.
|
||||
pub struct RunInput<'a> {
|
||||
/// Text in this run.
|
||||
pub text: &'a str,
|
||||
/// Its byte offset in the complete source.
|
||||
pub source_start: usize,
|
||||
/// Text before the run, within the same shaping context.
|
||||
pub pre_context: &'a str,
|
||||
/// Text after the run, within the same shaping context.
|
||||
pub post_context: &'a str,
|
||||
/// Direction of shaping.
|
||||
pub direction: Direction,
|
||||
/// Language used for language-specific forms.
|
||||
pub language: Option<&'a Language>,
|
||||
/// OpenType features with ranges in source byte coordinates.
|
||||
pub features: &'a [Feature],
|
||||
/// Use character-level instead of monotone grapheme clusters.
|
||||
pub character_clusters: bool,
|
||||
/// Uppercase each mapped character without losing its source cluster.
|
||||
pub uppercase: bool,
|
||||
}
|
||||
|
||||
/// A glyph in design units, with its source-byte cluster and directional advances and offsets.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RunGlyph {
|
||||
pub glyph_id: u32,
|
||||
pub cluster: u32,
|
||||
pub x_advance: i32,
|
||||
pub y_advance: i32,
|
||||
pub x_offset: i32,
|
||||
pub y_offset: i32,
|
||||
}
|
||||
|
||||
/// A run's source offsets cannot fit HarfRust's 32-bit clusters.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("shaping cluster exceeds the 32-bit source offset range")]
|
||||
pub struct ShapeRunError;
|
||||
|
||||
/// Shape a run using a caller's face-specific plan cache. `map_character` applies digit or other
|
||||
/// character mapping before case conversion; expansions retain the original byte cluster.
|
||||
/// The plan callback receives the guessed script, direction, language and feature set so it can
|
||||
/// reuse plans for the particular shaper and its variable-font instance.
|
||||
pub fn shape_run(
|
||||
shaper: &Shaper<'_>,
|
||||
input: &RunInput<'_>,
|
||||
mut map_character: impl FnMut(char) -> char,
|
||||
plan: impl FnOnce(&Shaper<'_>, Direction, Option<Script>, Option<&Language>, &[Feature]) -> Arc<ShapePlan>,
|
||||
) -> Result<Vec<RunGlyph>, ShapeRunError> {
|
||||
let mut buffer = UnicodeBuffer::new();
|
||||
for (offset, character) in input.text.char_indices() {
|
||||
let cluster = input.source_start.checked_add(offset).and_then(|n| u32::try_from(n).ok()).ok_or(ShapeRunError)?;
|
||||
let character = map_character(character);
|
||||
if input.uppercase {
|
||||
for upper in character.to_uppercase() {
|
||||
buffer.add(upper, cluster);
|
||||
}
|
||||
} else {
|
||||
buffer.add(character, cluster);
|
||||
}
|
||||
}
|
||||
buffer.set_direction(input.direction);
|
||||
buffer.guess_segment_properties();
|
||||
if input.character_clusters {
|
||||
buffer.set_cluster_level(BufferClusterLevel::Characters);
|
||||
}
|
||||
if let Some(language) = input.language {
|
||||
buffer.set_language(language.clone());
|
||||
}
|
||||
buffer.set_pre_context(input.pre_context);
|
||||
buffer.set_post_context(input.post_context);
|
||||
let script = Some(buffer.script()).filter(|s| *s != harfrust::script::UNKNOWN);
|
||||
let plan = plan(shaper, buffer.direction(), script, input.language, input.features);
|
||||
let glyphs = shaper.shape(buffer, ShapeOptions::new().features(input.features).plan(Some(&plan)));
|
||||
Ok(glyphs
|
||||
.glyph_infos()
|
||||
.iter()
|
||||
.zip(glyphs.glyph_positions())
|
||||
.map(|(info, pos)| RunGlyph {
|
||||
glyph_id: info.glyph_id,
|
||||
cluster: info.cluster,
|
||||
x_advance: pos.x_advance,
|
||||
y_advance: pos.y_advance,
|
||||
x_offset: pos.x_offset,
|
||||
y_offset: pos.y_offset,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use harfrust::{FontRef, ShaperData};
|
||||
|
||||
#[test]
|
||||
fn synthetic_face_runs_without_installed_fonts() {
|
||||
// A tiny face with a single .notdef glyph. The shaper still processes source
|
||||
// clusters, direction, mapping, features and context without external font files.
|
||||
let mut builder = write_fonts::FontBuilder::new();
|
||||
let mut head = vec![0; 54];
|
||||
head[18..20].copy_from_slice(&1000u16.to_be_bytes());
|
||||
let mut hhea = vec![0; 36];
|
||||
hhea[34..36].copy_from_slice(&1u16.to_be_bytes());
|
||||
for (tag, bytes) in [(b"head", head), (b"hhea", hhea), (b"hmtx", vec![0, 100, 0, 0]), (b"maxp", vec![0, 0, 0x50, 0, 0, 1])] {
|
||||
builder.add_raw(write_fonts::types::Tag::new(tag), bytes);
|
||||
}
|
||||
check_run(&builder.build());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_matches_direct_shaping_with_source_clusters_and_context() {
|
||||
let Ok(dir) = std::env::var("CRAFT_FONTS_DIR") else { return };
|
||||
let bytes = std::fs::read(std::path::Path::new(&dir).join("fonts/noto-sans-arabic/NotoSansArabic.ttf")).unwrap();
|
||||
check_run(&bytes);
|
||||
}
|
||||
|
||||
fn check_run(bytes: &[u8]) {
|
||||
let font = FontRef::from_index(bytes, 0).unwrap();
|
||||
let data = ShaperData::new(&font);
|
||||
let shaper = data.shaper(&font).build();
|
||||
let overflow = RunInput {
|
||||
text: "ab",
|
||||
source_start: usize::MAX,
|
||||
pre_context: "",
|
||||
post_context: "",
|
||||
direction: Direction::LeftToRight,
|
||||
language: None,
|
||||
features: &[],
|
||||
character_clusters: false,
|
||||
uppercase: false,
|
||||
};
|
||||
assert!(shape_run(&shaper, &overflow, |c| c, |s, d, script, lang, f| Arc::new(ShapePlan::new(s, d, script, lang, f))).is_err());
|
||||
let language: Language = "ar".parse().unwrap();
|
||||
let features = [Feature::new(harfrust::Tag::new(b"kern"), 0, 19..25)];
|
||||
for direction in [Direction::LeftToRight, Direction::RightToLeft, Direction::TopToBottom] {
|
||||
let input = RunInput {
|
||||
text: "بaß1",
|
||||
source_start: 19,
|
||||
pre_context: "س",
|
||||
post_context: "م",
|
||||
direction,
|
||||
language: Some(&language),
|
||||
features: &features,
|
||||
character_clusters: true,
|
||||
uppercase: true,
|
||||
};
|
||||
let map = |c| if c == '1' { '٢' } else { c };
|
||||
let actual =
|
||||
shape_run(&shaper, &input, map, |s, d, script, lang, features| Arc::new(ShapePlan::new(s, d, script, lang, features))).unwrap();
|
||||
let mut buffer = UnicodeBuffer::new();
|
||||
for (i, c) in input.text.char_indices() {
|
||||
for upper in map(c).to_uppercase() {
|
||||
buffer.add(upper, 19 + i as u32);
|
||||
}
|
||||
}
|
||||
buffer.set_direction(direction);
|
||||
buffer.guess_segment_properties();
|
||||
buffer.set_cluster_level(BufferClusterLevel::Characters);
|
||||
buffer.set_language(language.clone());
|
||||
buffer.set_pre_context(input.pre_context);
|
||||
buffer.set_post_context(input.post_context);
|
||||
let script = Some(buffer.script()).filter(|s| *s != harfrust::script::UNKNOWN);
|
||||
let plan = ShapePlan::new(&shaper, direction, script, Some(&language), &features);
|
||||
let expected = shaper.shape(buffer, ShapeOptions::new().features(&features).plan(Some(&plan)));
|
||||
let tuples: Vec<_> = expected
|
||||
.glyph_infos()
|
||||
.iter()
|
||||
.zip(expected.glyph_positions())
|
||||
.map(|(i, p)| (i.glyph_id, i.cluster, p.x_advance, p.y_advance, p.x_offset, p.y_offset))
|
||||
.collect();
|
||||
assert_eq!(actual.iter().map(|g| (g.glyph_id, g.cluster, g.x_advance, g.y_advance, g.x_offset, g.y_offset)).collect::<Vec<_>>(), tuples);
|
||||
assert!(!actual.is_empty());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Visual ordering of shaped clusters after line bidi levels are resolved.
|
||||
use std::ops::Range;
|
||||
use unicode_bidi::{BidiInfo, Level};
|
||||
|
||||
/// A glyph's source byte, source length and original resolved level.
|
||||
/// Zero-length glyphs represent list markers.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct VisualGlyph {
|
||||
/// Byte offset in the original text.
|
||||
pub byte: usize,
|
||||
/// Source length in bytes, or zero for a list marker.
|
||||
pub len: usize,
|
||||
/// Original level, also used when the line levels lack this byte.
|
||||
pub level: Level,
|
||||
}
|
||||
|
||||
/// Order glyph indices by cluster using caller-resolved line levels (UAX #9 L1–L2).
|
||||
/// `levels` is indexed relative to `paragraph_start`. Adjacent marker glyphs at the
|
||||
/// same byte form their own cluster and reverse internally at a right-to-left level.
|
||||
pub fn visual_order(glyphs: impl IntoIterator<Item = VisualGlyph>, paragraph_start: usize, levels: &[Level]) -> Vec<usize> {
|
||||
let mut clusters: Vec<(Range<usize>, VisualGlyph)> = Vec::new();
|
||||
for (i, glyph) in glyphs.into_iter().enumerate() {
|
||||
if let Some((range, _)) = clusters.last_mut().filter(|(_, prev)| prev.byte == glyph.byte && (prev.len == 0) == (glyph.len == 0)) {
|
||||
range.end = i + 1;
|
||||
} else {
|
||||
clusters.push((i..i + 1, glyph));
|
||||
}
|
||||
}
|
||||
let cluster_levels: Vec<_> = clusters
|
||||
.iter()
|
||||
.map(|(_, g)| if g.len == 0 { g.level } else { levels.get(g.byte.saturating_sub(paragraph_start)).copied().unwrap_or(g.level) })
|
||||
.collect();
|
||||
BidiInfo::reorder_visual(&cluster_levels)
|
||||
.into_iter()
|
||||
.filter_map(|i| clusters.get(i))
|
||||
.flat_map(|(range, glyph)| {
|
||||
let mut indices: Vec<_> = range.clone().collect();
|
||||
if glyph.len == 0 && glyph.level.is_rtl() {
|
||||
indices.reverse();
|
||||
}
|
||||
indices
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn clusters_and_markers_keep_their_distinct_order() {
|
||||
let l = Level::ltr();
|
||||
let r = Level::rtl();
|
||||
let glyphs = [
|
||||
VisualGlyph { byte: 5, len: 0, level: r },
|
||||
VisualGlyph { byte: 5, len: 0, level: r },
|
||||
VisualGlyph { byte: 5, len: 2, level: r },
|
||||
VisualGlyph { byte: 5, len: 2, level: r },
|
||||
VisualGlyph { byte: 7, len: 1, level: l },
|
||||
];
|
||||
assert_eq!(visual_order(glyphs, 5, &[r, r, l]), vec![2, 3, 1, 0, 4]);
|
||||
assert!(visual_order([], 0, &[]).is_empty());
|
||||
}
|
||||
#[test]
|
||||
fn missing_levels_fall_back_to_glyph_level() {
|
||||
let r = Level::rtl();
|
||||
let glyphs = [VisualGlyph { byte: 2, len: 1, level: r }, VisualGlyph { byte: 3, len: 1, level: r }];
|
||||
assert_eq!(visual_order(glyphs, 0, &[]), vec![1, 0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "craft-gridcraft-format"
|
||||
description = "GridCraft's native JSON workbook file: its extensions, reader and pretty writer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,17 @@
|
||||
# craft-gridcraft-format
|
||||
|
||||
GridCraft's native workbook file is one pretty-printed UTF-8 JSON object, with a two-space indent
|
||||
and no newline at the end. It is saved as `.json`, or as `.scjson` by older builds.
|
||||
|
||||
The workbook is a type parameter. GridCraft owns the model, and after a read it rebuilds the
|
||||
model's indexes, drops cells outside the grid and reads the macros. This crate owns the bytes:
|
||||
|
||||
- `EXTENSIONS` and `is_extension` name the format.
|
||||
- `read(bytes)` reads a workbook. A failure reads as "not a GridCraft JSON workbook: …".
|
||||
- `write(workbook)` writes one with `serde_json`'s pretty printer.
|
||||
- `write_with_kept(workbook, field, kept)` appends entries that a newer version wrote, and this
|
||||
build kept without reading, to the top-level list `field`, as the file held them. With nothing
|
||||
kept, the output is exactly `write`'s. Otherwise the workbook goes through a `serde_json::Value`
|
||||
first, so its object keys come out in map order, as GridCraft has always written them.
|
||||
|
||||
There is no `unsafe` and no panics, and it builds for `wasm32-unknown-unknown`.
|
||||
@@ -0,0 +1,59 @@
|
||||
//! GridCraft's native workbook file: the workbook as one pretty-printed UTF-8 JSON object,
|
||||
//! saved as `.json` (or `.scjson`, its older name).
|
||||
//!
|
||||
//! GridCraft owns the workbook model and what happens after a read: rebuilding its indexes,
|
||||
//! dropping cells outside the grid, and reading its macros. This crate owns the bytes: which
|
||||
//! extensions name the format, how the JSON is read and written, and how entries kept from a
|
||||
//! newer version are written back into a list as the file held them.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
use serde::Serialize;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
/// The extensions of the format, lower case. `scjson` is the name older builds saved.
|
||||
pub const EXTENSIONS: [&str; 2] = ["json", "scjson"];
|
||||
|
||||
/// Whether `extension` (without the dot, any case) names the format.
|
||||
pub fn is_extension(extension: &str) -> bool {
|
||||
EXTENSIONS.iter().any(|e| e.eq_ignore_ascii_case(extension))
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The bytes are not a workbook: not JSON, or JSON of another shape.
|
||||
#[error("not a GridCraft JSON workbook: {0}")]
|
||||
Read(serde_json::Error),
|
||||
/// The workbook could not be written as JSON.
|
||||
#[error("{0}")]
|
||||
Write(serde_json::Error),
|
||||
}
|
||||
|
||||
/// Read a workbook. Unknown fields are left to the model's own serde rules.
|
||||
pub fn read<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, Error> {
|
||||
serde_json::from_slice(bytes).map_err(Error::Read)
|
||||
}
|
||||
|
||||
/// Write a workbook as pretty-printed JSON (two-space indent, no newline at the end).
|
||||
pub fn write<T: Serialize>(workbook: &T) -> Result<Vec<u8>, Error> {
|
||||
serde_json::to_vec_pretty(workbook).map_err(Error::Write)
|
||||
}
|
||||
|
||||
/// [`write`], with `kept` appended to the top-level list `field` (made if absent): entries a
|
||||
/// newer version wrote that this build kept without reading. With nothing kept this is exactly
|
||||
/// [`write`]. Otherwise the workbook goes through a [`Value`] first, so its object keys are
|
||||
/// written in `serde_json`'s map order.
|
||||
pub fn write_with_kept<T: Serialize>(workbook: &T, field: &str, kept: &[Value]) -> Result<Vec<u8>, Error> {
|
||||
if kept.is_empty() {
|
||||
return write(workbook);
|
||||
}
|
||||
let mut v = serde_json::to_value(workbook).map_err(Error::Write)?;
|
||||
if let Some(list) = v.as_object_mut().map(|o| o.entry(field).or_insert_with(|| Value::Array(vec![]))).and_then(Value::as_array_mut) {
|
||||
list.extend(kept.iter().cloned());
|
||||
}
|
||||
serde_json::to_vec_pretty(&v).map_err(Error::Write)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,87 @@
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::json;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A stand-in for an app's workbook: fields in declaration order, one of them a list.
|
||||
#[derive(Debug, PartialEq, Serialize, Deserialize)]
|
||||
struct Book {
|
||||
sheets: Vec<String>,
|
||||
active: u32,
|
||||
#[serde(default)]
|
||||
macros: Vec<Value>,
|
||||
}
|
||||
|
||||
fn book() -> Book {
|
||||
Book { sheets: vec!["Sheet1".into(), "Été ✓".into()], active: 1, macros: vec![json!({"v": 1, "name": "Fill"})] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extensions_are_json_and_scjson_in_any_case() {
|
||||
for yes in ["json", "scjson", "JSON", "ScJson"] {
|
||||
assert!(is_extension(yes), "{yes}");
|
||||
}
|
||||
for no in ["", "xlsx", "jsonl", ".json", "scjs"] {
|
||||
assert!(!is_extension(no), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_workbook_is_written_pretty_in_field_order() {
|
||||
let bytes = write(&book()).unwrap();
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert_eq!(
|
||||
text,
|
||||
"{\n \"sheets\": [\n \"Sheet1\",\n \"Été ✓\"\n ],\n \"active\": 1,\n \"macros\": [\n {\n \"name\": \"Fill\",\n \"v\": 1\n }\n ]\n}"
|
||||
);
|
||||
assert_eq!(read::<Book>(text.as_bytes()).unwrap(), book());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_entries_are_appended_as_the_file_held_them() {
|
||||
let kept = [json!({"v": 9, "name": "Future", "extra": [1, 2]})];
|
||||
let bytes = write_with_kept(&book(), "macros", &kept).unwrap();
|
||||
let back: Book = read(&bytes).unwrap();
|
||||
assert_eq!(back.macros, [json!({"v": 1, "name": "Fill"}), kept[0].clone()]);
|
||||
// Through a JSON value, keys are in map order: `active` before `macros` before `sheets`.
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
assert!(text.find("\"active\"") < text.find("\"macros\"") && text.find("\"macros\"") < text.find("\"sheets\""), "{text}");
|
||||
// With nothing kept, the plain writer's bytes.
|
||||
assert_eq!(write_with_kept(&book(), "macros", &[]).unwrap(), write(&book()).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kept_entries_make_the_list_when_it_is_absent() {
|
||||
#[derive(Serialize)]
|
||||
struct Bare {
|
||||
sheets: Vec<String>,
|
||||
}
|
||||
let bytes = write_with_kept(&Bare { sheets: vec![] }, "macros", &[json!(1)]).unwrap();
|
||||
assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap(), json!({"sheets": [], "macros": [1]}));
|
||||
// A field that is not a list is left as it is.
|
||||
let bytes = write_with_kept(&json!({"macros": "text"}), "macros", &[json!(1)]).unwrap();
|
||||
assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap(), json!({"macros": "text"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn what_is_not_a_workbook_says_so() {
|
||||
for bad in [&b""[..], b"{", b"[]", b"{\"sheets\": 7, \"active\": 0}", b"\xff\xfe"] {
|
||||
let err = read::<Book>(bad).unwrap_err();
|
||||
assert!(matches!(err, Error::Read(_)));
|
||||
assert!(err.to_string().starts_with("not a GridCraft JSON workbook: "), "{err}");
|
||||
}
|
||||
assert_eq!(
|
||||
read::<Book>(b"{\"sheets\": 7}").unwrap_err().to_string(),
|
||||
"not a GridCraft JSON workbook: invalid type: integer `7`, expected a sequence at line 1 column 12"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_value_json_cannot_hold_is_a_write_error() {
|
||||
use std::collections::BTreeMap;
|
||||
let bad: BTreeMap<Vec<u8>, u8> = [(vec![1], 1)].into();
|
||||
assert!(matches!(write(&bad), Err(Error::Write(_))));
|
||||
assert!(matches!(write_with_kept(&bad, "macros", &[json!(1)]), Err(Error::Write(_))));
|
||||
}
|
||||
@@ -18,6 +18,9 @@
|
||||
//! Input is treated as hostile: the picture size is capped by [`Limits`], and a run-length file
|
||||
//! must be long enough to hold the pixels its header declares before anything is allocated.
|
||||
|
||||
/// Uncompressed RGBA8-to-Targa encoding.
|
||||
pub mod rgba8_raw;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Uncompressed RGB(A) output from top-down RGBA8 pixels.
|
||||
/// Why the supplied frame cannot be encoded.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Rgba8EncodeError {
|
||||
/// Empty, overflowing, or mismatched dimensions.
|
||||
FrameSize,
|
||||
/// A dimension cannot fit the 16-bit Targa header.
|
||||
Dimensions,
|
||||
/// The output buffer could not be allocated.
|
||||
OutOfMemory,
|
||||
}
|
||||
fn checked_len(rgba: &[u8], w: u32, h: u32) -> std::result::Result<usize, Rgba8EncodeError> {
|
||||
let n = (w as usize).checked_mul(h as usize).and_then(|n| n.checked_mul(4)).ok_or(Rgba8EncodeError::FrameSize)?;
|
||||
if w == 0 || h == 0 || rgba.len() != n {
|
||||
return Err(Rgba8EncodeError::FrameSize);
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
/// An uncompressed Targa file: 24-bit BGR, or 32-bit BGRA with `alpha` (straight alpha, as the
|
||||
/// frame carries it).
|
||||
pub fn encode_rgba8_raw(rgba: &[u8], w: u32, h: u32, alpha: bool) -> std::result::Result<Vec<u8>, Rgba8EncodeError> {
|
||||
checked_len(rgba, w, h)?;
|
||||
let (tw, th) = match (u16::try_from(w), u16::try_from(h)) {
|
||||
(Ok(tw), Ok(th)) => (tw, th),
|
||||
_ => return Err(Rgba8EncodeError::Dimensions),
|
||||
};
|
||||
let bpp: usize = if alpha { 4 } else { 3 };
|
||||
let row = w as usize * 4;
|
||||
// The caller already holds the frame; reserve the second, output-sized buffer fallibly so a
|
||||
// large export reports an error instead of aborting the process.
|
||||
let len = (w as usize * h as usize).checked_mul(bpp).and_then(|n| n.checked_add(18 + 26)).ok_or(Rgba8EncodeError::FrameSize)?;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(len).map_err(|_| Rgba8EncodeError::OutOfMemory)?;
|
||||
out.extend_from_slice(&[0, 0, 2]); // no ID, no colour map, uncompressed true-colour
|
||||
out.extend_from_slice(&[0; 5]); // colour map specification (unused)
|
||||
out.extend_from_slice(&[0, 0, 0, 0]); // x / y origin
|
||||
out.extend_from_slice(&tw.to_le_bytes());
|
||||
out.extend_from_slice(&th.to_le_bytes());
|
||||
out.push(if alpha { 32 } else { 24 });
|
||||
out.push(if alpha { 8 } else { 0 }); // attribute bits; bottom-left origin
|
||||
// bottom-left origin: the last frame row comes first
|
||||
for line in rgba.chunks_exact(row).rev() {
|
||||
for &[r, g, b, a] in line.as_chunks::<4>().0 {
|
||||
out.extend_from_slice(&[b, g, r]);
|
||||
if alpha {
|
||||
out.push(a);
|
||||
}
|
||||
}
|
||||
}
|
||||
// TGA 2.0 footer without extension or developer areas
|
||||
out.extend_from_slice(&[0; 8]);
|
||||
out.extend_from_slice(b"TRUEVISION-XFILE.\0");
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn raw_round_trip() {
|
||||
let bytes = encode_rgba8_raw(&[1, 2, 3, 4], 1, 1, true).unwrap();
|
||||
assert_eq!(&bytes[18..22], &[3, 2, 1, 4]);
|
||||
assert_eq!(&bytes[bytes.len() - 18..], b"TRUEVISION-XFILE.\0");
|
||||
assert_eq!(encode_rgba8_raw(&[], 0, 1, false), Err(Rgba8EncodeError::FrameSize));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user