From 3c7222b27e296054df9dec4923b08f16944dff45 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 12:50:23 -0800 Subject: [PATCH] Metafile import: each line of text with advances splits and underlines on its own Text on more than one line is placed a line at a time at every alignment, and each line splits where an advance that tracking can't give puts its characters, as a single line does. An underline or strikethrough also runs on to the end of a line's last advance when tracking can't reach it. --- crates/metafile/src/import/picture.rs | 172 +++++++++++++------------- crates/metafile/src/tests/import.rs | 20 +++ docs/mcp.md | 5 +- docs/target-app-parity.md | 2 +- 4 files changed, 107 insertions(+), 92 deletions(-) diff --git a/crates/metafile/src/import/picture.rs b/crates/metafile/src/import/picture.rs index 04a3419495..e114151f9d 100644 --- a/crates/metafile/src/import/picture.rs +++ b/crates/metafile/src/import/picture.rs @@ -14,8 +14,9 @@ //! 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. +//! 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. //! @@ -599,76 +600,96 @@ impl Mapper { 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 = dx.iter().map(|d| d * k).collect(); let chars: Vec = s.chars().collect(); - // The string in pieces, each a text object of its own: one piece, or with advances, a - // new piece after each cluster that tracking can't space by its advance. - let whole = point(&s); - let (pieces, mut tracked) = if dx.is_empty() { - (vec![(0, chars.len())], None) - } else { - let (pieces, text, laid) = pieces(whole.clone(), db, &dx); - (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); + 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 = 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 * k, dx.iter().sum(), &t.h_align); + 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() && !(f.underline || f.strike) { - at += dx.get(from..to).map_or(0.0, |dx| dx.iter().sum()); + if piece.trim().is_empty() && !line.decorated { + at += dx.iter().sum::(); continue; } - let (mut text, laid, start, end) = match dx.get(from..to) { - Some(dx) if !dx.is_empty() => { - // The whole string in one piece was already tracked to its advances. - let (text, laid) = match tracked.take().filter(|_| !split) { - Some(done) => done, - None => { - let mut text = 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, laid, start, x0 + span) - } - _ => { - let laid = vectorcraft_text::layout(db, &whole); - (whole.clone(), laid, 0.0, 0.0) + // 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) } }; - text.xf = base * Affine::translate((start, drop)); + 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, as one bar per piece from where its own bars end. - let gap = if split && i < last { gaps(&laid, db, &text, end) } else { BezPath::new() }; + // 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 = f32::from(t.color[3]) / 255.0; - self.push(chain.clone(), n); + 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(t.color), None, false) { - self.push(chain.clone(), n); + if let Some(n) = self.path_node(gap, Some(line.color), None, false) { + self.push(line.chain.to_vec(), n); } } } @@ -707,46 +728,18 @@ fn aligned(lead: f64, span: f64, align: &HAlign) -> f64 { } } -/// 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, +/// 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, - 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 = s.char_indices().map(|(at, _)| at).collect(); - let count = |to: usize| starts.partition_point(|at| *at < to); - let chars: Vec = 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 + color: [u8; 4], + opacity: f32, + point: &'a dyn Fn(&str) -> TextObject, + chain: &'a [Arc], } /// The most times [`advanced`] lays the type out again to correct its tracking. @@ -869,7 +862,8 @@ fn gaps(laid: &vectorcraft_text::TextLayout, db: &vectorcraft_text::FontDb, t: & 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) { - if end > b.x1 && end.is_finite() { + // 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()); } } diff --git a/crates/metafile/src/tests/import.rs b/crates/metafile/src/tests/import.rs index 52a0bce1df..5f8ca735a0 100644 --- a/crates/metafile/src/tests/import.rs +++ b/crates/metafile/src/tests/import.rs @@ -987,11 +987,22 @@ fn multiline_text_with_advances_aligns_each_line() { 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 = 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] @@ -1061,6 +1072,15 @@ fn split_type_keeps_its_underline_and_right_to_left_order() { 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 = + 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]))]; diff --git a/docs/mcp.md b/docs/mcp.md index 80b7b123f6..4f5062dbd5 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8718,8 +8718,9 @@ 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. 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 +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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f68b6ec3d8..22497f49b1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -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; 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`). + - 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).