Compare commits

..
Author SHA1 Message Date
FredApps 27256f0ba5 Merge main into codex/cad-shared-shx-reader 2026-11-16 07:23:33 +01:00
FredApps 386750bd56 Merge pull request #3193 from storytold/codex/cad-shared-shx-compiler
Use the shared SHP to SHX compiler
2026-11-16 07:22:41 +01:00
FredApps eec225a218 Merge pull request #3198 from storytold/codex/cad-shared-mtext-tokenizer
Use shared MTEXT tokenizer for CAD text
2026-11-16 07:22:26 +01:00
FredApps 7013ce459c Merge main into codex/cad-shared-mtext-tokenizer
Resolve the MTEXT conflicts with #3197 (jayzed80's #2952 fix) on the
shared tokenizer: Token::Unknown is now shown as typed (backslash kept,
code read as text) in plain_mtext, the layout parser and the paragraph
scan, matching main's behaviour. Drop the now-unneeded too_many_lines
expectation on parse.
2026-11-16 07:02:25 +01:00
Dylan M. Taylor 11e90d34fb Merge branch 'codex/cad-shared-mtext-escapes' into codex/cad-shared-mtext-tokenizer
# Conflicts:
#	Cargo.lock
2026-11-15 19:03:33 +00:00
Dylan M. Taylor a853649ffa Merge branch 'codex/cad-shared-mtext-escapes' into codex/cad-shared-mtext-tokenizer 2026-11-15 18:22:54 +00:00
Dylan M. Taylor 7cb07b2f3b Merge branch 'codex/cad-shared-mtext-escapes' of https://github.com/storytold/cadcraft into codex/cad-shared-mtext-tokenizer
# Conflicts:
#	Cargo.lock
#	Cargo.toml
2026-11-15 18:03:30 +00:00
Dylan M. Taylor db70717001 Use shared MTEXT lexical tokens 2026-11-15 16:06:13 +00:00
Dylan M. Taylor 305f452283 Use shared SHX container reader 2026-11-15 15:49:47 +00:00
6 changed files with 154 additions and 526 deletions
Generated
+4 -4
View File
@@ -1177,7 +1177,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=10f0fac31c3c7f063de8c359b39d247451324b48#10f0fac31c3c7f063de8c359b39d247451324b48"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
[[package]]
name = "craft-docpath"
@@ -1196,9 +1196,9 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=10f0fac31c3c7f063de8c359b39d247451324b48#10f0fac31c3c7f063de8c359b39d247451324b48"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
dependencies = [
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=10f0fac31c3c7f063de8c359b39d247451324b48)",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
"encoding_rs",
"kurbo",
"log",
@@ -1318,7 +1318,7 @@ dependencies = [
[[package]]
name = "craft-shx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=b3307f7814629961841b80ab907116252e41b34d#b3307f7814629961841b80ab907116252e41b34d"
source = "git+https://github.com/storytold/craft-libs?rev=3c5007339754def577b3c5274f523d96384a35c4#3c5007339754def577b3c5274f523d96384a35c4"
[[package]]
name = "craft-tiff"
+2 -2
View File
@@ -14,9 +14,9 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "10f0fac31c3c7f063de8c359b39d247451324b48" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "b3307f7814629961841b80ab907116252e41b34d" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "3c5007339754def577b3c5274f523d96384a35c4" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
cadcraft-color = { path = "crates/color" }
+108 -236
View File
@@ -12,80 +12,30 @@ pub fn plain_mtext(s: &str) -> String {
let s = unescape_codes(s);
let s = s.as_ref();
let mut out = String::with_capacity(s.len());
let chars: Vec<char> = s.chars().collect();
let mut i = 0;
while let Some(&c) = chars.get(i) {
match c {
'\\' => {
let code = chars.get(i + 1).copied().unwrap_or(' ');
match code {
'P' | 'N' => {
out.push('\n');
i += 2;
}
'~' => {
out.push(' ');
i += 2;
}
'\\' | '{' | '}' => {
out.push(code);
i += 2;
}
'S' => {
// \Snum^den; \Snum/den; \Snum#den;
let mut j = i + 2;
let mut stack = String::new();
while let Some(&ch) = chars.get(j) {
if ch == ';' {
break;
}
stack.push(match ch {
'^' | '#' => '/',
c => c,
});
j += 1;
}
// "6\S1/2;" reads as "6 1/2".
if out.chars().last().is_some_and(|c| c.is_ascii_digit()) && stack.starts_with(|c: char| c.is_ascii_digit()) {
out.push(' ');
}
out.push_str(stack.trim_end_matches('/'));
i = j + 1;
}
'L' | 'l' | 'O' | 'o' | 'K' | 'k' => i += 2,
// `\U+XXXX`: a character by its Unicode code, as the layout reads it.
'U' if crate::unicode_escape(&chars, i).is_some() => {
if let Some(u) = crate::unicode_escape(&chars, i) {
out.push(u);
}
i += 7;
}
// Codes with an argument terminated by ';' (\f, \F, \H, \W, \Q, \T, \A, \C, \c, \p).
_ if takes_arg(code) => {
let mut j = i + 2;
while let Some(&ch) = chars.get(j) {
if ch == ';' {
break;
}
j += 1;
}
i = j + 1;
}
// A trailing lone backslash is dropped.
_ if chars.get(i + 1).is_none() => i += 1,
// An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD
// shows it: keep the backslash and read on from the code.
_ => {
out.push('\\');
i += 1;
}
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens};
for token in Tokens::new(s, StackMode::Plain) {
match token {
Token::Control('P' | 'N') => out.push('\n'),
Token::Control('~') => out.push(' '),
Token::Control(c @ ('\\' | '{' | '}')) => out.push(c),
Token::Stack(raw) => {
let stack: String = raw.chars().map(|c| if matches!(c, '^' | '#') { '/' } else { c }).collect();
if out.chars().last().is_some_and(|c| c.is_ascii_digit()) && stack.starts_with(|c: char| c.is_ascii_digit()) {
out.push(' ');
}
out.push_str(stack.trim_end_matches('/'));
}
// An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD shows it:
// keep the backslash and read the code as text. A trailing lone backslash is dropped.
Token::Unknown(c) => {
out.push('\\');
if c != '\r' {
out.push(c);
}
}
'{' | '}' | '\r' => i += 1,
_ => {
out.push(c);
i += 1;
}
Token::Char('\r') => {}
Token::Char(c) => out.push(c),
_ => {}
}
}
out
@@ -227,7 +177,7 @@ const MAX_ATOMS: usize = 200_000;
const STACK_SCALE: f64 = 0.7;
// Shared DXF escape handling and parameterized-command classification.
pub(crate) use craft_dxf::mtext::{takes_arg, unescape_codes};
pub(crate) use craft_dxf::mtext::unescape_codes;
/// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or
/// non-finite value.
@@ -235,19 +185,6 @@ pub(crate) fn sane_line_spacing(v: f64) -> f64 {
if v.is_finite() && v > 0.0 { v.clamp(0.25, 4.0) } else { 1.0 }
}
fn arg(chars: &[char], from: usize) -> (String, usize) {
let mut j = from;
let mut a = String::new();
while let Some(&ch) = chars.get(j) {
if ch == ';' {
return (a, j + 1);
}
a.push(ch);
j += 1;
}
(a, j)
}
fn num(a: &str) -> Option<f64> {
a.trim().parse::<f64>().ok().filter(|v| v.is_finite())
}
@@ -284,12 +221,8 @@ fn font_switch(a: &str) -> Option<TextFont> {
}
/// Parse MTEXT contents into words, spaces and paragraph breaks with their formats.
#[expect(
clippy::too_many_lines,
reason = "The MTEXT escape grammar is one cohesive state machine; its ordered transitions are clearer in a single dispatch."
)]
fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
let chars: Vec<char> = contents.chars().collect();
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens, split_stack};
let h_min = base.height * 1e-3;
let h_max = if (base.height * 1e3).is_finite() { base.height * 1e3 } else { f64::MAX };
let mut fmts = vec![base];
@@ -311,6 +244,19 @@ fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
atoms.push(Atom::Word(std::mem::take(word)));
}
};
// A character read as text: a line feed breaks the paragraph and a space ends the word.
let text_char = |atoms: &mut Vec<Atom>, word: &mut Vec<(Seg, usize)>, c: char, f: usize| match c {
'\r' => {}
'\n' => {
end_word(atoms, word);
atoms.push(Atom::Para(f));
}
' ' => {
end_word(atoms, word);
atoms.push(Atom::Space(f));
}
c => push_char(word, c, f),
};
// Derive a new format from the current one.
let derive = |fmts: &mut Vec<Fmt>, cur: &mut usize, f: &dyn Fn(&mut Fmt)| {
let mut n = fmts.get(*cur).cloned().unwrap_or(Fmt {
@@ -329,165 +275,91 @@ fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
*cur = fmts.len() - 1;
}
};
let mut i = 0;
while let Some(&c) = chars.get(i) {
for token in Tokens::new(contents, StackMode::Structured) {
if atoms.len() > MAX_ATOMS {
break;
}
match c {
'\\' => {
let code = chars.get(i + 1).copied().unwrap_or(' ');
i += 2;
match code {
'P' | 'N' => {
end_word(&mut atoms, &mut word);
atoms.push(Atom::Para(cur));
}
'~' => push_char(&mut word, '\u{a0}', cur),
'\\' | '{' | '}' => push_char(&mut word, code, cur),
'L' => derive(&mut fmts, &mut cur, &|f| f.under = true),
'l' => derive(&mut fmts, &mut cur, &|f| f.under = false),
'O' => derive(&mut fmts, &mut cur, &|f| f.over = true),
'o' => derive(&mut fmts, &mut cur, &|f| f.over = false),
'K' | 'k' => {}
// `\U+XXXX`: a character by its Unicode code.
'U' if i >= 2 && crate::unicode_escape(&chars, i - 2).is_some() => {
if let Some(u) = crate::unicode_escape(&chars, i - 2) {
push_char(&mut word, u, cur);
}
i += 5;
}
'S' => {
let mut j = i;
let (mut top, mut bottom, mut sep) = (String::new(), String::new(), None);
while let Some(&ch) = chars.get(j) {
if ch == ';' {
break;
}
if ch == '\\' {
if let Some(&n) = chars.get(j + 1) {
if sep.is_none() { top.push(n) } else { bottom.push(n) }
}
j += 2;
continue;
}
if sep.is_none() && matches!(ch, '/' | '#' | '^') {
sep = Some(ch);
} else if sep.is_none() {
top.push(ch);
} else {
bottom.push(ch);
}
j += 1;
}
i = j + 1;
word.push((Seg::Stack(top, bottom, sep.unwrap_or('/')), cur));
}
'f' | 'F' => {
let (a, n) = arg(&chars, i);
i = n;
if let Some(font) = font_switch(&a) {
derive(&mut fmts, &mut cur, &|f| f.font = font.clone());
}
}
'H' => {
let (a, n) = arg(&chars, i);
i = n;
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
Some(r) => (true, num(r)),
None => (false, num(&a)),
};
if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) {
// Relative heights compound; keep the result within 1e-3..1e3 times the
// MTEXT's own height, never infinite.
derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v });
}
}
'W' => {
let (a, n) = arg(&chars, i);
i = n;
// `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it.
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
Some(r) => (true, num(r)),
None => (false, num(&a)),
};
if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) {
// Relative factors compound; keep the result within the absolute range.
derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v });
}
}
'Q' => {
let (a, n) = arg(&chars, i);
i = n;
if let Some(v) = num(&a).filter(|v| v.abs() < 85.0) {
derive(&mut fmts, &mut cur, &|f| f.oblique = v.to_radians());
}
}
'C' => {
let (a, n) = arg(&chars, i);
i = n;
if let Ok(v) = a.trim().parse::<u16>() {
let col = if v == 0 || v >= 256 { None } else { Some(MTextColor::Aci(v)) };
derive(&mut fmts, &mut cur, &|f| f.color = col);
}
}
'c' => {
let (a, n) = arg(&chars, i);
i = n;
if let Ok(v) = a.trim().parse::<u32>() {
derive(&mut fmts, &mut cur, &|f| f.color = Some(MTextColor::Rgb(v & 0xFF_FFFF)));
}
}
'A' => {
let (a, n) = arg(&chars, i);
i = n;
if let Ok(v @ 0..=2) = a.trim().parse::<u8>() {
derive(&mut fmts, &mut cur, &|f| f.valign = v);
}
}
_ if takes_arg(code) => {
// \T and \p: argument up to ';'.
let (_, n) = arg(&chars, i);
i = n;
}
// An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD
// shows it: keep the backslash and read on from the code. A trailing lone
// backslash is dropped.
_ => {
if chars.get(i - 1).is_some() {
push_char(&mut word, '\\', cur);
i -= 1;
}
}
match token {
Token::Control('P' | 'N') => {
end_word(&mut atoms, &mut word);
atoms.push(Atom::Para(cur));
}
Token::Control('~') => push_char(&mut word, '\u{a0}', cur),
Token::Control(c @ ('\\' | '{' | '}')) => push_char(&mut word, c, cur),
Token::Control('L') => derive(&mut fmts, &mut cur, &|f| f.under = true),
Token::Control('l') => derive(&mut fmts, &mut cur, &|f| f.under = false),
Token::Control('O') => derive(&mut fmts, &mut cur, &|f| f.over = true),
Token::Control('o') => derive(&mut fmts, &mut cur, &|f| f.over = false),
Token::Stack(raw) => {
let (top, bottom, sep) = split_stack(raw);
word.push((Seg::Stack(top, bottom, sep.unwrap_or('/')), cur));
}
Token::Argument('f' | 'F', a) => {
if let Some(font) = font_switch(a) {
derive(&mut fmts, &mut cur, &|f| f.font = font.clone());
}
}
'{' => {
Token::Argument('H', a) => {
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
Some(r) => (true, num(r)),
None => (false, num(a)),
};
if let Some(v) = v.filter(|v| *v > 0.0 && *v < 1e6) {
// Relative heights compound; keep the result within 1e-3..1e3 times the
// MTEXT's own height, never infinite.
derive(&mut fmts, &mut cur, &|f| f.height = if rel { (f.height * v).min(h_max).max(h_min) } else { v });
}
}
Token::Argument('W', a) => {
// `\W2x;` multiplies the current factor (like `\H2x;`); `\W2;` sets it.
let (rel, v) = match a.trim().strip_suffix(['x', 'X']) {
Some(r) => (true, num(r)),
None => (false, num(a)),
};
if let Some(v) = v.filter(|v| *v > 0.01 && *v < 100.0) {
// Relative factors compound; keep the result within the absolute range.
derive(&mut fmts, &mut cur, &|f| f.wf = if rel { (f.wf * v).clamp(0.01, 100.0) } else { v });
}
}
Token::Argument('Q', a) => {
if let Some(v) = num(a).filter(|v| v.abs() < 85.0) {
derive(&mut fmts, &mut cur, &|f| f.oblique = v.to_radians());
}
}
Token::Argument('C', a) => {
if let Ok(v) = a.trim().parse::<u16>() {
let col = if v == 0 || v >= 256 { None } else { Some(MTextColor::Aci(v)) };
derive(&mut fmts, &mut cur, &|f| f.color = col);
}
}
Token::Argument('c', a) => {
if let Ok(v) = a.trim().parse::<u32>() {
derive(&mut fmts, &mut cur, &|f| f.color = Some(MTextColor::Rgb(v & 0xFF_FFFF)));
}
}
Token::Argument('A', a) => {
if let Ok(v @ 0..=2) = a.trim().parse::<u8>() {
derive(&mut fmts, &mut cur, &|f| f.valign = v);
}
}
Token::OpenGroup => {
if stack.len() < 256 {
stack.push(cur);
}
i += 1;
}
'}' => {
Token::CloseGroup => {
if let Some(f) = stack.pop() {
cur = f;
}
i += 1;
}
'\r' => i += 1,
'\n' => {
end_word(&mut atoms, &mut word);
atoms.push(Atom::Para(cur));
i += 1;
}
' ' => {
end_word(&mut atoms, &mut word);
atoms.push(Atom::Space(cur));
i += 1;
}
_ => {
push_char(&mut word, c, cur);
i += 1;
// An unknown code or a malformed `\U+` / `\M+` is shown as typed, as AutoCAD shows it:
// keep the backslash and read the code as text (#2952).
Token::Unknown(c) => {
push_char(&mut word, '\\', cur);
text_char(&mut atoms, &mut word, c, cur);
}
Token::Char(c) => text_char(&mut atoms, &mut word, c, cur),
_ => {}
}
}
end_word(&mut atoms, &mut word);
+17 -45
View File
@@ -7,7 +7,7 @@
use cadcraft_geom::{Bounds2, Vec2};
use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, arg, num, parse, seg_plain, seg_shape, seg_width, split_thai};
use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, num, parse, seg_plain, seg_shape, seg_width, split_thai};
/// Columns an MTEXT's text flows through, each as wide as the MTEXT's width.
#[derive(Clone, Debug, Default, PartialEq)]
@@ -265,58 +265,30 @@ pub struct Paragraphs {
impl Paragraphs {
pub fn scan(contents: &str) -> Paragraphs {
let contents = super::unescape_codes(contents);
let chars: Vec<char> = contents.chars().collect();
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens};
let mut out = Paragraphs { states: vec![ParaProps::default()], ..Default::default() };
let mut cur = 0usize;
let mut i = 0;
let brk = |out: &mut Paragraphs, cur: usize, column: bool| {
out.para.push(cur);
out.column_break.push(column);
};
while let Some(&c) = chars.get(i) {
match c {
'\\' => {
let code = chars.get(i + 1).copied().unwrap_or(' ');
i += 2;
match code {
'P' => brk(&mut out, cur, false),
'N' => brk(&mut out, cur, true),
'~' | '\\' | '{' | '}' | 'L' | 'l' | 'O' | 'o' | 'K' | 'k' => {}
'S' => {
let mut j = i;
while let Some(&ch) = chars.get(j) {
if ch == ';' {
break;
}
j += if ch == '\\' { 2 } else { 1 };
}
i = j + 1;
}
'p' => {
let (a, n) = arg(&chars, i);
i = n;
if out.states.len() < MAX_STATES
&& let Some(st) = out.states.get(cur)
{
let mut st = st.clone();
st.apply(&a);
out.states.push(st);
cur = out.states.len() - 1;
}
}
_ if super::takes_arg(code) => {
let (_, n) = arg(&chars, i);
i = n;
}
// An unknown code is text, as typed: read on from the code, as the layout does.
_ => i -= 1,
for token in Tokens::new(&contents, StackMode::Structured) {
match token {
// An unknown code is text, as typed (as the layout reads it), so a line feed after a
// lone backslash still breaks the paragraph.
Token::Control('P') | Token::Char('\n') | Token::Unknown('\n') => brk(&mut out, cur, false),
Token::Control('N') => brk(&mut out, cur, true),
Token::Argument('p', a) => {
if out.states.len() < MAX_STATES
&& let Some(st) = out.states.get(cur)
{
let mut st = st.clone();
st.apply(a);
out.states.push(st);
cur = out.states.len() - 1;
}
}
'\n' => {
brk(&mut out, cur, false);
i += 1;
}
_ => i += 1,
_ => {}
}
}
// A `\p` anywhere in a paragraph applies to all of it: the break pushed the state at
+2 -19
View File
@@ -38,7 +38,8 @@ use std::sync::{Arc, PoisonError, RwLock};
use cadcraft_geom::Vec2;
pub use craft_shx::{ShxError, compile};
use craft_shx::Record;
pub use craft_shx::{ShxError, ShxKind, compile};
pub use table::{
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,
@@ -46,17 +47,6 @@ pub use table::{
pub use text::ShxText;
pub(crate) use text::{shape, width};
/// 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).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ShxGlyph {
@@ -66,13 +56,6 @@ pub struct ShxGlyph {
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).
type GlyphCache = HashMap<(u16, bool), Option<Arc<ShxGlyph>>>;
+21 -220
View File
@@ -1,225 +1,26 @@
//! Reading the compiled SHX containers (layouts in the module documentation). Every count and
//! offset comes from the file, so each is checked against its length; records that run past
//! the end are dropped and the rest kept.
//! Bridge the shared bounded container reader into CADCraft's font and glyph cache.
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 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> {
if bytes.len() > MAX_FILE_BYTES {
return Err(ShxError::TooLarge);
}
if bytes.starts_with(SHAPES_10) || bytes.starts_with(SHAPES_11) {
shapes(bytes)
} else if bytes.starts_with(BIGFONT) {
bigfont(bytes)
} else if bytes.starts_with(UNIFONT) {
unifont(bytes)
} else {
Err(ShxError::NotShx)
}
}
fn shapes(bytes: &[u8]) -> Result<ShxFont, ShxError> {
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())
let font = craft_shx::parse::parse(bytes)?;
Ok(ShxFont {
kind: font.kind,
name: font.name,
header: font.header,
above: font.above,
below: font.below,
dual: font.dual,
encoding: font.encoding,
char_width: font.char_width,
ranges: font.ranges,
data: font.data,
records: font.records,
cache: RwLock::default(),
hebrew: std::sync::OnceLock::new(),
})
}