diff --git a/crates/render/src/canvas.rs b/crates/render/src/canvas.rs index b5061c12fc..7c7650d9bd 100644 --- a/crates/render/src/canvas.rs +++ b/crates/render/src/canvas.rs @@ -31,6 +31,8 @@ struct Recording { ts: Transform, /// A layer is open ([`Canvas::layer`]). layer: bool, + /// The glyphs kept are a halo this wide ([`Canvas::halo`]). + halo: Option, } impl Canvas { @@ -48,7 +50,7 @@ impl Canvas { pub fn recording(width: u32, height: u32) -> Option { let pm = Pixmap::new(width, height)?; let drawing = Drawing::new(width as f32, height as f32); - Some(Canvas { pm, rec: Some(Box::new(Recording { drawing, dirty: false, ts: Transform::identity(), layer: false })) }) + Some(Canvas { pm, rec: Some(Box::new(Recording { drawing, dirty: false, ts: Transform::identity(), layer: false, halo: None })) }) } /// Whether it records. @@ -205,6 +207,7 @@ impl Canvas { pub fn glyphs(&mut self, mut run: GlyphRun) { self.keep(|r| { run.transform = r.ts.pre_concat(run.transform); + run.halo = run.halo.or(r.halo); r.drawing.glyphs(run); }); } @@ -223,6 +226,21 @@ impl Canvas { } } + /// Draws with `f` as a halo `width` wide (#1815): the glyphs it keeps are a halo's copy of the + /// text, filled and stroked that wide (see [`vector::GlyphRun::halo`]), so a PDF writes the + /// halo as text too. Only a recording keeps halos so; a canvas that draws pixels runs `f`. A + /// width that isn't a positive number is no halo: nothing is drawn, as on the pixels. + pub fn halo(&mut self, width: f32, f: impl FnOnce(&mut Canvas)) { + if !(width.is_finite() && width > 0.0) { + return; + } + let old = self.rec.as_mut().map(|r| r.halo.replace(width)); + f(self); + if let (Some(r), Some(old)) = (&mut self.rec, old) { + r.halo = old; + } + } + /// Draws with `f` as one group composited at `opacity` (so what `f` draws overlapping shows /// once); a canvas that draws pixels runs `f` on itself, for callers that only group what /// they record. @@ -466,8 +484,32 @@ mod tests { assert_eq!(alpha(27), Some(0), "the clip past the child"); } + /// A halo of no width, or of one that isn't a number, draws nothing (#1815): not a copy of + /// the text in the halo's colour set as plain text. + #[test] + fn a_halo_of_no_width_draws_nothing() { + let font = crate::text::label_font().unwrap(); + let run = || GlyphRun { + font, + size: 12.0, + color: Color::WHITE, + transform: Transform::identity(), + glyphs: vec![crate::vector::Glyph { id: ab_glyph::Font::glyph_id(font, 'A'), x: 0.0, ch: 'A' }], + halo: None, + }; + for width in [0.0, -1.0, f32::NAN, f32::INFINITY] { + let mut c = Canvas::recording(40, 20).unwrap(); + c.halo(width, |c| c.glyphs(run())); + assert!(c.into_drawing().unwrap().is_empty(), "{width}"); + } + let mut c = Canvas::recording(40, 20).unwrap(); + c.halo(2.0, |c| c.glyphs(run())); + let (_, _, items) = c.into_drawing().unwrap().finish(); + assert!(matches!(items.as_slice(), [Item::Glyphs(r)] if r.halo == Some(2.0))); + } + #[test] - fn a_label_keeps_its_halo_as_a_shape_and_its_text_once() { + fn a_label_keeps_its_halo_as_text_and_its_text_once() { let label = crate::PlacedLabel { text: "Memphis".into(), x: 50.0, @@ -493,9 +535,13 @@ mod tests { crate::text::draw(&mut c, &label, 1.0); let (_, _, items) = c.into_drawing().unwrap().finish(); let [Item::Group(halo), Item::Glyphs(run)] = items.as_slice() else { panic!("a halo and the text") }; - // The halo: the letters and their outline spread round them, opaque, in one coat. - assert!(matches!(halo.items.as_slice(), [Item::Fill { .. }, Item::Stroke { .. }])); - assert_eq!(run.glyphs.iter().map(|g| g.ch).collect::(), "Memphis"); + // The halo (#1815): a copy of the text under it, its glyphs filled and stroked twice the + // halo's reach (1.2 points) wide, opaque, in one coat. + let [Item::Glyphs(copy)] = halo.items.as_slice() else { panic!("the halo as a run of glyphs") }; + assert_eq!(copy.halo, Some(2.4)); + assert_eq!(copy.color, tiny_skia::Color::WHITE); + assert_eq!((copy.glyphs.as_slice(), copy.transform), (run.glyphs.as_slice(), run.transform), "the text's own glyphs, where it is"); + assert_eq!((run.halo, run.glyphs.iter().map(|g| g.ch).collect::().as_str()), (None, "Memphis")); // Turned with the label, not drawn as a turned picture. assert!(run.transform.ky.abs() > 0.1); // A halo of no width draws nothing, as on the pixels. diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index 846558c4f7..7db3f30457 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -260,6 +260,18 @@ impl Writer<'_> { /// Sets a run of glyphs in the document's fonts, each at its pen position. fn glyphs(&mut self, out: &mut Vec, st: &mut State, run: &GlyphRun) { + // A halo (#1815): in an embedded face, the same text filled and stroked (rendering mode + // 2), so an editor sees it as text too, marked as an artifact; in outlines (a Type 3 + // glyph is filled only), its glyphs' outlines filled and stroked, as before. + let halo = run.halo.filter(|w| w.is_finite() && *w > 0.0); + if let Some(w) = halo + && !self.fonts.is_real(run.font) + { + if let Some(path) = run.outline() { + self.fill_and_stroke(out, st, &path, run.color, FillRule::Winding, (run.color, &GlyphRun::halo_stroke(w)), run.transform); + } + return; + } let mut placed = Vec::with_capacity(run.glyphs.len()); for g in &run.glyphs { if let Some(p) = self.fonts.place(self.doc, run.font, g.id, g.ch) { @@ -271,7 +283,23 @@ impl Writer<'_> { } self.alpha(out, st, run.color.alpha()); set_color(out, &mut st.fill, run.color, "rg"); + if let Some(w) = halo { + // A text's stroke is in user space, not the text matrix's: the run's scale applied. + let t = run.transform; + let scale = (t.sx * t.sy - t.kx * t.ky).abs().sqrt(); + set_color(out, &mut st.stroke, run.color, "RG"); + stroke_state(out, st, &GlyphRun::halo_stroke(w * scale)); + } + if halo.is_some() { + // The copy is decoration, marked so (an artifact) for readers that leave artifacts out + // of what they copy and find. (An empty `ActualText` would hide it from every reader's + // text, but VectorCraft then drops the halo altogether.) + out.extend_from_slice(b"/Artifact BMC\n"); + } out.extend_from_slice(b"BT\n"); + if halo.is_some() { + out.extend_from_slice(b"2 Tr\n"); + } // Glyph space is y up: flipped into the run's y-down space. write_matrix(out, run.transform.pre_scale(1.0, -1.0)); out.extend_from_slice(b" Tm\n"); @@ -298,7 +326,8 @@ impl Writer<'_> { let _ = if p.wide { write!(out, "<{:04X}>", p.code) } else { write!(out, "<{:02X}>", p.code) }; pen = x + p.advance * size; } - out.extend_from_slice(b"] TJ\nET\n"); + // (The rendering mode is text state, kept past ET: set back for the text that follows.) + out.extend_from_slice(if halo.is_some() { b"] TJ\n0 Tr\nET\nEMC\n" } else { b"] TJ\nET\n" }); } /// Places a picture: an image object (with its alpha as a soft mask) drawn where it lies. @@ -720,6 +749,7 @@ mod tests { color: Color::from_rgba8(20, 20, 20, 255), transform: Transform::from_translate(210.0, 40.0), glyphs, + halo: None, }); let mut pic = Pixmap::new(4, 4).unwrap(); pic.fill(Color::from_rgba8(0, 160, 0, 200)); @@ -805,7 +835,7 @@ mod tests { let x = font.h_advance_unscaled(a) / upm * 20.0 + 5.0; let mut d = Drawing::new(100.0, 100.0); let glyphs = vec![Glyph { id: a, x: 0.0, ch: 'A' }, Glyph { id: v, x, ch: 'V' }]; - d.glyphs(GlyphRun { font, size: 20.0, color: Color::BLACK, transform: Transform::from_translate(10.0, 50.0), glyphs }); + d.glyphs(GlyphRun { font, size: 20.0, color: Color::BLACK, transform: Transform::from_translate(10.0, 50.0), glyphs, halo: None }); let objs = objects(&write(&[Page::drawing(d, 10.0, 10.0)], "")); let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|c| c.contains("TJ")).unwrap(); assert!(content.contains("1 0 0 -1 10 50 Tm\n") && content.contains("[<00>-250<01>] TJ"), "{content}"); diff --git a/crates/render/src/pdf/embed.rs b/crates/render/src/pdf/embed.rs index 71fa6bcf8d..5d3a5c68b8 100644 --- a/crates/render/src/pdf/embed.rs +++ b/crates/render/src/pdf/embed.rs @@ -153,7 +153,7 @@ pub(super) fn embed(font: &FontRef<'_>, glyphs: &[GlyphId], room: usize) -> Resu let name = if name.is_empty() { "Face".to_string() } else { name }; Ok(Embedded { cff: face.tables().cff.is_some(), - name: format!("{}+{name}", tag(&name, glyphs)), + name: format!("{}+{name}", tag(&name, glyphs, data)), remapper, bbox: [f32::from(b.x_min) * k, f32::from(b.y_min) * k, f32::from(b.x_max) * k, f32::from(b.y_max) * k], ascent: f32::from(face.ascender()) * k, @@ -188,10 +188,15 @@ fn curve_points(c: &OutlineCurve) -> (u8, [(f32, f32); 4]) { } } -/// A subset's six-letter tag, from its face's name and glyphs: the same subset, the same tag. -fn tag(name: &str, glyphs: &[GlyphId]) -> String { +/// A subset's six-letter tag, from its face's name, glyphs and file (its size and bytes): the same +/// subset, the same tag, and two files with the same name and glyphs, two tags. +fn tag(name: &str, glyphs: &[GlyphId], file: &[u8]) -> String { + // FNV-1a, a byte at a time: a multiplication carries a byte's bits only upwards, so a wider + // value mixed at once would leave its high bytes out of the low bits the letters are read from. let mut h: u64 = 0xcbf2_9ce4_8422_2325; - for b in name.bytes().chain(glyphs.iter().flat_map(|g| g.0.to_le_bytes())) { + let glyph_bytes = glyphs.iter().flat_map(|g| g.0.to_le_bytes()); + let len_bytes = (file.len() as u64).to_le_bytes(); + for b in name.bytes().chain(glyph_bytes).chain(len_bytes).chain(file.iter().copied()) { h = (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); } (0..6).map(|i| char::from(b'A' + ((h >> (i * 5)) % 26) as u8)).collect() @@ -230,6 +235,7 @@ mod tests { color: Color::BLACK, transform: Transform::from_row(1.0, 0.0, kx, 1.0, 10.0, 40.0), glyphs: text.chars().zip(0..).map(|(ch, i)| Glyph { id: font.glyph_id(ch), x: 11.0 * i as f32, ch }).collect(), + halo: None, }; let mut d = Drawing::new(200.0, 100.0); d.glyphs(run(0.0)); @@ -306,6 +312,23 @@ mod tests { checked } + /// A subset's tag follows its face's file, not only its name and glyphs: two files with the + /// same name and glyphs get two tags (#1815), whichever of their bytes differs, the high bytes + /// of an eight-byte word too. + #[test] + fn a_subset_tag_follows_its_file() { + let glyphs = [GlyphId(3), GlyphId(7)]; + let a = tag("Face", &glyphs, b"ABCDEFGHIJKLMNOP"); + assert_eq!(a, tag("Face", &glyphs, b"ABCDEFGHIJKLMNOP"), "the same subset, the same tag"); + assert!(a.len() == 6 && a.chars().all(|c| c.is_ascii_uppercase()), "{a}"); + // The same length, one byte apart: each of a word's eight bytes, in turn. + for at in 0..8 { + let mut other = *b"ABCDEFGHIJKLMNOP"; + other[at] ^= 0x5A; + assert_ne!(a, tag("Face", &glyphs, &other), "byte {at}"); + } + } + /// A CFF face (an OpenType .otf) is embedded as a CIDFontType0 over its subset as an /// OpenType file (FontFile3, PDF 1.6), each CID its character's glyph. The face is the /// test's own (testdata/README.md): a square, a triangle and two bars, each its own width. @@ -324,6 +347,48 @@ mod tests { assert_eq!(cids_are_their_glyphs(font, &objs, "/Subtype /CIDFontType0"), 3, "C, A, B"); } + /// A halo (#1815) is its text again under it, filled and stroked: in an embedded face, the + /// same font in rendering mode 2, its stroke rounded and as wide as the run's scale makes it, + /// marked as an artifact; in outlines, its glyphs' outlines filled and stroked, as before. + #[test] + fn a_halo_is_its_text_filled_and_stroked() { + let font = face(|_| ()); + let run = |halo: Option, color: Color| GlyphRun { + font, + size: 20.0, + color, + transform: Transform::from_row(2.0, 0.0, 0.0, 2.0, 10.0, 40.0), + glyphs: "Rio".chars().zip(0..).map(|(ch, i)| Glyph { id: font.glyph_id(ch), x: 11.0 * i as f32, ch }).collect(), + halo, + }; + let page = || { + let mut d = Drawing::new(200.0, 100.0); + d.begin_group(0.9, rustgis_map::effects::Blend::Normal, None); + d.glyphs(run(Some(2.4), Color::WHITE)); + d.end_group(); + d.glyphs(run(None, Color::BLACK)); + Page::drawing(d, 100.0, 50.0) + }; + let streams = + |pdf: &[u8]| objects(pdf).into_iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).collect::>().join("\n"); + let (pdf, outlined) = write_with(&[page()], "Halo", Options { text: Text::Fonts, ..Options::default() }); + assert!(outlined.is_empty()); + let text = String::from_utf8_lossy(&pdf); + assert_eq!(text.matches("/Subtype /Type0").count(), 1, "the halo in the text's own font"); + let content = streams(&pdf); + let halo = content.split("/Artifact BMC\n").nth(1).and_then(|h| h.split("EMC\n").next()).unwrap_or_else(|| panic!("{content}")); + assert!(halo.starts_with("BT\n2 Tr\n") && halo.ends_with("] TJ\n0 Tr\nET\n"), "{halo}"); + // Stroked in white, rounded, the run's 2.4 pixels doubled by its scale. + assert!( + content.contains("1 1 1 RG") && content.contains("4.8 w") && content.contains("1 J") && content.contains("1 j"), + "{content}" + ); + assert_eq!(content.matches(" Tr\n").count(), 2, "the text itself is filled only"); + // In outlines: the halo as its glyphs' outlines, filled and stroked. + let outlines = streams(&write_with(&[page()], "Halo", Options { text: Text::Outlines, ..Options::default() }).0); + assert!(!outlines.contains(" Tr\n") && !outlines.contains("/Artifact") && outlines.contains("\nB\n"), "{outlines}"); + } + /// A face whose licence forbids embedding (fsType 2) is set in outlines, and said. #[test] fn a_face_that_forbids_embedding_is_set_in_outlines() { diff --git a/crates/render/src/pdf/fonts.rs b/crates/render/src/pdf/fonts.rs index 439e2ec01b..d20836f72f 100644 --- a/crates/render/src/pdf/fonts.rs +++ b/crates/render/src/pdf/fonts.rs @@ -75,6 +75,11 @@ impl Fonts { Fonts { real, real_by_font, ..Fonts::default() } } + /// Whether `font` is embedded as itself (else its glyphs go to Type 3 fonts). + pub fn is_real(&self, font: &FontRef<'static>) -> bool { + self.real_by_font.contains_key(&(std::ptr::from_ref(font) as usize)) + } + /// `id` of `font` (standing for `ch`), given a code in one of its Type 3 fonts the first time; /// `None` only past what a font can hold. pub fn place(&mut self, doc: &mut Doc, font: &'static FontRef<'static>, id: GlyphId, ch: char) -> Option { diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index 6e8b7052a3..8967340301 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -199,7 +199,15 @@ fn glyphs(out: &mut String, defs: &mut Defs, run: &GlyphRun) { let face = std::ptr::from_ref(run.font) as usize; let k = run.size / upm; let text: String = run.glyphs.iter().map(|g| g.ch).collect(); - let _ = writeln!(out, r#""#, super::esc(&text), paint("fill", run.color), transform_attr(run.transform)); + // A halo's copy (#1815) stroked as well, its width in the glyphs' own units (each is placed + // scaled by `k`). + let stroke = run.halo.filter(|w| w.is_finite() && *w > 0.0 && k > 0.0).map_or(String::new(), |w| { + format!(r#"{} stroke-width="{}" stroke-linejoin="round" stroke-linecap="round""#, paint("stroke", run.color), trimmed(w / k, 4)) + }); + // The halo's copy is decoration: hidden from screen readers, which read the label once (as a + // PDF marks it an artifact). + let label = if run.halo.is_some() { r#" aria-hidden="true""#.to_string() } else { format!(r#" aria-label="{}""#, super::esc(&text)) }; + let _ = writeln!(out, r#""#, paint("fill", run.color), transform_attr(run.transform)); for g in &run.glyphs { let id = match defs.glyphs.get(&(face, g.id.0)) { Some(id) => id.clone(), @@ -378,7 +386,7 @@ mod tests { let o = font.glyph_id('o'); let glyphs = vec![Glyph { id: o, x: 0.0, ch: 'o' }, Glyph { id: font.glyph_id(' '), x: 6.0, ch: ' ' }, Glyph { id: o, x: 9.0, ch: 'o' }]; - d.glyphs(GlyphRun { font, size: 12.0, color: Color::BLACK, transform: Transform::from_translate(60.0, 40.0), glyphs }); + d.glyphs(GlyphRun { font, size: 12.0, color: Color::BLACK, transform: Transform::from_translate(60.0, 40.0), glyphs, halo: None }); let mut pic = tiny_skia::Pixmap::new(2, 2).unwrap(); pic.fill(Color::from_rgba8(0, 128, 0, 255)); d.image(pic.as_ref(), Transform::from_scale(5.0, 5.0), 0.5, false); @@ -415,6 +423,29 @@ mod tests { assert!(defs.text.contains(r#"