Repository navigation
SVG export: optionally write TEXT and MTEXT as <text> elements (#1876) #1897
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
6643bed
03dd616
48e4562
a0ff995
c958548
81168c4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| //! EXPORT's SVG `text` option: glyph outlines by default, `<text>` only for `text: "text"` | ||
| //! (#1876), handed verbatim to the host's exporter. | ||
| //! | ||
| //! The `<text>` element itself is checked in `cadcraft_io`'s `svg_text` tests, which build a | ||
| //! synthetic outline font (no font files live in the repository); here the drawing is in the | ||
| //! stroke font, which is always geometry, so the command-level checks are the forwarded options | ||
| //! and the byte-identical default. | ||
|
|
||
| use std::sync::Mutex; | ||
|
|
||
| use cadcraft_engine::Session; | ||
| use cadcraft_engine::cmd::file::{IoHooks, base64_decode, set_export_with, set_io}; | ||
| use serde_json::{Value, json}; | ||
|
|
||
| /// The exporter's `(name, text option)` for each call, in order. | ||
| static SEEN: Mutex<Vec<(String, Option<String>)>> = Mutex::new(Vec::new()); | ||
|
|
||
| /// Install the real exporter behind a recorder, as the apps install it. | ||
| fn install() { | ||
| set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Ok(b"plain".to_vec()), plot: None }); | ||
| set_export_with(|d, name, opts| { | ||
| let text = opts.get("text").and_then(Value::as_str).map(str::to_string); | ||
| if let Ok(mut seen) = SEEN.lock() { | ||
| seen.push((name.to_string(), text)); | ||
| } | ||
| cadcraft_io::export_with(d, name, opts).map_err(|e| e.to_string()) | ||
| }); | ||
| } | ||
|
|
||
| /// Run EXPORT for SVG and return its bytes as a string. | ||
| fn export(s: &mut Session, opts: Value) -> String { | ||
| let r = s.execute("export", &opts).expect("export runs"); | ||
| let data = r["data"].as_str().expect("base64 data"); | ||
| String::from_utf8(base64_decode(data).expect("valid base64")).expect("UTF-8 SVG") | ||
| } | ||
|
|
||
| /// Guards #1876: EXPORT writes glyph outlines when no `text` option is given (the default and | ||
| /// the `"geometry"` output are the same bytes), forwards `text: "text"` (its opt-in) and unknown | ||
| /// values to the host's exporter under the generated name `export.svg`, and returns that | ||
| /// exporter's bytes rather than the plain writer's. | ||
| #[test] | ||
| fn export_keeps_glyphs_unless_text_is_asked_for() { | ||
| install(); | ||
| let mut s = Session::new(); | ||
| s.cmdline("line 0,0 10,0").unwrap(); | ||
| s.execute("text", &json!({ "at": [0.0, 0.0], "text": "A B", "height": 2.5 })).expect("text runs"); | ||
|
|
||
| let default = export(&mut s, json!({ "format": "svg" })); | ||
| assert!(!default.contains("<text"), "glyph outlines are the default: {default}"); | ||
| assert_eq!(default, export(&mut s, json!({ "format": "svg", "text": "geometry" })), "the default is the geometry export"); | ||
| assert_eq!(default, export(&mut s, json!({ "format": "svg", "text": "kludge" })), "an unknown value falls back to geometry"); | ||
| let opted_in = export(&mut s, json!({ "format": "svg", "text": "text" })); | ||
| assert!(opted_in.starts_with("<svg") && opted_in.ends_with("</svg>"), "text mode still writes a document: {opted_in}"); | ||
|
|
||
| let seen = SEEN.lock().expect("recorder"); | ||
| assert_eq!( | ||
| *seen, | ||
| vec![ | ||
| ("export.svg".to_string(), None), | ||
| ("export.svg".to_string(), Some("geometry".to_string())), | ||
| ("export.svg".to_string(), Some("kludge".to_string())), | ||
| ("export.svg".to_string(), Some("text".to_string())), | ||
| ], | ||
| "every option reaches the exporter verbatim" | ||
| ); | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -80,6 +80,19 @@ impl Face { | |
| let map = f.charmap(); | ||
| chars.iter().map(|c| map.map(*c).map(|g| g.to_u32())).collect() | ||
| } | ||
| /// The face's family name (its typographic family, family, or full name): what output | ||
| /// formats that name fonts write as `font-family` (SVG). Empty when the font has none. | ||
| pub fn family_name(&self) -> String { | ||
| let Some(f) = self.font() else { return String::new() }; | ||
| [skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FAMILY_NAME, skrifa::string::StringId::FULL_NAME] | ||
| .into_iter() | ||
| .find_map(|id| f.localized_strings(id).english_or_first().map(|s| s.to_string())) | ||
| .unwrap_or_default() | ||
| .chars() | ||
| .filter(|c| !c.is_control()) | ||
| .take(120) | ||
| .collect() | ||
| } | ||
| fn names(&self) -> Vec<String> { | ||
| let Some(f) = self.font() else { return Vec::new() }; | ||
| [skrifa::string::StringId::FAMILY_NAME, skrifa::string::StringId::TYPOGRAPHIC_FAMILY_NAME, skrifa::string::StringId::FULL_NAME] | ||
|
|
@@ -824,6 +837,14 @@ fn outline(face: &Face, k: GlyphKey) -> Arc<GlyphOutline> { | |
| g | ||
| } | ||
|
|
||
| /// The advance width of glyph `gid` of `face`, in font units (1000 per em, the scale of a | ||
| /// [`crate::TextGlyph`]'s axes); `None` when it can't be measured. Output that writes text uses | ||
| /// it to tell a kerning gap from a space. | ||
| pub fn advance(face: &Face, gid: u16) -> Option<f64> { | ||
| let advance = glyph_by_id(face, u32::from(gid)).advance; | ||
| advance.is_finite().then_some(advance) | ||
| } | ||
|
|
||
| /// The outline of `c` from a fallback font, if any installed font has it. | ||
| pub(crate) fn fallback_glyph(c: char) -> Option<Arc<GlyphOutline>> { | ||
| let f = fallback_for(c)?; | ||
|
|
@@ -840,14 +861,23 @@ fn glyph_or_fallback(face: &Face, c: char) -> Arc<GlyphOutline> { | |
| } | ||
|
|
||
| /// The [`crate::TextGlyph`] of a glyph placed like [`place_glyph`] does (its outline index is | ||
| /// set when it is added). `None` for the missing-glyph shape. | ||
| pub(crate) fn text_glyph(g: &GlyphOutline, c: char, x: f64, h: f64, wf: f64, shear: f64) -> Option<crate::TextGlyph> { | ||
| /// set when it is added), with `spaces_before` whitespace characters of the source before it. | ||
| /// `None` for the missing-glyph shape. | ||
| pub(crate) fn text_glyph(g: &GlyphOutline, c: char, x: f64, h: f64, wf: f64, shear: f64, spaces_before: u32) -> Option<crate::TextGlyph> { | ||
| // Font units at 1000 per em scale by h / cap. | ||
| text_glyph_at(g, c, Vec2::new(x, 0.0), h / g.cap, wf, shear) | ||
| text_glyph_at(g, c, Vec2::new(x, 0.0), h / g.cap, wf, shear, spaces_before) | ||
| } | ||
|
|
||
| /// [`text_glyph`] with the glyph's origin at `origin` and font units scaled by `scale`. | ||
| pub(crate) fn text_glyph_at(g: &GlyphOutline, c: char, origin: Vec2, scale: f64, wf: f64, shear: f64) -> Option<crate::TextGlyph> { | ||
| pub(crate) fn text_glyph_at( | ||
| g: &GlyphOutline, | ||
| c: char, | ||
| origin: Vec2, | ||
| scale: f64, | ||
| wf: f64, | ||
| shear: f64, | ||
| spaces_before: u32, | ||
| ) -> Option<crate::TextGlyph> { | ||
| let gid = u16::try_from(g.gid).ok().filter(|_| g.mapped)?; | ||
| let face = g.face.clone()?; | ||
| let em = 1000.0 * scale; | ||
|
|
@@ -859,6 +889,7 @@ pub(crate) fn text_glyph_at(g: &GlyphOutline, c: char, origin: Vec2, scale: f64, | |
| origin, | ||
| x: Vec2::new(em * wf, 0.0), | ||
| y: Vec2::new(em * shear, em), | ||
| spaces_before, | ||
| }) | ||
| } | ||
|
|
||
|
|
@@ -910,16 +941,23 @@ pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) | |
| // outline, and a short repeated string copies it per occurrence, so cap the total geometry | ||
| // kept in the Shaped result (CWE-400). Advances still accumulate so the width stays sensible. | ||
| let mut points_left: usize = MAX_SHAPED_POINTS; | ||
| // Whitespace characters since the last visible one: whitespace has no outline, so its count | ||
| // travels to the next glyph (an output writing text restores every space, not just one). | ||
| let mut spaces = 0u32; | ||
| for (c, under, over) in crate::decode_controls(s) { | ||
| if crate::bidi::is_format_control(c) { | ||
| continue; | ||
| } | ||
| let g = glyph_or_fallback(face, c); | ||
| if !c.is_whitespace() | ||
| && let Some(contours) = place_glyph_budgeted(&g, x, h, wf, shear, &mut points_left) | ||
| { | ||
| // Even an empty mapped glyph needs a valid outline slot for text export. | ||
| out.push_glyph(contours, text_glyph(&g, c, x, h, wf, shear)); | ||
| if c.is_whitespace() { | ||
| spaces = spaces.saturating_add(1); | ||
| } else { | ||
| if let Some(contours) = place_glyph_budgeted(&g, x, h, wf, shear, &mut points_left) { | ||
| // Even an empty mapped glyph needs a valid outline slot for text export. | ||
| out.push_glyph(contours, text_glyph(&g, c, x, h, wf, shear, spaces)); | ||
| } | ||
| // Only the whitespace immediately before a glyph is its own; never carry it on. | ||
| spaces = 0; | ||
|
Comment on lines
+944
to
+960
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🔎 Supported by static analysis
Do not let non-space whitespace enter gap inference. Changing only Record a non-space-whitespace boundary and end the current SVG text run at that boundary. This preserves the shaped position of the following glyph. Ordinary-space and no-whitespace runs keep their current behavior. Suggested fix
|
||
| } | ||
| let adv = g.advance * h / g.cap * wf; | ||
| spans.push((x, x + adv, under, over)); | ||
|
|
@@ -1046,7 +1084,7 @@ mod geometry_budget_tests { | |
| let glyph = GlyphOutline { cap: 1.0, mapped: true, gid: 1, face: Some(Face { bytes: Arc::new(Vec::new()), index: 0 }), ..Default::default() }; | ||
| let contours = place_glyph_budgeted(&glyph, 0.0, 1.0, 1.0, 0.0, &mut 0).unwrap(); | ||
| let mut shaped = Shaped::default(); | ||
| shaped.push_glyph(contours, text_glyph(&glyph, 'x', 0.0, 1.0, 1.0, 0.0)); | ||
| shaped.push_glyph(contours, text_glyph(&glyph, 'x', 0.0, 1.0, 1.0, 0.0, 0)); | ||
| assert_eq!(shaped.text.len(), 1); | ||
| assert_eq!(shaped.text[0].outline, 0); | ||
| assert!(shaped.glyphs[shaped.text[0].outline].is_empty()); | ||
|
|
@@ -1058,7 +1096,7 @@ mod geometry_budget_tests { | |
| let glyph = GlyphOutline { cap: 1.0, ..Default::default() }; | ||
| let contours = place_glyph_budgeted(&glyph, 0.0, 1.0, 1.0, 0.0, &mut 0).unwrap(); | ||
| let mut shaped = Shaped::default(); | ||
| shaped.push_glyph(contours, text_glyph(&glyph, 'x', 0.0, 1.0, 1.0, 0.0)); | ||
| shaped.push_glyph(contours, text_glyph(&glyph, 'x', 0.0, 1.0, 1.0, 0.0, 0)); | ||
| assert!(shaped.is_empty()); | ||
| assert!(shaped.text.is_empty()); | ||
| } | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Account for leading spaces when positioning a text run.
If a
TEXTline starts with spaces,xalready includes their advance when this call records the first visible glyph's origin. SVGtext_runsprependsspaces_beforebut starts<text>at that origin. The exported glyph moves right by the leading spaces a second time. The existing leading-space test checks the characters, not their position. Start the run before those spaces, or retain the original glyph position without advancing it again. (raw.githubusercontent.com)