mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 04:51:52 +00:00
Metafile import: multi-line text with advances aligns each line by its own advances
Centered or right aligned text on more than one line was placed by the span of all its advances together, so a second line moved the first. Layout also leaves the tracking after each line's last character out of the width it aligns, so one object can't align every line by its advances. Such text now becomes one point type object per line, each aligned by its own advances and placed on its line's baseline. Left aligned text stays one object.
This commit is contained in:
@@ -14,6 +14,8 @@
|
||||
//! 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.
|
||||
//! Centered or right aligned type on more than one line is point type per line, each line
|
||||
//! aligned by its own advances.
|
||||
//! - Clip regions and clip paths become clipping groups around what they clip; a rectangle around
|
||||
//! the whole picture clips nothing and is left out.
|
||||
//!
|
||||
@@ -610,16 +612,20 @@ impl Mapper {
|
||||
(pieces, Some((text, laid)))
|
||||
};
|
||||
let split = pieces.len() > 1;
|
||||
// Centered or right aligned type on more than one line: a point type object per line.
|
||||
if let Some((_, laid)) = tracked.as_ref().filter(|(_, l)| l.lines.len() > 1 && !matches!(t.h_align, HAlign::Left)) {
|
||||
for (mut text, start, down) in per_line(laid, &s, &dx, lead * k, &t.h_align, f.underline || f.strike, &point) {
|
||||
text.xf = base * Affine::translate((start, drop + down));
|
||||
let mut n = Node::new(NodeId(0), NodeKind::Text(Box::new(text)));
|
||||
n.opacity = f32::from(t.color[3]) / 255.0;
|
||||
self.push(chain.clone(), n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// 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 total: f64 = lead * k + dx.iter().sum::<f64>();
|
||||
let mut at = lead * k
|
||||
+ match t.h_align {
|
||||
HAlign::Left => 0.0,
|
||||
HAlign::Center => -total / 2.0,
|
||||
HAlign::Right => -total,
|
||||
};
|
||||
let mut at = aligned(lead * k, dx.iter().sum(), &t.h_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();
|
||||
@@ -690,6 +696,59 @@ 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,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of `s` (laid out as `laid`, more than one line) as point type objects of their own,
|
||||
/// each tracked to its characters' entries of `dx` and aligned by them, with where it starts along
|
||||
/// the baseline from the reference point and how far its baseline is below the first line's.
|
||||
/// Layout leaves the tracking after a line's last character out of the width it aligns, and each
|
||||
/// line ends with its own, so one object can't align every line by its advances. `lead` (a leading
|
||||
/// NUL's advance) comes before the first line. Blank lines are left out unless `decorated`
|
||||
/// (underlined or struck through).
|
||||
fn per_line(
|
||||
laid: &vectorcraft_text::TextLayout,
|
||||
s: &str,
|
||||
dx: &[f64],
|
||||
lead: f64,
|
||||
align: &HAlign,
|
||||
decorated: bool,
|
||||
point: &dyn Fn(&str) -> TextObject,
|
||||
) -> Vec<(TextObject, f64, f64)> {
|
||||
let db = vectorcraft_text::FontDb::global();
|
||||
let first = laid.lines.first().map_or(0.0, |l| l.baseline);
|
||||
// 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 chars: Vec<char> = s.chars().collect();
|
||||
let mut out = vec![];
|
||||
for (n, l) in laid.lines.iter().enumerate() {
|
||||
let (from, to) = (count(l.start), count(l.end));
|
||||
let line: String = chars.get(from..to).unwrap_or_default().iter().collect();
|
||||
let Some(dx) = dx.get(from..to) else { continue };
|
||||
if line.is_empty() || (line.trim().is_empty() && !decorated) {
|
||||
continue;
|
||||
}
|
||||
let mut text = point(&line);
|
||||
let line_laid = advanced(&mut text, db, dx);
|
||||
let lead = if n == 0 { lead } else { 0.0 };
|
||||
let x0 = line_laid.lines.first().map_or(0.0, |l| l.x0);
|
||||
let start = aligned(lead, dx.iter().sum(), align) - x0;
|
||||
let down = l.baseline - first;
|
||||
text.cached_bounds = Some(line_laid.bounds);
|
||||
out.push((text, if start.is_finite() { start } else { 0.0 }, if down.is_finite() { down } else { 0.0 }));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The most times [`advanced`] lays the type out again to correct its tracking.
|
||||
const ADVANCE_PASSES: usize = 3;
|
||||
|
||||
|
||||
@@ -958,6 +958,42 @@ fn text_is_spaced_by_its_advances() {
|
||||
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:?}");
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
|
||||
+2
-1
@@ -8718,7 +8718,8 @@ and is missing from the picture" once for all such images.
|
||||
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. 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. An EMF that
|
||||
starts a new point type object at the position the advance gives, and an underline or strikethrough is filled across the space between. Centered
|
||||
or right aligned type on more than one line becomes one point type object per line, each aligned by its own advances. 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
|
||||
|
||||
@@ -1975,7 +1975,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 (`text_is_spaced_by_its_advances`, `wmf_text_is_spaced_by_its_advances`, `emf_plus_driver_strings_keep_their_positions`, `split_type_keeps_its_underline_and_right_to_left_order`).
|
||||
- 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; centered or right aligned type on more than one line is one point type object per line, each aligned by its own advances (`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).
|
||||
|
||||
Reference in New Issue
Block a user