Compare commits

..
11 changed files with 448 additions and 179 deletions
Generated
+3 -9
View File
@@ -828,6 +828,7 @@ dependencies = [
"cadcraft-io",
"cadcraft-render",
"chrono",
"craft-image-codecs",
"craft-ui",
"craft-update",
"craft-window",
@@ -1173,11 +1174,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"
@@ -1195,11 +1191,9 @@ 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",
]
@@ -1300,7 +1294,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",
]
+1 -1
View File
@@ -14,7 +14,7 @@ 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-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "0325b2d73676d736e94097dbcef01219cf25c7db" }
+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 = pm.encode_png().map_err(|_| bad("preview", "rendering the preview failed"))?;
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
let layout = space.tab_name();
Ok(json!({ "data": base64_encode(&png), "width": w, "height": h, "layout": layout, "paper": page.paper, "landscape": page.landscape }))
}
+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
+2 -12
View File
@@ -4,7 +4,7 @@
use crate::{IoError, Result};
use cadcraft_doc::Raster;
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, EncodeOptions, Format, Image, Limits, PngRows, SampleType};
use craft_image_codecs::{ChannelLayout, DecodeOptions, DecodeWarning, Format, Limits, SampleType};
/// Largest image file read (bytes).
pub const MAX_IMAGE_BYTES: usize = 256 << 20;
@@ -61,17 +61,7 @@ pub fn decode(bytes: &[u8]) -> Result<Raster> {
/// `raster` as a PNG file, encoded in rows to avoid a full extra image copy.
pub fn encode_png(raster: &Raster) -> Result<Vec<u8>> {
let stride = usize::try_from(raster.width()).ok().and_then(|w| w.checked_mul(4)).filter(|s| *s > 0).ok_or_else(|| bad("invalid image width"))?;
let mut chunks = raster.rgba().chunks_exact(stride);
let first = chunks.next().ok_or_else(|| bad("the image is empty"))?;
let row = |data: &[u8]| Image::from_u8(raster.width(), 1, ChannelLayout::Rgba, data.to_vec()).map_err(bad);
let first = row(first)?;
let mut out = Vec::new();
let mut 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)?;
cadcraft_render::raster::write_rgba_png(&mut out, raster.width(), raster.height(), raster.rgba()).ok_or_else(|| bad("PNG encoding failed"))?;
Ok(out)
}
+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,6 +354,25 @@ 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,6 +16,8 @@ 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 }
@@ -40,8 +42,6 @@ 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 }
+45 -3
View File
@@ -691,6 +691,29 @@ impl Drop for PathlessShots {
}
}
fn write_screenshot_png(img: &image::RgbaImage, output: impl std::io::Write) -> std::io::Result<()> {
cadcraft_render::raster::write_rgba_png(output, img.width(), img.height(), img.as_raw())
.ok_or_else(|| std::io::Error::other("PNG encoding failed"))
}
fn save_explicit_screenshot(img: &image::RgbaImage, path: &str) -> std::io::Result<()> {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image};
let format = match image::ImageFormat::from_path(path).map_err(std::io::Error::other)? {
image::ImageFormat::Png => Format::Png,
image::ImageFormat::Jpeg => Format::Jpeg,
image::ImageFormat::Bmp => Format::Bmp,
image::ImageFormat::Tiff => Format::Tiff,
_ => return Err(std::io::Error::other("unsupported screenshot format")),
};
if format == Format::Png {
return write_screenshot_png(img, std::fs::File::create(path)?);
}
let pixels = Image::from_u8(img.width(), img.height(), ChannelLayout::Rgba, img.as_raw().clone()).map_err(std::io::Error::other)?;
let opts = EncodeOptions { jpeg_quality: 75, jpeg_chroma_subsampling: false, ..EncodeOptions::default() };
let bytes = craft_image_codecs::encode(&pixels, format, &opts).map_err(std::io::Error::other)?;
std::fs::write(path, bytes)
}
/// Save a pathless screenshot into the private per-process directory: re-validate or recreate it as an owner-only real directory (0700 on Unix; plain create elsewhere), then create up to 64 exclusive files (0600 on Unix) and write a PNG.
fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Result<std::path::PathBuf> {
use std::io::Write as _;
@@ -713,7 +736,7 @@ fn save_pathless_screenshot(img: &image::RgbaImage, token: u64) -> std::io::Resu
let path = dir.join(format!("cadcraft-shot-{token}-{}.png", next_pathless_nonce()));
match create_private_file(&path) {
Ok(mut file) => {
let written = img.write_to(&mut file, image::ImageFormat::Png).map_err(std::io::Error::other).and_then(|()| file.flush());
let written = write_screenshot_png(img, &mut file).and_then(|()| file.flush());
if let Err(e) = written {
// The reply carries no path on failure, so nobody else could remove the partial file.
drop(file);
@@ -752,7 +775,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64)
return inline_screenshot(&img, token);
}
let saved = match path {
Some(path) => img.save(path).map(|()| path.to_string()).map_err(std::io::Error::other),
Some(path) => save_explicit_screenshot(&img, path).map(|()| path.to_string()),
None => save_pathless_screenshot(&img, token).map(|path| path.to_string_lossy().into_owned()),
};
match saved {
@@ -766,7 +789,7 @@ pub fn save_screenshot(image: &egui::ColorImage, path: Option<&str>, token: u64)
fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
let (w, h) = img.dimensions();
let mut png = Vec::new();
if let Err(e) = img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) {
if let Err(e) = write_screenshot_png(img, &mut png) {
return json!({"ok": false, "error": e.to_string(), "request": token});
}
json!({"ok": true, "request": token, "result": {"pngBase64": cadcraft_engine::cmd::file::base64_encode(&png), "width": w, "height": h, "bytes": png.len()}})
@@ -776,6 +799,25 @@ fn inline_screenshot(img: &image::RgbaImage, token: u64) -> Value {
mod tests {
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]));
+21 -6
View File
@@ -70,16 +70,12 @@ fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, Strin
if let Some(f) = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))) {
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 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 tex = preview_texture(ctx, &png)?;
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 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 tex = preview_texture(ctx, &png)?;
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");
@@ -87,6 +83,15 @@ 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");
@@ -169,6 +174,16 @@ 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();