Merge pull request #8218 from dotCooCoo/fix/emf-text-advances

Metafile import: EMF and WMF text keeps the character advances the file gives
This commit is contained in:
BFlat
2026-11-17 09:46:25 +07:00
committed by GitHub
4 changed files with 593 additions and 13 deletions
+319 -10
View File
@@ -10,7 +10,13 @@
//! - A bitmap becomes an image (its pixels as PNG) placed where the picture draws it, turned or
//! skewed with it.
//! - Text becomes point type in the font the file names, underlined or struck through as the font
//! is, and clipped to its rectangle when the file clips it.
//! is, and clipped to its rectangle when the file clips it. Characters the file gives advances
//! for are spaced by them: tracking on each character, with pair kerning off. On a single left
//! to right line, the characters after an advance that tracking can't give (further than its
//! range reaches, or a tab) are point type of their own, and an underline or strikethrough is carried across the space between.
//! It is also carried on to the end of the last character's advance. Type on more than one line
//! is placed a line at a time: each line is aligned by its own advances and split as a single
//! line is.
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
//! the whole picture clips nothing and is left out.
//!
@@ -28,7 +34,7 @@ use vectorcraft_color::Paint;
use vectorcraft_doc::clipnest::{Clip, Drawn, MAX_NEST, deep_clips, nest};
use vectorcraft_doc::{
Appearance, AppearanceItem, CharStyle, Dash, Document, FillLayer, ImageBlob, ImageObject, Justify, LayerColor, LineCap, LineJoin, Node, NodeId,
NodeKind, StrokeLayer, TextObject,
NodeKind, StrokeLayer, TextObject, TextRun,
};
use vectorcraft_geom::{Affine, BezPath, FillRule, PathData, PathEl, Point, Rect, Shape, shapes};
@@ -524,7 +530,25 @@ impl Mapper {
}
fn text(&mut self, t: &craft_metafile::Text, chain: Vec<Arc<Clip>>) {
let s: String = t.text.chars().filter(|c| *c != '\0').collect();
// The characters without NULs, and each one's advance (text units) when the file gives
// one for every character: a NUL's advance goes to the character before it, or moves the
// start when the string begins with one.
let advances = t.dx.len() == t.text.chars().count() && t.dx.iter().all(|d| d.is_finite());
let (mut s, mut dx, mut lead) = (String::new(), Vec::new(), 0.0f64);
for (c, d) in t.text.chars().zip(t.dx.iter().map(|d| f64::from(*d)).chain(std::iter::repeat(0.0))) {
if c != '\0' {
s.push(c);
dx.push(d);
} else if let Some(last) = dx.last_mut() {
*last += d;
} else {
lead += d;
}
}
if !advances {
dx.clear();
lead = 0.0;
}
if s.trim().is_empty() || t.color[3] == 0 {
return;
}
@@ -553,6 +577,11 @@ impl Mapper {
.into();
style.underline = f.underline;
style.strikethrough = f.strike;
let db = vectorcraft_text::FontDb::global();
// Characters placed by their advances take no pair kerning: the advances place them.
if !dx.is_empty() {
style.kerning = Some(0.0);
}
// Where the baseline is below the reference point.
let drop = match t.v_align {
VAlign::Baseline => 0.0,
@@ -560,17 +589,110 @@ impl Mapper {
VAlign::Top => 0.8 * size,
};
let origin = self.xf * Point::new(t.transform[4], t.transform[5]);
let mut text = TextObject::point(Point::ZERO, &s, style);
text.xf = Affine::translate(origin.to_vec2()) * shape * Affine::translate((0.0, drop));
text.para.justify = match t.h_align {
let base = Affine::translate(origin.to_vec2()) * shape;
let justify = match t.h_align {
HAlign::Center => Justify::Center,
HAlign::Right => Justify::Right,
HAlign::Left => Justify::Left,
};
text.cached_bounds = Some(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &text).bounds);
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
n.opacity = f32::from(t.color[3]) / 255.0;
self.push(chain, n);
let point = |s: &str| {
let mut text = TextObject::point(Point::ZERO, s, style.clone());
text.para.justify = justify;
text
};
let whole = point(&s);
let opacity = f32::from(t.color[3]) / 255.0;
if dx.is_empty() {
let mut text = whole;
text.xf = base * Affine::translate((0.0, drop));
text.cached_bounds = Some(vectorcraft_text::layout(db, &text).bounds);
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
n.opacity = opacity;
self.push(chain, n);
return;
}
// Text units grow by `k` along the baseline in the text object's own space.
let dx: Vec<f64> = dx.iter().map(|d| d * k).collect();
let chars: Vec<char> = s.chars().collect();
let line = Line { base, drop, align: &t.h_align, decorated: f.underline || f.strike, color: t.color, opacity, point: &point, chain: &chain };
// Type on more than one line is placed a line at a time, each line aligned by its own
// advances (layout leaves the tracking after a line's last character out of the width it
// aligns, and each line ends with its own) and its underline carried on to its own end.
let laid = vectorcraft_text::layout(db, &whole);
if laid.lines.len() > 1 {
// Where each character starts (bytes): the character a byte offset starts is found by
// a search.
let starts: Vec<usize> = s.char_indices().map(|(at, _)| at).collect();
let count = |to: usize| starts.partition_point(|at| *at < to);
let first = laid.lines.first().map_or(0.0, |l| l.baseline);
for (n, l) in laid.lines.iter().enumerate() {
let (from, to) = (count(l.start), count(l.end));
let (Some(cs), Some(dx)) = (chars.get(from..to), dx.get(from..to)) else { continue };
// A leading NUL's advance comes before the first line only.
let lead = if n == 0 { lead * k } else { 0.0 };
let down = l.baseline - first;
self.line(&line, cs, dx, lead, if down.is_finite() { down } else { 0.0 });
}
} else {
self.line(&line, &chars, &dx, lead * k, 0.0);
}
}
/// One line of text with advances `dx` (points along the baseline) for its characters `chars`,
/// `down` below the first line's baseline: in pieces, each a text object of its own, a new
/// piece after each cluster that tracking can't space by its advance.
fn line(&mut self, line: &Line, chars: &[char], dx: &[f64], lead: f64, down: f64) {
if chars.is_empty() || (chars.iter().all(|c| c.is_whitespace()) && !line.decorated) {
return;
}
let db = vectorcraft_text::FontDb::global();
let s: String = chars.iter().collect();
let (pieces, text, laid) = pieces((line.point)(&s), db, dx);
let split = pieces.len() > 1;
let mut tracked = Some((text, laid));
// Along the baseline (the text object's own space), where the next piece starts from the
// reference point: the line as long as its advances (a leading NUL's included), where the
// alignment puts it.
let mut at = aligned(lead, dx.iter().sum(), line.align);
let last = pieces.len().saturating_sub(1);
for (i, (from, to)) in pieces.into_iter().enumerate() {
let piece: String = chars.get(from..to).unwrap_or_default().iter().collect();
let dx = dx.get(from..to).unwrap_or_default();
// Blanks of their own draw nothing unless they are underlined or struck through.
if piece.trim().is_empty() && !line.decorated {
at += dx.iter().sum::<f64>();
continue;
}
// The line in one piece was already tracked to its advances.
let (mut text, laid) = match tracked.take().filter(|_| !split) {
Some(done) => done,
None => {
let mut text = (line.point)(&piece);
let laid = advanced(&mut text, db, dx);
(text, laid)
}
};
let x0 = laid.lines.first().map_or(0.0, |l| l.x0);
let start = if (at - x0).is_finite() { at - x0 } else { 0.0 };
let span: f64 = dx.iter().sum();
at += span;
text.xf = line.base * Affine::translate((start, line.drop + down));
text.cached_bounds = Some(laid.bounds);
// An underline or strikethrough runs on across the space an advance leaves before
// the next piece, or after the line's last character, as one bar per piece from where
// its own bars end.
let gap = if (split && i < last) || (i == last && line.decorated) { gaps(&laid, db, &text, x0 + span) } else { BezPath::new() };
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text.clone())));
n.opacity = line.opacity;
self.push(line.chain.to_vec(), n);
if !gap.elements().is_empty() {
let mut gap = gap;
gap.apply_affine(text.xf);
if let Some(n) = self.path_node(gap, Some(line.color), None, false) {
self.push(line.chain.to_vec(), n);
}
}
}
}
/// The document: what was drawn on one layer, clipped art in clipping groups.
@@ -595,6 +717,193 @@ impl Mapper {
}
}
/// Where a line `lead + span` long (along the baseline) starts from the reference point, as
/// `align` puts it, and `lead` on from there: where its first character starts.
fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 {
let total = lead + span;
lead + match align {
HAlign::Left => 0.0,
HAlign::Center => -total / 2.0,
HAlign::Right => -total,
}
}
/// What every piece of a text record's lines shares: the text space (`base`, with the baseline
/// `drop` below the reference point), the alignment, whether the type is underlined or struck
/// through, its color and opacity, a point type object of a string in its style, and its clips.
struct Line<'a> {
base: Affine,
drop: f64,
align: &'a HAlign,
decorated: bool,
color: [u8; 4],
opacity: f32,
point: &'a dyn Fn(&str) -> TextObject,
chain: &'a [Arc<Clip>],
}
/// The most times [`advanced`] lays the type out again to correct its tracking.
const ADVANCE_PASSES: usize = 3;
/// Sets `t`'s tracking so that each cluster (a ligature, a letter with its marks) advances by the
/// sum of its characters' entries of `dx` (points along the baseline), and gives its layout.
/// Tracking can change how the type is shaped (it drops standard ligatures past a limit), so the
/// tracking is measured against the type laid out with the last tracking and corrected, a few
/// times at most. A tracking that would pass the attribute's range is held at its end. When the
/// corrections still miss (a ligature that forms at one tracking and breaks at the next), standard
/// ligatures are turned off and the tracking is corrected again.
fn advanced(t: &mut TextObject, db: &vectorcraft_text::FontDb, dx: &[f64]) -> vectorcraft_text::TextLayout {
let laid = tracked(t, db, dx);
let (_, clusters) = clusters(t, &laid, dx);
let settled = clusters.iter().all(|c| (c.want - c.has).abs() <= c.em * 1e-4 || !(TRACKING.0..=TRACKING.1).contains(&c.wanted()));
if settled {
return laid;
}
for r in &mut t.runs {
if !r.style.features.iter().any(|f| f == "-liga") {
r.style.features.push("-liga".to_string());
}
}
tracked(t, db, dx)
}
/// `t` laid out with its tracking corrected towards `dx` at most [`ADVANCE_PASSES`] times.
fn tracked(t: &mut TextObject, db: &vectorcraft_text::FontDb, dx: &[f64]) -> vectorcraft_text::TextLayout {
let mut laid = vectorcraft_text::layout(db, t);
for _ in 0..ADVANCE_PASSES {
match retracked(t, &laid, dx) {
Some(runs) => t.runs = runs,
None => break,
}
laid = vectorcraft_text::layout(db, t);
}
laid
}
/// The tracking range of a character (thousandths of an em), as the Character panel holds it.
const TRACKING: (f64, f64) = (-1000.0, 10000.0);
/// One cluster of characters (a ligature, a letter with its marks): the advance the file wants
/// for it and its advance laid out (points, tracking included), its em as its first character's
/// Horizontal Scale draws it (which tracking is measured in) and its tracking.
struct Cluster {
want: f64,
has: f64,
em: f64,
tracking: f64,
}
impl Cluster {
/// The tracking that gives the cluster the advance the file wants, not held to the range.
fn wanted(&self) -> f64 {
self.tracking + (self.want - self.has) / self.em * 1000.0
}
}
/// `t`'s clusters as `laid` sets them, with the sum of their characters' entries of `dx`, and the
/// cluster of each character.
fn clusters(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) -> (Vec<usize>, Vec<Cluster>) {
// The advance of the cluster that starts at each byte offset.
let mut own: HashMap<usize, f64> = HashMap::new();
for g in &laid.glyphs {
*own.entry(g.byte).or_insert(0.0) += g.advance;
}
let mut cluster = Vec::new();
let mut clusters: Vec<Cluster> = Vec::new();
let mut byte = 0;
for r in &t.runs {
let em = (r.style.size * vectorcraft_text::spacing_scale(&r.style, false)).max(1e-3);
for c in r.text.chars() {
let want = dx.get(cluster.len()).copied().unwrap_or(0.0);
match (own.get(&byte), clusters.last_mut()) {
(None, Some(last)) => last.want += want,
(has, _) => clusters.push(Cluster { want, has: has.copied().unwrap_or(0.0), em, tracking: r.style.tracking }),
}
cluster.push(clusters.len().saturating_sub(1));
byte += c.len_utf8();
}
}
(cluster, clusters)
}
/// `t`'s characters in pieces (first and past the last character index) that tracking can space
/// by their advances `dx`: a piece ends after each cluster whose advance, once tracked, still
/// differs from the one the file gives (further than the tracking range reaches, or a tab, which
/// layout advances to its tab stop). The clusters are the ones the type has once tracked
/// towards its advances, so that a ligature the tracking breaks apart can split between its letters.
/// Type laid out right to left, or on more than one line, stays in one piece: pieces are placed
/// one after another left to right along a single line. Also gives `t` tracked to its advances and
/// its layout, for the type that stays in one piece.
fn pieces(mut t: TextObject, db: &vectorcraft_text::FontDb, dx: &[f64]) -> (Vec<(usize, usize)>, TextObject, vectorcraft_text::TextLayout) {
let laid = advanced(&mut t, db, dx);
let (cluster, clusters) = clusters(&t, &laid, dx);
let mut out = vec![];
let mut from = 0;
if laid.lines.len() <= 1 && !laid.glyphs.iter().any(|g| g.rtl) {
for (i, c) in cluster.iter().enumerate() {
let ends = cluster.get(i + 1) != Some(c);
if ends && clusters.get(*c).is_some_and(|c| (c.want - c.has).abs() > c.em * 1e-4) {
out.push((from, i + 1));
from = i + 1;
}
}
}
if from < cluster.len() || out.is_empty() {
out.push((from, cluster.len()));
}
(out, t, laid)
}
/// The underline and strikethrough of `t` (laid out as `laid`) carried on to `end` along the
/// baseline, in text space: the runs of a piece each draw bars of their own, and only the bars
/// that end the piece (furthest along) are carried on.
fn gaps(laid: &vectorcraft_text::TextLayout, db: &vectorcraft_text::FontDb, t: &TextObject, end: f64) -> BezPath {
let bars: Vec<Rect> = vectorcraft_text::decorations(laid, db, t).iter().map(|(_, bar)| bar.bounding_box()).collect();
let far = bars.iter().map(|b| b.x1).fold(f64::NEG_INFINITY, f64::max);
let mut bp = BezPath::new();
for b in bars.into_iter().filter(|b| b.x1 >= far - 1e-6) {
// A thousandth of a point is short of anything drawn.
if end > b.x1 + 1e-3 && end.is_finite() {
bp.extend(shapes::rectangle(Rect::new(b.x1, b.y0, end, b.y1)).to_bezpath());
}
}
bp
}
/// `t`'s runs with each cluster's tracking corrected by how far its advance in `laid` is from the
/// sum of its characters' entries of `dx`; None when every cluster is already within a ten
/// thousandth of an em of it. Layout adds a cluster's tracking once, so every character of a
/// cluster takes the same value and a cluster stays in one run. Characters with the same tracking
/// share a run.
fn retracked(t: &TextObject, laid: &vectorcraft_text::TextLayout, dx: &[f64]) -> Option<Vec<TextRun>> {
let (cluster, clusters) = clusters(t, laid, dx);
if clusters.iter().all(|c| (c.want - c.has).abs() <= c.em * 1e-4) {
return None;
}
let tracking: Vec<f64> = clusters
.iter()
.map(|c| {
let v = c.wanted().clamp(TRACKING.0, TRACKING.1);
// Hundredths of a thousandth of an em, so that characters spaced alike share a run.
if v.is_finite() { (v * 100.0).round() / 100.0 } else { 0.0 }
})
.collect();
let mut out: Vec<TextRun> = Vec::with_capacity(t.runs.len());
let mut i = 0;
for r in &t.runs {
for c in r.text.chars() {
let tracking = cluster.get(i).and_then(|k| tracking.get(*k)).copied().unwrap_or(0.0);
i += 1;
let style = CharStyle { tracking, ..r.style.clone() };
match out.last_mut() {
Some(last) if last.style == style && last.inline.is_none() && r.inline.is_none() => last.text.push(c),
_ => out.push(TextRun { text: c.to_string(), style, inline: r.inline.clone() }),
}
}
}
Some(out)
}
/// Does the file stop before its end-of-file record?
fn ends_early(bytes: &[u8], kind: Kind) -> bool {
let u32_at = |at: usize| bytes.get(at..at.checked_add(4)?).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
+267 -1
View File
@@ -2,7 +2,7 @@
//! writers play as they draw, and damaged files fail or import partly without a panic.
use vectorcraft_color::{Gradient, GradientPaint, Paint};
use vectorcraft_doc::{AppearanceItem, Dash, Document, Node, NodeKind};
use vectorcraft_doc::{AppearanceItem, Dash, Document, Node, NodeKind, TextObject};
use vectorcraft_geom::{Affine, Rect, shapes};
use crate::bytes::Out;
@@ -823,6 +823,272 @@ fn clipped_text_is_clipped_to_its_rectangle() {
assert!(matches!(children[1].kind, NodeKind::Text(_)));
}
/// The first text object of `d`.
fn first_text(d: &Document) -> TextObject {
all(d)
.into_iter()
.find_map(|n| match n.kind {
NodeKind::Text(t) => Some(*t),
_ => None,
})
.unwrap()
}
/// Where each glyph of `t` starts across the document (points), and where the last one ends.
fn glyph_xs(t: &TextObject) -> (Vec<f64>, f64) {
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t);
let xs = laid.glyphs.iter().map(|g| (t.xf * g.origin).x).collect();
let end = laid.glyphs.last().map_or(0.0, |g| (t.xf * (g.origin + vectorcraft_geom::Vec2::new(g.advance, 0.0))).x);
(xs, end)
}
/// EXTTEXTOUTW of `s` at (`x`, 1500), with the advances `dx` when there are any.
fn text_out(x: i32, s: &str, dx: &[i32]) -> Vec<u8> {
let units: Vec<u8> = s.encode_utf16().flat_map(u16::to_le_bytes).collect();
let n = units.len() as i32 / 2;
// The string 76 bytes from the record start, the advances after it on a 4-byte boundary.
let dx_at = if dx.is_empty() { 0 } else { 76 + units.len().next_multiple_of(4) as i32 };
let mut text = vec![0; 16];
text.extend(le(&[1, 0, 0]));
text.extend(le(&[x, 1500, n, 76, 0, 0, 0, 0, 0, dx_at]));
text.extend(&units);
text.resize(68 + units.len().next_multiple_of(4), 0);
text.extend(le(dx));
text
}
/// EXTCREATEFONTINDIRECTW: a 10 mm Arial in slot 2.
fn arial() -> Vec<u8> {
font_of("Arial", false)
}
/// EXTCREATEFONTINDIRECTW: a 10 mm `family` in slot 2, underlined when `underline` is set.
fn font_of(family: &str, underline: bool) -> Vec<u8> {
let mut font = le(&[2, -1000, 0, 0, 0, 400]);
font.extend([0, u8::from(underline), 0, 0, 0, 0, 0, 0]);
let name: Vec<u16> = family.encode_utf16().collect();
font.extend(name.iter().copied().chain(std::iter::repeat_n(0, 32 - name.len())).flat_map(u16::to_le_bytes));
font
}
/// The text and glyph starts (millimeters, rounded to hundredths) of every text object in `d`.
fn texts_at(d: &Document) -> Vec<(String, Vec<f64>)> {
let mm = 72.0 / 25.4;
all(d)
.into_iter()
.filter_map(|n| match n.kind {
NodeKind::Text(t) => Some((t.plain_text(), glyph_xs(&t).0.iter().map(|x| (x / mm * 100.0).round() / 100.0).collect())),
_ => None,
})
.collect()
}
#[test]
fn text_is_spaced_by_its_advances() {
let mm = 72.0 / 25.4;
// "Hi" with advances of 20 and 10 mm, left, centered and right aligned (SETTEXTALIGN), its
// line from 10 to 40 mm each time.
for (align, x) in [(0, 1000), (6, 2500), (2, 4000)] {
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hi", &[2000, 1000]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
let t = first_text(&back.document);
assert_eq!(t.plain_text(), "Hi");
assert!(t.runs.iter().all(|r| r.style.kerning == Some(0.0)), "{:?}", t.runs);
let (xs, end) = glyph_xs(&t);
assert_eq!(xs.len(), 2, "{align}");
assert!((xs[0] - 10.0 * mm).abs() < 0.01 && (xs[1] - 30.0 * mm).abs() < 0.01, "{align}: {xs:?}");
assert!((end - 40.0 * mm).abs() < 0.01, "{align}: {end}");
}
// Characters 5 mm apart and a last "x" 10 mm wide, whatever the font joins or reorders before
// it: ligatures that the tracking drops, a letter with a combining mark and a conjunct. The
// "x" starts 5 mm after each character before it, and ends 10 mm later.
for s in ["ffix", "e\u{301}x", "\u{928}\u{94d}\u{924}x"] {
let n = s.chars().count();
let dx: Vec<i32> = (0..n).map(|i| if i + 1 == n { 1000 } else { 500 }).collect();
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, s, &dx))];
let t = first_text(&import(&hand_emf(5000, 3000, &records)).unwrap().document);
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let x = laid.glyphs.iter().find(|g| g.byte == s.len() - 1).map(|g| (t.xf * g.origin).x).unwrap();
let want = 10.0 + 5.0 * (n - 1) as f64;
assert!((x - want * mm).abs() < 0.01, "{s:?}: {x} {:?}", t.runs);
let (_, end) = glyph_xs(&t);
assert!((end - (want + 10.0) * mm).abs() < 0.01, "{s:?}: {end}");
}
// An advance further than tracking reaches (120 mm on a 10 mm em): the characters after it are
// type of their own, where the advances put them, left or right aligned.
for (align, x) in [(0, 1000), (2, 14500)] {
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hiy", &[12000, 500, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
let texts: Vec<TextObject> = all(&back.document)
.into_iter()
.filter_map(|n| match n.kind {
NodeKind::Text(t) => Some(*t),
_ => None,
})
.collect();
let found: Vec<(String, Vec<f64>)> =
texts.iter().map(|t| (t.plain_text(), glyph_xs(t).0.iter().map(|x| (x / mm * 100.0).round() / 100.0).collect())).collect();
assert_eq!(found, vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])], "{align}");
}
// The same advance inside a ligature ("fi" in a font that joins it): the type splits between
// the "f" and the "i".
let records = vec![(82, font_of("Source Serif 4", false)), (37, le(&[2])), (84, text_out(1000, "fix", &[12000, 500, 1000]))];
let found = texts_at(&import(&hand_emf(20000, 3000, &records)).unwrap().document);
assert_eq!(found, vec![("f".to_string(), vec![10.0]), ("ix".to_string(), vec![130.0, 135.0])]);
// Advances between the "fi" ligature's and the separate letters' (3.64, 3.08 and 5.26 mm), where
// the ligature forms at one tracking and breaks at the next: the "x" starts at 16.72 mm.
let records = vec![(82, font_of("Source Serif 4", false)), (37, le(&[2])), (84, text_out(1000, "fix", &[364, 308, 526]))];
let t = first_text(&import(&hand_emf(5000, 3000, &records)).unwrap().document);
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
let x = laid.glyphs.iter().find(|g| g.byte == 2).map(|g| (t.xf * g.origin).x).unwrap();
let (_, end) = glyph_xs(&t);
assert!((x - 16.72 * mm).abs() < 0.01 && (end - 21.98 * mm).abs() < 0.01, "{x} {end} {:?}", t.runs);
// A tab, which layout advances to its tab stop, ends a piece: the "B" after a 15 mm tab starts
// at 35 mm.
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "A\tB", &[1000, 1500, 1000]))];
let found = texts_at(&import(&hand_emf(10000, 3000, &records)).unwrap().document);
let b = found.iter().find(|(s, _)| s.ends_with('B')).and_then(|(_, xs)| xs.last().copied());
assert_eq!(b, Some(35.0), "{found:?}");
// A leading NUL's advance counts in the line's width: right aligned at 50 mm, the 10 mm NUL
// starts at 10 mm and "Hi" at 20 mm.
let records = vec![(22, le(&[2])), (82, arial()), (37, le(&[2])), (84, text_out(5000, "\0Hi", &[1000, 2000, 1000]))];
let t = first_text(&import(&hand_emf(5000, 3000, &records)).unwrap().document);
assert_eq!(t.plain_text(), "Hi");
let (xs, end) = glyph_xs(&t);
assert!((xs[0] - 20.0 * mm).abs() < 0.01 && (end - 50.0 * mm).abs() < 0.01, "{xs:?} {end}");
}
#[test]
fn multiline_text_with_advances_aligns_each_line() {
let mm = 72.0 / 25.4;
// "Hi\nHi" with advances of 20 and 10 mm on each line, left, centered and right aligned: each
// line runs from 10 to 40 mm, as "Hi" alone does, the second on the baseline below the first.
// A second line of 15 and 5 mm, centered or right aligned, leaves the first where it is.
let at = |records: &[(u32, Vec<u8>)]| -> Vec<(f64, f64)> {
let back = import(&hand_emf(5000, 3000, records)).unwrap();
let mut at = vec![];
for n in all(&back.document) {
let NodeKind::Text(t) = n.kind else { continue };
let laid = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t);
for g in laid.glyphs.iter().filter(|g| g.advance > 0.0) {
let p = t.xf * g.origin;
at.push(((p.x / mm * 100.0).round() / 100.0, (p.y / mm * 100.0).round() / 100.0));
}
}
at
};
let mut drops = vec![];
for (align, x) in [(0, 1000), (6, 2500), (2, 4000)] {
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))];
let found = at(&records);
let xs: Vec<f64> = found.iter().map(|p| p.0).collect();
assert_eq!(xs, vec![10.0, 30.0, 10.0, 30.0], "{align}: {found:?}");
assert!(found[0].1 == found[1].1 && found[2].1 == found[3].1 && found[2].1 > found[0].1, "{align}: {found:?}");
drops.push(found[2].1 - found[0].1);
}
assert!(drops.iter().all(|d| (d - drops[0]).abs() < 0.01), "{drops:?}");
// Underlined and left aligned, each line's underline ends with its own advances: no bar runs on
// past either line.
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hi\nHi", &[2000, 1000, 0, 2000, 1000]))];
let back = import(&hand_emf(5000, 3000, &records)).unwrap();
assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. })));
for (align, x, second) in [(6, 2500, [15.0, 30.0]), (2, 4000, [20.0, 35.0])] {
let records = vec![(22, le(&[align])), (82, arial()), (37, le(&[2])), (84, text_out(x, "Hi\nHi", &[2000, 1000, 0, 1500, 500]))];
let xs: Vec<f64> = at(&records).iter().map(|p| p.0).collect();
assert_eq!(xs, vec![10.0, 30.0, second[0], second[1]], "{align}");
}
// An advance further than tracking reaches on the second line of centered type (at 100 mm):
// that line splits where the advance puts its characters, and the first line stays in place.
let records = vec![(22, le(&[6])), (82, arial()), (37, le(&[2])), (84, text_out(10000, "Hi\nHiy", &[2000, 1000, 0, 12000, 500, 1000]))];
let found = texts_at(&import(&hand_emf(20000, 3000, &records)).unwrap().document);
let want = vec![("Hi".to_string(), vec![85.0, 105.0]), ("H".to_string(), vec![32.5]), ("iy".to_string(), vec![152.5, 157.5])];
assert_eq!(found, want);
}
#[test]
fn emf_plus_driver_strings_keep_their_positions() {
// An EMF+ only file: a 1000 pixel Arial (font object 0) and DrawDriverString of "Hi" in black,
// as characters (CmapLookup), its glyphs at x = 1000 and 3000 pixels (10 and 30 mm).
let header = le(&[0xDBC0_1002u32 as i32, 0, 96, 96]);
let mut font = [le(&[0xDBC0_1002u32 as i32]), le_f32(&[1000.0]), le(&[2, 0, 0, 5])].concat();
font.extend("Arial".encode_utf16().chain([0]).flat_map(u16::to_le_bytes));
let mut draw = le(&[0xFF00_0000u32 as i32, 1, 0, 2]);
draw.extend("Hi".encode_utf16().flat_map(u16::to_le_bytes));
draw.extend(le_f32(&[1000.0, 1500.0, 3000.0, 1500.0]));
let comment = emf_plus(&[(0x4001, 0, header), (0x4008, 6 << 8, font), (0x4036, 0x8000, draw), (0x4002, 0, vec![])]);
let back = import(&hand_emf(5000, 3000, &[(70, comment)])).unwrap();
let t = first_text(&back.document);
assert_eq!(t.plain_text(), "Hi");
let (xs, _) = glyph_xs(&t);
let mm = 72.0 / 25.4;
assert_eq!(xs.len(), 2);
assert!((xs[0] - 10.0 * mm).abs() < 0.01 && (xs[1] - 30.0 * mm).abs() < 0.01, "{xs:?}");
}
#[test]
fn wmf_text_is_spaced_by_its_advances() {
// CREATEFONTINDIRECT of a 10 pt Arial (slot 0), selected, and EXTTEXTOUT of "Hi" at x = 10 pt
// with advances of 20 and 10 pt, at 20 units a point.
let mut font = le16(&[-200, 0, 0, 0, 400]);
font.extend([0u8; 8]);
font.extend(b"Arial".iter().copied().chain(std::iter::repeat_n(0, 27)));
let mut text = le16(&[500, 200, 2, 0]);
text.extend(b"Hi");
text.extend(le16(&[400, 200]));
let records = vec![(0x02FB, font), (0x012D, le16(&[0])), (0x0A32, text)];
let t = first_text(&import(&hand_wmf(4000, 1000, &records)).unwrap().document);
assert_eq!(t.plain_text(), "Hi");
let (xs, end) = glyph_xs(&t);
assert_eq!(xs.len(), 2);
assert!((xs[0] - 10.0).abs() < 0.01 && (xs[1] - 30.0).abs() < 0.01 && (end - 40.0).abs() < 0.01, "{xs:?} {end}");
}
#[test]
fn split_type_keeps_its_underline_and_right_to_left_order() {
let mm = 72.0 / 25.4;
// Underlined "Hiy" with an advance further than tracking reaches after the "H": the bar runs on
// from the end of the "H"'s underline to where "iy" starts, at 130 mm.
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert_eq!(texts_at(&back.document), vec![("H".to_string(), vec![10.0]), ("iy".to_string(), vec![130.0, 135.0])]);
let bars: Vec<Rect> =
all(&back.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).collect();
assert_eq!(bars.len(), 1, "{bars:?}");
let b = bars[0];
assert!(b.x0 > 10.0 * mm && b.x0 < 130.0 * mm && (b.x1 - 130.0 * mm).abs() < 0.01 && b.height() < 2.0 * mm, "{b:?}");
// The "H" and the "i" before the split are tracked apart and draw a bar each: only the bar that
// ends the piece runs on, from the end of the "i" to 130 mm.
let records = vec![(82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(1000, "Hiy", &[1000, 12000, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0]), ("y".to_string(), vec![140.0])]);
let gaps: Vec<Node> = all(&back.document).into_iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).collect();
assert_eq!(gaps.len(), 1);
let NodeKind::Path { path, .. } = &gaps[0].kind else { panic!("a path") };
let rects = path.to_bezpath().elements().iter().filter(|e| matches!(e, vectorcraft_geom::PathEl::MoveTo(_))).count();
assert_eq!(rects, 1);
let b = gaps[0].geometric_bounds().unwrap();
assert!(b.x0 > 20.0 * mm && (b.x1 - 140.0 * mm).abs() < 0.01, "{b:?}");
// Without an underline, nothing but the type.
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, "Hiy", &[12000, 500, 1000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert!(all(&back.document).iter().all(|n| !matches!(n.kind, NodeKind::Path { .. })));
// A last advance further than tracking reaches, right aligned at 140 mm: the "H" and the "i"
// start at 10 and 20 mm, and the underline runs on from the "i" to 140 mm.
let records = vec![(22, le(&[2])), (82, font_of("Arial", true)), (37, le(&[2])), (84, text_out(14000, "Hi", &[1000, 12000]))];
let back = import(&hand_emf(20000, 3000, &records)).unwrap();
assert_eq!(texts_at(&back.document), vec![("Hi".to_string(), vec![10.0, 20.0])]);
let bars: Vec<Rect> =
all(&back.document).iter().filter(|n| matches!(n.kind, NodeKind::Path { .. })).filter_map(|n| n.geometric_bounds()).collect();
assert_eq!(bars.len(), 1, "{bars:?}");
assert!(bars[0].x0 > 20.0 * mm && (bars[0].x1 - 140.0 * mm).abs() < 0.01, "{bars:?}");
// Right to left type with the same advance stays one text object, its characters in order.
let s = "\u{5e9}\u{5dc}\u{5d5}\u{5dd}";
let records = vec![(82, arial()), (37, le(&[2])), (84, text_out(1000, s, &[12000, 500, 500, 1000]))];
let found = texts_at(&import(&hand_emf(20000, 3000, &records)).unwrap().document);
assert_eq!(found.len(), 1, "{found:?}");
assert_eq!(found[0].0, s);
}
#[test]
fn excluded_clip_rectangles_clip() {
// EXCLUDECLIPRECT cuts the top-left of the picture out of the clip; the rectangle crosses it.
+6 -2
View File
@@ -8732,8 +8732,12 @@ and is missing from the picture" once for all such images.
`document.open` and `file.place` read `.emf` and `.wmf` (placeable or not) into one artboard, the picture's frame, and
one layer: paths with their fills and strokes (pens become strokes with caps, joins and dashes), clipping groups,
images and point type in the font the file names. An EMF that draws with EMF+ records is read from them. Hatched and
pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning.
images and point type in the font the file names. Type keeps the file's character advances as tracking, with pair
kerning off. On a single left to right line, an advance that tracking can't give (wider than its range, or a tab)
starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between and on to the end
of the last character's advance. Type on more than one line is placed a line at a time: each line is aligned by its own advances and
split as a single line is. An EMF that
draws with EMF+ records is read from them. Hatched and pattern brushes fill with their average color. Records VectorCraft doesn't read are skipped with one warning.
`clipboard.importEmf {dataBase64, center?}` loads an EMF or WMF picture into the clipboard for `edit.paste`; the app
pastes `image/emf` from the system clipboard ahead of text and bitmaps when the platform's clipboard service offers it
(the Windows desktop service doesn't read metafiles yet).
+1
View File
@@ -1998,6 +1998,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- HP-GL/2 plot files (`.plt`, `.hpgl`, `.hgl`, `.hpg`, or a name no other format reads when the file starts with plotter instructions) open and place as paths on one layer, the artboard round the art: each line drawn with the pen down is a stroked path in its pen's color and width, line types become dash patterns, circles, arcs, wedges and Bézier curves are curves, filled and edged rectangles, wedges and polygons (polygon mode) are filled or stroked paths, and encoded polylines, scaling points, user units and rotation are read. Labels, symbol mode's symbols, raster images and hatching aren't drawn and are listed in the warnings (`crates/cad/src/hpgl/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- PICT pictures (`.pct`, `.pic`, and `.pict` as VectorCraft's own name) open and place, as [the help page](https://helpx.adobe.com/archive/illustrator/illustrator-cs5-5-troubleshooting.pdf) lists Macintosh PICT under both opening and placing: versions 1 and 2, with or without the file's 512 bytes of application data, read by the opcodes of Apple's [Opcodes in Pictures](https://dev.os9.ca/techpubs/mac/QuickDraw/QuickDraw-461.html). Lines, rectangles, rounded rectangles, ovals, arcs, polygons and regions become paths in their pen and pattern colors, text becomes point type in the font the picture names, bitmaps, pixel maps and QuickTime JPEG images become images, and the clip region clips what follows it; File › Place places the picture as one group clipped to its frame. Inverted shapes, other transfer modes and other QuickTime formats come back as warnings, and a picture cut short keeps what came before it (`crates/metafile/src/tests/pict.rs`, `crates/engine/src/cmd/fileio/tests_pict.rs`).
- EMF and WMF files are read by the shared `craft-metafile` reader and open, place and paste as editable paths, clipping groups, images and point type: an EMF drawn with EMF+ records (on their own, or beside plain records) is read from them instead of opening empty, and hatched and pattern brushes fill with their average color (`crates/metafile/src/tests/import.rs`).
- EMF, WMF and EMF+ text keeps the character advances the file gives (ExtTextOut's `lpDx`, DrawDriverString positions) as tracking, with pair kerning off; on a single left to right line, an advance that tracking can't give (wider than its range, or a tab) starts a new point type object where the advance puts it, with an underline or strikethrough filled across the space between and on to the end of the last character's advance; type on more than one line is placed a line at a time, each line aligned by its own advances and split as a single line is (`text_is_spaced_by_its_advances`, `multiline_text_with_advances_aligns_each_line`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`).
- Export As › HP-GL (`document.export {format: "hpgl"}`) writes a `.plt` plot of an artboard, each artboard or the art for pen plotters and cutters: each visible path once along its line in plotter units from the artboard's bottom-left corner or center, a pen per color or a pen table, curves flattened to a tolerance, type as outlines, clipping masks and the artboard's edges applied, and HP-GL or HP-GL/2 (pen colors and encoded polylines); plots read back by the HP-GL reader give the same lines (`crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- HP-GL export's `insideFirst` cuts each pen's paths inside before outside: a path is drawn only after the pen's paths that lie inside it (a letter's counter, a part's holes, rings within rings), touching outlines counted as inside and crossing ones not, in paint order or nearest first with `sortPaths`, within the plot's work budget; these order rules are VectorCraft's own (`crates/cad/src/hpgl/write/nest.rs`, `crates/cad/src/hpgl/write/tests.rs`, `crates/engine/src/cmd/fileio/tests_hpgl.rs`).
- EPS and DXF in and out, EMF/WMF in and out; PNG (with PNG-8), JPEG, WebP, GIF, TIFF, BMP, Targa and layered PSD export; grayscale TIFFs with an alpha channel or other extra channels place, relink and open, the alpha as the image's transparency (#1466 in part); PSD and PSB files open and place, linked or embedded, as their merged image in every colour mode and depth (#918). EPS import runs a PostScript Level 3 interpreter written from the PostScript Language Reference: resource categories and `resourceforall`, local and global VM (`currentglobal`/`setglobal`/`gcheck`), `clipsave`/`cliprestore`, subarrays and substrings that share storage, the standard dictionaries in `systemdict`, `dictstack`, `internaldict`, executable filters and strings, `load` by any key, `//name` immediate names, `token`, `execform`, user paths, `cshow`, `rootfont`, `cachestatus`, colour rendering and halftone queries, file `status` and data read with `flushfile`, and `pdfmark` marks dropped (Discord feedback, #466, #469, #474). Masked images (`ImageType 3` in its three interleavings) and reusable streams are read, and an image's several data sources are read in turn, as the reference defines (procedures that read one file get their own rows: such images came in banded, #498). `restore` puts dictionaries back as they were at the `save`, so programs that count their saves in a dictionary read to their end (part of #505). Tiling patterns come in as pattern swatches, uncoloured ones too; Type 3 fonts' glyphs as their outlines, spaced by `ashow`/`widthshow`/`xshow`/`kshow`; mesh and function-based shadings (types 1, 4–7) as gradient meshes; sampled functions (type 0) and Flate/LZW predictors are read. It is tested with programs written from the specification in the ways common generators use these features; Inkscape/cairo EPS files open as vectors. When a file's PostScript still can't be read, it opens as its TIFF preview, its Windows metafile preview (as vectors) or its EPSI preview, and the warning (in the status bar, `document.open`/`app.open`/MCP `open_file` replies and `vectorcraft-cli info`) names the error, the operator that raised it and the procedures it ran in. Legacy PostScript `.ai` files (Illustrator 3–8, written with the prolog that defines their operators) keep their groups and nested groups (`u` … `U`), between and inside clipping groups; EPS and EMF/WMF import nest clips (and groups) at most 128 deep, so a hostile file can't exhaust the stack. DXF TEXT justified Fit or Aligned spans its two points (stretched, or scaled as a whole). PDF export writes type as real, searchable text in embedded subset fonts by default, as Illustrator's PDF presets do (Convert Text to Outlines is an option; printer's marks stay shapes), so text-heavy PDFs stay small (#733). DXF export writes each fill as its outlines followed by its hatch, so laser and cutter software, which skips hatches, gets filled art and type too (#546).