diff --git a/apps/cadcraft-cli/src/lib.rs b/apps/cadcraft-cli/src/lib.rs index c858417e26..867f78249e 100644 --- a/apps/cadcraft-cli/src/lib.rs +++ b/apps/cadcraft-cli/src/lib.rs @@ -37,6 +37,8 @@ use run::run_cmds; use run::{fill_last, returned_handle}; use sample::sample; +/// Install the CLI's file-format hooks in the engine (read, write, plot, save-as and export), so +/// the engine stays I/O-agnostic; DXF entities are also exposed to AutoLISP as groups. fn install_io() { cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks { read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()), @@ -46,6 +48,7 @@ fn install_io() { cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); + cadcraft_engine::cmd::file::set_export_with(|d, name, opts| cadcraft_io::export_with(d, name, opts).map_err(|e| e.to_string())); // AutoLISP's entget, entmake and entmod see entities as DXF groups. cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec { groups: cadcraft_io::entity_groups, diff --git a/apps/cadcraft-web/src/main.rs b/apps/cadcraft-web/src/main.rs index a25782d6e0..d0055e6c14 100644 --- a/apps/cadcraft-web/src/main.rs +++ b/apps/cadcraft-web/src/main.rs @@ -112,6 +112,9 @@ mod web { Services { pick_save: Some(Box::new(|name: &str| Some(name.to_string()))), no_file_system: true, ..Services::default() } } + /// Start the web app: install the browser's file-format hooks (read, write, plot, save-as and + /// export), choose the parent-frame bridge for `?host=parent` or browser downloads otherwise, + /// and run the app on the page's canvas. pub fn start() { eframe::WebLogger::init(log::LevelFilter::Info).ok(); cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks { @@ -122,6 +125,7 @@ mod web { cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); + cadcraft_engine::cmd::file::set_export_with(|d, name, opts| cadcraft_io::export_with(d, name, opts).map_err(|e| e.to_string())); // AutoLISP's entget, entmake and entmod see entities as DXF groups. cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec { groups: cadcraft_io::entity_groups, diff --git a/apps/cadcraft/src/main.rs b/apps/cadcraft/src/main.rs index c591c10b3b..d8d3fbe593 100644 --- a/apps/cadcraft/src/main.rs +++ b/apps/cadcraft/src/main.rs @@ -148,6 +148,7 @@ pub fn install_io() { cadcraft_engine::cmd::file::set_write_as(|d, name, o| { cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); + cadcraft_engine::cmd::file::set_export_with(|d, name, opts| cadcraft_io::export_with(d, name, opts).map_err(|e| e.to_string())); // AutoLISP's entget, entmake and entmod see entities as DXF groups. cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec { groups: cadcraft_io::entity_groups, diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index f6ce1e9b67..3b72338433 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -30,6 +30,8 @@ const MAX_PREVIEW_PX: u64 = 4096; /// Most sheets one PUBLISH plots. const MAX_SHEETS: usize = 256; +/// The File menu's exchange commands: IMPORT, EXPORT (with its SVG `text` option), PREVIEW, +/// PUBLISH, PDFBOOK and the not-yet-available ATTACH, SHARE and 3DORBIT. pub fn specs() -> Vec { vec![ CommandSpec::new("import", "Import...", run_import) @@ -39,7 +41,7 @@ pub fn specs() -> Vec { CommandSpec::new("export", "Export...", run_export) .menu(&["File", "Export..."]) .alias(&["exp"]) - .params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data}") + .params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension), text?: \"text\" | \"geometry\" (SVG: glyph outlines by default; `text: \"text\"` opts in to TEXT/MTEXT as elements)} → {format, bytes, path? | data}") .noundo(), CommandSpec::new("preview", "Plot Preview", run_preview) .menu(&["File", "Plot Preview"]) @@ -107,6 +109,9 @@ pub(super) fn deliver_file(cmd: &str, path: &str, bytes: &[u8], hook: Option Result { let hooks = io().ok_or_else(|| bad("export", "file formats are not available in this build"))?; let path = str_param(p, "path"); @@ -117,7 +122,11 @@ fn run_export(s: &mut Session, p: &Value) -> Result { if !EXPORT_FORMATS.contains(&format.as_str()) { return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)")); } - let bytes = (hooks.write)(s.doc()?, &format!("export.{format}")).map_err(|e| bad("export", e))?; + let bytes = match super::file::export_with() { + Some(write) => write(s.doc()?, &format!("export.{format}"), p), + None => (hooks.write)(s.doc()?, &format!("export.{format}")), + } + .map_err(|e| bad("export", e))?; match path { Some(path) => { write_file("export", path, &bytes)?; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 234769ad4d..6d85915abb 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -103,10 +103,28 @@ static WRITE_AS: OnceLock = OnceLock::new(); pub fn set_write_as(h: WriteAsHook) { let _ = WRITE_AS.set(h); } +/// The host's writer for [`SaveAs`] options, when it installed one; saves that ask for none use +/// [`IoHooks::write`]. pub fn write_as() -> Option { WRITE_AS.get().copied() } +/// Write a drawing as an image or vector with the export command's JSON options (installed by +/// hosts whose writer supports them; otherwise [`IoHooks::write`] is used). +pub type ExportWithHook = fn(&Drawing, &str, &Value) -> std::result::Result, String>; + +static EXPORT_WITH: OnceLock = OnceLock::new(); + +/// Install the host's exporter for JSON options (SVG's `text: "text"` opt-in and the like). +pub fn set_export_with(h: ExportWithHook) { + let _ = EXPORT_WITH.set(h); +} +/// The host's exporter for JSON options, when it installed one; EXPORT falls back to +/// [`IoHooks::write`] otherwise. +pub fn export_with() -> Option { + EXPORT_WITH.get().copied() +} + /// The versions a drawing can be saved in, for messages ("2000, 2004, …, 2018"). fn version_list() -> String { Version::ALL.iter().map(|v| v.year()).collect::>().join(", ") diff --git a/crates/engine/tests/it/export_options.rs b/crates/engine/tests/it/export_options.rs new file mode 100644 index 0000000000..6c3ee9a1e2 --- /dev/null +++ b/crates/engine/tests/it/export_options.rs @@ -0,0 +1,66 @@ +//! EXPORT's SVG `text` option: glyph outlines by default, `` only for `text: "text"` +//! (#1876), handed verbatim to the host's exporter. +//! +//! The `` 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)>> = 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 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" + ); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 54ea40675d..da887faa98 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -46,6 +46,7 @@ mod draworder; mod dyn_input; mod dynamic_block_data; mod dynamic_grips; +mod export_options; mod fillet_chamfer; mod fix_holds_grips; mod followups_626; diff --git a/crates/fonts/src/complex.rs b/crates/fonts/src/complex.rs index 4a4ac461f7..4290d73087 100644 --- a/crates/fonts/src/complex.rs +++ b/crates/fonts/src/complex.rs @@ -134,7 +134,8 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64 .copied() .flatten() .filter(|c| !c.is_whitespace()) - .and_then(|c| ttf::text_glyph_at(&outline, c, origin, h / outline.cap, wf, shear)); + // Shaped runs carry no source-space count: the shaper drops spaces into advances. + .and_then(|c| ttf::text_glyph_at(&outline, c, origin, h / outline.cap, wf, shear, 0)); out.push_glyph(contours, text); } let adv = g.advance * k; diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs index beb8996fff..0f50e6a145 100644 --- a/crates/fonts/src/lib.rs +++ b/crates/fonts/src/lib.rs @@ -174,7 +174,8 @@ pub fn shape_stroke(s: &str, height: f64, width_factor: f64, oblique: f64) -> Sh let (y, scale) = stroke_fallback_metrics(&g, c, h); let contours = ttf::place_glyph_at(&g, Vec2::new(x, y), scale, wf, shear); if !contours.is_empty() { - out.push_glyph(contours, ttf::text_glyph_at(&g, c, Vec2::new(x + y * shear, y), scale, wf, shear)); + // The stroke font does not count spaces; its fallbacks write none. + out.push_glyph(contours, ttf::text_glyph_at(&g, c, Vec2::new(x + y * shear, y), scale, wf, shear, 0)); } adv = g.advance * scale * wf; gap = 0.0; @@ -333,6 +334,17 @@ pub struct TextGlyph { pub x: Vec2, /// One em up (obliquing applied). pub y: Vec2, + /// How many whitespace characters of the source text immediately preceded this glyph. + /// + /// Whitespace has no outline glyph, so it is not in [`Shaped::glyphs`]; an output that writes + /// the text back (SVG ``) would otherwise have to infer a space from the gap + /// between two glyphs and could only ever write one, collapsing `A B` to `A B`. + /// + /// Right-to-left text shaped by the complex shaper records no [`TextGlyph`]s at all, so it + /// carries no space count; a fallback outline glyph in the stroke font passes 0. Repeated + /// spaces around those glyphs are therefore not restored. Whitespace at the end of a line has + /// no following glyph to carry it, so it is not recorded either. + pub spaces_before: u32, } impl Shaped { diff --git a/crates/fonts/src/subset.rs b/crates/fonts/src/subset.rs index 18f59872b3..dcb2337281 100644 --- a/crates/fonts/src/subset.rs +++ b/crates/fonts/src/subset.rs @@ -4,10 +4,19 @@ //! (CFF-flavoured OpenType) aren't embedded either. use skrifa::FontRef; +use skrifa::instance::{LocationRef, Size}; use skrifa::raw::types::Tag; use crate::ttf::Face; +/// A glyph's horizontal advance in thousandths of an em (the units SVG measures text in), from +/// the face's own metrics: 0 when the face or the glyph has none. +pub fn advance(face: &Face, gid: u16) -> f64 { + use skrifa::MetadataProvider as _; + let Some(font) = face.font() else { return 0.0 }; + font.glyph_metrics(Size::new(1000.0), LocationRef::default()).advance_width(skrifa::GlyphId::new(u32::from(gid))).map_or(0.0, f64::from) +} + /// Whether a face may be embedded as a subset. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Embedding { diff --git a/crates/fonts/src/ttf.rs b/crates/fonts/src/ttf.rs index c426db243a..b7d2d8c015 100644 --- a/crates/fonts/src/ttf.rs +++ b/crates/fonts/src/ttf.rs @@ -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 { 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 { 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 { + 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> { let f = fallback_for(c)?; @@ -840,14 +861,23 @@ fn glyph_or_fallback(face: &Face, c: char) -> Arc { } /// 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 { +/// 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 { // 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 { +pub(crate) fn text_glyph_at( + g: &GlyphOutline, + c: char, + origin: Vec2, + scale: f64, + wf: f64, + shear: f64, + spaces_before: u32, +) -> Option { 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; } 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()); } diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index ccfba201ee..70af633e8e 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -113,6 +113,16 @@ pub fn write_with(d: &Drawing, name: impl AsRef, opts: &SaveOptions) -> Re } } +/// Like [`write`], with the export command's JSON options. SVG honours `text?: "text" | +/// "geometry"` ([`svg::TextMode`]: glyph outlines by default, `` elements for `"text"`); +/// other formats ignore it. +pub fn export_with(d: &Drawing, name: &str, opts: &serde_json::Value) -> Result> { + match ext(name).as_str() { + "svg" => Ok(svg::export_window_with_text(d, &Space::Model, None, true, svg::TextMode::from_json(opts)).into_bytes()), + _ => write(d, name), + } +} + /// Like [`write`], but image formats (PNG, SVG, PDF) show `window` (a model-space rectangle in /// drawing units, centred and scaled to fit the image without distortion) instead of the /// extents. Formats that are not images (DXF, DWG) ignore the window. The window is checked with diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index ba9d658678..1f827cab35 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -557,6 +557,7 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String view: None, skip_viewport: None, cancel: None, + text_glyphs: false, }; let k = unit_mm * PT_PER_MM; let window = o.window.filter(|w| !w.is_empty()); diff --git a/crates/io/src/plotter.rs b/crates/io/src/plotter.rs index f0a174ea16..3447fd47dd 100644 --- a/crates/io/src/plotter.rs +++ b/crates/io/src/plotter.rs @@ -62,6 +62,8 @@ fn fit_scale(b: &Bounds2, sheet: &Sheet, o: &PdfOptions) -> f64 { pdf::plot_scale(b, sheet, o.fit != Some(false), o.scale) } +/// Plot `space` to PNG through the raster renderer of the display list, with the requested +/// resolution; image size is capped so a hostile sheet cannot allocate unboundedly. fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { let o = pdf::with_saved_setup(d, space, &PdfOptions::from_json(opts)); let (sheet, page) = sheet(d, space, &o)?; @@ -119,12 +121,16 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result> { pm.encode_png().map_err(|_| IoError::Format("render failed".into())) } +/// Plot `space` to SVG: a layout shows its sheet, model space goes through the plot style table, +/// lineweights and the scale that fits the paper; `text` selects `` elements or the glyph +/// outlines the list holds (the default, as on paper). fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result> { let o = PdfOptions::from_json(opts); + let text = crate::svg::TextMode::from_json(opts); let Space::Model = space else { let (sheet, page) = sheet(d, space, &o)?; let transparency = o.plot_transparency.unwrap_or(page.plot_transparency); - return Ok(crate::svg::export_window_with(d, space, Some(sheet.bounds()), transparency).into_bytes()); + return Ok(crate::svg::export_window_with_text(d, space, Some(sheet.bounds()), transparency, text).into_bytes()); }; // Model space as plotted: the plot style table, lineweights, and the table's ends, joins and // fills at the scale that fits the window (or the extents) on the device's paper. @@ -137,11 +143,18 @@ fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result> { let tolerance = (0.05 / (sheet.unit_mm * est)).max(1e-9); let tolerance = if tolerance.is_finite() { tolerance } else { cadcraft_render::Options::default().tolerance }; let transparency = o.plot_transparency.unwrap_or(page.plot_transparency); - let ropts = cadcraft_render::Options { tolerance, lineweights, plot_style_table: table, transparency, ..cadcraft_render::Options::default() }; + let ropts = cadcraft_render::Options { + tolerance, + lineweights, + plot_style_table: table, + transparency, + text_glyphs: text == crate::svg::TextMode::Text, + ..cadcraft_render::Options::default() + }; let mut list = cadcraft_render::build_plot(d, space, &ropts); let s = fit_scale(&window.unwrap_or(list.bounds), &sheet, &o); cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm); - Ok(crate::svg::export_list(&list, window).into_bytes()) + Ok(crate::svg::export_list_with(&list, window, text).into_bytes()) } #[cfg(test)] diff --git a/crates/io/src/svg.rs b/crates/io/src/svg.rs index b5ace3bcf1..03f3bc629e 100644 --- a/crates/io/src/svg.rs +++ b/crates/io/src/svg.rs @@ -1,11 +1,34 @@ //! SVG export of a space (vector, for the web and documents). +use std::collections::HashMap; use std::fmt::Write as _; use cadcraft_color::Rgb; use cadcraft_doc::{Drawing, Space}; -use cadcraft_geom::Bounds2; -use cadcraft_render::Kind; +use cadcraft_fonts::TextGlyph; +use cadcraft_geom::{Bounds2, Vec2}; +use cadcraft_render::{DisplayList, Kind, PlotText}; +use serde_json::Value; + +/// How SVG export writes TEXT and MTEXT set in an installed outline font. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum TextMode { + /// As `` elements: searchable and editable, with their font, size, position and + /// rotation. Opt in with the export option `text: "text"`; stroke-font text is always + /// geometry. + Text, + /// As glyph outlines: exactly as plotted, with no text elements (the default). + #[default] + Geometry, +} + +impl TextMode { + /// The `text` option of an export or plot: `"text"` (in any case) writes `` elements; + /// anything else, or no option, keeps the glyph outlines. + pub fn from_json(v: &Value) -> TextMode { + if v.get("text").and_then(Value::as_str).is_some_and(|t| t.eq_ignore_ascii_case("text")) { TextMode::Text } else { TextMode::Geometry } + } +} /// Export with a white background (colour 7 prints black), fitted to the extents. pub fn export(d: &Drawing, space: &Space) -> String { @@ -14,15 +37,22 @@ pub fn export(d: &Drawing, space: &Space) -> String { /// Export showing exactly `window` (the `viewBox`; geometry outside it is clipped by the viewer), /// or the extents with a 2% margin when `window` is `None`. Objects are drawn with their -/// transparency, as on screen. +/// transparency, as on screen; outline-font text is drawn as glyph outlines (pass +/// [`TextMode::Text`] to [`export_window_with_text`] for `` elements). pub fn export_window(d: &Drawing, space: &Space, window: Option) -> String { export_window_with(d, space, window, true) } /// [`export_window`], drawing transparency only when `transparency` is on (plots). pub fn export_window_with(d: &Drawing, space: &Space, window: Option, transparency: bool) -> String { - let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency, ..cadcraft_render::Options::default() }); - export_list(&list, window) + export_window_with_text(d, space, window, transparency, TextMode::Geometry) +} + +/// [`export_window_with`], writing text or its glyph outlines per `text`. +pub fn export_window_with_text(d: &Drawing, space: &Space, window: Option, transparency: bool, text: TextMode) -> String { + let opts = cadcraft_render::Options { transparency, text_glyphs: text == TextMode::Text, ..cadcraft_render::Options::default() }; + let list = cadcraft_render::build(d, space, &opts); + export_list_with(&list, window, text) } /// ` opacity="…"` for a transparent primitive (none for an opaque one or a wipeout's mask). @@ -33,8 +63,14 @@ fn opacity(p: &cadcraft_render::DPrim) -> String { format!(r#" opacity="{:.2}""#, f64::from(p.alpha()) / 255.0) } -/// Write a display list (as [`export_window`] does for a space's own). -pub fn export_list(list: &cadcraft_render::DisplayList, window: Option) -> String { +/// Write a display list (as [`export_window`] does for a space's own), drawing glyph outlines. +pub fn export_list(list: &DisplayList, window: Option) -> String { + export_list_with(list, window, TextMode::Geometry) +} + +/// [`export_list`], writing outline-font text as `` (`text` = [`TextMode::Text`]) or as +/// the glyph outlines the list holds ([`TextMode::Geometry`], the default). +pub fn export_list_with(list: &DisplayList, window: Option, text: TextMode) -> String { let window = window.filter(|w| !w.is_empty()); let b = window.unwrap_or(list.bounds); // A single point (or a zero-size window) has no extent: show a unit box centred on it. @@ -69,7 +105,29 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option) let white = Rgb(255, 255, 255); let tx = |x: f64| x - x0; let ty = |y: f64| y1 - y; - for p in &list.prims { + // Text runs (and the glyph outlines they replace), when text is written as text. + let runs = if text == TextMode::Text { text_runs(list) } else { Vec::new() }; + let mut run_at: HashMap = HashMap::new(); + let mut replaced = vec![false; list.prims.len()]; + for (i, run) in runs.iter().enumerate() { + run_at.insert(run.first, i); + } + for (i, p) in list.prims.iter().enumerate() { + if let Some(&ri) = u32::try_from(i).ok().and_then(|k| run_at.get(&k)) + && let Some(run) = runs.get(ri) + && write_run(&mut s, list, run, white, dp, &tx, &ty) + { + // The text replaces its glyph outlines only when it was written: a run whose + // transform can't be written stays geometry. + for p in run.prims.iter().filter_map(|p| usize::try_from(*p).ok()) { + if let Some(slot) = replaced.get_mut(p) { + *slot = true; + } + } + } + if replaced.get(i).copied().unwrap_or(false) { + continue; + } let c = p.display_rgb(white).hex(); let op = opacity(p); let pts = list.points(p); @@ -122,3 +180,245 @@ pub fn export_list(list: &cadcraft_render::DisplayList, window: Option) s.push_str(""); s } + +/// One line of text: the glyphs of a text run and where its baseline starts. +struct TextRun { + /// The primitive of the first glyph (the run is written before it and the glyphs' own + /// outline primitives are left out). + first: u32, + /// The primitives of all the run's glyphs, whose outlines are left out once it is written. + prims: Vec, + /// The run's characters, in drawing order: the source's whitespace (from each glyph's + /// [`TextGlyph::spaces_before`]) plus one inferred space for a gap that had none. + text: String, + /// The baseline origin of the first glyph, in world coordinates. + origin: Vec2, + /// One em along the glyphs' baseline, in world units (font-unit axes in em). + x: Vec2, + /// One em up the glyphs' vertical axis, in world units (font-unit axes in em). + y: Vec2, + /// The font face the glyphs were shaped from (its family names the SVG font). + face: cadcraft_fonts::ttf::Face, + /// The font size (one em) in world units, from the glyph's two axes. + em: f64, +} + +/// Most characters written in one `` run, the source's spaces included; a longer run +/// continues in another element, so a hostile line can't build a huge string. +const MAX_RUN_CHARS: usize = 100_000; +/// Largest text em (world units) written as text; a hostile height stays outlines. +const MAX_TEXT_EM: f64 = 1.0e12; + +/// The outline-font glyphs of `list` grouped into lines of text. Consecutive glyphs of one +/// object, font, colour and orientation form a run; a line break (a jump across the baseline) +/// starts a new one. Glyphs whose placement is degenerate stay outlines. +fn text_runs(list: &DisplayList) -> Vec { + let mut runs = Vec::new(); + let mut i = 0; + while let Some(t) = list.texts.get(i) { + let Some((em, prim)) = glyph_prim(list, t) else { + i += 1; + continue; + }; + let glyph = &t.glyph; + let Some(first_char) = text_char(glyph.ch) else { + i += 1; + continue; + }; + // Whitespace before the line's first glyph belongs to the text too. + let mut text = String::new(); + if !push_spaces(&mut text, glyph.spaces_before, 1) { + // More leading spaces than a run holds: the glyph stays an outline. + i += 1; + continue; + } + text.push(first_char); + let mut run = + TextRun { first: t.prim, prims: vec![t.prim], text, origin: glyph.origin, x: glyph.x, y: glyph.y, face: glyph.face.clone(), em }; + let mut prev = t; + let mut j = i + 1; + while let Some(n) = list.texts.get(j) { + let Some((_, nprim)) = glyph_prim(list, n) else { break }; + if nprim.color != prim.color + || nprim.aci7 != prim.aci7 + || nprim.transparency != prim.transparency + || nprim.handle != prim.handle + || n.glyph.face != glyph.face + || !same_vec(glyph.x, n.glyph.x) + || !same_vec(glyph.y, n.glyph.y) + || !on_line(prev, n, em) + { + break; + } + let Some(c) = text_char(n.glyph.ch) else { break }; + // The source's own spaces are part of the run's text, so they must fit in it; when + // they don't, the run ends here and the glyph continues in the next one (or stays an + // outline when even a fresh run can't hold its spaces). + if !push_spaces(&mut run.text, n.glyph.spaces_before, 1) { + break; + } + // A gap that the source's whitespace already explains needs no inferred space. + if n.glyph.spaces_before == 0 && space_between(prev, n, em) { + run.text.push(' '); + } + run.text.push(c); + run.prims.push(n.prim); + prev = n; + j += 1; + } + if !run.text.is_empty() { + runs.push(run); + } + i = j.max(i + 1); + } + runs +} + +/// The em size and outline primitive of a plot glyph, when it can be written as text. +fn glyph_prim<'a>(list: &'a DisplayList, t: &PlotText) -> Option<(f64, &'a cadcraft_render::DPrim)> { + let prim = usize::try_from(t.prim).ok().and_then(|i| list.prims.get(i))?; + if prim.kind != Kind::Tris || t.glyph.gid == 0 { + return None; + } + let em = glyph_em(&t.glyph)?; + Some((em, prim)) +} + +/// One em of a glyph in world units, from its two axes (the determinant gives the area, the +/// baseline axis its width): finite, positive and not hostile. +fn glyph_em(g: &TextGlyph) -> Option { + let (xx, xy, yx, yy) = (g.x.x, g.x.y, g.y.x, g.y.y); + let (ox, oy) = (g.origin.x, g.origin.y); + if ![xx, xy, yx, yy, ox, oy].iter().all(|v| v.is_finite()) { + return None; + } + let width = xx.hypot(xy); + if !(width.is_finite() && width > 0.0) { + return None; + } + let em = (xx * yy - xy * yx).abs() / width; + (em.is_finite() && em > 0.0 && em <= MAX_TEXT_EM).then_some(em) +} + +/// Whether two vectors agree to within floating-point noise (relative to their length), so glyphs +/// of one shaping pass keep their run. +fn same_vec(a: Vec2, b: Vec2) -> bool { + let scale = 1.0 + a.len().max(b.len()); + a.dist(b) <= 1e-9 * scale +} + +/// Whether `next` sits on the same baseline as `prev` (across it by at most a fifth of an em). +fn on_line(prev: &PlotText, next: &PlotText, em: f64) -> bool { + let x = prev.glyph.x; + let width = x.len(); + if !(width.is_finite() && width > 0.0) { + return false; + } + let d = next.glyph.origin - prev.glyph.origin; + let perp = (d.x * x.y - d.y * x.x).abs() / width; + let along = d.dot(x) / width; + perp <= 0.2 * em && along >= -0.5 * em +} + +/// Whether the gap between two glyphs is a space (a gap wider than the previous glyph's own +/// advance). Only asked when the source recorded no whitespace before `next` (see +/// [`TextGlyph::spaces_before`]); whitespace has no outline glyph, so a gap is all that's left of +/// it in the display list. +fn space_between(prev: &PlotText, next: &PlotText, em: f64) -> bool { + let x = prev.glyph.x; + let width = x.len(); + if !(width.is_finite() && width > 0.0) { + return false; + } + let Some(advance) = cadcraft_fonts::ttf::advance(&prev.glyph.face, prev.glyph.gid) else { + return false; + }; + let expected = advance / 1000.0 * width; + let along = (next.glyph.origin - prev.glyph.origin).dot(x) / width; + let extra = along - expected; + extra > 0.15 * em && extra <= MAX_TEXT_EM +} + +/// Append `count` ASCII spaces to `text` when they fit, together with `extra` more characters, +/// in one run (`MAX_RUN_CHARS`). A count too large for the run leaves `text` untouched (and +/// spends no memory): the caller ends the run instead, so a hostile line of spaces can't build +/// an enormous element. +fn push_spaces(text: &mut String, count: u32, extra: usize) -> bool { + let count = usize::try_from(count).unwrap_or(usize::MAX); + let room = MAX_RUN_CHARS.saturating_sub(text.len()); + if count.saturating_add(extra) > room { + return false; + } + text.extend(std::iter::repeat_n(' ', count)); + true +} + +/// A character SVG text may hold: not a control character or an XML noncharacter. +fn text_char(c: char) -> Option { + let u = u32::from(c); + if c.is_control() || (u & 0xFFFE) == 0xFFFE { + return None; + } + Some(c) +} + +/// Write one text run: a `` with the glyphs' font, size and a matrix mapping em units +/// (font size) to world coordinates. SVG's y axis points down, so the matrix includes the flip. +/// Returns whether it wrote the element (its transform must be finite). +fn write_run(s: &mut String, list: &DisplayList, run: &TextRun, white: Rgb, dp: usize, tx: &impl Fn(f64) -> f64, ty: &impl Fn(f64) -> f64) -> bool { + let Some(p) = usize::try_from(run.first).ok().and_then(|i| list.prims.get(i)) else { return false }; + let color = p.display_rgb(white).hex(); + let op = opacity(p); + let family = run.face.family_name(); + // `font-family` takes quoted family names or a sequence of CSS identifiers: a name such as + // `Font Awesome 6 Free` is neither (a digit can't start an identifier), so quote it and + // keep `sans-serif` as the fallback. XML escaping turns the quotes into entities. + let family = if family.is_empty() { + "sans-serif".to_string() + } else { + escape(&format!("'{}', sans-serif", family.replace('\\', "\\\\").replace('\'', "\\'"))) + }; + let em = run.em; + let a = run.x.x / em; + let b = -run.x.y / em; + let c = run.y.x / em; + let d = -run.y.y / em; + let e = tx(run.origin.x); + let f = ty(run.origin.y); + if ![a, b, c, d, e, f, em].iter().all(|v| v.is_finite()) { + return false; + } + let _ = write!( + s, + r#""# + ); + escape_into(s, &run.text); + s.push_str(""); + true +} + +/// `s` with `&`, `<`, `>`, `"` and `'` escaped for XML, and characters XML can't hold left out. +fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + escape_into(&mut out, s); + out +} + +/// Append `s` to `out`, escaping XML's five predefined entities and leaving out characters XML +/// cannot hold. +fn escape_into(out: &mut String, s: &str) { + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + c => { + if let Some(c) = text_char(c) { + out.push(c); + } + } + } + } +} diff --git a/crates/io/tests/it/main.rs b/crates/io/tests/it/main.rs index 79c4e4b3eb..f41d9d5e66 100644 --- a/crates/io/tests/it/main.rs +++ b/crates/io/tests/it/main.rs @@ -65,6 +65,7 @@ mod spline_fit_data; mod split_entities_section; mod style_typeface; mod svg_arc_budget; +mod svg_text; mod svg_tiny_extents; mod table_cellstyle_roundtrip; mod tables_objects_roundtrip; diff --git a/crates/io/tests/it/svg_text.rs b/crates/io/tests/it/svg_text.rs new file mode 100644 index 0000000000..5a75d31c79 --- /dev/null +++ b/crates/io/tests/it/svg_text.rs @@ -0,0 +1,577 @@ +//! SVG export writes TEXT and MTEXT in installed outline fonts as `` (searchable and +//! editable) when the export asks for it with `text: "text"`; glyph outlines stay the default +//! (#1876). +//! +//! The font is a tiny synthetic TrueType file built here (no font files in the repository). + +use cadcraft_color::Rgb; +use cadcraft_doc::{Common, Drawing, EntityKind, MText, Space, Text, TextStyle, Viewport}; +use cadcraft_fonts::TextGlyph; +use cadcraft_geom::{Bounds2, Vec2, Vec3}; +use cadcraft_io::svg::{self, TextMode}; +use cadcraft_render::{DPrim, DisplayList, Kind, Options, PlotText}; +use serde_json::json; + +// ---------- a minimal TrueType font: .notdef, "A" (triangle), "B" (square) ---------- + +/// Append `x` to `v` big-endian, as a TrueType table stores 16-bit values. +fn be16(v: &mut Vec, x: u16) { + v.extend_from_slice(&x.to_be_bytes()); +} +/// Append `x` to `v` big-endian, as a TrueType table stores 32-bit values. +fn be32(v: &mut Vec, x: u32) { + v.extend_from_slice(&x.to_be_bytes()); +} + +/// One simple TrueType glyph from `pts`, all flagged on-curve, padded to a 4-byte boundary. +fn simple_glyph(pts: &[(i16, i16)]) -> Vec { + let mut g = Vec::new(); + let xs: Vec = pts.iter().map(|p| p.0).collect(); + let ys: Vec = pts.iter().map(|p| p.1).collect(); + be16(&mut g, 1); + for v in [*xs.iter().min().unwrap(), *ys.iter().min().unwrap(), *xs.iter().max().unwrap(), *ys.iter().max().unwrap()] { + be16(&mut g, v as u16); + } + be16(&mut g, pts.len() as u16 - 1); + be16(&mut g, 0); + g.extend(std::iter::repeat_n(1u8, pts.len())); + let (mut px, mut py) = (0i16, 0i16); + for (x, _) in pts { + be16(&mut g, (x - px) as u16); + px = *x; + } + for (_, y) in pts { + be16(&mut g, (y - py) as u16); + py = *y; + } + while g.len() % 4 != 0 { + g.push(0); + } + g +} + +/// A name table naming the family (and full/PostScript names) `family`. +fn name_table(family: &str) -> Vec { + let string: Vec = family.encode_utf16().flat_map(u16::to_be_bytes).collect(); + let mut t = Vec::new(); + be16(&mut t, 0); + be16(&mut t, 3); + be16(&mut t, 6 + 3 * 12); + for id in [1u16, 4, 6] { + for v in [3u16, 1, 0x0409, id, string.len() as u16, 0] { + be16(&mut t, v); + } + } + t.extend(string); + t +} + +/// A TrueType font with glyphs .notdef (empty), A (triangle) and B (square); its cmap also maps +/// `&`, `<` and `>` so XML escaping can be tested. +fn test_font_named(family: &str) -> Vec { + let glyphs = [Vec::new(), simple_glyph(&[(50, 0), (550, 0), (300, 700)]), simple_glyph(&[(50, 0), (550, 0), (550, 700), (50, 700)])]; + let mut glyf = Vec::new(); + let mut loca = Vec::new(); + for g in &glyphs { + be32(&mut loca, glyf.len() as u32); + glyf.extend_from_slice(g); + } + be32(&mut loca, glyf.len() as u32); + let mut head = Vec::new(); + be32(&mut head, 0x0001_0000); + be32(&mut head, 0x0001_0000); + be32(&mut head, 0); + be32(&mut head, 0x5F0F_3CF5); + be16(&mut head, 0); + be16(&mut head, 1000); + head.extend_from_slice(&[0; 16]); + for v in [0i16, 0, 600, 700] { + be16(&mut head, v as u16); + } + for v in [0u16, 8, 2, 1, 0] { + be16(&mut head, v); + } + let mut hhea = Vec::new(); + be32(&mut hhea, 0x0001_0000); + for v in [800i16, -200, 0, 600, 0, 0, 600, 1, 0, 0, 0, 0, 0, 0, 0] { + be16(&mut hhea, v as u16); + } + be16(&mut hhea, 3); + let mut maxp = Vec::new(); + be32(&mut maxp, 0x0001_0000); + for v in [3u16, 4, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] { + be16(&mut maxp, v); + } + let mut hmtx = Vec::new(); + for _ in 0..3 { + be16(&mut hmtx, 600); + be16(&mut hmtx, 50); + } + // cmap: format 4, segments for &, <, > and 'A'..'B'. + let segs: [(u16, u16, u16); 5] = [ + (0x26, 0x26, 1u16.wrapping_sub(0x26)), + (0x3C, 0x3C, 2u16.wrapping_sub(0x3C)), + (0x3E, 0x3E, 1u16.wrapping_sub(0x3E)), + (0x41, 0x42, 1u16.wrapping_sub(0x41)), + (0xFFFF, 0xFFFF, 1), + ]; + let mut sub = Vec::new(); + be16(&mut sub, 4); + be16(&mut sub, (16 + segs.len() * 8) as u16); + be16(&mut sub, 0); + be16(&mut sub, (segs.len() * 2) as u16); + for v in [4u16, 1, 0] { + be16(&mut sub, v); + } + for s in segs { + be16(&mut sub, s.1); + } + be16(&mut sub, 0); + for s in segs { + be16(&mut sub, s.0); + } + for s in segs { + be16(&mut sub, s.2); + } + for _ in segs { + be16(&mut sub, 0); + } + let mut cmap = Vec::new(); + for v in [0u16, 1, 3, 1] { + be16(&mut cmap, v); + } + be32(&mut cmap, 12); + cmap.extend_from_slice(&sub); + let mut os2 = vec![0u8; 78]; + os2[8..10].copy_from_slice(&0u16.to_be_bytes()); + let mut tables: Vec<(&[u8; 4], Vec)> = vec![ + (b"OS/2", os2), + (b"cmap", cmap), + (b"glyf", glyf), + (b"head", head), + (b"hhea", hhea), + (b"hmtx", hmtx), + (b"loca", loca), + (b"maxp", maxp), + (b"name", name_table(family)), + ]; + tables.sort_by_key(|t| *t.0); + let mut out = Vec::new(); + be32(&mut out, 0x0001_0000); + for v in [tables.len() as u16, 128, 3, tables.len() as u16 * 16 - 128] { + be16(&mut out, v); + } + let mut off = 12 + 16 * tables.len(); + for (t, d) in &tables { + out.extend_from_slice(*t); + be32(&mut out, 0); + be32(&mut out, off as u32); + be32(&mut out, d.len() as u32); + off += d.len().div_ceil(4) * 4; + } + for (_, d) in &tables { + out.extend_from_slice(d); + while out.len() % 4 != 0 { + out.push(0); + } + } + out +} + +/// The test font with the family name `SvgTest`. +fn test_font() -> Vec { + test_font_named("SvgTest") +} + +/// Register the synthetic test fonts once per process, so every drawing here can use them. +fn fonts() { + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + cadcraft_fonts::ttf::register("cadcraft-svg-test.ttf", test_font()); + // A family name that is not a sequence of CSS identifiers (it starts with a letter but a + // later word starts with a digit), so `font-family` must quote it. + cadcraft_fonts::ttf::register("cadcraft-svg-fa.ttf", test_font_named("Font Awesome 6 Free")); + }); +} + +/// A metric drawing whose "Real" text style uses the synthetic outline font. +fn drawing() -> Drawing { + fonts(); + let mut d = Drawing::new_metric(); + d.text_styles.push(TextStyle { name: "Real".into(), font: "cadcraft-svg-test.ttf".into(), ..TextStyle::default() }); + d +} + +/// Add a single-line TEXT of `value` at `at`, `height` tall, in the synthetic font. +fn text(d: &mut Drawing, at: (f64, f64), value: &str, height: f64) { + let t = Text { + insert: Vec3::new(at.0, at.1, 0.0), + align_pt: None, + height, + value: value.into(), + rotation: 0.0, + width_factor: 1.0, + oblique: 0.0, + style: "Real".into(), + halign: Default::default(), + valign: Default::default(), + }; + d.add(&Space::Model, Common::default(), EntityKind::Text(t)).unwrap(); +} + +/// Add an MTEXT at `at`, 10 units tall and unbounded wide, whose `contents` use `\P` for line +/// breaks. +fn mtext(d: &mut Drawing, at: (f64, f64), contents: &str) { + let t = MText { + insert: Vec3::new(at.0, at.1, 0.0), + height: 10.0, + width: 0.0, + attach: 1, + rotation: 0.0, + style: "Real".into(), + contents: contents.into(), + line_spacing: 1.0, + line_spacing_exact: false, + columns: None, + }; + d.add(&Space::Model, Common::default(), EntityKind::MText(t)).unwrap(); +} + +/// The numbers of attribute `name="…"` of the first element carrying it. +fn attr(s: &str, name: &str) -> Vec { + let key = format!("{name}=\""); + let rest = s.split(&key).nth(1).unwrap_or_default(); + let val = rest.split('"').next().unwrap_or_default(); + val.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()).filter_map(|t| t.parse().ok()).collect() +} + +/// Guards #1876's main promise: TEXT and every MTEXT line become `` elements with the +/// font family, a positive font size and the glyphs' matrix, and the outlines they replace are +/// not drawn as well. +#[test] +fn text_and_mtext_are_written_as_text() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), "ABBA", 10.0); + mtext(&mut d, (0.0, 20.0), "AB\\PBA"); + let s = svg::export_window_with_text(&d, &Space::Model, None, true, TextMode::Text); + + assert!(s.matches("= 3, "one TEXT and two MTEXT lines: {s}"); + assert!(s.contains(">ABBA"), "{s}"); + assert!(s.contains(">AB") && s.contains(">BA"), "MTEXT lines: {s}"); + assert!(s.contains(r#"font-family="'SvgTest', sans-serif""#), "{s}"); + assert!(s.matches("font-size=\"").count() >= 3, "{s}"); + let size = attr(&s, "font-size"); + assert!(size.len() == 1 && size[0].is_finite() && size[0] > 0.0, "{s}"); + // Rotation, size and shear are in the text's own matrix; nothing is positioned by guesswork. + assert!(s.contains("transform=\"matrix("), "{s}"); + assert!(s.contains(r#"text-anchor="start""#), "{s}"); + // The glyph outlines that the text replaces are not drawn as well. + assert!(!s.contains("` elements and keeps the glyphs +/// as outline polylines (here with TEXTFILL off), exactly like a plot. +#[test] +fn geometry_mode_keeps_glyph_outlines() { + let mut d = drawing(); + d.header.set_i64("TEXTFILL", 0); + text(&mut d, (0.0, 0.0), "ABBA", 10.0); + mtext(&mut d, (0.0, 20.0), "AB\\PBA"); + let s = svg::export_window_with_text(&d, &Space::Model, None, true, TextMode::Geometry); + + assert!(!s.contains("A B"), "the space between the words is kept: {s}"); + let m: Vec = s + .split("matrix(") + .nth(1) + .unwrap_or_default() + .split(')') + .next() + .unwrap_or_default() + .split_whitespace() + .filter_map(|v| v.parse().ok()) + .collect(); + assert_eq!(m.len(), 6, "{s}"); + // The baseline rotation is in the matrix (SVG's y axis is down). + assert!((m[0] - 0.5f64.cos()).abs() < 1e-5 && (m[1] + 0.5f64.sin()).abs() < 1e-5, "{m:?}"); + assert!((m[2] + 0.5f64.sin()).abs() < 1e-5 && (m[3] + 0.5f64.cos()).abs() < 1e-5, "{m:?}"); +} + +/// Guards that `&`, `<` and `>` in drawing text are XML-escaped inside ``, so a drawing +/// with those characters still yields a well-formed document. +#[test] +fn special_characters_are_escaped() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), "A&B", 10.0); + let s = svg::export_window_with_text(&d, &Space::Model, None, true, TextMode::Text); + assert!(s.contains(">A&B<A>"), "{s}"); + assert!(!s.contains(">A&B"), "unescaped text: {s}"); +} + +/// Guards that hostile text heights (zero, negative, NaN, infinite, huge, tiny) and control +/// characters still produce a complete SVG instead of panicking. +#[test] +fn hostile_text_never_panics() { + let mut d = drawing(); + for (i, h) in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e300, 1e-300].into_iter().enumerate() { + text(&mut d, (i as f64 * 20.0, 0.0), "AB\u{0}\u{1}", h); + } + let s = svg::export_window_with_text(&d, &Space::Model, None, true, TextMode::Text); + assert!(s.starts_with(""), "{s}"); +} + +/// Guards that `export_with` keeps glyph outlines unless `text: "text"` asks for `` +/// elements, that the default output is byte-identical to an explicit `"geometry"` export, and +/// that an unknown value falls back to geometry; other formats ignore the option. +#[test] +fn the_export_json_option_selects_the_mode() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), "ABBA", 10.0); + let default = cadcraft_io::export_with(&d, "a.svg", &json!({})).unwrap(); + assert!(!String::from_utf8_lossy(&default).contains("` element preserves them with `xml:space="preserve"`. +#[test] +fn repeated_spaces_are_kept() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), "A B", 10.0); + text(&mut d, (0.0, 20.0), "A B", 10.0); + text(&mut d, (0.0, 40.0), " AB", 10.0); + text(&mut d, (0.0, 60.0), "A B", 10.0); + let s = svg::export_window_with_text(&d, &Space::Model, None, true, TextMode::Text); + + assert!(s.contains(">A B"), "two spaces stay two: {s}"); + assert!(s.contains(">A B"), "three spaces stay three: {s}"); + assert!(s.contains("> AB"), "a leading space stays: {s}"); + assert!(s.contains(">A B"), "one space is unchanged: {s}"); + assert_eq!(s.matches("AA"), "a kern adds no space: {s}"); + assert_eq!(s.matches("A A"), "one source space, one space: {s}"); + assert!(!s.contains(">A A"), "not doubled by the inferred space: {s}"); + + // Without a recorded space, a gap wide enough to be one still falls back to an inferred space + // (text positioned glyph by glyph, which other shapers record no counts for). + list.texts[1] = glyph(1, 1.0, 0); + let s = svg::export_list_with(&list, None, TextMode::Text); + assert!(s.contains(">A A"), "a wide gap is still a space: {s}"); +} + +/// Guards that a hostile number of spaces stays bounded: no huge element, no enormous +/// allocation, and the glyph whose spaces don't fit stays an outline (its primitive is written), +/// so the drawing keeps every glyph. +#[test] +fn a_very_long_run_of_spaces_is_bounded() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), &format!("A{}B", " ".repeat(300_000)), 10.0); + let s = svg::export_window_with_text(&d, &Space::Model, None, true, TextMode::Text); + assert!(s.starts_with(""), "still a complete document"); + let chars: usize = s.split("").next()).map(str::len).sum(); + assert!(chars <= 100_000, "the text of the runs stays bounded: {chars}"); + assert!(s.contains(">A"), "the first glyph is still text: {s}"); + assert!(s.contains("` matrix overflows leaves its outline as geometry instead of vanishing (the text run +/// replaces the outline only when it was written). +#[test] +fn an_ill_conditioned_glyph_stays_geometry() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), "A", 10.0); + let opts = Options { text_glyphs: true, ..Options::default() }; + let mut list = cadcraft_render::build(&d, &Space::Model, &opts); + assert_eq!(list.texts.len(), 1, "one glyph to write"); + // A huge baseline axis with a tiny vertical axis: the em is finite and positive (the + // determinant over the axis length), but dividing the axis by it overflows. + list.texts[0].glyph.x = Vec2::new(1e300, 0.0); + list.texts[0].glyph.y = Vec2::new(0.0, 1e-300); + let s = svg::export_list_with(&list, None, TextMode::Text); + assert!(!s.contains("` by a non-plot +/// export: `resolve_viewport_text` gives each whole glyph its outline primitive back and clears +/// the encoded text index from the handle (#1876). +#[test] +fn viewport_text_is_written_as_text() { + let mut d = drawing(); + text(&mut d, (0.0, 0.0), "AB", 10.0); + let vp = Viewport { + center: Vec3::new(50.0, 50.0, 0.0), + width: 100.0, + height: 100.0, + view_center: Vec2::new(0.0, 0.0), + view_height: 100.0, + id: 2, + locked: false, + frozen_layers: Vec::new(), + layer_colors: Vec::new(), + clip: None, + on: true, + }; + d.add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Viewport(vp)).unwrap(); + let paper = Space::Paper("Layout1".into()); + + let opts = Options { text_glyphs: true, ..Options::default() }; + let list = cadcraft_render::build(&d, &paper, &opts); + assert!(!list.texts.is_empty(), "the viewport's text glyphs are recorded"); + assert!(list.texts.iter().all(|t| t.prim != PlotText::NONE), "each whole glyph keeps its outline primitive"); + assert!(list.prims.iter().all(|p| p.handle.0 >> 32 == 0), "no encoded text index is left in a handle"); + + let s = svg::export_window_with_text(&d, &paper, None, true, TextMode::Text); + assert!(s.contains(">AB"), "viewport text is an SVG text element: {s}"); + assert!(!s.contains(", - /// Plots: outline-font glyphs that a plotter can write as text instead of drawing the - /// filled outline primitive they stand for ([`PlotText::prim`]), in drawing order. + /// Plots and text exports: outline-font glyphs that a plotter can write as text instead of + /// drawing the filled outline primitive they stand for ([`PlotText::prim`]), in drawing + /// order. Empty for other builds. pub texts: Vec, pub bounds: Bounds2, /// The paper sheet when the list was built for a layout (paper space); the UI draws the diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 6fa236e4ca..1cb1ddf135 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -220,8 +220,9 @@ impl Builder<'_> { if sh.glyphs.is_empty() { return; } - let fill = self.opts.fill && ctx.d.header.i64("TEXTFILL", 1) != 0; - // Plots note which filled outlines are font glyphs (see `DisplayList::texts`). + let fill = self.opts.fill && (ctx.d.header.i64("TEXTFILL", 1) != 0 || self.opts.text_glyphs); + // Plots note which filled outlines are font glyphs (see `DisplayList::texts`); so do + // exports that want to write text. let mut text = sh.text.iter().peekable(); let pixel = if self.plotting { 0.0 } else { self.opts.min_dash * 0.5 }; for (i, g) in sh.glyphs.iter().enumerate() { @@ -239,7 +240,7 @@ impl Builder<'_> { self.tris(ctx, color, &tris); tris.len() }; - if let Some(t) = glyph.filter(|_| self.plotting) + if let Some(t) = glyph.filter(|_| self.plotting || self.opts.text_glyphs) && self.list.prims.len() > at && let (Ok(prim), Ok(verts)) = (u32::try_from(at), u32::try_from(len)) { diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index 3fc72f5180..19e55699ca 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -41,6 +41,10 @@ pub struct Options { /// rebuild the view no longer needs). A cancelled build returns a partial list, which the /// caller must discard; see [`Options::cancelled`]. pub cancel: Option>, + /// Record the outline-font glyphs that stand for filled glyph primitives in + /// [`DisplayList::texts`], so output formats can write text instead of outlines. Plots + /// record them anyway; exports ask for them with this flag. + pub text_glyphs: bool, } impl Options { @@ -51,6 +55,8 @@ impl Options { } impl Default for Options { + /// The defaults a build starts from: text and fills on, lineweights off, the whole space in + /// view, opaque, and no plot style, cancellation or recorded text glyphs. fn default() -> Self { Options { tolerance: 0.001, @@ -65,6 +71,7 @@ impl Default for Options { skip_viewport: None, transparency: false, cancel: None, + text_glyphs: false, } } } @@ -117,9 +124,14 @@ fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> Di if paper && let EntityKind::Viewport(vp) = &e.kind { if viewports < MAX_VIEWPORTS { viewports += 1; + let start = b.list.prims.len(); viewport(&mut b, d, e, vp); if plotting { take_viewport_layers(&mut b.list); + } else if opts.text_glyphs { + // A text export replaces the outlines with ``: resolve the glyphs + // it should write (a plot does this in `take_viewport_layers`). + resolve_viewport_text(&mut b.list, start); } } continue; @@ -240,3 +252,31 @@ fn take_viewport_layers(list: &mut DisplayList) { } } } + +/// The non-plot counterpart of the glyph half of [`take_viewport_layers`]: text seen through a +/// layout viewport is marked with its index in the handle's high half until it is clipped. A +/// glyph outline that came through whole takes its own primitive back, so an SVG text export can +/// write it as ``; one the clip changed stays geometry. The handle loses the index (it goes +/// back to [`VIEWPORT_CONTENT`]) without plot-only layer bookkeeping. +fn resolve_viewport_text(list: &mut DisplayList, start: usize) { + for i in start..list.prims.len() { + let Some(p) = list.prims.get(i).copied() else { break }; + let Some(k) = (p.handle.0 >> 32).checked_sub(1) else { continue }; + let bounds = Bounds2::from_points(list.points(&p).iter().copied()); + let same = |a: Vec2, b: Vec2| a.dist(b) <= 1e-9 * (1.0 + a.len()); + let whole = usize::try_from(k).ok().and_then(|k| list.texts.get(k)).is_some_and(|t| { + t.prim == PlotText::NONE + && p.kind == Kind::Tris + && p.len == t.verts + && same(bounds.min, t.bounds.min) + && same(bounds.max, t.bounds.max) + && u32::try_from(i).is_ok() + }); + if whole && let Some(t) = usize::try_from(k).ok().and_then(|k| list.texts.get_mut(k)) { + t.prim = u32::try_from(i).unwrap_or(PlotText::NONE); + } + if let Some(p) = list.prims.get_mut(i) { + p.handle = Handle(p.handle.0 & 0xFFFF_FFFF); + } + } +} diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index f965b0ae13..f979c0a1a4 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -137,6 +137,7 @@ pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], c transparency: app.session.settings.transparency_display, skip_viewport: split, cancel: None, + text_glyphs: false, }; if view_only { let t = Tokens::get(); diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index 0857e23ee1..2b085cbae4 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -137,6 +137,7 @@ pub(super) fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Con skip_viewport: None, transparency, cancel: None, + text_glyphs: false, }; c.list = cadcraft_render::viewport_content(&st.doc, &st.space, h, area, &opts); c.key = Some(key);