mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-22 13:57:08 -06:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
29e17181bf | ||
|
|
b3d11070e4 | ||
|
|
155fd45d61 | ||
|
|
0bc69feed0 | ||
|
|
27256f0ba5 | ||
|
|
386750bd56 | ||
|
|
eec225a218 | ||
|
|
7b525189c0 | ||
|
|
13de76e5b2 | ||
|
|
e5091e052e | ||
|
|
a009f7d022 | ||
|
|
305f452283 | ||
|
|
78bcdce794 | ||
|
|
fd11b47915 | ||
|
|
ca6c100342 | ||
|
|
072ec4500a | ||
|
|
58a13b5a64 | ||
|
|
281f86d602 | ||
|
|
caaa0e37f7 |
Generated
+39
@@ -746,6 +746,8 @@ version = "0.21.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cadcraft-geom",
|
"cadcraft-geom",
|
||||||
"craft-dxf",
|
"craft-dxf",
|
||||||
|
"craft-font-catalog",
|
||||||
|
"craft-shx",
|
||||||
"encoding_rs",
|
"encoding_rs",
|
||||||
"harfrust 0.14.0",
|
"harfrust 0.14.0",
|
||||||
"icu_segmenter",
|
"icu_segmenter",
|
||||||
@@ -828,6 +830,7 @@ dependencies = [
|
|||||||
"cadcraft-io",
|
"cadcraft-io",
|
||||||
"cadcraft-render",
|
"cadcraft-render",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
"craft-image-codecs",
|
||||||
"craft-ui",
|
"craft-ui",
|
||||||
"craft-update",
|
"craft-update",
|
||||||
"craft-window",
|
"craft-window",
|
||||||
@@ -1204,6 +1207,16 @@ dependencies = [
|
|||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "craft-font-catalog"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "git+https://github.com/storytold/craft-libs?rev=c07e38090879ffa994f893df9956c6d5b96c049c#c07e38090879ffa994f893df9956c6d5b96c049c"
|
||||||
|
dependencies = [
|
||||||
|
"skrifa 0.47.0",
|
||||||
|
"thiserror 2.0.21",
|
||||||
|
"windows-registry",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "craft-fonts-build"
|
name = "craft-fonts-build"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -1314,6 +1327,11 @@ dependencies = [
|
|||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "craft-shx"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "git+https://github.com/storytold/craft-libs?rev=3c5007339754def577b3c5274f523d96384a35c4#3c5007339754def577b3c5274f523d96384a35c4"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "craft-tiff"
|
name = "craft-tiff"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -4166,6 +4184,17 @@ dependencies = [
|
|||||||
"once_cell",
|
"once_cell",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "read-fonts"
|
||||||
|
version = "0.44.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"font-types 0.12.7",
|
||||||
|
"once_cell",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "read-fonts"
|
name = "read-fonts"
|
||||||
version = "0.45.1"
|
version = "0.45.1"
|
||||||
@@ -4630,6 +4659,16 @@ dependencies = [
|
|||||||
"read-fonts 0.41.0",
|
"read-fonts 0.41.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "skrifa"
|
||||||
|
version = "0.47.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f"
|
||||||
|
dependencies = [
|
||||||
|
"bytemuck",
|
||||||
|
"read-fonts 0.44.0",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "skrifa"
|
name = "skrifa"
|
||||||
version = "0.48.0"
|
version = "0.48.0"
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ cadcraft-geom = { path = "crates/geom" }
|
|||||||
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
|
||||||
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
|
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
|
||||||
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
|
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
|
||||||
|
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "3c5007339754def577b3c5274f523d96384a35c4" }
|
||||||
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
|
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
|
||||||
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
|
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
|
||||||
cadcraft-color = { path = "crates/color" }
|
cadcraft-color = { path = "crates/color" }
|
||||||
@@ -34,6 +35,8 @@ craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-l
|
|||||||
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
|
||||||
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
|
||||||
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
|
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", default-features = false }
|
||||||
|
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
|
||||||
|
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "c07e38090879ffa994f893df9956c6d5b96c049c", default-features = false }
|
||||||
clap = { version = "4", features = ["derive", "env"] }
|
clap = { version = "4", features = ["derive", "env"] }
|
||||||
clap_complete = "4.6.11"
|
clap_complete = "4.6.11"
|
||||||
clap_mangen = { version = "0.3.3", features = ["env"] }
|
clap_mangen = { version = "0.3.3", features = ["env"] }
|
||||||
|
|||||||
@@ -363,7 +363,7 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
|
|||||||
let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
|
let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
|
||||||
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
|
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
|
||||||
}
|
}
|
||||||
let png = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?;
|
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
|
||||||
let layout = space.tab_name();
|
let layout = space.tab_name();
|
||||||
Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape }))
|
Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape }))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,8 @@ workspace = true
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
cadcraft-geom = { workspace = true }
|
cadcraft-geom = { workspace = true }
|
||||||
craft-dxf = { workspace = true }
|
craft-dxf = { workspace = true }
|
||||||
|
craft-font-catalog = { workspace = true }
|
||||||
|
craft-shx = { workspace = true }
|
||||||
skrifa = { workspace = true }
|
skrifa = { workspace = true }
|
||||||
harfrust = { workspace = true }
|
harfrust = { workspace = true }
|
||||||
unicode-bidi = { workspace = true }
|
unicode-bidi = { workspace = true }
|
||||||
|
|||||||
@@ -1,313 +0,0 @@
|
|||||||
//! Shape source (`.shp`) to a compiled SHX file, as COMPILE does.
|
|
||||||
//!
|
|
||||||
//! A source is a list of definitions: a header line `*number,defbytes,NAME` followed by its
|
|
||||||
//! specification bytes (on as many lines as needed, ending with 0). Numbers are decimal, or
|
|
||||||
//! hexadecimal after a leading `0` (`012`, `08cfb`); parentheses only group; `;` starts a
|
|
||||||
//! comment. A big font starts with `*BIGFONT nchars,nranges,first,last,…` and a Unicode font
|
|
||||||
//! with `*UNIFONT,6,name` followed by `above,below,modes,encoding,type,0`. Shape 0 is a text
|
|
||||||
//! font's record (`above,below,modes,0`).
|
|
||||||
//!
|
|
||||||
//! Operands are encoded by what they are: a subshape number takes two bytes in a Unicode font
|
|
||||||
//! (and after `7,0` in a big font), displacements and bulges are two's complement, and an arc's
|
|
||||||
//! direction byte (`-043`) keeps its sign in the high bit. `defbytes` is not checked: the
|
|
||||||
//! program's own length is written.
|
|
||||||
|
|
||||||
use super::ShxError;
|
|
||||||
use super::parse::{BIGFONT, SHAPES_10, UNIFONT};
|
|
||||||
|
|
||||||
/// Largest source compiled.
|
|
||||||
const MAX_SOURCE: usize = 8 << 20;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq)]
|
|
||||||
enum Kind {
|
|
||||||
Shapes,
|
|
||||||
Big,
|
|
||||||
Uni,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Shape {
|
|
||||||
number: u16,
|
|
||||||
name: String,
|
|
||||||
program: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A number token: value (sign included).
|
|
||||||
fn number(tok: &str, line: usize) -> Result<i64, ShxError> {
|
|
||||||
let t: String = tok.chars().filter(|c| !matches!(c, '(' | ')') && !c.is_whitespace()).collect();
|
|
||||||
let (neg, digits) = match t.strip_prefix('-') {
|
|
||||||
Some(d) => (true, d),
|
|
||||||
None => (false, t.strip_prefix('+').unwrap_or(&t)),
|
|
||||||
};
|
|
||||||
let err = || ShxError::Source(line, format!("not a number: {tok:?}"));
|
|
||||||
let v = if digits.len() > 1 && digits.starts_with('0') {
|
|
||||||
i64::from_str_radix(digits.get(1..).unwrap_or_default(), 16).map_err(|_| err())?
|
|
||||||
} else {
|
|
||||||
digits.parse::<i64>().map_err(|_| err())?
|
|
||||||
};
|
|
||||||
if v > 0xFFFF {
|
|
||||||
return Err(err());
|
|
||||||
}
|
|
||||||
Ok(if neg { -v } else { v })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The comma-separated numbers of a line (comment removed, blank fields skipped).
|
|
||||||
fn numbers(text: &str, line: usize) -> Result<Vec<i64>, ShxError> {
|
|
||||||
text.split(',').map(str::trim).filter(|t| !t.is_empty() && *t != "(" && *t != ")").map(|t| number(t, line)).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The spec-byte encoder: walks the tokens as the reader walks the bytes.
|
|
||||||
struct Enc<'a> {
|
|
||||||
toks: &'a [i64],
|
|
||||||
i: usize,
|
|
||||||
out: Vec<u8>,
|
|
||||||
kind: Kind,
|
|
||||||
line: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Enc<'_> {
|
|
||||||
fn next(&mut self) -> Result<i64, ShxError> {
|
|
||||||
let v = self.toks.get(self.i).copied().ok_or_else(|| ShxError::Source(self.line, "the shape ends inside a command".into()))?;
|
|
||||||
self.i += 1;
|
|
||||||
Ok(v)
|
|
||||||
}
|
|
||||||
fn byte(&mut self) -> Result<(), ShxError> {
|
|
||||||
let v = self.next()?;
|
|
||||||
let b = u8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a byte")))?;
|
|
||||||
self.out.push(b);
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
/// Two's complement −128..127.
|
|
||||||
fn signed(&mut self) -> Result<i64, ShxError> {
|
|
||||||
let v = self.next()?;
|
|
||||||
let b = i8::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not −128..127")))?;
|
|
||||||
self.out.extend(b.to_le_bytes());
|
|
||||||
Ok(v)
|
|
||||||
}
|
|
||||||
/// Sign in the high bit (an arc's direction byte).
|
|
||||||
fn sign_magnitude(&mut self) -> Result<(), ShxError> {
|
|
||||||
let v = self.next()?;
|
|
||||||
let m = u8::try_from(v.unsigned_abs())
|
|
||||||
.ok()
|
|
||||||
.filter(|m| *m < 0x80)
|
|
||||||
.ok_or_else(|| ShxError::Source(self.line, format!("{v} is not an octant byte")))?;
|
|
||||||
self.out.push(if v < 0 { m | 0x80 } else { m });
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
fn word(&mut self) -> Result<(), ShxError> {
|
|
||||||
let v = self.next()?;
|
|
||||||
let w = u16::try_from(v).map_err(|_| ShxError::Source(self.line, format!("{v} is not a shape number")))?;
|
|
||||||
self.out.extend(w.to_be_bytes());
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn program(mut self) -> Result<Vec<u8>, ShxError> {
|
|
||||||
while self.i < self.toks.len() {
|
|
||||||
let code = self.next()?;
|
|
||||||
let c = u8::try_from(code).map_err(|_| ShxError::Source(self.line, format!("{code} is not a code")))?;
|
|
||||||
self.out.push(c);
|
|
||||||
match c {
|
|
||||||
0 => break,
|
|
||||||
3 | 4 => self.byte()?,
|
|
||||||
7 => match self.kind {
|
|
||||||
Kind::Uni => self.word()?,
|
|
||||||
Kind::Big => {
|
|
||||||
let first = self.toks.get(self.i).copied().unwrap_or(0);
|
|
||||||
if first == 0 {
|
|
||||||
self.byte()?;
|
|
||||||
self.word()?;
|
|
||||||
for _ in 0..4 {
|
|
||||||
self.byte()?;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.byte()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Kind::Shapes => self.byte()?,
|
|
||||||
},
|
|
||||||
8 => {
|
|
||||||
self.signed()?;
|
|
||||||
self.signed()?;
|
|
||||||
}
|
|
||||||
9 => loop {
|
|
||||||
let (x, y) = (self.signed()?, self.signed()?);
|
|
||||||
if x == 0 && y == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
10 => {
|
|
||||||
self.byte()?;
|
|
||||||
self.sign_magnitude()?;
|
|
||||||
}
|
|
||||||
11 => {
|
|
||||||
for _ in 0..4 {
|
|
||||||
self.byte()?;
|
|
||||||
}
|
|
||||||
self.sign_magnitude()?;
|
|
||||||
}
|
|
||||||
12 => {
|
|
||||||
for _ in 0..3 {
|
|
||||||
self.signed()?;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
13 => loop {
|
|
||||||
let (x, y) = (self.signed()?, self.signed()?);
|
|
||||||
if x == 0 && y == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
self.signed()?;
|
|
||||||
},
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if self.out.last() != Some(&0) {
|
|
||||||
self.out.push(0);
|
|
||||||
}
|
|
||||||
Ok(self.out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compile shape source into an SHX file (a shape file or text font, a big font, or a Unicode
|
|
||||||
/// font, as its first definition says).
|
|
||||||
pub fn compile(source: &str) -> Result<Vec<u8>, ShxError> {
|
|
||||||
if source.len() > MAX_SOURCE {
|
|
||||||
return Err(ShxError::TooLarge);
|
|
||||||
}
|
|
||||||
let mut kind = Kind::Shapes;
|
|
||||||
let mut ranges: Vec<(u16, u16)> = Vec::new();
|
|
||||||
let mut uni_info: Option<(String, Vec<u8>)> = None;
|
|
||||||
// Definitions: header (number, name, line) and the numbers that follow it.
|
|
||||||
let mut defs: Vec<(i64, String, usize, Vec<i64>)> = Vec::new();
|
|
||||||
let mut uni_header_pending = false;
|
|
||||||
for (no, raw) in source.lines().enumerate() {
|
|
||||||
let line = no + 1;
|
|
||||||
let text = raw.split(';').next().unwrap_or_default().trim();
|
|
||||||
if text.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if let Some(head) = text.strip_prefix('*') {
|
|
||||||
let upper = head.trim_start().to_ascii_uppercase();
|
|
||||||
if let Some(rest) = upper.strip_prefix("BIGFONT") {
|
|
||||||
kind = Kind::Big;
|
|
||||||
let v = numbers(rest, line)?;
|
|
||||||
let n = usize::try_from(v.get(1).copied().unwrap_or(0)).unwrap_or(0);
|
|
||||||
for k in 0..n {
|
|
||||||
let lo = v.get(2 + 2 * k).copied().unwrap_or(0);
|
|
||||||
let hi = v.get(3 + 2 * k).copied().unwrap_or(lo);
|
|
||||||
let to = |x: i64| u16::try_from(x).map_err(|_| ShxError::Source(line, "bad escape range".into()));
|
|
||||||
ranges.push((to(lo)?, to(hi)?));
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if upper.starts_with("UNIFONT") {
|
|
||||||
kind = Kind::Uni;
|
|
||||||
let name = head.splitn(3, ',').nth(2).unwrap_or_default().trim().to_string();
|
|
||||||
uni_info = Some((name, Vec::new()));
|
|
||||||
uni_header_pending = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
uni_header_pending = false;
|
|
||||||
let mut parts = head.splitn(3, ',');
|
|
||||||
let num = number(parts.next().unwrap_or_default().trim(), line)?;
|
|
||||||
let _defbytes = parts.next();
|
|
||||||
let name = parts.next().unwrap_or_default().trim().to_string();
|
|
||||||
defs.push((num, name, line, Vec::new()));
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let v = numbers(text, line)?;
|
|
||||||
if uni_header_pending {
|
|
||||||
if let Some((_, info)) = uni_info.as_mut() {
|
|
||||||
for x in v {
|
|
||||||
info.push(u8::try_from(x).map_err(|_| ShxError::Source(line, "bad font record".into()))?);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
match defs.last_mut() {
|
|
||||||
Some(d) => d.3.extend(v),
|
|
||||||
None => return Err(ShxError::Source(line, "specification bytes before any *number,defbytes,NAME line".into())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut shapes: Vec<Shape> = Vec::new();
|
|
||||||
for (num, name, line, toks) in defs {
|
|
||||||
let number = u16::try_from(num).map_err(|_| ShxError::Source(line, format!("shape number {num} out of range")))?;
|
|
||||||
let program = if number == 0 {
|
|
||||||
// The font record: plain bytes.
|
|
||||||
toks.iter().map(|x| u8::try_from(*x).map_err(|_| ShxError::Source(line, "bad font record".into()))).collect::<Result<Vec<u8>, _>>()?
|
|
||||||
} else {
|
|
||||||
Enc { toks: &toks, i: 0, out: Vec::new(), kind, line }.program()?
|
|
||||||
};
|
|
||||||
if shapes.iter().any(|s| s.number == number) {
|
|
||||||
return Err(ShxError::Source(line, format!("shape {number} is defined twice")));
|
|
||||||
}
|
|
||||||
shapes.push(Shape { number, name, program });
|
|
||||||
}
|
|
||||||
if shapes.is_empty() {
|
|
||||||
return Err(ShxError::Empty);
|
|
||||||
}
|
|
||||||
shapes.sort_by_key(|s| s.number);
|
|
||||||
let record = |s: &Shape| -> Result<Vec<u8>, ShxError> {
|
|
||||||
let mut r: Vec<u8> = s.name.bytes().filter(|b| *b != 0).collect();
|
|
||||||
r.push(0);
|
|
||||||
r.extend(&s.program);
|
|
||||||
if r.len() > usize::from(u16::MAX) { Err(ShxError::TooLarge) } else { Ok(r) }
|
|
||||||
};
|
|
||||||
let count = u16::try_from(shapes.len()).map_err(|_| ShxError::TooLarge)?;
|
|
||||||
let len16 = |r: &[u8]| u16::try_from(r.len()).unwrap_or(u16::MAX);
|
|
||||||
let mut out = Vec::new();
|
|
||||||
match kind {
|
|
||||||
Kind::Shapes => {
|
|
||||||
out.extend(SHAPES_10);
|
|
||||||
out.extend(shapes.first().map_or(0, |s| s.number).to_le_bytes());
|
|
||||||
out.extend(shapes.last().map_or(0, |s| s.number).to_le_bytes());
|
|
||||||
out.extend(count.to_le_bytes());
|
|
||||||
let recs: Vec<Vec<u8>> = shapes.iter().map(record).collect::<Result<_, _>>()?;
|
|
||||||
for (s, r) in shapes.iter().zip(&recs) {
|
|
||||||
out.extend(s.number.to_le_bytes());
|
|
||||||
out.extend(len16(r).to_le_bytes());
|
|
||||||
}
|
|
||||||
for r in &recs {
|
|
||||||
out.extend(r);
|
|
||||||
}
|
|
||||||
out.extend(b"EOF");
|
|
||||||
}
|
|
||||||
Kind::Big => {
|
|
||||||
out.extend(BIGFONT);
|
|
||||||
let nranges = u16::try_from(ranges.len()).map_err(|_| ShxError::TooLarge)?;
|
|
||||||
out.extend(count.to_le_bytes());
|
|
||||||
out.extend(count.to_le_bytes());
|
|
||||||
out.extend(nranges.to_le_bytes());
|
|
||||||
for (lo, hi) in &ranges {
|
|
||||||
out.extend(lo.to_le_bytes());
|
|
||||||
out.extend(hi.to_le_bytes());
|
|
||||||
}
|
|
||||||
let recs: Vec<Vec<u8>> = shapes.iter().map(record).collect::<Result<_, _>>()?;
|
|
||||||
let mut off = out.len() + 8 * recs.len();
|
|
||||||
for (s, r) in shapes.iter().zip(&recs) {
|
|
||||||
out.extend(s.number.to_le_bytes());
|
|
||||||
out.extend(len16(r).to_le_bytes());
|
|
||||||
out.extend(u32::try_from(off).map_err(|_| ShxError::TooLarge)?.to_le_bytes());
|
|
||||||
off += r.len();
|
|
||||||
}
|
|
||||||
for r in &recs {
|
|
||||||
out.extend(r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Kind::Uni => {
|
|
||||||
out.extend(UNIFONT);
|
|
||||||
let (name, info) = uni_info.unwrap_or_default();
|
|
||||||
out.extend((u32::from(count) + 1).to_le_bytes());
|
|
||||||
let mut rec: Vec<u8> = name.bytes().filter(|b| *b != 0).collect();
|
|
||||||
rec.push(0);
|
|
||||||
rec.extend(&info);
|
|
||||||
out.extend(len16(&rec).to_le_bytes());
|
|
||||||
out.extend(&rec);
|
|
||||||
for s in &shapes {
|
|
||||||
let r = record(s)?;
|
|
||||||
out.extend(s.number.to_le_bytes());
|
|
||||||
out.extend(len16(&r).to_le_bytes());
|
|
||||||
out.extend(r);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
@@ -26,7 +26,6 @@
|
|||||||
//! above, below, modes, encoding, embedding, 0) and then each shape as (number, length,
|
//! above, below, modes, encoding, embedding, 0) and then each shape as (number, length,
|
||||||
//! record).
|
//! record).
|
||||||
|
|
||||||
mod compile;
|
|
||||||
mod parse;
|
mod parse;
|
||||||
mod program;
|
mod program;
|
||||||
mod table;
|
mod table;
|
||||||
@@ -39,7 +38,8 @@ use std::sync::{Arc, PoisonError, RwLock};
|
|||||||
|
|
||||||
use cadcraft_geom::Vec2;
|
use cadcraft_geom::Vec2;
|
||||||
|
|
||||||
pub use compile::compile;
|
use craft_shx::Record;
|
||||||
|
pub use craft_shx::{ShxError, ShxKind, compile};
|
||||||
pub use table::{
|
pub use table::{
|
||||||
FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, installed, register, search_path, set_font_dirs,
|
FontProvider, add_drawing_dir, clear_registered, drawing_dirs, find, font_map, generation, installed, register, search_path, set_font_dirs,
|
||||||
set_font_map, set_provider, set_search_path,
|
set_font_map, set_provider, set_search_path,
|
||||||
@@ -47,46 +47,6 @@ pub use table::{
|
|||||||
pub use text::ShxText;
|
pub use text::ShxText;
|
||||||
pub(crate) use text::{shape, width};
|
pub(crate) use text::{shape, width};
|
||||||
|
|
||||||
/// Why a font file can't be read or a shape source can't be compiled.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum ShxError {
|
|
||||||
/// Not an SHX file (unknown signature).
|
|
||||||
NotShx,
|
|
||||||
/// The file ends inside its header or index.
|
|
||||||
Truncated,
|
|
||||||
/// The file is larger, or has more of something, than CADCraft reads.
|
|
||||||
TooLarge,
|
|
||||||
/// The file is well-formed but holds no shape.
|
|
||||||
Empty,
|
|
||||||
/// Shape source error: line and message.
|
|
||||||
Source(usize, String),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::fmt::Display for ShxError {
|
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
match self {
|
|
||||||
ShxError::NotShx => f.write_str("not an SHX shape or font file"),
|
|
||||||
ShxError::Truncated => f.write_str("the SHX file is truncated"),
|
|
||||||
ShxError::TooLarge => f.write_str("the SHX file is too large"),
|
|
||||||
ShxError::Empty => f.write_str("the SHX file has no shapes"),
|
|
||||||
ShxError::Source(line, msg) => write!(f, "line {line}: {msg}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for ShxError {}
|
|
||||||
|
|
||||||
/// The kind of SHX file.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum ShxKind {
|
|
||||||
/// A shape file or a text font with single-byte character codes (`shapes 1.0/1.1`).
|
|
||||||
Shapes,
|
|
||||||
/// A big font: double-byte character codes after an escape (lead) byte.
|
|
||||||
BigFont,
|
|
||||||
/// A Unicode font: shape numbers are Unicode code points.
|
|
||||||
Unifont,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A shape's program run into polylines, in font units (pen starts at the origin).
|
/// A shape's program run into polylines, in font units (pen starts at the origin).
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
pub struct ShxGlyph {
|
pub struct ShxGlyph {
|
||||||
@@ -96,13 +56,6 @@ pub struct ShxGlyph {
|
|||||||
pub advance: Vec2,
|
pub advance: Vec2,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One shape record: where its name and program are in [`ShxFont::data`].
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub(crate) struct Record {
|
|
||||||
name: (usize, usize),
|
|
||||||
program: (usize, usize),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Glyphs cached per font, keyed by (shape, vertical).
|
/// Glyphs cached per font, keyed by (shape, vertical).
|
||||||
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
|
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
|
||||||
|
|
||||||
|
|||||||
+21
-220
@@ -1,225 +1,26 @@
|
|||||||
//! Reading the compiled SHX containers (layouts in the module documentation). Every count and
|
//! Bridge the shared bounded container reader into CADCraft's font and glyph cache.
|
||||||
//! offset comes from the file, so each is checked against its length; records that run past
|
|
||||||
//! the end are dropped and the rest kept.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use super::{ShxError, ShxFont};
|
||||||
|
pub(super) use craft_shx::parse::MAX_FILE_BYTES;
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(super) use craft_shx::parse::{BIGFONT, SHAPES_10, UNIFONT};
|
||||||
use std::sync::RwLock;
|
use std::sync::RwLock;
|
||||||
|
|
||||||
use super::{Record, ShxError, ShxFont, ShxKind};
|
|
||||||
|
|
||||||
pub(super) const SHAPES_10: &[u8] = b"AutoCAD-86 shapes 1.0\r\n\x1a";
|
|
||||||
pub(super) const SHAPES_11: &[u8] = b"AutoCAD-86 shapes 1.1\r\n\x1a";
|
|
||||||
pub(super) const BIGFONT: &[u8] = b"AutoCAD-86 bigfont 1.0\r\n\x1a";
|
|
||||||
pub(super) const UNIFONT: &[u8] = b"AutoCAD-86 unifont 1.0\r\n\x1a";
|
|
||||||
|
|
||||||
/// Largest file read (the largest big fonts are a few megabytes).
|
|
||||||
pub(super) const MAX_FILE_BYTES: usize = 32 << 20;
|
|
||||||
/// Most escape ranges in a big font (lead bytes: at most 256).
|
|
||||||
const MAX_RANGES: usize = 256;
|
|
||||||
|
|
||||||
/// A checked little-endian reader.
|
|
||||||
struct Rd<'a> {
|
|
||||||
b: &'a [u8],
|
|
||||||
pos: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Rd<'a> {
|
|
||||||
fn take(&mut self, n: usize) -> Result<&'a [u8], ShxError> {
|
|
||||||
let end = self.pos.checked_add(n).ok_or(ShxError::Truncated)?;
|
|
||||||
let s = self.b.get(self.pos..end).ok_or(ShxError::Truncated)?;
|
|
||||||
self.pos = end;
|
|
||||||
Ok(s)
|
|
||||||
}
|
|
||||||
fn u16(&mut self) -> Result<u16, ShxError> {
|
|
||||||
match self.take(2)? {
|
|
||||||
[a, b] => Ok(u16::from_le_bytes([*a, *b])),
|
|
||||||
_ => Err(ShxError::Truncated),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fn u32(&mut self) -> Result<u32, ShxError> {
|
|
||||||
match self.take(4)? {
|
|
||||||
[a, b, c, d] => Ok(u32::from_le_bytes([*a, *b, *c, *d])),
|
|
||||||
_ => Err(ShxError::Truncated),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A font being read.
|
|
||||||
struct Font {
|
|
||||||
kind: ShxKind,
|
|
||||||
name: String,
|
|
||||||
header: bool,
|
|
||||||
above: f64,
|
|
||||||
below: f64,
|
|
||||||
dual: bool,
|
|
||||||
encoding: u8,
|
|
||||||
char_width: f64,
|
|
||||||
ranges: Vec<(u16, u16)>,
|
|
||||||
records: HashMap<u16, Record>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Font {
|
|
||||||
fn new(kind: ShxKind) -> Font {
|
|
||||||
Font {
|
|
||||||
kind,
|
|
||||||
name: String::new(),
|
|
||||||
header: false,
|
|
||||||
above: 0.0,
|
|
||||||
below: 0.0,
|
|
||||||
dual: false,
|
|
||||||
encoding: 0,
|
|
||||||
char_width: 0.0,
|
|
||||||
ranges: Vec::new(),
|
|
||||||
records: HashMap::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Add the record of shape `number` at `start..end` of `data`: a NUL-terminated name, then
|
|
||||||
/// the program. Shape 0 is the font record. A record without a name terminator is dropped;
|
|
||||||
/// the first record of a number wins.
|
|
||||||
fn record(&mut self, data: &[u8], number: u16, start: usize, end: usize) {
|
|
||||||
let Some(bytes) = data.get(start..end) else { return };
|
|
||||||
let Some(nul) = bytes.iter().position(|b| *b == 0) else { return };
|
|
||||||
let name = (start, start + nul);
|
|
||||||
let program = (start + nul + 1, end);
|
|
||||||
if number == 0 {
|
|
||||||
if !self.header {
|
|
||||||
self.font_record(data.get(program.0..program.1).unwrap_or_default(), data.get(name.0..name.1).unwrap_or_default());
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.records.entry(number).or_insert(Record { name, program });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The font record: above, below, modes (and for a unifont encoding and embedding); an
|
|
||||||
/// extended big font's is character height, 0, modes, character width.
|
|
||||||
fn font_record(&mut self, info: &[u8], name: &[u8]) {
|
|
||||||
self.header = true;
|
|
||||||
self.name = name.iter().take(255).map(|c| char::from(*c)).collect();
|
|
||||||
let byte = |i: usize| info.get(i).copied().unwrap_or(0);
|
|
||||||
self.above = f64::from(byte(0));
|
|
||||||
self.below = f64::from(byte(1));
|
|
||||||
self.dual = byte(2) == 2;
|
|
||||||
if self.kind == ShxKind::Unifont {
|
|
||||||
self.encoding = byte(3);
|
|
||||||
}
|
|
||||||
if self.kind == ShxKind::BigFont && info.len() >= 5 && byte(1) == 0 {
|
|
||||||
// Extended: height, 0, modes, width, 0.
|
|
||||||
self.below = 0.0;
|
|
||||||
self.char_width = f64::from(byte(3));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn finish(self, data: Vec<u8>) -> Result<ShxFont, ShxError> {
|
|
||||||
if self.records.is_empty() {
|
|
||||||
return Err(ShxError::Empty);
|
|
||||||
}
|
|
||||||
Ok(ShxFont {
|
|
||||||
kind: self.kind,
|
|
||||||
name: self.name,
|
|
||||||
header: self.header,
|
|
||||||
above: self.above,
|
|
||||||
below: self.below,
|
|
||||||
dual: self.dual,
|
|
||||||
encoding: self.encoding,
|
|
||||||
char_width: if self.char_width > 0.0 { self.char_width } else { self.above },
|
|
||||||
ranges: self.ranges,
|
|
||||||
data,
|
|
||||||
records: self.records,
|
|
||||||
cache: RwLock::default(),
|
|
||||||
hebrew: std::sync::OnceLock::new(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn parse(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
pub(super) fn parse(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
||||||
if bytes.len() > MAX_FILE_BYTES {
|
let font = craft_shx::parse::parse(bytes)?;
|
||||||
return Err(ShxError::TooLarge);
|
Ok(ShxFont {
|
||||||
}
|
kind: font.kind,
|
||||||
if bytes.starts_with(SHAPES_10) || bytes.starts_with(SHAPES_11) {
|
name: font.name,
|
||||||
shapes(bytes)
|
header: font.header,
|
||||||
} else if bytes.starts_with(BIGFONT) {
|
above: font.above,
|
||||||
bigfont(bytes)
|
below: font.below,
|
||||||
} else if bytes.starts_with(UNIFONT) {
|
dual: font.dual,
|
||||||
unifont(bytes)
|
encoding: font.encoding,
|
||||||
} else {
|
char_width: font.char_width,
|
||||||
Err(ShxError::NotShx)
|
ranges: font.ranges,
|
||||||
}
|
data: font.data,
|
||||||
}
|
records: font.records,
|
||||||
|
cache: RwLock::default(),
|
||||||
fn shapes(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
hebrew: std::sync::OnceLock::new(),
|
||||||
let mut r = Rd { b: bytes, pos: SHAPES_10.len() };
|
})
|
||||||
let _first = r.u16()?;
|
|
||||||
let _last = r.u16()?;
|
|
||||||
let count = usize::from(r.u16()?);
|
|
||||||
// The whole index must be there before anything is read from it.
|
|
||||||
let index = r.take(count.checked_mul(4).ok_or(ShxError::TooLarge)?)?;
|
|
||||||
let mut f = Font::new(ShxKind::Shapes);
|
|
||||||
let mut pos = r.pos;
|
|
||||||
for [a, b, c, d] in index.as_chunks::<4>().0 {
|
|
||||||
let (number, len) = (u16::from_le_bytes([*a, *b]), usize::from(u16::from_le_bytes([*c, *d])));
|
|
||||||
let Some(end) = pos.checked_add(len).filter(|e| *e <= bytes.len()) else { break };
|
|
||||||
f.record(bytes, number, pos, end);
|
|
||||||
pos = end;
|
|
||||||
}
|
|
||||||
f.finish(bytes.to_vec())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bigfont(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
|
||||||
let mut r = Rd { b: bytes, pos: BIGFONT.len() };
|
|
||||||
let index_size = usize::from(r.u16()?);
|
|
||||||
let count = usize::from(r.u16()?);
|
|
||||||
let nranges = usize::from(r.u16()?);
|
|
||||||
if nranges > MAX_RANGES {
|
|
||||||
return Err(ShxError::TooLarge);
|
|
||||||
}
|
|
||||||
let mut f = Font::new(ShxKind::BigFont);
|
|
||||||
for _ in 0..nranges {
|
|
||||||
let (lo, hi) = (r.u16()?, r.u16()?);
|
|
||||||
f.ranges.push((lo.min(hi), lo.max(hi)));
|
|
||||||
}
|
|
||||||
// The index has `count` entries of 8 bytes; a file whose count doesn't fit but whose index
|
|
||||||
// size does is read by that.
|
|
||||||
let fits = |n: usize| n.checked_mul(8).and_then(|l| r.pos.checked_add(l)).is_some_and(|e| e <= bytes.len());
|
|
||||||
let n = if fits(count) {
|
|
||||||
count
|
|
||||||
} else if fits(index_size) {
|
|
||||||
index_size
|
|
||||||
} else {
|
|
||||||
return Err(ShxError::Truncated);
|
|
||||||
};
|
|
||||||
let index = r.take(n.checked_mul(8).ok_or(ShxError::TooLarge)?)?;
|
|
||||||
for [a, b, c, d, o0, o1, o2, o3] in index.as_chunks::<8>().0 {
|
|
||||||
let number = u16::from_le_bytes([*a, *b]);
|
|
||||||
let len = usize::from(u16::from_le_bytes([*c, *d]));
|
|
||||||
let Ok(off) = usize::try_from(u32::from_le_bytes([*o0, *o1, *o2, *o3])) else { continue };
|
|
||||||
if len == 0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Some(end) = off.checked_add(len).filter(|e| *e <= bytes.len()) else { continue };
|
|
||||||
f.record(bytes, number, off, end);
|
|
||||||
}
|
|
||||||
f.finish(bytes.to_vec())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unifont(bytes: &[u8]) -> Result<ShxFont, ShxError> {
|
|
||||||
let mut r = Rd { b: bytes, pos: UNIFONT.len() };
|
|
||||||
let count = r.u32()?;
|
|
||||||
let info_len = usize::from(r.u16()?);
|
|
||||||
let info = r.take(info_len)?;
|
|
||||||
let mut f = Font::new(ShxKind::Unifont);
|
|
||||||
let nul = info.iter().position(|b| *b == 0).unwrap_or(info.len());
|
|
||||||
f.font_record(info.get(nul.saturating_add(1)..).unwrap_or_default(), info.get(..nul).unwrap_or_default());
|
|
||||||
// `count` includes the font record; never trusted beyond the data that is there.
|
|
||||||
let mut left = count.saturating_sub(1);
|
|
||||||
while left > 0 {
|
|
||||||
left -= 1;
|
|
||||||
let Ok(number) = r.u16() else { break };
|
|
||||||
let Ok(len) = r.u16().map(usize::from) else { break };
|
|
||||||
let start = r.pos;
|
|
||||||
let Some(end) = start.checked_add(len).filter(|e| *e <= bytes.len()) else { break };
|
|
||||||
r.pos = end;
|
|
||||||
f.record(bytes, number, start, end);
|
|
||||||
}
|
|
||||||
f.finish(bytes.to_vec())
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,50 +3,14 @@
|
|||||||
//! never embedded; callers draw their text as outlines instead. Fonts without TrueType outlines
|
//! never embedded; callers draw their text as outlines instead. Fonts without TrueType outlines
|
||||||
//! (CFF-flavoured OpenType) aren't embedded either.
|
//! (CFF-flavoured OpenType) aren't embedded either.
|
||||||
|
|
||||||
use skrifa::FontRef;
|
|
||||||
use skrifa::raw::types::Tag;
|
|
||||||
|
|
||||||
use crate::ttf::Face;
|
use crate::ttf::Face;
|
||||||
|
|
||||||
/// Whether a face may be embedded as a subset.
|
/// Whether a face may be embedded as a subset.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
pub use craft_font_catalog::SubsetEmbedding as Embedding;
|
||||||
pub enum Embedding {
|
|
||||||
/// Installable, editable or preview & print embedding (or no OS/2 table).
|
|
||||||
Allowed,
|
|
||||||
/// `fsType` restricted licence: no embedding.
|
|
||||||
Restricted,
|
|
||||||
/// `fsType` bit 8: the font may only be embedded whole.
|
|
||||||
NoSubsetting,
|
|
||||||
/// `fsType` bit 9: only bitmaps may be embedded.
|
|
||||||
BitmapOnly,
|
|
||||||
/// No TrueType outlines (`glyf` / `loca`), or the font doesn't parse.
|
|
||||||
NotTrueType,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn table<'a>(f: &FontRef<'a>, t: [u8; 4]) -> Option<&'a [u8]> {
|
|
||||||
f.table_data(Tag::new(&t)).map(|d| d.as_bytes())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn u16_at(b: &[u8], i: usize) -> Option<u16> {
|
|
||||||
Some(u16::from_be_bytes([*b.get(i)?, *b.get(i + 1)?]))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The embedding permission of a face.
|
/// The embedding permission of a face.
|
||||||
pub fn embedding(face: &Face) -> Embedding {
|
pub fn embedding(face: &Face) -> Embedding {
|
||||||
let Ok(f) = FontRef::from_index(&face.bytes, face.index) else { return Embedding::NotTrueType };
|
craft_font_catalog::subset_embedding(&face.bytes, face.index)
|
||||||
if table(&f, *b"glyf").is_none() || table(&f, *b"loca").is_none() || table(&f, *b"head").is_none() {
|
|
||||||
return Embedding::NotTrueType;
|
|
||||||
}
|
|
||||||
let Some(fs_type) = table(&f, *b"OS/2").and_then(|o| u16_at(o, 8)) else { return Embedding::Allowed };
|
|
||||||
if fs_type & 0x0200 != 0 {
|
|
||||||
Embedding::BitmapOnly
|
|
||||||
} else if fs_type & 0x000F == 0x0002 {
|
|
||||||
Embedding::Restricted
|
|
||||||
} else if fs_type & 0x0100 != 0 {
|
|
||||||
Embedding::NoSubsetting
|
|
||||||
} else {
|
|
||||||
Embedding::Allowed
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
+2
-12
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
use crate::{IoError, Result};
|
use crate::{IoError, Result};
|
||||||
use cadcraft_doc::Raster;
|
use cadcraft_doc::Raster;
|
||||||
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType};
|
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType};
|
||||||
|
|
||||||
/// Largest image file read (bytes).
|
/// Largest image file read (bytes).
|
||||||
pub const MAX_IMAGE_BYTES: usize = 256 << 20;
|
pub const MAX_IMAGE_BYTES: usize = 256 << 20;
|
||||||
@@ -61,17 +61,7 @@ pub fn decode(bytes: &[u8]) -> Result<Raster> {
|
|||||||
|
|
||||||
/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy.
|
/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy.
|
||||||
pub fn encode_png(raster: &Raster) -> Result<Vec<u8>> {
|
pub fn encode_png(raster: &Raster) -> Result<Vec<u8>> {
|
||||||
let stride = usize::try_from(raster.width()).ok().and_then(|w| w.checked_mul(4)).filter(|s| *s > 0).ok_or_else(|| bad("invalid image width"))?;
|
|
||||||
let mut chunks = raster.rgba().chunks_exact(stride);
|
|
||||||
let first = chunks.next().ok_or_else(|| bad("the image is empty"))?;
|
|
||||||
let row = |data: &[u8]| Image::from_u8(raster.width(), 1, ChannelLayout::Rgba, data.to_vec()).map_err(bad);
|
|
||||||
let first = row(first)?;
|
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
let mut writer = PngRows::new(&mut out, &first, raster.height(), &EncodeOptions::default()).map_err(bad)?;
|
cadcraft_render::raster::write_rgba_png(&mut out, raster.width(), raster.height(), raster.rgba()).ok_or_else(|| bad("PNG encoding failed"))?;
|
||||||
writer.push(&first).map_err(bad)?;
|
|
||||||
for chunk in chunks {
|
|
||||||
writer.push(&row(chunk)?).map_err(bad)?;
|
|
||||||
}
|
|
||||||
writer.finish().map_err(bad)?;
|
|
||||||
Ok(out)
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -354,6 +354,25 @@ fn premultiplied(r: &cadcraft_doc::Raster) -> Option<Pixmap> {
|
|||||||
Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?)
|
Pixmap::from_vec(data, tiny_skia::IntSize::from_wh(r.width(), r.height())?)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Write straight-alpha RGBA8 pixels as PNG a row at a time.
|
||||||
|
pub fn write_rgba_png(mut output: impl std::io::Write, width: u32, height: u32, pixels: &[u8]) -> Option<()> {
|
||||||
|
use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows};
|
||||||
|
let stride = usize::try_from(width).ok()?.checked_mul(4).filter(|n| *n > 0)?;
|
||||||
|
let expected = stride.checked_mul(usize::try_from(height).ok()?)?;
|
||||||
|
if height == 0 || pixels.len() != expected {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut rows = pixels.chunks_exact(stride);
|
||||||
|
let row = |data: &[u8]| Image::from_u8(width, 1, ChannelLayout::Rgba, data.to_vec()).ok();
|
||||||
|
let first = row(rows.next()?)?;
|
||||||
|
let mut encoder = PngRows::new(&mut output, &first, height, &EncodeOptions::default()).ok()?;
|
||||||
|
encoder.push(&first).ok()?;
|
||||||
|
for data in rows {
|
||||||
|
encoder.push(&row(data)?).ok()?;
|
||||||
|
}
|
||||||
|
encoder.finish().ok()
|
||||||
|
}
|
||||||
|
|
||||||
/// Encode a premultiplied pixmap as PNG without a second full-frame copy.
|
/// Encode a premultiplied pixmap as PNG without a second full-frame copy.
|
||||||
pub fn encode_png(pixmap: &Pixmap) -> Option<Vec<u8>> {
|
pub fn encode_png(pixmap: &Pixmap) -> Option<Vec<u8>> {
|
||||||
use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows};
|
use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows};
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ cadcraft-color = { workspace = true }
|
|||||||
cadcraft-doc = { workspace = true }
|
cadcraft-doc = { workspace = true }
|
||||||
cadcraft-render = { workspace = true }
|
cadcraft-render = { workspace = true }
|
||||||
cadcraft-engine = { workspace = true }
|
cadcraft-engine = { workspace = true }
|
||||||
|
cadcraft-io = { workspace = true }
|
||||||
|
craft-image-codecs = { workspace = true }
|
||||||
cadcraft-fonts = { workspace = true }
|
cadcraft-fonts = { workspace = true }
|
||||||
craft-window = { workspace = true }
|
craft-window = { workspace = true }
|
||||||
egui = { workspace = true }
|
egui = { workspace = true }
|
||||||
@@ -40,8 +42,6 @@ craft-ui = { workspace = true, features = ["native-windows"] }
|
|||||||
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
|
||||||
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses).
|
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses).
|
||||||
naga = { version = "30", features = ["wgsl-in", "glsl-out"] }
|
naga = { version = "30", features = ["wgsl-in", "glsl-out"] }
|
||||||
# Reads the synthetic dynamic-block fixture of the io tests for the dynamic grips tests.
|
|
||||||
cadcraft-io = { workspace = true }
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
serde_json = { workspace = true }
|
serde_json = { workspace = true }
|
||||||
|
|||||||
@@ -691,6 +691,29 @@ impl Drop for PathlessShots {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn write_screenshot_png(img: &image::RgbaImage, output: impl std::io::Write) -> std::io::Result<()> {
|
||||||
|
cadcraft_render::raster::write_rgba_png(output, img.width(), img.height(), img.as_raw())
|
||||||
|
.ok_or_else(|| std::io::Error::other("PNG encoding failed"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn save_explicit_screenshot(img: &image::RgbaImage, path: &str) -> std::io::Result<()> {
|
||||||
|
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image};
|
||||||
|
let format = match image::ImageFormat::from_path(path).map_err(std::io::Error::other)? {
|
||||||
|
image::ImageFormat::Png => Format::Png,
|
||||||
|
image::ImageFormat::Jpeg => Format::Jpeg,
|
||||||
|
image::ImageFormat::Bmp => Format::Bmp,
|
||||||
|
image::ImageFormat::Tiff => Format::Tiff,
|
||||||
|
_ => return Err(std::io::Error::other("unsupported screenshot format")),
|
||||||
|
};
|
||||||
|
if format == Format::Png {
|
||||||
|
return write_screenshot_png(img, std::fs::File::create(path)?);
|
||||||
|
}
|
||||||
|
let pixels = Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, img.as_raw().clone()).map_err(std::io::Error::other)?;
|
||||||
|
let opts = EncodeOptions { jpeg_quality: 75, jpeg_chroma_subsampling: false, ..EncodeOptions::default() };
|
||||||
|
let bytes = craft_image_codecs::encode(&pixels, format, &opts).map_err(std::io::Error::other)?;
|
||||||
|
std::fs::write(path, bytes)
|
||||||
|
}
|
||||||
|
|
||||||
/// Save a pathless screenshot into the private per-process directory: re-validate or recreate it as an owner-only real directory (0700 on Unix; plain create elsewhere), then create up to 64 exclusive files (0600 on Unix) and write a PNG.
|
/// Save a pathless screenshot into the private per-process directory: re-validate or recreate it as an owner-only real directory (0700 on Unix; plain create elsewhere), then create up to 64 exclusive files (0600 on Unix) and write a PNG.
|
||||||
fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result<std::path::PathBuf> {
|
fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result<std::path::PathBuf> {
|
||||||
use std::io::Write as _;
|
use std::io::Write as _;
|
||||||
@@ -713,7 +736,7 @@ fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Resu
|
|||||||
let path = dir.join(format!("cadcraft-shot-{token}-{}.png", next_pathless_nonce()));
|
let path = dir.join(format!("cadcraft-shot-{token}-{}.png", next_pathless_nonce()));
|
||||||
match create_private_file(&path) {
|
match create_private_file(&path) {
|
||||||
Ok(mut file) => {
|
Ok(mut file) => {
|
||||||
let written = img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other).and_then(|()| file.flush());
|
let written = write_screenshot_png(img, &mut file).and_then(|()| file.flush());
|
||||||
if let Err(e) = written {
|
if let Err(e) = written {
|
||||||
// The reply carries no path on failure, so nobody else could remove the partial file.
|
// The reply carries no path on failure, so nobody else could remove the partial file.
|
||||||
drop(file);
|
drop(file);
|
||||||
@@ -752,7 +775,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64)
|
|||||||
return inline_screenshot(&img, token);
|
return inline_screenshot(&img, token);
|
||||||
}
|
}
|
||||||
let saved = match path {
|
let saved = match path {
|
||||||
Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other),
|
Some(path) => save_explicit_screenshot(&img, path).map(|()| path.to_string()),
|
||||||
None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()),
|
None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()),
|
||||||
};
|
};
|
||||||
match saved {
|
match saved {
|
||||||
@@ -766,7 +789,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64)
|
|||||||
fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
|
fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
|
||||||
let (w, h) = img.dimensions();
|
let (w, h) = img.dimensions();
|
||||||
let mut png = Vec::new();
|
let mut png = Vec::new();
|
||||||
if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) {
|
if let Err(e) = write_screenshot_png(img, &mut png) {
|
||||||
return json!({"ok": false, "error": e.to_string(), "request": token});
|
return json!({"ok": false, "error": e.to_string(), "request": token});
|
||||||
}
|
}
|
||||||
json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}})
|
json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}})
|
||||||
@@ -776,6 +799,25 @@ fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_screenshot_retains_supported_file_formats() {
|
||||||
|
let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 128]));
|
||||||
|
for ext in ["png", "bmp", "tiff", "jpg"] {
|
||||||
|
let path = std::env::temp_dir().join(format!("cadcraft-format-{}-{}.{}", std::process::id(), next_pathless_nonce(), ext));
|
||||||
|
let name = path.to_string_lossy().to_string();
|
||||||
|
save_explicit_screenshot(&img, &name).unwrap();
|
||||||
|
let decoded = image::open(&path).unwrap().to_rgba8();
|
||||||
|
assert_eq!(decoded.dimensions(), img.dimensions(), "{ext}");
|
||||||
|
if ext != "jpg" {
|
||||||
|
let mut original = std::io::Cursor::new(Vec::new());
|
||||||
|
img.write_to(&mut original, image::ImageFormat::from_path(&path).unwrap()).unwrap();
|
||||||
|
let original = image::load_from_memory(&original.into_inner()).unwrap().to_rgba8();
|
||||||
|
assert_eq!(decoded.as_raw(), original.as_raw(), "{ext}");
|
||||||
|
}
|
||||||
|
std::fs::remove_file(path).unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_inline_screenshot_carries_the_png_and_its_size() {
|
fn an_inline_screenshot_carries_the_png_and_its_size() {
|
||||||
let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255]));
|
let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255]));
|
||||||
|
|||||||
@@ -70,16 +70,12 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin
|
|||||||
if let Some(f) = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))) {
|
if let Some(f) = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))) {
|
||||||
let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?;
|
let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?;
|
||||||
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
||||||
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8();
|
let tex = preview_texture(ctx, &png)?;
|
||||||
let size = [img.width() as usize, img.height() as usize];
|
|
||||||
let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR);
|
|
||||||
return Ok((tex, f.info));
|
return Ok((tex, f.info));
|
||||||
}
|
}
|
||||||
let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?;
|
let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?;
|
||||||
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
|
||||||
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8();
|
let tex = preview_texture(ctx, &png)?;
|
||||||
let size = [img.width() as usize, img.height() as usize];
|
|
||||||
let tex = ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.as_raw()), egui::TextureOptions::LINEAR);
|
|
||||||
let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or(""));
|
let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or(""));
|
||||||
if r["landscape"].as_bool() == Some(true) {
|
if r["landscape"].as_bool() == Some(true) {
|
||||||
info.push_str(" · landscape");
|
info.push_str(" · landscape");
|
||||||
@@ -87,6 +83,15 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin
|
|||||||
Ok((tex, info))
|
Ok((tex, info))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn preview_texture(ctx: &egui::Context, png: &[u8]) -> Result<TextureHandle, String> {
|
||||||
|
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
|
||||||
|
return Err("the preview is not a PNG".into());
|
||||||
|
}
|
||||||
|
let img = cadcraft_io::raster::decode(png).map_err(|e| e.to_string())?;
|
||||||
|
let size = [img.width() as usize, img.height() as usize];
|
||||||
|
Ok(ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR))
|
||||||
|
}
|
||||||
|
|
||||||
/// The Plot Preview window: the sheet as it plots, with Print and Close.
|
/// The Plot Preview window: the sheet as it plots, with Print and Close.
|
||||||
pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
|
||||||
let id = egui::Id::unique("cc_plot_preview");
|
let id = egui::Id::unique("cc_plot_preview");
|
||||||
@@ -169,6 +174,16 @@ mod tests {
|
|||||||
(CadApp::new(Session::new(), services), asked)
|
(CadApp::new(Session::new(), services), asked)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn plot_preview_reads_shared_png_and_rejects_other_bytes() {
|
||||||
|
let ctx = egui::Context::default();
|
||||||
|
let mut png = Vec::new();
|
||||||
|
cadcraft_render::raster::write_rgba_png(&mut png, 1, 1, &[10, 20, 30, 255]).unwrap();
|
||||||
|
let texture = super::preview_texture(&ctx, &png).unwrap();
|
||||||
|
assert_eq!(texture.size(), [1, 1]);
|
||||||
|
assert!(super::preview_texture(&ctx, b"not a PNG").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn typed_and_menu_commands_ask_json_calls_never_do() {
|
fn typed_and_menu_commands_ask_json_calls_never_do() {
|
||||||
let (mut app, asked) = app();
|
let (mut app, asked) = app();
|
||||||
|
|||||||
Reference in New Issue
Block a user