Compare commits

..
Author SHA1 Message Date
FredApps d7b200d666 Merge remote-tracking branch 'origin/main' into w3189
# Conflicts:
#	Cargo.lock
#	Cargo.toml
2026-11-16 00:34:13 +01:00
Dylan M. Taylor bc5023dba0 Check raster depth and TIFF page fidelity 2026-11-15 15:43:31 +00:00
25 changed files with 2119 additions and 700 deletions
-4
View File
@@ -114,7 +114,3 @@ People trust CADCraft with their drawings; a crash loses their work. **This outr
- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here.
- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time.
- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it.
## Shared libraries
Before adding or changing file-format, codec, protocol, or reusable UI code, check `storytold/craft-libs` and its open PRs first; reuse or extend the shared library rather than duplicating it locally, keep app-specific policy and model mapping in the app, and preserve behavior, security/resource limits, attribution, and regression coverage during cutovers.
Generated
+8 -181
View File
@@ -299,9 +299,6 @@ name = "arrayvec"
version = "0.7.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
dependencies = [
"serde",
]
[[package]]
name = "as-raw-xcb-connection"
@@ -749,8 +746,6 @@ version = "0.21.0"
dependencies = [
"cadcraft-geom",
"craft-dxf",
"craft-font-catalog",
"craft-shx",
"encoding_rs",
"harfrust 0.14.0",
"icu_segmenter",
@@ -777,11 +772,11 @@ dependencies = [
"cadcraft-render",
"craft-dwg",
"craft-dxf",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-image-codecs",
"craft-pdf",
"craft-svg",
"image",
"miniz_oxide 0.9.1",
"quick-xml 0.42.0",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -814,7 +809,7 @@ dependencies = [
"cadcraft-doc",
"cadcraft-fonts",
"cadcraft-geom",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-image-codecs",
"lyon_tessellation",
"rayon",
"serde_json",
@@ -833,7 +828,6 @@ dependencies = [
"cadcraft-io",
"cadcraft-render",
"chrono",
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-ui",
"craft-update",
"craft-window",
@@ -1179,11 +1173,6 @@ name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
[[package]]
name = "craft-docpath"
version = "0.1.0"
@@ -1201,25 +1190,13 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
source = "git+https://github.com/storytold/craft-libs?rev=006e4df225fca57e95ead0fb1f91920900798a99#006e4df225fca57e95ead0fb1f91920900798a99"
dependencies = [
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
"encoding_rs",
"kurbo",
"log",
"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]]
name = "craft-fonts-build"
version = "0.1.0"
@@ -1253,33 +1230,8 @@ name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12#ae5020c1ed922cf7976a3a5545f05b07f466be12"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"crc32fast",
"exr",
"flate2",
"half",
"hayro-jpeg2000",
"image",
"image-webp",
"jpeg-encoder",
"png",
"rayon",
"serde_json",
"thiserror 2.0.21",
"tiff",
"zune-core",
"zune-jpeg",
"zune-jpegxl",
]
[[package]]
name = "craft-image-codecs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"craft-jpeg 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-metadata 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-jpeg",
"craft-metadata",
"crc32fast",
"exr",
"flate2",
@@ -1306,14 +1258,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jpeg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-jsonrpc"
version = "0.1.0"
@@ -1338,19 +1282,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=ae5020c1ed922cf7976a3a5545f05b07f466be12)",
"quick-xml 0.41.0",
"serde",
]
[[package]]
name = "craft-metadata"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"brotli-decompressor",
"chrono",
"craft-tiff 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-tiff",
"quick-xml 0.41.0",
"serde",
]
@@ -1361,7 +1293,7 @@ version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db#0325b2d73676d736e94097dbcef01219cf25c7db"
dependencies = [
"chrono",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097dbcef01219cf25c7db)",
"craft-codepage",
"encoding_rs",
]
@@ -1375,27 +1307,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-shx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2f2d1d84e3a36b3f93e81507aeff3f0da97a7162#2f2d1d84e3a36b3f93e81507aeff3f0da97a7162"
[[package]]
name = "craft-svg"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52)",
"craft-xml",
"flate2",
"kurbo",
"quick-xml 0.41.0",
"roxmltree",
"thiserror 2.0.21",
"vectorcraft-geom",
"vectorcraft-pathops",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
@@ -1405,15 +1316,6 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-tiff"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
@@ -1493,16 +1395,6 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52#c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "crc32fast"
version = "1.5.3"
@@ -3051,7 +2943,6 @@ dependencies = [
"arrayvec",
"euclid",
"polycool",
"serde",
"smallvec",
]
@@ -3107,19 +2998,6 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4"
[[package]]
name = "linesweeper"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a25df1b0c5432893f41bba817150e323703ee5f6d974f3a6808ac7fd7f046d18"
dependencies = [
"arrayvec",
"kurbo",
"polycool",
"rustc-hash 2.1.3",
"smallvec",
]
[[package]]
name = "linux-raw-sys"
version = "0.4.15"
@@ -4281,17 +4159,6 @@ dependencies = [
"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]]
name = "read-fonts"
version = "0.45.1"
@@ -4399,15 +4266,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "roxmltree"
version = "0.21.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907"
dependencies = [
"memchr",
]
[[package]]
name = "rstar"
version = "0.13.0"
@@ -4765,16 +4623,6 @@ dependencies = [
"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]]
name = "skrifa"
version = "0.48.0"
@@ -5421,27 +5269,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "vectorcraft-geom"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "vectorcraft-pathops"
version = "0.18.0"
source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e"
dependencies = [
"kurbo",
"linesweeper",
"thiserror 2.0.21",
"vectorcraft-geom",
]
[[package]]
name = "vello_common"
version = "0.2.0"
+1 -6
View File
@@ -14,9 +14,8 @@ 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 = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "006e4df225fca57e95ead0fb1f91920900798a99" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
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" }
@@ -30,15 +29,11 @@ cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "b6222158fbc2a628f27d2c1fff9f648cd194404c" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "c4c4547b7b0151e7c79ab50fa97cb64fbdff4e52" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" }
# 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 = { 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_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
+1 -1
View File
@@ -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)));
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
}
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
let png = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?;
let layout = space.tab_name();
Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape }))
}
+1 -3
View File
@@ -126,11 +126,9 @@ fn write_text_file(path: &str, text: &str, append: bool) {
#[cfg(target_arch = "wasm32")]
fn write_text_file(_path: &str, _text: &str, _append: bool) {}
/// A file or a folder: routines test whether a module is installed with `(findfile "module/.")`.
#[cfg(not(target_arch = "wasm32"))]
fn file_exists(path: &str) -> bool {
let p = std::path::Path::new(path);
p.is_file() || p.is_dir()
std::path::Path::new(path).is_file()
}
#[cfg(target_arch = "wasm32")]
-37
View File
@@ -1,37 +0,0 @@
//! LISP `findfile` finds folders as well as files (#2985): routines test whether an optional
//! module is installed with `(findfile "module/.")`.
use cadcraft_engine::Session;
use serde_json::json;
#[path = "../support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
/// `(findfile name)` as LISP prints it.
fn findfile(name: &str) -> String {
let mut s = Session::new();
let r = s.execute("lisp", &json!({ "code": format!("(findfile \"{name}\")") })).unwrap();
r["value"].as_str().unwrap().to_string()
}
#[test]
fn findfile_finds_a_folder_with_and_without_a_trailing_dot() {
let dir = TempDir::new("findfile-folder");
std::fs::create_dir_all(dir.join("module")).unwrap();
// Forward slashes, so the name needs no escaping in the LISP string on Windows.
let folder = dir.join("module").to_string_lossy().replace('\\', "/");
assert_eq!(findfile(&folder), format!("\"{folder}\""));
assert_eq!(findfile(&format!("{folder}/.")), format!("\"{folder}/.\""));
// A folder that isn't there is still nil.
assert_eq!(findfile(&format!("{folder}-missing")), "nil");
assert_eq!(findfile(&format!("{folder}-missing/.")), "nil");
}
#[test]
fn findfile_still_finds_a_file() {
let dir = TempDir::new("findfile-file");
let file = dir.file("routine.lsp", "(princ)").replace('\\', "/");
assert_eq!(findfile(&file), format!("\"{file}\""));
}
-1
View File
@@ -79,7 +79,6 @@ mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod lisp_corpus;
mod lisp_findfile;
mod lisp_undo_in_routine;
mod malformed_handles;
mod matchprop;
-2
View File
@@ -11,8 +11,6 @@ workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
craft-dxf = { workspace = true }
craft-font-catalog = { workspace = true }
craft-shx = { workspace = true }
skrifa = { workspace = true }
harfrust = { workspace = true }
unicode-bidi = { workspace = true }
+307 -124
View File
@@ -12,30 +12,74 @@ 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());
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);
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;
}
// An unknown code has no argument: drop the backslash and the code only.
_ => i += 2,
}
}
Token::Char('\r') => {}
Token::Char(c) => out.push(c),
_ => {}
'{' | '}' | '\r' => i += 1,
_ => {
out.push(c);
i += 1;
}
}
}
out
@@ -176,8 +220,11 @@ const MAX_ATOMS: usize = 200_000;
/// Scale of stacked text relative to the surrounding text.
const STACK_SCALE: f64 = 0.7;
// Shared DXF escape handling and parameterized-command classification.
pub(crate) use craft_dxf::mtext::unescape_codes;
/// Codes that take an argument terminated by `;` (besides `\S`, which has its own scan). Any
/// other code stands alone, so a missing `;` must not swallow the text after it.
pub(crate) fn takes_arg(code: char) -> bool {
matches!(code, 'f' | 'F' | 'H' | 'W' | 'Q' | 'T' | 'A' | 'C' | 'c' | 'p')
}
/// The line-spacing factor to lay out with: AutoCAD's 0.25..=4 range, 1 for a missing or
/// non-finite value.
@@ -185,6 +232,90 @@ 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 }
}
/// Four hex digits at `chars[at..at + 4]`.
fn hex4(chars: &[char], at: usize) -> Option<u32> {
let digits = chars.get(at..at.checked_add(4)?)?;
digits.iter().try_fold(0u32, |acc, c| Some(acc * 16 + c.to_digit(16)?))
}
/// Push a decoded character so that the tokenizers read it as text, never as markup.
fn push_literal(out: &mut String, c: char) {
if matches!(c, '\\' | '{' | '}') {
out.push('\\');
}
out.push(c);
}
/// Decode `\U+hhhh` (one UTF-16 unit; a surrogate pair gives one character, a lone surrogate
/// U+FFFD) and `\M+nhhhh` (double-byte East Asian characters) to the characters they stand
/// for. Malformed escapes are left for the tokenizers, which drop the backslash and the code.
/// An escaped backslash (`\\U+0041`) is not an escape.
pub(crate) fn unescape_codes(s: &str) -> std::borrow::Cow<'_, str> {
if !s.contains("\\U+") && !s.contains("\\M+") {
return std::borrow::Cow::Borrowed(s);
}
let chars: Vec<char> = s.chars().collect();
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(&c) = chars.get(i) {
if c != '\\' {
out.push(c);
i += 1;
continue;
}
let (n, plus) = (chars.get(i + 1).copied(), chars.get(i + 2).copied());
if n == Some('U') && plus == Some('+') {
if let Some(unit) = hex4(&chars, i + 3) {
i += 7;
let low = |at: usize| {
(chars.get(at) == Some(&'\\') && chars.get(at + 1) == Some(&'U') && chars.get(at + 2) == Some(&'+'))
.then(|| hex4(&chars, at + 3))
.flatten()
.filter(|u| (0xDC00..0xE000).contains(u))
};
let ch = if (0xD800..0xDC00).contains(&unit) {
match low(i) {
Some(lo) => {
i += 7;
char::from_u32(0x10000 + ((unit - 0xD800) << 10) + (lo - 0xDC00))
}
None => None,
}
} else {
char::from_u32(unit)
};
push_literal(&mut out, ch.unwrap_or('\u{fffd}'));
continue;
}
} else if n == Some('M') && plus == Some('+') && chars.get(i + 3).is_some_and(char::is_ascii_digit) && hex4(&chars, i + 4).is_some() {
push_literal(&mut out, craft_dxf::mif_escape_at(&chars, i).unwrap_or('\u{fffd}'));
i += 8;
continue;
}
// Any other backslash pair stays as it is (and an escaped backslash stays one).
out.push('\\');
i += 1;
if let Some(&next) = chars.get(i) {
out.push(next);
i += 1;
}
}
std::borrow::Cow::Owned(out)
}
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())
}
@@ -221,8 +352,12 @@ 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>) {
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens, split_stack};
let chars: Vec<char> = contents.chars().collect();
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];
@@ -244,19 +379,6 @@ 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 {
@@ -275,91 +397,158 @@ fn parse(contents: &str, base: Fmt) -> (Vec<Atom>, Vec<Fmt>) {
*cur = fmts.len() - 1;
}
};
for token in Tokens::new(contents, StackMode::Structured) {
let mut i = 0;
while let Some(&c) = chars.get(i) {
if atoms.len() > MAX_ATOMS {
break;
}
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());
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 has no argument: only the backslash and the code are dropped.
_ => {}
}
}
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;
}
// 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);
'\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;
}
Token::Char(c) => text_char(&mut atoms, &mut word, c, cur),
_ => {}
}
}
end_word(&mut atoms, &mut word);
@@ -767,7 +956,7 @@ mod tests {
assert_eq!(plain_mtext("\\H2.5x;Big"), "Big");
assert_eq!(plain_mtext("unterminated \\H2"), "unterminated ");
assert_eq!(plain_mtext("\\U+0041B \\U+00E8"), "AB è");
assert_eq!(plain_mtext("\\U+12"), "\\U+12", "a short escape is shown as typed");
assert_eq!(plain_mtext("\\U+12"), "+12", "a short escape loses only the backslash and the code");
}
#[test]
@@ -789,24 +978,18 @@ mod tests {
assert_eq!(plain_mtext("\\\\U+0041"), "\\U+0041");
// `\M+n` double-byte characters, decoded like the DXF reader does.
assert_eq!(plain_mtext("\\M+5BCFE x;y"), "\u{4ef6} x;y");
// Malformed escapes are shown as typed, backslash included, as AutoCAD 2024 shows them.
for s in ["a\\U+12 b", "\\U+12x", "a\\U+12;b", "a\\U+123 b", "a\\U+ b", "a\\U+00G1b", "a\\M+ b"] {
assert_eq!(plain_mtext(s), s);
assert_eq!(lay(s, 0.0).lines, vec![s]);
assert_eq!(lay(&format!("\\pxql;{s}"), 0.0).lines, vec![s]);
}
// A valid escape takes exactly four digits.
assert_eq!(plain_mtext("a\\U+12345b"), "a\u{1234}5b");
// Malformed escapes lose only the backslash and the code.
assert_eq!(plain_mtext("a\\U+12 b"), "a+12 b");
assert_eq!(lay("a\\U+12 b", 0.0).lines, vec!["a+12 b"]);
assert_eq!(lay("\\pxql;a\\U+12 b", 0.0).lines, vec!["a+12 b"]);
assert_eq!(plain_mtext("a\\M+ b"), "a+ b");
}
#[test]
fn unknown_code_without_semicolon_keeps_the_text() {
// An unknown code is shown as typed, as AutoCAD 2024 shows it.
assert_eq!(plain_mtext("A\\Zbc d"), "A\\Zbc d");
assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["A\\Zbc d"]);
assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["A\\Zbc d"]);
// The text after it is read as usual: here a paragraph break.
assert_eq!(plain_mtext("A\\Z\\Pb"), "A\\Z\nb");
assert_eq!(plain_mtext("A\\Zbc d"), "Abc d");
assert_eq!(lay("A\\Zbc d", 0.0).lines, vec!["Abc d"]);
assert_eq!(lay("\\pxql;A\\Zbc d", 0.0).lines, vec!["Abc d"]);
// A trailing lone backslash is dropped.
assert_eq!(plain_mtext("A\\"), "A");
// Codes with an argument still take it up to the `;`, or to the end.
+45 -17
View File
@@ -7,7 +7,7 @@
use cadcraft_geom::{Bounds2, Vec2};
use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, num, parse, seg_plain, seg_shape, seg_width, split_thai};
use super::{Atom, Fmt, MTextLayout, MTextParams, MTextPiece, Seg, arg, 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,30 +265,58 @@ pub struct Paragraphs {
impl Paragraphs {
pub fn scan(contents: &str) -> Paragraphs {
let contents = super::unescape_codes(contents);
use craft_dxf::mtext_tokens::{StackMode, Token, Tokens};
let chars: Vec<char> = contents.chars().collect();
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);
};
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;
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 has no argument: only the backslash and the code go.
_ => {}
}
}
_ => {}
'\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
+313
View File
@@ -0,0 +1,313 @@
//! 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)
}
+49 -2
View File
@@ -26,6 +26,7 @@
//! above, below, modes, encoding, embedding, 0) and then each shape as (number, length,
//! record).
mod compile;
mod parse;
mod program;
mod table;
@@ -38,8 +39,7 @@ use std::sync::{Arc, PoisonError, RwLock};
use cadcraft_geom::Vec2;
use craft_shx::Record;
pub use craft_shx::{ShxError, ShxKind, compile};
pub use compile::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,
@@ -47,6 +47,46 @@ pub use table::{
pub use text::ShxText;
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).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ShxGlyph {
@@ -56,6 +96,13 @@ 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>>>;
+220 -21
View File
@@ -1,26 +1,225 @@
//! Bridge the shared bounded container reader into CADCraft's font and glyph cache.
//! 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.
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::collections::HashMap;
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> {
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(),
})
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())
}
+338 -23
View File
@@ -1,29 +1,344 @@
//! Map the shared SHX pen interpreter's neutral strokes into CAD geometry.
use super::{ShxFont, ShxGlyph, ShxKind};
//! The shape pen program: vector length/direction bytes and special codes 0–14, run into
//! polylines. Bounded everywhere: subshape depth, location stack, steps, points, coordinates.
//!
//! - A byte with a non-zero high nibble is a vector: length (high nibble) in one of 16
//! directions (low nibble, counter-clockwise from east in 22.5° steps; the off-axis ones
//! are half-unit or unit steps on the minor axis).
//! - 0 end, 1 pen down, 2 pen up, 3/4 divide/multiply vector lengths by the next byte,
//! 5/6 push/pop the location, 7 subshape (one byte; two bytes high first in a Unicode font;
//! `0`, a two-byte number, base point, width and height in an extended big font),
//! 8 one X-Y displacement, 9 displacements up to (0,0), 10 octant arc (radius,
//! ±0SC: sign = clockwise, S start octant, C octants, 0 = 8), 11 fractional arc (start
//! offset, end offset, high and low radius, ±0SC; offsets in 1/256 of 45° from the octant
//! boundaries), 12 bulge arc (dx, dy, bulge: ±127 = semicircle), 13 bulge arcs up to (0,0),
//! 14 the next command is for vertical text only (dual-orientation fonts).
//! - Displacements and bulges are two's complement bytes; the arc direction byte keeps its
//! sign in the high bit.
use std::f64::consts::{FRAC_PI_4, TAU};
use cadcraft_geom::Vec2;
impl craft_shx::program::Font for ShxFont {
fn kind(&self) -> ShxKind {
self.kind
}
fn dual(&self) -> bool {
self.dual
}
fn above(&self) -> f64 {
self.above
}
fn char_width(&self) -> f64 {
self.char_width
}
fn program(&self, number: u16) -> Option<&[u8]> {
ShxFont::program(self, number)
use super::{ShxFont, ShxGlyph, ShxKind};
/// Subshape nesting (a cycle ends here).
const MAX_DEPTH: usize = 16;
/// Location stack (the format promises four).
const MAX_STACK: usize = 64;
/// Bytes run per glyph, subshapes included.
const MAX_STEPS: usize = 200_000;
/// Points per glyph.
const MAX_POINTS: usize = 50_000;
/// Coordinates in font units.
const MAX_COORD: f64 = 1.0e7;
/// Arc segments per full turn.
const ARC_STEPS: f64 = 64.0;
/// Why a program stops early: the glyph is then not drawn.
#[derive(Debug)]
pub(super) struct Broken;
type Res = Result<(), Broken>;
struct Pen<'a> {
font: &'a ShxFont,
vertical: bool,
pos: Vec2,
down: bool,
/// Vector length factor (codes 3 and 4).
scale: f64,
/// Per-axis factor of an extended big font subshape.
axes: Vec2,
stack: Vec<Vec2>,
strokes: Vec<Vec<Vec2>>,
active: Vec<Vec2>,
steps: usize,
points: usize,
}
pub(super) fn outline(font: &ShxFont, number: u16, vertical: bool) -> Result<ShxGlyph, Broken> {
let mut pen = Pen {
font,
vertical,
pos: Vec2::ZERO,
down: true,
scale: 1.0,
axes: Vec2::new(1.0, 1.0),
stack: Vec::new(),
strokes: Vec::new(),
active: Vec::new(),
steps: 0,
points: 0,
};
pen.run(number, 0)?;
pen.flush();
Ok(ShxGlyph { strokes: pen.strokes, advance: pen.pos })
}
/// The 16 vector directions (unit length on the major axis).
fn direction(d: u8) -> Vec2 {
let (x, y) = match d & 15 {
0 => (1.0, 0.0),
1 => (1.0, 0.5),
2 => (1.0, 1.0),
3 => (0.5, 1.0),
4 => (0.0, 1.0),
5 => (-0.5, 1.0),
6 => (-1.0, 1.0),
7 => (-1.0, 0.5),
8 => (-1.0, 0.0),
9 => (-1.0, -0.5),
10 => (-1.0, -1.0),
11 => (-0.5, -1.0),
12 => (0.0, -1.0),
13 => (0.5, -1.0),
14 => (1.0, -1.0),
_ => (1.0, -0.5),
};
Vec2::new(x, y)
}
/// A two's complement operand byte.
fn signed(b: u8) -> f64 {
f64::from(i8::from_le_bytes([b]))
}
/// A program being read: its bytes and position.
struct Cur<'p> {
b: &'p [u8],
pos: usize,
}
impl Cur<'_> {
fn byte(&mut self) -> Result<u8, Broken> {
let v = self.b.get(self.pos).copied().ok_or(Broken)?;
self.pos += 1;
Ok(v)
}
}
pub(super) fn outline(font: &ShxFont, number: u16, vertical: bool) -> Result<ShxGlyph, craft_shx::program::Broken> {
let glyph = craft_shx::program::outline(font, number, vertical)?;
Ok(ShxGlyph {
strokes: glyph.strokes.into_iter().map(|stroke| stroke.into_iter().map(|p| Vec2::new(p.x, p.y)).collect()).collect(),
advance: Vec2::new(glyph.advance.x, glyph.advance.y),
})
impl Pen<'_> {
fn step(&mut self) -> Res {
self.steps += 1;
if self.steps > MAX_STEPS { Err(Broken) } else { Ok(()) }
}
fn flush(&mut self) {
if self.active.len() >= 2 {
self.strokes.push(std::mem::take(&mut self.active));
} else {
self.active.clear();
}
}
/// Move the pen by `d` font units (already scaled), drawing when the pen is down.
fn to(&mut self, target: Vec2) -> Res {
if !target.is_finite() || target.x.abs().max(target.y.abs()) > MAX_COORD {
return Err(Broken);
}
if self.down {
if self.active.is_empty() {
self.active.push(self.pos);
self.points += 1;
}
self.active.push(target);
self.points += 1;
if self.points > MAX_POINTS {
return Err(Broken);
}
} else {
self.flush();
}
self.pos = target;
Ok(())
}
/// A displacement in vector units (times the length factor and the subshape axes).
fn by(&mut self, d: Vec2) -> Res {
let k = d * self.scale;
self.to(self.pos + Vec2::new(k.x * self.axes.x, k.y * self.axes.y))
}
/// An arc of `radius` vector units from the pen, starting at angle `start` on its circle
/// and turning `sweep` radians (positive counter-clockwise).
fn arc(&mut self, radius: f64, start: f64, sweep: f64) -> Res {
let r = radius * self.scale;
if !(r.is_finite() && r > 0.0 && sweep.is_finite()) {
return Ok(());
}
let n = if self.down { (sweep.abs() / TAU * ARC_STEPS).ceil().clamp(1.0, ARC_STEPS) as usize } else { 1 };
let from = self.pos;
let s0 = Vec2::new(start.cos(), start.sin());
for i in 1..=n {
let a = start + sweep * i as f64 / n as f64;
let d = (Vec2::new(a.cos(), a.sin()) - s0) * r;
self.to(from + Vec2::new(d.x * self.axes.x, d.y * self.axes.y))?;
}
Ok(())
}
/// An arc to the displacement `d` with `bulge` (−127..127, ±127 a semicircle).
fn bulge(&mut self, d: Vec2, bulge: f64) -> Res {
let b = bulge.clamp(-127.0, 127.0) / 127.0;
if b == 0.0 || !self.down || d.len2() == 0.0 {
return self.by(d);
}
// Centre from the chord midpoint along its left normal; sweep 4·atan(b).
let centre = d * 0.5 + Vec2::new(-d.y, d.x) * ((1.0 - b * b) / (4.0 * b));
let rel = -centre;
self.arc(rel.len(), rel.y.atan2(rel.x), 4.0 * b.atan())
}
/// The octant byte `±0SC`: (clockwise, start octant, octants with 0 = 8).
fn octants(spec: u8) -> (f64, f64, f64) {
let sign = if spec & 0x80 != 0 { -1.0 } else { 1.0 };
let s = f64::from((spec >> 4) & 7);
let c = match spec & 7 {
0 => 8.0,
c => f64::from(c),
};
(sign, s, c)
}
/// The vector unit size of an extended big font's subshape cell.
fn cell(&self) -> Vec2 {
let h = if self.font.above > 0.0 { self.font.above } else { 1.0 };
let w = if self.font.char_width > 0.0 { self.font.char_width } else { h };
Vec2::new(w, h)
}
fn run(&mut self, number: u16, depth: usize) -> Res {
if depth >= MAX_DEPTH {
return Err(Broken);
}
let program = self.font.program(number).ok_or(Broken)?;
let mut r = Cur { b: program, pos: 0 };
let mut skip = false;
while r.pos < r.b.len() {
self.step()?;
let code = r.byte()?;
// Code 14: in a dual-orientation font the next command is for vertical text only.
let exec = !skip;
skip = false;
match code {
0 => return Ok(()),
1 if exec => self.down = true,
2 if exec => {
self.down = false;
self.flush();
}
3 | 4 => {
let k = f64::from(r.byte()?);
if exec && k > 0.0 {
let s = if code == 3 { self.scale / k } else { self.scale * k };
if !(1e-9..=MAX_COORD).contains(&s) {
return Err(Broken);
}
self.scale = s;
}
}
5 if exec => {
if self.stack.len() >= MAX_STACK {
return Err(Broken);
}
self.stack.push(self.pos);
}
6 if exec => {
self.flush();
if let Some(p) = self.stack.pop() {
self.pos = p;
}
}
7 => self.subshape(&mut r, exec, depth)?,
8 | 9 | 12 | 13 => loop {
self.step()?;
let d = Vec2::new(signed(r.byte()?), signed(r.byte()?));
if matches!(code, 9 | 13) && d == Vec2::ZERO {
break;
}
let bulge = if matches!(code, 12 | 13) { signed(r.byte()?) } else { 0.0 };
if exec {
self.bulge(d, bulge)?;
}
if matches!(code, 8 | 12) {
break;
}
},
10 => {
let radius = f64::from(r.byte()?);
let (sign, s, c) = Self::octants(r.byte()?);
if exec {
self.arc(radius, s * FRAC_PI_4, sign * c * FRAC_PI_4)?;
}
}
11 => {
let start = f64::from(r.byte()?) / 256.0;
let end = match r.byte()? {
0 => 1.0,
e => f64::from(e) / 256.0,
};
let radius = f64::from(u16::from_be_bytes([r.byte()?, r.byte()?]));
let (sign, s, c) = Self::octants(r.byte()?);
if exec {
// From `start` past the first octant boundary to `end` past the last
// octant's.
self.arc(radius, (s + sign * start) * FRAC_PI_4, sign * (c - 1.0 + end - start) * FRAC_PI_4)?;
}
}
14 => skip = self.font.dual && !self.vertical && exec,
1..=15 => {}
v => {
if exec {
self.by(direction(v) * f64::from(v >> 4))?;
}
}
}
}
Ok(())
}
/// Code 7 and its operands.
fn subshape(&mut self, r: &mut Cur, exec: bool, depth: usize) -> Res {
match self.font.kind {
ShxKind::Unifont => {
let n = u16::from_be_bytes([r.byte()?, r.byte()?]);
if exec {
self.run(n, depth + 1)?;
}
}
ShxKind::BigFont => {
let first = r.byte()?;
if first != 0 {
if exec {
self.run(u16::from(first), depth + 1)?;
}
return Ok(());
}
// Extended: the primitive drawn in the box (x, y, width, height) of the cell.
let n = u16::from_be_bytes([r.byte()?, r.byte()?]);
let (x, y, w, h) = (f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?), f64::from(r.byte()?));
if !exec {
return Ok(());
}
let (pos, axes, down) = (self.pos, self.axes, self.down);
let cell = self.cell();
self.flush();
self.pos = pos + Vec2::new(x * axes.x, y * axes.y) * self.scale;
self.axes = Vec2::new(axes.x * w / cell.x, axes.y * h / cell.y);
let res = self.run(n, depth + 1);
self.flush();
self.axes = axes;
self.pos = pos;
self.down = down;
res?;
}
ShxKind::Shapes => {
let n = u16::from(r.byte()?);
if exec {
self.run(n, depth + 1)?;
}
}
}
Ok(())
}
}
+38 -2
View File
@@ -3,14 +3,50 @@
//! never embedded; callers draw their text as outlines instead. Fonts without TrueType outlines
//! (CFF-flavoured OpenType) aren't embedded either.
use skrifa::FontRef;
use skrifa::raw::types::Tag;
use crate::ttf::Face;
/// Whether a face may be embedded as a subset.
pub use craft_font_catalog::SubsetEmbedding as Embedding;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
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.
pub fn embedding(face: &Face) -> Embedding {
craft_font_catalog::subset_embedding(&face.bytes, face.index)
let Ok(f) = FontRef::from_index(&face.bytes, face.index) else { return Embedding::NotTrueType };
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)]
+2 -2
View File
@@ -14,17 +14,17 @@ cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
craft-dxf = { workspace = true }
craft-dwg = { workspace = true }
craft-svg = { workspace = true }
craft-image-codecs = { workspace = true }
cadcraft-render = { workspace = true }
cadcraft-fonts = { workspace = true }
thiserror = { workspace = true }
serde_json = { workspace = true }
serde = { workspace = true }
miniz_oxide = "0.9"
craft-pdf = { workspace = true, features = ["write"] }
quick-xml = { workspace = true }
[dev-dependencies]
miniz_oxide = "0.9"
tiff = "0.11"
image = { workspace = true }
tiny-skia = { workspace = true }
+12 -2
View File
@@ -4,7 +4,7 @@
use crate::{IoError, Result};
use cadcraft_doc::Raster;
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType};
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType};
/// Largest image file read (bytes).
pub const MAX_IMAGE_BYTES: usize = 256 << 20;
@@ -61,7 +61,17 @@ pub fn decode(bytes: &[u8]) -> Result<Raster> {
/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy.
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();
cadcraft_render::raster::write_rgba_png(&mut out, raster.width(), raster.height(), raster.rgba()).ok_or_else(|| bad("PNG encoding failed"))?;
let mut writer = PngRows::new(&mut out, &first, raster.height(), &EncodeOptions::default()).map_err(bad)?;
writer.push(&first).map_err(bad)?;
for chunk in chunks {
writer.push(&row(chunk)?).map_err(bad)?;
}
writer.finish().map_err(bad)?;
Ok(out)
}
+43 -48
View File
@@ -1,5 +1,7 @@
//! SVG export of a space (vector, for the web and documents).
use std::fmt::Write as _;
use cadcraft_color::Rgb;
use cadcraft_doc::{Drawing, Space};
use cadcraft_geom::Bounds2;
@@ -23,9 +25,12 @@ pub fn export_window_with(d: &Drawing, space: &Space, window: Option<Bounds2>, t
export_list(&list, window)
}
/// Opacity for a transparent primitive (none for an opaque one or a wipeout's mask).
fn opacity(p: &cadcraft_render::DPrim) -> Option<String> {
(p.kind != Kind::Mask && p.transparency != 0).then(|| format!("{:.2}", f64::from(p.alpha()) / 255.0))
/// ` opacity="…"` for a transparent primitive (none for an opaque one or a wipeout's mask).
fn opacity(p: &cadcraft_render::DPrim) -> String {
if p.kind == Kind::Mask || p.transparency == 0 {
return String::new();
}
format!(r#" opacity="{:.2}""#, f64::from(p.alpha()) / 255.0)
}
/// Write a display list (as [`export_window`] does for a space's own).
@@ -54,15 +59,13 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option<Bounds2>)
let stroke = vw.max(vh) / 1500.0;
// Decimals: at least 6, more when the stroke would otherwise lose its leading digits.
let dp = (3.0 - stroke.log10().floor()).clamp(6.0, 15.0) as usize;
use craft_svg::write::{SvgWriter, num};
let mut writer = SvgWriter::fragment();
writer
.root()
.attr("viewBox", format!("0 0 {} {}", num(vw, dp), num(vh, dp)))
.attr("width", format!("{:.0}", 1600.0))
.attr("height", format!("{:.0}", 1600.0 * vh / vw))
.open();
writer.tag("rect").attr("width", "100%").attr("height", "100%").attr("fill", "white").empty();
let mut s = String::new();
let _ = write!(
s,
r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {vw:.dp$} {vh:.dp$}" width="{:.0}" height="{:.0}"><rect width="100%" height="100%" fill="white"/>"#,
1600.0,
1600.0 * vh / vw
);
let white = Rgb(255, 255, 255);
let tx = |x: f64| x - x0;
let ty = |y: f64| y1 - y;
@@ -72,60 +75,52 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option<Bounds2>)
let pts = list.points(p);
match p.kind {
Kind::Polyline => {
let points = craft_svg::drawing_write::points(pts.iter().map(|q| [tx(q.x), ty(q.y)]), dp);
let mut tag = writer.tag("polyline").attr("fill", "none").attr("stroke", &c);
if let Some(op) = &op {
tag = tag.attr("opacity", op);
let _ = write!(
s,
r#"<polyline fill="none" stroke="{c}"{op} stroke-width="{stroke:.dp$}" stroke-linecap="round" stroke-linejoin="round" points=""#
);
for q in pts {
let _ = write!(s, "{:.dp$},{:.dp$} ", tx(q.x), ty(q.y));
}
tag.attr("stroke-width", num(stroke, dp))
.attr("stroke-linecap", "round")
.attr("stroke-linejoin", "round")
.attr("points", points)
.empty();
s.push_str(r#""/>"#);
}
Kind::Tris | Kind::Mask => {
// A wipeout's mask hides what lies under it with the white background.
let c = if p.kind == Kind::Mask { white.hex() } else { c };
let triangles = pts
.chunks(3)
.filter_map(|t| if let [a, b, c] = t { Some([[tx(a.x), ty(a.y)], [tx(b.x), ty(b.y)], [tx(c.x), ty(c.y)]]) } else { None });
let path = craft_svg::drawing_write::triangles(triangles, dp);
let mut tag = writer.tag("path").attr("fill", &c);
if let Some(op) = &op {
tag = tag.attr("opacity", op);
let _ = write!(s, r#"<path fill="{c}"{op} d=""#);
for t in pts.chunks(3) {
if let [a, b2, cc] = t {
let _ =
write!(s, "M{:.dp$} {:.dp$}L{:.dp$} {:.dp$}L{:.dp$} {:.dp$}Z", tx(a.x), ty(a.y), tx(b2.x), ty(b2.y), tx(cc.x), ty(cc.y));
}
}
tag.attr("d", path).empty();
s.push_str(r#""/>"#);
}
// Raster images are not written to SVG yet: their frame is.
Kind::Image { .. } => {}
Kind::Point => {
if let Some(q) = pts.first() {
let mut tag =
writer.tag("circle").attr("cx", num(tx(q.x), dp)).attr("cy", num(ty(q.y), dp)).attr("r", num(stroke, dp)).attr("fill", &c);
if let Some(op) = &op {
tag = tag.attr("opacity", op);
}
tag.empty();
let _ = write!(s, r#"<circle cx="{:.dp$}" cy="{:.dp$}" r="{:.dp$}" fill="{c}"{op}/>"#, tx(q.x), ty(q.y), stroke);
}
}
Kind::Infinite { ray } => {
if let (Some(bp), Some(dir)) = (pts.first(), pts.get(1)) {
// A window can lie far from the base point: reach past it.
let far = (vw + vh) * 2.0 + if window.is_some() { bp.dist(b.center()) } else { 0.0 };
let a = if ray { *bp } else { *bp - *dir * far };
let e = *bp + *dir * far;
let mut tag = writer
.tag("line")
.attr("x1", num(tx(a.x), dp))
.attr("y1", num(ty(a.y), dp))
.attr("x2", num(tx(e.x), dp))
.attr("y2", num(ty(e.y), dp))
.attr("stroke", &c);
if let Some(op) = &op {
tag = tag.attr("opacity", op);
}
tag.attr("stroke-width", num(stroke, dp)).empty();
let _ = write!(
s,
r#"<line x1="{:.dp$}" y1="{:.dp$}" x2="{:.dp$}" y2="{:.dp$}" stroke="{c}"{op} stroke-width="{stroke:.dp$}"/>"#,
tx(a.x),
ty(a.y),
tx(e.x),
ty(e.y)
);
}
}
}
}
writer.close();
writer.finish()
s.push_str("</svg>");
s
}
+728 -97
View File
@@ -13,11 +13,14 @@
//! line segments instead of losing the shape). What the drawing shows of those (all but fills,
//! gradients and patterns) is named in a read note, so it is never left out silently.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, HashSet};
use cadcraft_color::Color;
use cadcraft_doc::{Circle, Common, Drawing, Ellipse, EntityKind, Layer, Line, LwPolyline, Space};
use cadcraft_geom::{Mat3, PolyVertex, Spline, Vec2, Vec3};
use quick_xml::Reader;
use quick_xml::XmlVersion;
use quick_xml::events::{BytesStart, Event};
use crate::{IoError, Result};
@@ -25,20 +28,47 @@ use crate::{IoError, Result};
const MAX_DECOMPRESSED: usize = 64 << 20;
/// Shape elements per file (rect, circle, path, …; each counted once).
const MAX_ELEMENTS: usize = 500_000;
/// Path data segments per `d` attribute.
const MAX_PATH_SEGMENTS: usize = 100_000;
/// Vertices in one polyline, and control points in one spline.
const MAX_CURVE_POINTS: usize = 100_001;
/// Layers created from Inkscape layer groups.
const MAX_LAYERS: usize = 256;
/// Nested `<g>`/`<svg>` transforms.
const MAX_TRANSFORM_DEPTH: usize = 64;
/// Flattened chords per elliptical arc under a non-uniform transform.
const MAX_ARC_CHORDS: usize = 10_000;
/// Generated vertices retained across the whole document (all paths and shapes), so repeated
/// arc/curve flattening cannot amplify a compact input into unbounded geometry.
const MAX_TOTAL_VERTS: usize = 8_000_000;
/// Elements whose whole subtree is skipped (paint servers, text, raster images, metadata).
const SKIP: &[&[u8]] = &[
b"defs",
b"symbol",
b"clipPath",
b"mask",
b"pattern",
b"marker",
b"linearGradient",
b"radialGradient",
b"filter",
b"style",
b"text",
b"image",
b"title",
b"desc",
b"metadata",
];
/// Elements that hold children and push a transform stack frame.
const CONTAINERS: &[&[u8]] = &[b"g", b"svg", b"a", b"switch"];
/// Read an SVG document, or a gzip-compressed one (`.svgz`, Inkscape's "Compressed SVG").
pub fn read(bytes: &[u8]) -> Result<Drawing> {
let unpacked;
let plain: &[u8] = if bytes.starts_with(&[0x1f, 0x8b]) {
unpacked =
craft_svg::svgz::inflate(bytes, MAX_DECOMPRESSED).map_err(|_| IoError::Format("this SVGZ file's gzip stream is damaged".into()))?;
unpacked = gunzip(bytes)?;
&unpacked
} else {
bytes
@@ -49,6 +79,39 @@ pub fn read(bytes: &[u8]) -> Result<Drawing> {
Ok(parser.drawing)
}
/// Decompress a gzip member (RFC 1952) with a hard output cap.
fn gunzip(bytes: &[u8]) -> Result<Vec<u8>> {
let damaged = || IoError::Format("this SVGZ file's gzip stream is damaged".into());
if bytes.get(2) != Some(&8) {
return Err(damaged());
}
let flg = bytes.get(3).copied().unwrap_or(0);
let mut pos = 10usize;
if flg & 0x04 != 0 {
// FEXTRA
let extra = bytes.get(pos..pos + 2).ok_or_else(damaged)?;
pos += 2 + usize::from(u16::from_le_bytes([extra[0], extra[1]]));
}
if flg & 0x08 != 0 {
pos = skip_cstring(bytes, pos).ok_or_else(damaged)?; // FNAME
}
if flg & 0x10 != 0 {
pos = skip_cstring(bytes, pos).ok_or_else(damaged)?; // FCOMMENT
}
if flg & 0x02 != 0 {
pos = pos.saturating_add(2); // FHCRC
}
let end = bytes.len().checked_sub(8).filter(|e| *e >= pos).ok_or_else(damaged)?;
miniz_oxide::inflate::decompress_to_vec_with_limit(&bytes[pos..end], MAX_DECOMPRESSED).map_err(|_| damaged())
}
/// Skip a NUL-terminated field; `None` when the terminator is missing.
fn skip_cstring(bytes: &[u8], from: usize) -> Option<usize> {
let rest = bytes.get(from..)?;
let nul = rest.iter().position(|b| *b == 0)?;
Some(from + nul + 1)
}
fn parse_err<E: std::fmt::Display>(e: E) -> IoError {
IoError::Format(format!("SVG: {e}"))
}
@@ -63,11 +126,15 @@ struct Parser {
stack: Vec<Mat3>,
/// Current Inkscape layer name.
layer: String,
layers: HashSet<String>,
layer_color: u8,
elements: usize,
/// Generated vertices still allowed across the whole document. Arc/curve flattening can turn
/// a compact path into many samples, and each flushed run is retained, so without a shared
/// budget repeated arcs amplify a small input into gigabytes of geometry (CWE-400).
verts_left: usize,
/// > 0 while inside a skipped subtree; counts the starts seen there.
skip: usize,
/// What was left out, by kind ([`LeftOut`]).
left_out: BTreeMap<LeftOut, usize>,
}
@@ -83,6 +150,15 @@ enum LeftOut {
}
impl LeftOut {
/// The kind of a skipped element ([`SKIP`]) that the drawing shows.
fn of(name: &[u8]) -> Option<Self> {
match name {
b"text" => Some(Self::Text),
b"image" => Some(Self::Image),
_ => None,
}
}
fn describe(self, n: usize) -> String {
let (one, many) = match self {
Self::Text => ("text", "texts"),
@@ -102,12 +178,19 @@ impl Parser {
drawing: Drawing::new_metric(),
stack: vec![Mat3::IDENTITY],
layer: "0".into(),
layers: HashSet::from(["0".to_string()]),
layer_color: 1,
elements: 0,
verts_left: MAX_TOTAL_VERTS,
skip: 0,
left_out: BTreeMap::new(),
}
}
fn left_out(&mut self, kind: LeftOut) {
*self.left_out.entry(kind).or_default() += 1;
}
/// The read note on what was left out, if anything was.
fn note(&self) -> Option<String> {
if self.left_out.is_empty() {
@@ -118,85 +201,140 @@ impl Parser {
}
fn parse(&mut self, text: &str) -> Result<()> {
use craft_svg::neutral_document::{self, Event, Skipped};
let mut failure = None;
let mut layer_color = 1u8;
let result = neutral_document::visit(text, &mut |event| {
let r = match event {
Event::Layer(name) => {
let color = Color::Index(layer_color);
layer_color = if layer_color >= 7 { 1 } else { layer_color + 1 };
self.drawing.layers.push(Layer { name, color, ..Layer::default() });
Ok(())
let mut reader = Reader::from_str(text);
reader.config_mut().trim_text(true);
loop {
match reader.read_event().map_err(parse_err)? {
Event::Start(e) => {
let name = e.name();
self.on_start(name.into_inner().as_bytes(), &e)?;
}
Event::Shape(shape) => self.map_shape(shape),
};
r.map_err(|e| {
failure = Some(e);
neutral_document::Error("CAD geometry mapping failed".into())
})
});
if let Some(e) = failure {
return Err(e);
}
let doc = result.map_err(|e| IoError::Format(e.to_string()))?;
for (kind, count) in doc.skipped {
let kind = match kind {
Skipped::Text => LeftOut::Text,
Skipped::Image => LeftOut::Image,
Skipped::Use => LeftOut::Use,
Skipped::Style => LeftOut::Style,
Skipped::RoundedCorners => LeftOut::RoundedCorners,
};
self.left_out.insert(kind, count);
Event::Empty(e) => {
let name = e.name();
self.on_element(name.into_inner().as_bytes(), &e)?;
}
Event::End(e) => {
let name = e.name();
self.on_end(name.into_inner().as_bytes());
}
Event::Eof => break,
_ => {}
}
}
self.drawing.read_notes.extend(self.note());
Ok(())
}
fn map_shape(&mut self, shape: craft_svg::neutral_document::Shape) -> Result<()> {
use craft_svg::neutral_document::Primitive;
let point = |p: craft_svg::path_data::Point| Vec2::new(p.x, p.y);
let [a, b, c, d, e, f] = shape.transform;
if let Some(current) = self.stack.first_mut() {
*current = Mat3 { a, b, c, d, e, f };
/// A start tag: open a transform frame, descend into a skipped subtree, or treat a
/// shape written as start+end the same as a self-closed one.
fn on_start(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
// A style sheet applies wherever it is (Inkscape keeps it in `<defs>`).
if name == b"style" {
self.left_out(LeftOut::Style);
}
self.layer = shape.layer;
match shape.primitive {
Primitive::Rect { x, y, width, height } => {
let pts = [Vec2::new(x, y), Vec2::new(x + width, y), Vec2::new(x + width, y + height), Vec2::new(x, y + height)];
self.add_polyline(&pts.map(|p| self.map(p)), true)?;
if self.skip > 0 {
self.skip += 1;
return Ok(());
}
if hidden(e) {
self.skip = 1;
return Ok(());
}
if SKIP.contains(&name) {
if let Some(kind) = LeftOut::of(name) {
self.left_out(kind);
}
Primitive::Circle { center, radius } => self.add_rounded(point(center), radius, radius)?,
Primitive::Ellipse { center, rx, ry } => self.add_rounded(point(center), rx, ry)?,
Primitive::Line { a, b } => self.add(EntityKind::Line(Line { a: v3(self.map(point(a))), b: v3(self.map(point(b))) }))?,
Primitive::Polyline { points, closed } => {
self.add_polyline(&points.into_iter().map(|p| self.map(point(p))).collect::<Vec<_>>(), closed)?
self.skip = 1;
return Ok(());
}
if CONTAINERS.contains(&name) { self.enter_group(name, e) } else { self.on_element(name, e) }
}
fn on_element(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
if self.skip > 0 {
return Ok(());
}
if SKIP.contains(&name) || hidden(e) {
if !hidden(e)
&& let Some(kind) = LeftOut::of(name)
{
self.left_out(kind);
}
Primitive::Path(paths) => {
for path in paths {
let path = Subpath {
start: point(path.start),
closed: path.closed,
segs: path
.segs
.into_iter()
.map(|seg| match seg {
craft_svg::path_data::Segment::Line(p) => Seg::Line(point(p)),
craft_svg::path_data::Segment::Cubic(a, b, c) => Seg::Cubic(point(a), point(b), point(c)),
craft_svg::path_data::Segment::Arc { rx, ry, rot, large, sweep, end } => {
Seg::Arc { rx, ry, rot, large, sweep, end: point(end) }
}
})
.collect(),
};
self.emit_subpath(&path)?;
}
return Ok(());
}
// A shape's own `transform` (SVG 1.1 §7.5) maps it after its groups', for this element only.
let local = attr(e, b"transform").as_deref().and_then(parse_transform);
if let Some(local) = local {
self.stack.push(self.cur().then_before(local));
}
let read = self.shape(name, e);
if local.is_some() {
self.stack.pop();
}
read
}
fn shape(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
match name {
b"use" => {
self.left_out(LeftOut::Use);
Ok(())
}
b"rect" => self.rect(e),
b"circle" => self.circle(e),
b"ellipse" => self.ellipse(e),
b"line" => self.line(e),
b"polyline" => self.poly_points(e, false),
b"polygon" => self.poly_points(e, true),
b"path" => self.path(e),
_ => Ok(()),
}
}
fn on_end(&mut self, name: &[u8]) {
if self.skip > 0 {
self.skip -= 1;
} else if CONTAINERS.contains(&name) && self.stack.len() > 1 {
self.stack.pop();
}
}
fn enter_group(&mut self, name: &[u8], e: &BytesStart) -> Result<()> {
if name == b"svg" && self.stack.len() == 1 {
self.stack[0] = viewport(e)?;
}
if name == b"g" && attr(e, b"inkscape:groupmode").as_deref() == Some("layer") {
let raw = attr(e, b"inkscape:label").or_else(|| attr(e, b"id"));
if let Some(raw) = raw {
self.set_layer(&raw);
}
}
if self.stack.len() >= MAX_TRANSFORM_DEPTH {
return Err(IoError::Format(format!("SVG: more than {MAX_TRANSFORM_DEPTH} nested groups")));
}
let current = *self.stack.last().unwrap_or(&Mat3::IDENTITY);
let next = match attr(e, b"transform").as_deref().and_then(parse_transform) {
Some(local) => current.then_before(local),
None => current,
};
self.stack.push(next);
Ok(())
}
fn set_layer(&mut self, raw: &str) {
let name = sanitize_layer(raw);
if !self.layers.contains(&name) {
if self.layers.len() >= MAX_LAYERS {
return;
}
let color = Color::Index(self.layer_color);
self.layer_color = if self.layer_color >= 7 { 1 } else { self.layer_color + 1 };
self.drawing.layers.push(Layer { name: name.clone(), color, ..Layer::default() });
self.layers.insert(name.clone());
}
self.layer = name;
}
/// The composed mapping for the current nesting: SVG user units → drawing units (mm).
fn cur(&self) -> Mat3 {
*self.stack.last().unwrap_or(&Mat3::IDENTITY)
@@ -228,6 +366,40 @@ impl Parser {
self.drawing.add(&Space::Model, common, kind).map(|_| ()).map_err(parse_err)
}
// --- shapes -------------------------------------------------------------
fn rect(&mut self, e: &BytesStart) -> Result<()> {
let x = num(e, b"x", 0.0);
let y = num(e, b"y", 0.0);
let w = num(e, b"width", 0.0);
let h = num(e, b"height", 0.0);
if w <= 0.0 || h <= 0.0 {
return Ok(());
}
if num(e, b"rx", 0.0) > 0.0 || num(e, b"ry", 0.0) > 0.0 {
self.left_out(LeftOut::RoundedCorners);
}
let pts = [Vec2::new(x, y), Vec2::new(x + w, y), Vec2::new(x + w, y + h), Vec2::new(x, y + h)];
self.add_polyline(&pts.map(|p| self.map(p)), true)
}
fn circle(&mut self, e: &BytesStart) -> Result<()> {
let r = num(e, b"r", 0.0);
if r <= 0.0 {
return Ok(());
}
self.add_rounded(Vec2::new(num(e, b"cx", 0.0), num(e, b"cy", 0.0)), r, r)
}
fn ellipse(&mut self, e: &BytesStart) -> Result<()> {
let rx = num(e, b"rx", 0.0);
let ry = num(e, b"ry", 0.0);
if rx <= 0.0 || ry <= 0.0 {
return Ok(());
}
self.add_rounded(Vec2::new(num(e, b"cx", 0.0), num(e, b"cy", 0.0)), rx, ry)
}
/// A circle or ellipse through a transform. A circle stays a `CIRCLE` under rotations,
/// uniform scales and reflections; anything else becomes an `ELLIPSE` holding the axes
/// of the transformed shape — a linear map sends the unit circle to an ellipse whose
@@ -267,6 +439,24 @@ impl Parser {
self.add(EntityKind::Ellipse(Ellipse { center: v3(center), major: v3(major), ratio, start: 0.0, end: std::f64::consts::TAU }))
}
fn line(&mut self, e: &BytesStart) -> Result<()> {
let a = Vec2::new(num(e, b"x1", 0.0), num(e, b"y1", 0.0));
let b = Vec2::new(num(e, b"x2", 0.0), num(e, b"y2", 0.0));
self.add(EntityKind::Line(Line { a: v3(self.map(a)), b: v3(self.map(b)) }))
}
fn poly_points(&mut self, e: &BytesStart, closed: bool) -> Result<()> {
let Some(raw) = attr(e, b"points") else {
return Ok(());
};
let nums: Vec<f64> = Numbers::new(&raw).collect();
let mut pts: Vec<Vec2> = nums.as_chunks::<2>().0.iter().map(|[x, y]| self.map(Vec2::new(*x, *y))).collect();
if pts.len() > MAX_CURVE_POINTS {
pts.truncate(MAX_CURVE_POINTS);
}
self.add_polyline(&pts, closed)
}
fn add_polyline(&mut self, pts: &[Vec2], closed: bool) -> Result<()> {
if pts.len() < 2 {
return Ok(());
@@ -275,6 +465,18 @@ impl Parser {
self.add(EntityKind::LwPolyline(LwPolyline { vertices, closed, const_width: 0.0, elevation: 0.0, plinegen: false }))
}
// --- path data ----------------------------------------------------------
fn path(&mut self, e: &BytesStart) -> Result<()> {
let Some(d) = attr(e, b"d") else {
return Ok(());
};
for sp in parse_path(&d)? {
self.emit_subpath(&sp)?;
}
Ok(())
}
/// Emit one subpath: runs of lines and arcs become an `LWPOLYLINE` (an arc becomes a
/// bulge vertex, exactly like DXF's polyline bulge), runs of Bézier curves become a
/// `SPLINE`. Under a non-uniform transform a circular arc is no longer circular, so it
@@ -379,6 +581,182 @@ impl Parser {
}
}
/// The element is not rendered (`display="none"`, or a style that says so).
fn hidden(e: &BytesStart) -> bool {
if attr(e, b"display").as_deref() == Some("none") {
return true;
}
attr(e, b"style").is_some_and(|s| s.replace(' ', "").contains("display:none"))
}
fn attr(e: &BytesStart, name: &[u8]) -> Option<String> {
// Stop at the first malformed attribute: skipping errors resumed the parser's duplicate check,
// which rescans the attributes before it each time, so many duplicates were quadratic.
for a in e.attributes() {
let Ok(a) = a else { return None };
if a.key.into_inner().as_bytes() == name {
return a.normalized_value(XmlVersion::Explicit1_0).ok().map(|v| v.into_owned());
}
}
None
}
fn num(e: &BytesStart, name: &[u8], fallback: f64) -> f64 {
attr(e, name).as_deref().and_then(parse_length_mm).unwrap_or(fallback)
}
/// A bare number, or a number with an absolute CSS/SVG unit: millimetres here, everything
/// else (px, the default; pt, pc, in, cm) through the CSS reference pixel (96 per inch).
fn parse_length_mm(s: &str) -> Option<f64> {
let s = s.trim();
let cut = s.find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-' || c == '+' || c == 'e' || c == 'E')).unwrap_or(s.len());
let (n, unit) = s.split_at(cut);
let value: f64 = n.trim().parse().ok()?;
if !value.is_finite() {
return None;
}
match unit.trim() {
"" | "px" => Some(value),
"mm" => Some(value),
"cm" => Some(value * 10.0),
"in" => Some(value * 25.4),
"pt" => Some(value * 25.4 / 72.0),
"pc" => Some(value * 25.4 / 6.0),
_ => Some(value * 25.4 / 96.0),
}
}
/// The root mapping: `viewBox` and unit-bearing `width`/`height` become millimetres per user
/// unit, and the page's Y axis is flipped so the drawing keeps its appearance with Y up.
fn viewport(e: &BytesStart) -> Result<Mat3> {
let vb = attr(e, b"viewBox").and_then(|raw| {
let nums: Vec<f64> = Numbers::new(&raw).collect();
match nums.as_slice() {
[x, y, w, h] if w.is_finite() && h.is_finite() && *w > 0.0 && *h > 0.0 => Some((*x, *y, *w, *h)),
_ => None,
}
});
// A bare or `px` root size is in CSS pixels, not millimetres.
let root_mm = |name: &[u8]| {
let raw = attr(e, name)?;
let mm = parse_length_mm(&raw)?;
let unit = raw.trim().trim_start_matches(|c: char| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).trim();
Some(if matches!(unit, "" | "px") { mm * 25.4 / 96.0 } else { mm })
};
let w_mm = root_mm(b"width");
let h_mm = root_mm(b"height");
let unit = match (vb, w_mm, h_mm) {
(Some((_, _, vw, _)), Some(w), _) if w > 0.0 => w / vw,
(Some((_, _, _, vh)), _, Some(h)) if h > 0.0 => h / vh,
(Some(_), _, _) => 25.4 / 96.0,
(None, _, _) => 25.4 / 96.0,
};
let (vx, vy, vh) = match vb {
Some((x, y, _, h)) => (x, y, h),
None => (0.0, 0.0, 0.0),
};
Ok(Mat3 { a: unit, b: 0.0, c: 0.0, d: -unit, e: -vx * unit, f: (vy + vh) * unit })
}
/// `transform="…"`: a list of functions, applied left to right.
fn parse_transform(s: &str) -> Option<Mat3> {
let mut out: Option<Mat3> = None;
let mut rest = s.trim();
while !rest.is_empty() {
let open = rest.find('(')?;
let name = rest[..open].trim();
let close = rest[open..].find(')')? + open;
let args: Vec<f64> = Numbers::new(&rest[open + 1..close]).collect();
let m = match (name, args.as_slice()) {
("matrix", [a, b, c, d, e, f]) => Mat3 { a: *a, b: *b, c: *c, d: *d, e: *e, f: *f },
("translate", [x]) => Mat3::translate(Vec2::new(*x, 0.0)),
("translate", [x, y]) => Mat3::translate(Vec2::new(*x, *y)),
("scale", [s]) => Mat3::scale(*s, *s),
("scale", [sx, sy]) => Mat3::scale(*sx, *sy),
("rotate", [a]) => Mat3::rotate(a.to_radians()),
("rotate", [a, cx, cy]) => Mat3::rotate_about(Vec2::new(*cx, *cy), a.to_radians()),
("skewX", [a]) => Mat3 { a: 1.0, b: 0.0, c: a.to_radians().tan(), d: 1.0, e: 0.0, f: 0.0 },
("skewY", [a]) => Mat3 { a: 1.0, b: a.to_radians().tan(), c: 0.0, d: 1.0, e: 0.0, f: 0.0 },
_ => return None,
};
out = Some(match out {
Some(prev) => prev.then_before(m),
None => m,
});
rest = rest[close + 1..].trim_start_matches(|c: char| c == ',' || c.is_whitespace());
}
out
}
fn sanitize_layer(raw: &str) -> String {
let cleaned: String =
raw.trim().chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '$') { c } else { '_' }).take(128).collect();
let cleaned = cleaned.trim_matches('_').to_string();
if cleaned.is_empty() { "SVG".into() } else { cleaned }
}
/// A scanner over an SVG number list: separators are whitespace and commas, and a sign
/// starts a new number, so `10-20` is two numbers and `1e-5 2` is two numbers.
struct Numbers<'a> {
s: &'a [u8],
i: usize,
}
impl<'a> Numbers<'a> {
fn new(s: &'a str) -> Self {
Numbers { s: s.as_bytes(), i: 0 }
}
fn skip_seps(&mut self) {
while matches!(self.s.get(self.i), Some(b' ' | b'\t' | b'\r' | b'\n' | b',')) {
self.i += 1;
}
}
fn next_num(&mut self) -> Option<f64> {
self.skip_seps();
let start = self.i;
if matches!(self.s.get(self.i), Some(b'+' | b'-')) {
self.i += 1;
}
let mut digits = 0;
let mut dot = false;
let mut exp = false;
while let Some(c) = self.s.get(self.i) {
match c {
b'0'..=b'9' => {
digits += 1;
self.i += 1;
}
b'.' if !dot && !exp => {
dot = true;
self.i += 1;
}
b'e' | b'E' if !exp && digits > 0 => {
exp = true;
self.i += 1;
if matches!(self.s.get(self.i), Some(b'+' | b'-')) {
self.i += 1;
}
}
_ => break,
}
}
if digits == 0 {
self.i = start;
return None;
}
std::str::from_utf8(&self.s[start..self.i]).ok()?.parse::<f64>().ok().filter(|v| v.is_finite())
}
}
impl Iterator for Numbers<'_> {
type Item = f64;
fn next(&mut self) -> Option<f64> {
self.next_num()
}
}
/// One `M …` run of a `d` attribute.
struct Subpath {
start: Vec2,
@@ -392,9 +770,252 @@ enum Seg {
Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Vec2 },
}
/// Tokens of a `d` attribute: command letters and numbers, in order.
enum Tok {
Cmd(u8),
Num(f64),
}
struct Tokenizer<'a> {
s: &'a [u8],
i: usize,
/// Start of the most recently returned token.
tok_start: usize,
}
impl<'a> Tokenizer<'a> {
fn new(s: &'a str) -> Self {
Tokenizer { s: s.as_bytes(), i: 0, tok_start: 0 }
}
/// Read an arc flag: a single `0` or `1` character, which needs no separator after it.
fn next_flag(&mut self) -> Option<f64> {
let mut nums = Numbers { s: self.s, i: self.i };
nums.skip_seps();
let v = match self.s.get(nums.i)? {
b'0' => 0.0,
b'1' => 1.0,
_ => return None,
};
self.i = nums.i + 1;
Some(v)
}
fn next_tok(&mut self) -> Option<Tok> {
let mut nums = Numbers { s: self.s, i: self.i };
nums.skip_seps();
self.i = nums.i;
self.tok_start = self.i;
let c = self.s.get(self.i).copied()?;
if c.is_ascii_alphabetic() {
self.i += 1;
return Some(Tok::Cmd(c));
}
let tok = nums.next_num().map(Tok::Num);
self.i = nums.i;
tok
}
}
/// Split `d` into subpaths, resolving relative commands and the S/T control reflections.
fn parse_path(d: &str) -> Result<Vec<Subpath>> {
let mut tk = Tokenizer::new(d);
let mut lookahead: Option<Tok> = None;
let mut cmd = 0u8;
let mut cur = Vec2::ZERO;
let mut start = Vec2::ZERO;
let mut segs: Vec<Seg> = Vec::new();
let mut out: Vec<Subpath> = Vec::new();
let closed = false;
let mut prev_cubic: Option<Vec2> = None;
let mut prev_quad: Option<Vec2> = None;
let mut segments = 0usize;
let next_num = |tk: &mut Tokenizer, look: &mut Option<Tok>| -> Result<f64> {
match look.take() {
Some(Tok::Num(v)) => Ok(v),
Some(other @ Tok::Cmd(_)) => {
*look = Some(other);
Err(IoError::Format("SVG: path command is missing coordinates".into()))
}
None => match tk.next_tok() {
Some(Tok::Num(v)) => Ok(v),
Some(other @ Tok::Cmd(_)) => {
*look = Some(other);
Err(IoError::Format("SVG: path command is missing coordinates".into()))
}
None => Err(IoError::Format("SVG: path command is missing coordinates".into())),
},
}
};
while let Some(tok) = lookahead.take().or_else(|| tk.next_tok()) {
let rel = match tok {
Tok::Cmd(c) => {
if c.eq_ignore_ascii_case(&b'z') {
if !segs.is_empty() {
out.push(Subpath { start, segs, closed: true });
segs = Vec::new();
}
cur = start;
cmd = 0;
continue;
}
cmd = c;
c.is_ascii_lowercase()
}
tok @ Tok::Num(_) => {
if cmd == 0 {
return Err(IoError::Format("SVG: path data does not start with a command".into()));
}
lookahead = Some(tok);
cmd.is_ascii_lowercase()
}
};
let abs = cmd.to_ascii_uppercase();
let count = match abs {
b'M' | b'L' => 2,
b'H' | b'V' | b'T' => 1,
b'C' => 6,
b'S' | b'Q' => 4,
b'A' => 7,
_ => return Err(IoError::Format(format!("SVG: unknown path command `{}`", cmd as char))),
};
let mut args = [0.0f64; 7];
for (idx, slot) in args.iter_mut().enumerate().take(count) {
if abs == b'A' && (idx == 3 || idx == 4) {
// Flags are single characters; re-scan a pending number token from its start.
if matches!(lookahead, Some(Tok::Num(_))) {
lookahead = None;
tk.i = tk.tok_start;
}
if lookahead.is_none() {
*slot = tk.next_flag().ok_or_else(|| IoError::Format("SVG: path command is missing coordinates".into()))?;
continue;
}
}
*slot = next_num(&mut tk, &mut lookahead)?;
}
let point = |x: f64, y: f64| if rel { cur + Vec2::new(x, y) } else { Vec2::new(x, y) };
match abs {
b'M' => {
if !segs.is_empty() {
out.push(Subpath { start, segs, closed: false });
segs = Vec::new();
}
cur = point(args[0], args[1]);
start = cur;
cmd = if rel { b'l' } else { b'L' };
prev_cubic = None;
prev_quad = None;
}
b'L' => {
cur = point(args[0], args[1]);
segs.push(Seg::Line(cur));
prev_cubic = None;
prev_quad = None;
}
b'H' => {
cur = Vec2::new(if rel { cur.x + args[0] } else { args[0] }, cur.y);
segs.push(Seg::Line(cur));
prev_cubic = None;
prev_quad = None;
}
b'V' => {
cur = Vec2::new(cur.x, if rel { cur.y + args[0] } else { args[0] });
segs.push(Seg::Line(cur));
prev_cubic = None;
prev_quad = None;
}
b'C' => {
let (c1, c2, p) = (point(args[0], args[1]), point(args[2], args[3]), point(args[4], args[5]));
segs.push(Seg::Cubic(c1, c2, p));
prev_cubic = Some(c2);
prev_quad = None;
cur = p;
}
b'S' => {
let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2);
let (c2, p) = (point(args[0], args[1]), point(args[2], args[3]));
segs.push(Seg::Cubic(c1, c2, p));
prev_cubic = Some(c2);
prev_quad = None;
cur = p;
}
b'Q' => {
let (q, p) = (point(args[0], args[1]), point(args[2], args[3]));
segs.push(Seg::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p));
prev_quad = Some(q);
prev_cubic = None;
cur = p;
}
b'T' => {
let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q);
let p = point(args[0], args[1]);
segs.push(Seg::Cubic(cur + (reflect - cur) * (2.0 / 3.0), p + (reflect - p) * (2.0 / 3.0), p));
prev_quad = Some(reflect);
prev_cubic = None;
cur = p;
}
b'A' => {
let end = point(args[5], args[6]);
segs.push(Seg::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end });
cur = end;
prev_cubic = None;
prev_quad = None;
}
_ => return Err(IoError::Format("SVG: unsupported path command".into())),
}
segments += 1;
if segments > MAX_PATH_SEGMENTS {
return Err(IoError::Format("SVG: path has too many segments".into()));
}
if segs.len() > MAX_CURVE_POINTS {
return Err(IoError::Format("SVG: path has too many segments".into()));
}
}
if !segs.is_empty() {
out.push(Subpath { start, segs, closed });
}
Ok(out)
}
/// The centre and signed sweep of a circular arc from `p0` to `p1` in a Y-up frame, per the
/// SVG endpoint parameterisation (F.6.5). Radii that cannot span the chord are scaled up,
/// as the specification requires.
fn arc_center_circular(p0: Vec2, p1: Vec2, r: f64, large: bool, sweep: bool) -> Option<(Vec2, f64)> {
let point = |p: Vec2| craft_svg::path_data::Point::new(p.x, p.y);
craft_svg::path_data::arc_center_circular(point(p0), point(p1), r, large, sweep).map(|(p, angle)| (Vec2::new(p.x, p.y), angle))
if r <= 0.0 || !r.is_finite() {
return None;
}
let d = p1 - p0;
let dist = d.x.hypot(d.y);
let r = if dist > 2.0 * r { dist / 2.0 } else { r };
if dist <= f64::EPSILON {
return None;
}
let mid = (p0 + p1) * 0.5;
let h = (r * r - (dist * dist) / 4.0).max(0.0).sqrt();
let n = Vec2::new(-d.y / dist, d.x / dist);
let sign = if large != sweep { 1.0 } else { -1.0 };
let center = mid + n * (h * sign);
let a0 = (p0.y - center.y).atan2(p0.x - center.x);
let a1 = (p1.y - center.y).atan2(p1.x - center.x);
let ccw = (a1 - a0).rem_euclid(std::f64::consts::TAU);
Some((center, pick_sweep(ccw, large, sweep)))
}
/// The signed sweep (CCW positive) for a chord sweep `ccw` in `[0, 2π)`: the centre is
/// already chosen so that the magnitude matches `large`, so only the direction is left.
fn pick_sweep(ccw: f64, large: bool, sweep: bool) -> f64 {
let tau = std::f64::consts::TAU;
let eps = f64::EPSILON;
if sweep {
if ccw <= eps { if large { tau } else { eps } } else { ccw }
} else if ccw >= tau - eps {
if large { -tau } else { -eps }
} else {
ccw - tau
}
}
/// Flatten a general elliptical arc (any `rx`/`ry`/rotation) from `p0` to `p1` in user
@@ -420,34 +1041,44 @@ fn flatten_arc(m: &Mat3, p0: Vec2, p1: Vec2, (rx, ry): (f64, f64), rot_deg: f64,
Ok(out)
}
/// Endpoint → centre parameterisation for a rotated elliptical arc (SVG F.6.5), in the
/// frame the points are given in. Returns the centre, the start parameter and the signed
/// sweep.
fn elliptical_params(p0: Vec2, p1: Vec2, rx: f64, ry: f64, phi: f64, large: bool, sweep: bool) -> Option<(Vec2, f64, f64)> {
let point = |p: Vec2| craft_svg::path_data::Point::new(p.x, p.y);
craft_svg::path_data::elliptical_params(point(p0), point(p1), rx, ry, phi, large, sweep)
.map(|(p, start, sweep)| (Vec2::new(p.x, p.y), start, sweep))
}
/// Convert shared SVG path segments to CADCraft's geometry types.
#[cfg(test)]
fn parse_path(d: &str) -> Result<Vec<Subpath>> {
use craft_svg::path_data::{Point, Segment};
let point = |p: Point| Vec2::new(p.x, p.y);
let paths = craft_svg::path_data::parse_path(d).map_err(|e| IoError::Format(e.to_string()))?;
Ok(paths
.into_iter()
.map(|sp| Subpath {
start: point(sp.start),
closed: sp.closed,
segs: sp
.segs
.into_iter()
.map(|seg| match seg {
Segment::Line(p) => Seg::Line(point(p)),
Segment::Cubic(c1, c2, p) => Seg::Cubic(point(c1), point(c2), point(p)),
Segment::Arc { rx, ry, rot, large, sweep, end } => Seg::Arc { rx, ry, rot, large, sweep, end: point(end) },
})
.collect(),
})
.collect())
if rx <= 0.0 || ry <= 0.0 {
return None;
}
let (sphi, cphi) = phi.sin_cos();
let dx = (p0.x - p1.x) / 2.0;
let dy = (p0.y - p1.y) / 2.0;
let x1 = cphi * dx + sphi * dy;
let y1 = -sphi * dx + cphi * dy;
let (rx, ry) = {
let lambda = x1 * x1 / (rx * rx) + y1 * y1 / (ry * ry);
if lambda > 1.0 {
let s = lambda.sqrt();
(rx * s, ry * s)
} else {
(rx, ry)
}
};
let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
let coef = if sweep != large { 1.0 } else { -1.0 } * (num.max(0.0) / den.max(f64::MIN_POSITIVE)).sqrt();
let cxp = coef * rx * y1 / ry;
let cyp = -coef * ry * x1 / rx;
let center = Vec2::new(cphi * cxp - sphi * cyp + (p0.x + p1.x) / 2.0, sphi * cxp + cphi * cyp + (p0.y + p1.y) / 2.0);
let angle = |ux: f64, uy: f64, vx: f64, vy: f64| {
let dot = ux * vx + uy * vy;
let det = ux * vy - uy * vx;
let denom = (ux.hypot(uy) * vx.hypot(vy)).max(f64::MIN_POSITIVE);
(dot / denom).clamp(-1.0, 1.0).acos().copysign(det)
};
let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry);
let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry);
let theta = angle(1.0, 0.0, ux, uy);
let ccw = angle(ux, uy, vx, vy).rem_euclid(std::f64::consts::TAU);
Some((center, theta, pick_sweep(ccw, large, sweep)))
}
#[cfg(test)]
-36
View File
@@ -2943,15 +2943,6 @@ fn svg_path_lines_curves_and_arcs() {
assert!((bulge.abs() - 1.0).abs() < 1e-6, "semicircle bulge is ±1, got {bulge}");
}
#[test]
fn svg_smooth_quadratic_has_two_coordinates() {
let smooth = format!("{SVG_PAGE}<path d=\"M0 0 Q3 3 6 0 T12 0\"/></svg>");
let explicit = format!("{SVG_PAGE}<path d=\"M0 0 Q3 3 6 0 Q9 -3 12 0\"/></svg>");
let smooth = read(smooth.as_bytes(), "smooth.svg").unwrap();
let explicit = read(explicit.as_bytes(), "explicit.svg").unwrap();
assert_eq!(geometry(&smooth), geometry(&explicit));
}
#[test]
fn svg_group_transforms_apply() {
let svg = format!("{SVG_PAGE}<g transform=\"translate(5,2)\"><line x1=\"0\" y1=\"0\" x2=\"10\" y2=\"0\"/></g></svg>");
@@ -3081,33 +3072,6 @@ fn svgz_gunzips_to_the_same_drawing() {
assert_eq!(plain.model.iter().map(|e| &e.kind).collect::<Vec<_>>(), packed.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
}
#[test]
fn svgz_checks_the_gzip_trailer_and_combines_members() {
let svg = format!("{SVG_PAGE}<circle cx=\"5\" cy=\"5\" r=\"1\"/></svg>");
let split = svg.len() / 2;
let mut members = gzip_of(&svg.as_bytes()[..split]);
members.extend(gzip_of(&svg.as_bytes()[split..]));
let plain = read(svg.as_bytes(), "a.svg").unwrap();
let decoded = read(&members, "a.svgz").unwrap();
assert_eq!(plain.model.iter().map(|e| &e.kind).collect::<Vec<_>>(), decoded.model.iter().map(|e| &e.kind).collect::<Vec<_>>());
let mut corrupt = gzip_of(svg.as_bytes());
let crc_offset = corrupt.len() - 8;
corrupt[crc_offset] ^= 1;
assert!(read(&corrupt, "a.svgz").is_err());
}
#[test]
fn svgz_open_and_svg_export_follow_the_public_dispatch() {
let source = format!("{SVG_PAGE}<line x1=\"1\" y1=\"2\" x2=\"9\" y2=\"7\"/></svg>");
let drawing = read(&gzip_of(source.as_bytes()), "input.svgz").unwrap();
assert_eq!(kinds(&drawing), ["Line"]);
let output = write(&drawing, "output.svg").unwrap();
assert!(std::str::from_utf8(&output).unwrap().contains("<polyline"));
let reopened = read(&output, "output.svg").unwrap();
assert!(!reopened.model.is_empty());
}
#[test]
fn svg_read_dispatches_by_extension() {
let svg = format!("{SVG_PAGE}<circle cx=\"5\" cy=\"5\" r=\"1\"/></svg>");
+2 -4
View File
@@ -99,7 +99,7 @@ fn utf8_wins_when_valid() {
/// A code page CADCraft doesn't know (or none) reads as ANSI_1252, as before.
#[test]
fn unknown_code_page_falls_back_to_ansi_1252() {
for cp in ["ANSI_UNKNOWN", "EBCDIC", "", "\u{1}"] {
for cp in ["ANSI_1361", "EBCDIC", "", "\u{1}"] {
let d = cadcraft_io::read_dxf(&ascii_dxf("AC1015", cp, b"Caf\xE9", b"B", b"\x80 \xD8")).unwrap();
assert_eq!(names(&d), ("Café".into(), "B".into(), "€ Ø".into()), "{cp:?}");
}
@@ -209,9 +209,7 @@ fn binary_dxf_honours_the_code_page() {
// a pre-R2007 binary file has no way to escape to UTF-8, so its strings are never read as it.
assert_eq!(read(&bin("AC1015", "ANSI_1251", b"\xD1\xB2")), "СІ");
assert_eq!(read(&bin("AC1021", "ANSI_1251", "Привет".as_bytes())), "Привет");
assert_eq!(read(&bin("AC1015", "ANSI_UNKNOWN", b"Caf\xE9")), "Café");
assert_eq!(read(&bin("AC1015", "ANSI_1361", b"\xD0\x65\x8B\x69")), "한글");
assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Caf\u{FFFD}");
assert_eq!(read(&bin("AC1015", "ANSI_1361", b"Caf\xE9")), "Café");
}
/// Truncated and invalid multibyte sequences become U+FFFD; nothing panics and the structure of
-19
View File
@@ -354,25 +354,6 @@ fn premultiplied(r: &cadcraft_doc::Raster) -> Option<Pixmap> {
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.
pub fn encode_png(pixmap: &Pixmap) -> Option<Vec<u8>> {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Image, PngRows};
+2 -2
View File
@@ -16,8 +16,6 @@ cadcraft-color = { workspace = true }
cadcraft-doc = { workspace = true }
cadcraft-render = { workspace = true }
cadcraft-engine = { workspace = true }
cadcraft-io = { workspace = true }
craft-image-codecs = { workspace = true }
cadcraft-fonts = { workspace = true }
craft-window = { workspace = true }
egui = { workspace = true }
@@ -42,6 +40,8 @@ craft-ui = { workspace = true, features = ["native-windows"] }
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).
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]
serde_json = { workspace = true }
+3 -45
View File
@@ -691,29 +691,6 @@ 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.
fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result<std::path::PathBuf> {
use std::io::Write as _;
@@ -736,7 +713,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()));
match create_private_file(&path) {
Ok(mut file) => {
let written = write_screenshot_png(img, &mut file).and_then(|()| file.flush());
let written = img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other).and_then(|()| file.flush());
if let Err(e) = written {
// The reply carries no path on failure, so nobody else could remove the partial file.
drop(file);
@@ -775,7 +752,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64)
return inline_screenshot(&img, token);
}
let saved = match path {
Some(path) => save_explicit_screenshot(&img, path).map(|()| path.to_string()),
Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other),
None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()),
};
match saved {
@@ -789,7 +766,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64)
fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
let (w, h) = img.dimensions();
let mut png = Vec::new();
if let Err(e) = write_screenshot_png(img, &mut png) {
if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) {
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()}})
@@ -799,25 +776,6 @@ fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
mod tests {
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]
fn an_inline_screenshot_carries_the_png_and_its_size() {
let img = image::RgbaImage::from_pixel(3, 2, image::Rgba([10, 20, 30, 255]));
+6 -21
View File
@@ -70,12 +70,16 @@ 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))) {
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 tex = preview_texture(ctx, &png)?;
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8();
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));
}
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 tex = preview_texture(ctx, &png)?;
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).map_err(|e| e.to_string())?.to_rgba8();
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(""));
if r["landscape"].as_bool() == Some(true) {
info.push_str(" · landscape");
@@ -83,15 +87,6 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin
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.
pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let id = egui::Id::unique("cc_plot_preview");
@@ -174,16 +169,6 @@ mod tests {
(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]
fn typed_and_menu_commands_ask_json_calls_never_do() {
let (mut app, asked) = app();