mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-23 21:00:42 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eeca965d35 | ||
|
|
285059ce98 | ||
|
|
68fbf2a58d | ||
|
|
ee25f48c7b | ||
|
|
a6981415bf |
@@ -1,7 +1,9 @@
|
||||
//! OFFSET Erase/Layer/Multiple/Undo and the MOVE/COPY Displacement option at the command line.
|
||||
|
||||
use cadcraft_engine::Input;
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::EntityKind;
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use serde_json::json;
|
||||
|
||||
/// Every line as ((ax, ay), (bx, by), layer), sorted by the first y.
|
||||
@@ -62,6 +64,27 @@ fn offset_multiple_and_undo() {
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.0), (10.0, 2.0), "0"), l((0.0, 4.0), (10.0, 4.0), "0")]);
|
||||
}
|
||||
|
||||
// Regression test for #618: OFFSET's distance prompt took only a typed number; clicking two points
|
||||
// (the distance between them) was rejected, and the second click had no distance guide.
|
||||
#[test]
|
||||
fn offset_distance_from_two_clicked_points() {
|
||||
let mut s = one_line();
|
||||
s.start("offset").unwrap();
|
||||
s.input(Input::Point(Vec2::new(20.0, 20.0))).unwrap();
|
||||
let p = s.current_prompt().unwrap();
|
||||
assert!(p.message.contains("second point"), "{}", s.prompt_text());
|
||||
assert!(p.base.is_some_and(|b| b.near(Vec2::new(20.0, 20.0), 1e-9)), "the second click is measured from the first");
|
||||
// The guide from the first click to the cursor is the previewed distance.
|
||||
let guide = s.preview(Vec2::new(20.0, 22.5));
|
||||
assert!(matches!(guide.first().map(|e| &e.kind), Some(EntityKind::Line(g)) if g.a.xy().near(Vec2::new(20.0, 20.0), 1e-9)), "{guide:?}");
|
||||
s.input(Input::Point(Vec2::new(20.0, 22.5))).unwrap();
|
||||
assert!(s.current_prompt().unwrap().message.contains("Select object"), "{}", s.prompt_text());
|
||||
assert_eq!(s.doc().unwrap().header.f64("OFFSETDIST", -1.0), 2.5);
|
||||
s.script("5,0 5,1\n\n").unwrap();
|
||||
assert!(s.running.is_none(), "{}", s.prompt_text());
|
||||
assert_eq!(lines(&s), vec![l((0.0, 0.0), (10.0, 0.0), "0"), l((0.0, 2.5), (10.0, 2.5), "0")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offset_json_erase_and_layer() {
|
||||
let mut s = one_line();
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
//! A synthetic TrueType (sfnt) font file, built in code for tests that need a real font without a
|
||||
//! font file in the repository or one installed on the machine: `head`, `hhea`, `maxp`, `hmtx`,
|
||||
//! `glyf`, `loca`, a format-4 `cmap` and `OS/2`, laid out in a sorted table directory.
|
||||
//!
|
||||
//! Test-only, and shared: `crates/render/src/tests.rs` (the level-of-detail fixture) and
|
||||
//! `crates/io/tests/pdf_text.rs` (the PDF writer's embedding fixtures) build their fonts with it,
|
||||
//! each including this file with `#[path]`, so neither needs a published API, a dependency or a
|
||||
//! copy of the other's tables. `crates/fonts` is the layer that reads those tables
|
||||
//! (`crates/fonts/src/ttf.rs`), which is why the skeleton lives beside its tests; the glyph shapes,
|
||||
//! the character map ranges and the metrics a font records stay at the caller that needs them.
|
||||
|
||||
fn be16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
fn be32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
/// A simple glyph, with the point and contour counts `maxp` records for the font.
|
||||
pub struct Glyph {
|
||||
bytes: Vec<u8>,
|
||||
points: usize,
|
||||
contours: usize,
|
||||
}
|
||||
|
||||
/// `.notdef`: no contours, no bytes.
|
||||
pub fn notdef() -> Glyph {
|
||||
Glyph { bytes: Vec::new(), points: 0, contours: 0 }
|
||||
}
|
||||
|
||||
/// One simple glyph: closed contours of on-curve points, with the box the file records for it.
|
||||
pub fn glyph(contours: &[Vec<(i16, i16)>]) -> Glyph {
|
||||
let points: Vec<(i16, i16)> = contours.iter().flatten().copied().collect();
|
||||
let mut g = Vec::new();
|
||||
be16(&mut g, contours.len() as u16);
|
||||
let box_ = points.iter().fold((i16::MAX, i16::MAX, i16::MIN, i16::MIN), |b, p| (b.0.min(p.0), b.1.min(p.1), b.2.max(p.0), b.3.max(p.1)));
|
||||
for v in [box_.0, box_.1, box_.2, box_.3] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
let mut end = 0u16;
|
||||
for c in contours {
|
||||
end = end.saturating_add(c.len() as u16);
|
||||
be16(&mut g, end.saturating_sub(1));
|
||||
}
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, points.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in &points {
|
||||
be16(&mut g, x.wrapping_sub(px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in &points {
|
||||
be16(&mut g, y.wrapping_sub(py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
Glyph { bytes: g, points: points.len(), contours: contours.len() }
|
||||
}
|
||||
|
||||
/// What the callers differ in; every other table field is the same in each font this builds.
|
||||
pub struct Sfnt<'a> {
|
||||
/// `glyf` entries, `.notdef` first.
|
||||
pub glyphs: &'a [Glyph],
|
||||
/// `cmap` format-4 segments: first character code, last character code, and glyph id minus
|
||||
/// code. The `0xFFFF` segment that ends the map is added here.
|
||||
pub cmap: &'a [(u16, u16, i16)],
|
||||
/// The advance width every glyph shares, in em units.
|
||||
pub advance: u16,
|
||||
/// The left side bearing every glyph shares.
|
||||
pub lsb: i16,
|
||||
/// `hmtx` entries written. Fewer than the glyphs `hhea` declares is a deliberately short
|
||||
/// table: that font is malformed on purpose, and a reader must cope with it, not repair it.
|
||||
pub metrics: usize,
|
||||
/// `OS/2` `fsType`: the embedding permissions, `0` for any use.
|
||||
pub fs_type: u16,
|
||||
/// `head`'s ink box: xMin, yMin, xMax, yMax.
|
||||
pub ink_box: [i16; 4],
|
||||
}
|
||||
|
||||
/// Em units per em: with a 700-unit cap height, one em is 1000 units, so a text height of one unit
|
||||
/// is a cap height of one unit.
|
||||
const UNITS_PER_EM: u16 = 1000;
|
||||
|
||||
/// The font file `f` describes, as a TrueType file.
|
||||
pub fn bytes(f: &Sfnt<'_>) -> Vec<u8> {
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in f.glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(&g.bytes);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000); // version
|
||||
be32(&mut head, 0x0001_0000); // fontRevision
|
||||
be32(&mut head, 0); // checkSumAdjustment
|
||||
be32(&mut head, 0x5F0F_3CF5); // magic
|
||||
be16(&mut head, 0); // flags
|
||||
be16(&mut head, UNITS_PER_EM);
|
||||
head.extend_from_slice(&[0; 16]); // created, modified
|
||||
for v in f.ink_box {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
// macStyle, lowestRecPPEM, fontDirectionHint, indexToLocFormat 1 = long offsets (`loca` holds
|
||||
// `u32`), glyphDataFormat.
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
// ascender, descender, lineGap, advanceWidthMax, minLeftSideBearing, minRightSideBearing,
|
||||
// xMaxExtent, caretSlopeRise, caretSlopeRun, caretOffset, four reserved, metricDataFormat.
|
||||
for v in [800i16, -200, 0, f.advance as i16, 0, 0, f.advance as i16, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, f.glyphs.len() as u16); // numberOfHMetrics
|
||||
let max_points = f.glyphs.iter().map(|g| g.points).max().unwrap_or(0);
|
||||
let max_contours = f.glyphs.iter().map(|g| g.contours).max().unwrap_or(0);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
// numGlyphs, maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones, and
|
||||
// the composite and instruction maxima after them.
|
||||
for v in [f.glyphs.len() as u16, max_points as u16, max_contours as u16, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..f.metrics {
|
||||
be16(&mut hmtx, f.advance);
|
||||
be16(&mut hmtx, f.lsb as u16);
|
||||
}
|
||||
// cmap: version 0 with one encoding record (Windows, Unicode BMP), a format-4 subtable over
|
||||
// the caller's segments and the `0xFFFF` one that ends it.
|
||||
let segs: Vec<(u16, u16, i16)> = f.cmap.iter().copied().chain([(0xFFFF, 0xFFFF, 1)]).collect();
|
||||
let seg_count = segs.len() as u32;
|
||||
let seg_selector = seg_count.ilog2();
|
||||
let seg_search_range = 2 * (1 << seg_selector);
|
||||
let mut sub = Vec::new();
|
||||
be16(&mut sub, 4); // format
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16); // length
|
||||
be16(&mut sub, 0); // language
|
||||
be16(&mut sub, (segs.len() * 2) as u16); // segCountX2
|
||||
for v in [seg_search_range as u16, seg_selector as u16, (2 * seg_count - seg_search_range) as u16] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0); // reservedPad
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in &segs {
|
||||
be16(&mut sub, s.2 as u16);
|
||||
}
|
||||
for _ in &segs {
|
||||
be16(&mut sub, 0); // idRangeOffset
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12); // the subtable, straight after the records
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&f.fs_type.to_be_bytes());
|
||||
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
|
||||
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
tables.sort_by_key(|t| *t.0);
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000); // sfnt version 1.0
|
||||
let num_tables = tables.len() as u32;
|
||||
let table_selector = num_tables.ilog2();
|
||||
let dir_search_range = 16 * (1 << table_selector);
|
||||
// numTables, searchRange, entrySelector, rangeShift: 16-byte records, largest power of two first.
|
||||
for v in [num_tables as u16, dir_search_range as u16, table_selector as u16, (16 * num_tables - dir_search_range) as u16] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut off = 12 + 16 * tables.len();
|
||||
for (t, d) in &tables {
|
||||
out.extend_from_slice(*t);
|
||||
be32(&mut out, 0); // checkSum: the readers here do not verify it
|
||||
be32(&mut out, off as u32);
|
||||
be32(&mut out, d.len() as u32);
|
||||
off += d.len().div_ceil(4) * 4;
|
||||
}
|
||||
for (_, d) in &tables {
|
||||
out.extend_from_slice(d);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -422,6 +422,30 @@ fn hostile_dxf_does_not_panic() {
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #1336: the LAYER table of a DXF had no record cap, so a hostile file could
|
||||
// grow the layer list without bound (its VIEW/UCS/VPORT peers stop at one million records).
|
||||
#[test]
|
||||
fn dxf_layer_table_stops_at_the_record_cap() {
|
||||
use std::fmt::Write as _;
|
||||
let records = 1_000_100;
|
||||
let mut text = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n");
|
||||
for i in 0..records {
|
||||
let _ = write!(text, "0\nLAYER\n2\nL{i}\n");
|
||||
}
|
||||
text.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
|
||||
let d = read(text.as_bytes(), "layers.dxf").unwrap();
|
||||
// The exact total, not a range: the layer list stops at 1,000,000 layers, the drawing's own
|
||||
// default layers counted among them, so a cap that truncates early or late fails as loudly as
|
||||
// none at all. The count is a literal on purpose -- if the constant changes, this test must fail
|
||||
// rather than follow it.
|
||||
assert_eq!(
|
||||
d.layers.len(),
|
||||
1_000_000,
|
||||
"the LAYER table must stop at exactly 1,000,000 layers in total, defaults included, reading {records} records, but kept {}",
|
||||
d.layers.len()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_and_png_export() {
|
||||
let d = sample();
|
||||
|
||||
+22
-128
@@ -3,7 +3,8 @@
|
||||
//! rotation, width factor and obliquing; fonts whose licence bits forbid embedding, the stroke
|
||||
//! font and the `text: "geometry"` option keep filled outlines.
|
||||
//!
|
||||
//! The fonts are tiny synthetic TrueType files built here (no font files in the repository).
|
||||
//! The fonts are tiny synthetic TrueType files built by the shared test helper in
|
||||
//! `crates/fonts/tests/support/sfnt.rs` (no font files in the repository).
|
||||
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Space, Text, TextStyle, Viewport};
|
||||
use cadcraft_geom::{Vec2, Vec3};
|
||||
@@ -15,137 +16,30 @@ mod pdf_read;
|
||||
|
||||
use pdf_read::Doc;
|
||||
|
||||
// The synthetic TrueType file: the fonts layer's test-only helper, inlined rather than published
|
||||
// or depended on.
|
||||
#[path = "../../fonts/tests/support/sfnt.rs"]
|
||||
mod sfnt;
|
||||
|
||||
// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ----------
|
||||
|
||||
fn be16(v: &mut Vec<u8>, x: u16) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
fn be32(v: &mut Vec<u8>, x: u32) {
|
||||
v.extend_from_slice(&x.to_be_bytes());
|
||||
}
|
||||
|
||||
/// A simple glyph: one closed contour of on-curve points.
|
||||
fn simple_glyph(pts: &[(i16, i16)]) -> Vec<u8> {
|
||||
let mut g = Vec::new();
|
||||
let xs: Vec<i16> = pts.iter().map(|p| p.0).collect();
|
||||
let ys: Vec<i16> = pts.iter().map(|p| p.1).collect();
|
||||
be16(&mut g, 1);
|
||||
for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] {
|
||||
be16(&mut g, v as u16);
|
||||
}
|
||||
be16(&mut g, pts.len() as u16 - 1);
|
||||
be16(&mut g, 0);
|
||||
g.extend(std::iter::repeat_n(1u8, pts.len()));
|
||||
let (mut px, mut py) = (0i16, 0i16);
|
||||
for (x, _) in pts {
|
||||
be16(&mut g, (x - px) as u16);
|
||||
px = *x;
|
||||
}
|
||||
for (_, y) in pts {
|
||||
be16(&mut g, (y - py) as u16);
|
||||
py = *y;
|
||||
}
|
||||
while g.len() % 4 != 0 {
|
||||
g.push(0);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
/// A TrueType font with glyphs .notdef (empty), A and B, and OS/2 `fsType`. `hmtx` holds
|
||||
/// `metrics` of the three metrics `hhea` declares.
|
||||
/// `metrics` of the three metrics `hhea` declares: fewer is a font the writer cannot subset.
|
||||
fn test_font(fs_type: u16, metrics: usize) -> Vec<u8> {
|
||||
let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])];
|
||||
let mut glyf = Vec::new();
|
||||
let mut loca = Vec::new();
|
||||
for g in &glyphs {
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
glyf.extend_from_slice(g);
|
||||
}
|
||||
be32(&mut loca, glyf.len() as u32);
|
||||
let mut head = Vec::new();
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0x0001_0000);
|
||||
be32(&mut head, 0);
|
||||
be32(&mut head, 0x5F0F_3CF5);
|
||||
be16(&mut head, 0);
|
||||
be16(&mut head, 1000);
|
||||
head.extend_from_slice(&[0; 16]);
|
||||
for v in [0i16, 0, 600, 700] {
|
||||
be16(&mut head, v as u16);
|
||||
}
|
||||
for v in [0u16, 8, 2, 1, 0] {
|
||||
be16(&mut head, v);
|
||||
}
|
||||
let mut hhea = Vec::new();
|
||||
be32(&mut hhea, 0x0001_0000);
|
||||
for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut hhea, v as u16);
|
||||
}
|
||||
be16(&mut hhea, 3);
|
||||
let mut maxp = Vec::new();
|
||||
be32(&mut maxp, 0x0001_0000);
|
||||
for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] {
|
||||
be16(&mut maxp, v);
|
||||
}
|
||||
let mut hmtx = Vec::new();
|
||||
for _ in 0..metrics {
|
||||
be16(&mut hmtx, 600);
|
||||
be16(&mut hmtx, 50);
|
||||
}
|
||||
// cmap: format 4, 'A'..'B' → 1..2.
|
||||
let mut sub = Vec::new();
|
||||
let segs: [(u16, u16, u16); 2] = [(0x41, 0x42, 1u16.wrapping_sub(0x41)), (0xFFFF, 0xFFFF, 1)];
|
||||
be16(&mut sub, 4);
|
||||
be16(&mut sub, (16 + segs.len() * 8) as u16);
|
||||
be16(&mut sub, 0);
|
||||
be16(&mut sub, (segs.len() * 2) as u16);
|
||||
for v in [4u16, 1, 0] {
|
||||
be16(&mut sub, v);
|
||||
}
|
||||
for s in segs {
|
||||
be16(&mut sub, s.1);
|
||||
}
|
||||
be16(&mut sub, 0);
|
||||
for s in segs {
|
||||
be16(&mut sub, s.0);
|
||||
}
|
||||
for s in segs {
|
||||
be16(&mut sub, s.2);
|
||||
}
|
||||
for _ in segs {
|
||||
be16(&mut sub, 0);
|
||||
}
|
||||
let mut cmap = Vec::new();
|
||||
for v in [0u16, 1, 3, 1] {
|
||||
be16(&mut cmap, v);
|
||||
}
|
||||
be32(&mut cmap, 12);
|
||||
cmap.extend_from_slice(&sub);
|
||||
let mut os2 = vec![0u8; 78];
|
||||
os2[8..10].copy_from_slice(&fs_type.to_be_bytes());
|
||||
let mut tables: Vec<(&[u8; 4], Vec<u8>)> =
|
||||
vec![(b"OS/2", os2), (b"cmap", cmap), (b"glyf", glyf), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"loca", loca), (b"maxp", maxp)];
|
||||
tables.sort_by_key(|t| *t.0);
|
||||
let mut out = Vec::new();
|
||||
be32(&mut out, 0x0001_0000);
|
||||
for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] {
|
||||
be16(&mut out, v);
|
||||
}
|
||||
let mut off = 12 + 16 * tables.len();
|
||||
for (t, d) in &tables {
|
||||
out.extend_from_slice(*t);
|
||||
be32(&mut out, 0);
|
||||
be32(&mut out, off as u32);
|
||||
be32(&mut out, d.len() as u32);
|
||||
off += d.len().div_ceil(4) * 4;
|
||||
}
|
||||
for (_, d) in &tables {
|
||||
out.extend_from_slice(d);
|
||||
while out.len() % 4 != 0 {
|
||||
out.push(0);
|
||||
}
|
||||
}
|
||||
out
|
||||
sfnt::bytes(&sfnt::Sfnt {
|
||||
// "A" is a triangle and "B" a square: one contour each.
|
||||
glyphs: &[
|
||||
sfnt::notdef(),
|
||||
sfnt::glyph(&[vec![(50, 0), (550, 0), (300, 700)]]),
|
||||
sfnt::glyph(&[vec![(50, 0), (550, 0), (550, 700), (50, 700)]]),
|
||||
],
|
||||
cmap: &[(0x41, 0x42, 1 - 0x41)], // "A".."B" → glyphs 1..2
|
||||
advance: 600,
|
||||
lsb: 50,
|
||||
metrics,
|
||||
fs_type,
|
||||
ink_box: [0, 0, 600, 700],
|
||||
})
|
||||
}
|
||||
|
||||
/// Register the test fonts once: an embeddable one, one with a restricted licence, and one
|
||||
|
||||
@@ -3,6 +3,11 @@ use crate::*;
|
||||
use cadcraft_doc::{Common, Drawing, EntityKind, Hatch, HatchLoop, Space};
|
||||
use cadcraft_geom::{PolyVertex, Vec3};
|
||||
|
||||
// The synthetic TrueType file both this suite and the PDF writer's build: the fonts layer's
|
||||
// test-only helper, inlined rather than published or depended on.
|
||||
#[path = "../../fonts/tests/support/sfnt.rs"]
|
||||
mod sfnt;
|
||||
|
||||
fn sample() -> Drawing {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(10.0, 0.0, 0.0) }))
|
||||
@@ -277,6 +282,44 @@ fn system_font() -> Option<&'static str> {
|
||||
["Arial", "Helvetica", "DejaVuSans", "Verdana", "LiberationSans-Regular"].into_iter().find(|n| cadcraft_fonts::ttf::find(n).is_some())
|
||||
}
|
||||
|
||||
// ---------- a fixture TrueType font: no font file, no installed font ----------
|
||||
|
||||
/// A closed ellipse round (500, 350), wound by `clockwise`: one contour of a glyph outline.
|
||||
fn ring(rx: f64, ry: f64, points: usize, clockwise: bool) -> Vec<(i16, i16)> {
|
||||
let dir = if clockwise { -1.0 } else { 1.0 };
|
||||
(0..points)
|
||||
.map(|i| {
|
||||
(
|
||||
(500.0 + rx * (dir * std::f64::consts::TAU * i as f64 / points as f64).cos()) as i16,
|
||||
(350.0 + ry * (dir * std::f64::consts::TAU * i as f64 / points as f64).sin()) as i16,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A TrueType font whose only glyph, "O", is a 128-point ring: the flattened outline a real font's
|
||||
/// curve gives, at the same scale, with plenty of detail to simplify. It is built in code so the
|
||||
/// level-of-detail test needs no installed font and no font file in the repository (#651).
|
||||
fn fixture_font() -> &'static str {
|
||||
const NAME: &str = "cadcraft-render-lod.ttf";
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| cadcraft_fonts::ttf::register(NAME, fixture_font_bytes()));
|
||||
NAME
|
||||
}
|
||||
|
||||
fn fixture_font_bytes() -> Vec<u8> {
|
||||
sfnt::bytes(&sfnt::Sfnt {
|
||||
// Glyph 1 is "O": a 128-point ring, its counter a second, oppositely wound contour.
|
||||
glyphs: &[sfnt::notdef(), sfnt::glyph(&[ring(500.0, 350.0, 128, false), ring(250.0, 150.0, 128, true)])],
|
||||
cmap: &[(0x4F, 0x4F, 1 - 0x4F)], // "O" → glyph 1
|
||||
advance: 1000, // one em wide
|
||||
lsb: 0,
|
||||
metrics: 2, // hmtx matches the two metrics hhea declares
|
||||
fs_type: 0, // any use
|
||||
ink_box: [0, 0, 1000, 700], // the ring's box; the 700-unit cap height is the unit scale
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truetype_text_is_filled_or_outlined() {
|
||||
let Some(font) = system_font() else { return };
|
||||
@@ -298,6 +341,31 @@ fn truetype_text_is_filled_or_outlined() {
|
||||
assert!(l.prims.len() >= 3, "O has two contours, H one");
|
||||
}
|
||||
|
||||
// Regression test for #651: filled TrueType text was triangulated at full outline detail at every
|
||||
// zoom, so a page of small text on screen produced millions of triangles and froze the canvas.
|
||||
#[test]
|
||||
fn small_filled_text_on_screen_is_simplified_but_plots_keep_full_detail() {
|
||||
let d = text_doc(fixture_font(), "OOOO");
|
||||
let tris = |l: &DisplayList| l.prims.iter().filter(|p| p.kind == Kind::Tris).map(|p| l.points(p).len() / 3).sum::<usize>();
|
||||
let plot = build_plot(&d, &Space::Model, &Options::default());
|
||||
let full = tris(&plot);
|
||||
assert!(full > 100, "a plot keeps every point of the 128-point rings: {full} triangles");
|
||||
// One pixel is a tenth of the cap height: the rings are simplified to a few points, the shapes
|
||||
// stay.
|
||||
let reduced = build(&d, &Space::Model, &screen(0.1, None));
|
||||
assert!(tris(&reduced) < full / 2, "{} triangles at 10 px per cap height, {full} in a plot", tris(&reduced));
|
||||
assert!(tris(&reduced) > 0 && reduced.bounds.width() > plot.bounds.width() * 0.9, "{:?} vs {:?}", reduced.bounds, plot.bounds);
|
||||
// An em under two pixels is drawn as the ink's box: two triangles a glyph, same extent.
|
||||
let tiny = build(&d, &Space::Model, &screen(2.0, None));
|
||||
assert_eq!(tris(&tiny), 2 * 4, "one box per glyph");
|
||||
assert!(
|
||||
tiny.bounds.width() > plot.bounds.width() * 0.9 && tiny.bounds.height() > plot.bounds.height() * 0.9,
|
||||
"{:?} vs {:?}",
|
||||
tiny.bounds,
|
||||
plot.bounds
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_font_falls_back_to_stroke() {
|
||||
let d = text_doc("NoSuchFontAnywhere.ttf", "OH");
|
||||
|
||||
@@ -256,6 +256,34 @@ mod tests {
|
||||
assert!(tris.iter().all(|p| (5.0e5..=5.0e5 + 2.0).contains(&p.x) && (-3.0e5..=-3.0e5 + 2.0).contains(&p.y)));
|
||||
}
|
||||
|
||||
// Regression test for #651: the level of detail followed the pixel size, so a page of small
|
||||
// filled text on screen kept a few points a glyph while a plot kept all of them.
|
||||
#[test]
|
||||
fn a_small_on_screen_pixel_simplifies_glyphs_and_a_plot_does_not() {
|
||||
// Text of height 1 has a 700-unit cap height: one font unit is 1/700 of a drawing unit.
|
||||
let xf = Mat3 { a: 1.0 / 700.0, b: 0.0, c: 0.0, d: 1.0 / 700.0, e: 0.0, f: 0.0 };
|
||||
assert!(matches!(detail(xf, 0.0), Detail::Full), "a plot keeps every point");
|
||||
assert!(matches!(detail(xf, 2.0), Detail::Box), "an em under two pixels is the ink's box");
|
||||
assert!(matches!(detail(xf, 0.1), Detail::Reduced(band) if band >= 2), "10 px per cap height simplifies");
|
||||
assert!(matches!(detail(xf, f64::NAN), Detail::Full), "a pixel size that is not a size keeps full detail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_coarse_band_drops_the_points_of_a_flattened_curve() {
|
||||
// A ring of 64 points, the outline a flattened curve gives.
|
||||
let ring: Vec<Vec2> = (0..64u32)
|
||||
.map(|i| {
|
||||
let t = std::f64::consts::TAU * f64::from(i) / 64.0;
|
||||
Vec2::new(500.0 * t.cos(), 350.0 * t.sin())
|
||||
})
|
||||
.collect();
|
||||
let coarse = simplify(&ring, 8.0);
|
||||
assert!(coarse.len() < ring.len() / 2, "{} of {} points kept at 8 font units", coarse.len(), ring.len());
|
||||
assert!(coarse.len() >= 4, "a ring never collapses to a line: {}", coarse.len());
|
||||
let fine = simplify(&ring, 0.01);
|
||||
assert!(fine.len() >= ring.len(), "a fine band keeps every point: {} of {}", fine.len(), ring.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_placed_outline_never_panics() {
|
||||
assert!(triangulate_placed(&[]).is_empty());
|
||||
|
||||
@@ -27,6 +27,7 @@ mod mtext_double_click;
|
||||
mod named_viewports_dialog;
|
||||
mod native_menu_text_keys;
|
||||
mod native_windows;
|
||||
mod offset_clicks;
|
||||
mod options_dialog;
|
||||
mod options_right_click;
|
||||
mod page_setup_paper_units;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! OFFSET on the canvas: the distance can be clicked, and picking the source is not moved by the
|
||||
//! grid snap (#618).
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Line, Space};
|
||||
use cadcraft_engine::geom::Vec2;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
|
||||
use egui_kittest::Harness;
|
||||
use serde_json::json;
|
||||
|
||||
fn harness() -> Harness<'static, CadApp> {
|
||||
let mut d = Drawing::new_imperial();
|
||||
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec2::new(0.0, 2.0).to3(0.0), b: Vec2::new(10.0, 2.0).to3(0.0) })).unwrap();
|
||||
let mut session = Session::empty();
|
||||
session.open_drawing(d, "Offset clicks", None);
|
||||
session.execute("view.set", &json!({"center":[5,5],"height":20})).unwrap();
|
||||
session.settings.osmode = 0;
|
||||
session.settings.snapmode = true;
|
||||
session.execute("setvar", &json!({"name":"SNAPUNIT","value":[5,5]})).unwrap();
|
||||
session.settings.orthomode = false;
|
||||
let mut app = CadApp::new(session, Services::default());
|
||||
app.canvas.zoom_pending = false;
|
||||
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|
||||
|ui, app: &mut CadApp| {
|
||||
app.logic(ui.ctx());
|
||||
app.ui(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
h.run_steps(5);
|
||||
h
|
||||
}
|
||||
|
||||
fn click(h: &mut Harness<'_, CadApp>, world: Vec2) {
|
||||
let pos: Pos2 = h.state().canvas.xf.unwrap().to_screen(world);
|
||||
h.event(Event::PointerMoved(pos));
|
||||
h.run_steps(2);
|
||||
for pressed in [true, false] {
|
||||
h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
}
|
||||
}
|
||||
|
||||
// Regression test for #618: OFFSET's distance could not be clicked, and with grid snap on a click
|
||||
// meant to pick the source object was moved to the nearest grid point, missing the object.
|
||||
#[test]
|
||||
fn offset_takes_a_clicked_distance_and_picks_its_source_under_grid_snap() {
|
||||
let mut h = harness();
|
||||
h.state_mut().start("offset");
|
||||
h.run_steps(2);
|
||||
// Two clicks, snapped to the grid points (5, 5) and (10, 5): a distance of 5.
|
||||
click(&mut h, Vec2::new(5.1, 4.9));
|
||||
assert!(h.state().session.prompt_text().contains("second point"), "{}", h.state().session.prompt_text());
|
||||
click(&mut h, Vec2::new(9.9, 5.1));
|
||||
assert_eq!(h.state().session.doc().unwrap().header.f64("OFFSETDIST", -1.0), 5.0);
|
||||
assert!(h.state().session.prompt_text().contains("Select object"), "{}", h.state().session.prompt_text());
|
||||
// The source line is at y = 2, two units from the grid point (5, 0) the click would snap to.
|
||||
click(&mut h, Vec2::new(7.0, 2.04));
|
||||
let prompt = h.state().session.prompt_text();
|
||||
assert!(prompt.contains("side to offset"), "the line was not picked: {prompt}");
|
||||
// A side click above the line (snapped to (5, 5)) makes the copy 5 units up, at y = 7.
|
||||
click(&mut h, Vec2::new(7.0, 7.0));
|
||||
let lines: Vec<(f64, f64)> = h
|
||||
.state()
|
||||
.session
|
||||
.doc()
|
||||
.unwrap()
|
||||
.model
|
||||
.iter()
|
||||
.filter_map(|e| match &e.kind {
|
||||
EntityKind::Line(line) => Some((line.a.y, line.b.y)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(lines.len(), 2, "OFFSET added no line: {lines:?}");
|
||||
assert!(lines.iter().any(|&(a, b)| (a - 7.0).abs() < 1e-9 && (b - 7.0).abs() < 1e-9), "no copy at y = 7: {lines:?}");
|
||||
// OFFSET asks for the next object; Enter ends it.
|
||||
assert!(h.state().session.prompt_text().contains("Select object to offset"), "{}", h.state().session.prompt_text());
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.prompt_text(), "Command:", "Enter ends OFFSET");
|
||||
}
|
||||
Reference in New Issue
Block a user